import pandas as pd
import numpy as np
from scipy.optimize import minimize
Example:
Objective Function: $$ \min x^2_1 + x_1 \times x_2 $$ s.t. Constraints:
$$ \begin{aligned} x^3_1 + x_1 \times x_2 & = 100 \\ x^2_1 + x_2 \leq 50 \\ -100 \leq x_1, x_2 & \le 100 \end{aligned} $$# define the objective function and constraints
def objective_fcn(x):
# parameters:
x1 = x[0]
x2 = x[1]
return x1**2 + x1 * x2
def equality_constraint(x):
x1 = x[0]
x2 = x[1]
return x1**3 + x1 * x2 - 100 # Remember that we need to put everything from the RHS to the LHS so its = 0
def inequality_constraint(x):
x1 = x[0]
x2 = x[1]
return x1**2 + x2 - 50
# Note: could also make all of these lambda functions
bounds_x1 = (-100, 100)
bounds_x2 = (-100, 100)
# we need to make it into a list
bounds = [bounds_x1, bounds_x2]
# we need to define the equality types
constraint1 = {'type': 'eq', 'fun': equality_constraint}
constraint2 = {'type': 'ineq', 'fun': inequality_constraint}
constraints = [constraint1, constraint2]
# finally, give an initial value for x0. As long as it's reasonable, any pairs of numbers in between the
# bounds should be ok
x0 = [1,1]
# now we apply the minimization function.
# scipy.optimize.minimize(fun, x0, method, bounds, constraints)
result = minimize(objective_fcn, x0, method='SLSQP', bounds=bounds, constraints=constraints)
result
fun: 96.00000027660178 jac: array([50.00000095, 2. ]) message: 'Optimization terminated successfully' nfev: 32 nit: 10 njev: 10 status: 0 success: True x: array([ 1.99999997, 46.00000084])
The result returns: