Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximize Optimization using Scipy

Tags:

python

scipy

I'm trying to solve this linear programming function with the restraints shown below, the answer for x1 and x2 should be 2 and 6 respectively, and the value of the objective function should be equal to 36. The code that I wrote gives me as answers 4 and 3. What may I be doing wrong? Function to maximize z=3*x1 + 5*x2. Restraints are x1 <= 4;2*x2 <=12; 3*x1 + 2*x2 <= 18; x1>=0;x2>=0.

import numpy as np
from scipy.optimize import minimize
def objective(x, sign=1.0):
    x1 = x[0]
    x2 = x[1]
    return sign*((3*x1) + (5*x2))
def constraint1(x, sign=1.0):
    return sign*(3*x[0] +2*x[1]- 18.0)
x0=[0,0]

b1 = (0,4)
b2 = (0,12)
bnds= (b1,b2)
con1 = {'type': 'ineq', 'fun': constraint1}

cons = [con1]
sol = minimize (objective,x0,method='SLSQP',bounds=bnds,constraints=cons)

print(sol)
like image 878
JM Esgar Avatar asked Apr 30 '17 02:04

JM Esgar


People also ask

Does SciPy have maximize?

The SciPy Optimize library provides a set of functions to minimize (or maximize) objective functions.

Is SciPy optimize multithreaded?

NumPy/SciPy's functions are usually optimized for multithreading. Did you look at your CPU utilization to confirm that only one core is being used while the simulation is being ran? Otherwise you have nothing to gain from running multiple instances.

How do I stop SciPy optimizing minimize?

optimize. minimize can be terminated by using tol and maxiter (maxfev also for some optimization methods). There are also some method-specific terminators like xtol, ftol, gtol, etc., as mentioned on scipy.


1 Answers

Your code has the following issues:

  • The way you are passing your objective to minimize results in a minimization rather than a maximization of the objective. If you want to maximize objective with minimize you should set the sign parameter to -1. See the maximization example in scipy documentation.
  • minimize assumes that the value returned by a constraint function is greater than zero. Therefore, the way you have written your constraint implies that 3*x1 + 2*x2 - 18.0 >=0, whereas the actual constraint employs <=.
  • The upper bound in b2 does not correspond to the bound implied by the constraint 2*x2 <= 12.
like image 100
Stelios Avatar answered Oct 05 '22 14:10

Stelios