0
0
SciPydata~5 mins

Nonlinear constraint optimization in SciPy

Choose your learning style9 modes available
Introduction

We use nonlinear constraint optimization to find the best solution when the problem has limits that are not straight lines. It helps us solve real problems with complex rules.

Planning the best route for delivery trucks with speed and road limits
Finding the best mix of ingredients in a recipe with taste and nutrition rules
Designing a product that must meet safety and size limits
Allocating budget to projects with minimum and maximum spending rules
Syntax
SciPy
from scipy.optimize import minimize

result = minimize(
    fun,               # The function to minimize
    x0,                # Starting guess for variables
    constraints=[      # List of constraints
        {'type': 'eq', 'fun': constraint_eq},   # Equality constraint
        {'type': 'ineq', 'fun': constraint_ineq} # Inequality constraint
    ],
    method='SLSQP'     # Optimization method that handles constraints
)

fun is the function you want to minimize.

Constraints can be equality (must be zero) or inequality (must be ≥ 0).

Examples
Minimize the sum of squares with the rule that x + y = 1.
SciPy
def fun(x):
    return x[0]**2 + x[1]**2

def constraint_eq(x):
    return x[0] + x[1] - 1

result = minimize(fun, [0, 0], constraints=[{'type': 'eq', 'fun': constraint_eq}], method='SLSQP')
Minimize distance to point (1, 2.5) with the rule x - 2y + 2 ≥ 0.
SciPy
def fun(x):
    return (x[0]-1)**2 + (x[1]-2.5)**2

def constraint_ineq(x):
    return x[0] - 2*x[1] + 2

result = minimize(fun, [2, 0], constraints=[{'type': 'ineq', 'fun': constraint_ineq}], method='SLSQP')
Sample Program

This code finds the point (x, y) closest to the origin (0,0) that satisfies two rules: x + y = 1 and x - y ≥ 1.

SciPy
from scipy.optimize import minimize

# Objective function: minimize x^2 + y^2
def objective(x):
    return x[0]**2 + x[1]**2

# Equality constraint: x + y = 1
def eq_constraint(x):
    return x[0] + x[1] - 1

# Inequality constraint: x - y >= 1  (rewritten as x - y - 1 >= 0)
def ineq_constraint(x):
    return x[0] - x[1] - 1

constraints = [
    {'type': 'eq', 'fun': eq_constraint},
    {'type': 'ineq', 'fun': ineq_constraint}
]

# Starting guess
x0 = [0, 0]

result = minimize(objective, x0, constraints=constraints, method='SLSQP')

print('Optimal solution:', result.x)
print('Objective value:', result.fun)
OutputSuccess
Important Notes

The method 'SLSQP' is good for problems with nonlinear constraints.

Always provide a reasonable starting guess to help the solver find the best answer.

Constraints functions must return zero for equality and non-negative for inequality.

Summary

Nonlinear constraint optimization finds the best solution with complex rules.

Use scipy.optimize.minimize with constraints and method 'SLSQP'.

Define your objective and constraint functions clearly for the solver.