Constraints

import numpy as np from scipy.optimize import minimize # 1. Objective: Minimize f(x, y) = x^2 + y^2 def objective(pt): x, y = pt return x**2 + y**2 # 2. Variable Bounds: x must be between 1 and 5; y must be between 2 and 5 # Format: (min, max) for each variable variable_bounds = [(1, 5), (2, 5)] # 3. Constraints: linking variables together # SciPy expects constraints to be written so they equal zero, or are greater/equal to zero (>= 0). # Example: We want x + y to be at least 4 -> (x + y) - 4 >= 0 def constraint_equation(pt): x, y = pt return (x + y) - 4 constraints_list = [ {'type': 'ineq', 'fun': constraint_equation} # 'ineq' means: fun(x) >= 0 ] # 4. Execution with an Iteration Cap search_options = { 'maxiter': 100, # Cap at 100 iterations 'disp': True # Show the termination message } result = minimize( objective, x0=[0.0, 0.0], # Starting guess method='SLSQP', # Premier constrained solver bounds=variable_bounds, constraints=constraints_list, options=search_options ) print(f"Optimal solution found: {result.x}")