Reputation: 31
I'm trying to solve a linear programming function with two restraints. Basically, I need to maximize profit with a restraint of capacity and budget.
import numpy as np
from scipy.optimize import minimize
"""
maximize g1*g1_profit + g2*g2_profit (or minimize -...)
st (g1*g1_price + g2*g2_price) <= budget
(g1*g1_size + g2*g2_size) <= total_size
"""
budget = 10000
total_size = 50
g1_price = 300
g2_price = 600
g1_size = 2
g2_size = 1
g1_profit = 1200
g2_profit = 1000
def objective(x):
global g1, g2
g1 = x[0]
g2 = x[1]
return g1*g1_profit + g2*g2_profit
def constraint1(x):
return -(g1*g1_price + g2*g2_price) + budget
def constraint2(x):
return -(g1*g1_size + g2*g2_size) + total_size
x0 = [1,1]
print(-objective(x0))
cons1 = {'type': 'ineq', 'fun': constraint1}
cons2 = {'type': 'ineq', 'fun': constraint2}
cons = (cons1, cons2)
sol = minimize(objective,x0,method='SLSQP',constraints=cons)
print(sol)
I am getting this result:
print(sol)
fun: -1.334563245874159e+38
jac: array([1200.00002082, 1000.0000038 ])
message: 'Singular matrix E in LSQ subproblem'
nfev: 144
nit: 48
njev: 48
status: 5
success: False
x: array([-6.56335026e+34, -5.46961214e+34])
So the success is False and the result is wrong. I did read optimize help page and I checked a few example online but I can't find any solution. Thanks in advance.
Upvotes: 0
Views: 370
Reputation: 7157
First, please avoid global variables whenever possible. You can easily rewrite your functions as:
def objective(x):
g1, g2 = x
return g1*g1_profit + g2*g2_profit
def constraint1(x):
g1, g2 = x
return -(g1*g1_price + g2*g2_price) + budget
def constraint2(x):
g1, g2 = x
return -(g1*g1_size + g2*g2_size) + total_size
Then, you need to multiply the objective with -1.0 in order to transform your maximization problem into a minimization problem:
minimize(lambda x: -1.0*objective(x),x0, method='SLSQP', constraints=cons)
This gives me
fun: -32222.222047310468
jac: array([-1200., -1000.])
message: 'Optimization terminated successfully'
nfev: 6
nit: 6
njev: 2
status: 0
success: True
x: array([22.22222214, 5.55555548])
Hence, the optimal objective function value is 32222.
Upvotes: 1