#!/usr/bin/env python # coding: utf-8 # In[1]: 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} # $$ # In[2]: # 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) # In[3]: result # The result returns: # * fun = values of objective function # * jac = jacobian # * message = description of the cause of the termination # * nfev, njev = No. of evaluations of the objective functions and of its Jacobian # * nit = NO. of iterations # * status, success = Termination and exit status # * x = Solution of the optimization # In[ ]: