SkilVaultSign inStart free

Catalogue / python-optimization

python-optimization

MITSignedExpert guidance for mathematical optimization in Python - systematic problem classification, library selection (scipy, pyomo, cvxpy, GEKKO), solver configuration, and implementation patterns for LP, QP, NLP, MIP, convex, and global optimization problems
---
name: python-optimization
description: Expert guidance for mathematical optimization in Python - systematic problem classification, library selection (scipy, pyomo, cvxpy, GEKKO), solver configuration, and implementation patterns for LP, QP, NLP, MIP, convex, and global optimization problems
allowed-tools: ["*"]
---

Python Optimization Expert

Overview

Master mathematical optimization in Python through systematic problem analysis, appropriate library selection, and robust implementation. This skill guides you through classifying optimization problems, choosing the right solver, implementing efficient solutions, and troubleshooting convergence issues across linear programming, nonlinear programming, mixed-integer problems, and global optimization.

Core value: Transform optimization problems from mathematical formulation to working Python code with the most appropriate library and solver for your specific problem type.

When to Use

Use this skill when:

  • Minimizing or maximizing objective functions
  • Parameter estimation and curve fitting
  • Portfolio optimization and resource allocation
  • Production planning and scheduling
  • Engineering design optimization
  • Control and dynamic optimization
  • Solving constrained or unconstrained optimization problems
  • Choosing between scipy, pyomo, cvxpy, or other optimization libraries

Don't use when:

  • Simple root finding (use scipy.optimize.root instead)
  • Linear algebra only (use numpy/scipy.linalg)
  • Symbolic mathematics needed (use sympy)

Problem Analysis Framework

Step 1: Extract Problem Components

Always identify:

  1. Objective function: What to minimize or maximize?
  • Example: minimize cost, maximize profit, minimize error
  1. Decision variables: What can be changed?
  • Continuous (real numbers) or discrete (integers)?
  • How many variables?
  1. Constraints: What restrictions exist?
  • Equality constraints: h(x) = 0
  • Inequality constraints: g(x) ≥ 0
  • Bounds: lower ≤ x ≤ upper
  1. Data/parameters: What values are given?
  • Constants, measurements, input data

Step 2: Classify Problem Type

Linear Programming (LP)

  • Linear objective function
  • Linear constraints only
  • Example: max c'x subject to Ax ≤ b

Quadratic Programming (QP)

  • Quadratic objective function
  • Linear constraints
  • Example: min (1/2)x'Qx + c'x subject to Ax ≤ b

Nonlinear Programming (NLP)

  • Nonlinear objective or constraints
  • Smooth, differentiable functions
  • Example: min f(x) subject to g(x) ≥ 0

Mixed-Integer Programming (MIP/MILP/MINLP)

  • Some or all variables must be integers
  • Combinatorial optimization
  • Example: scheduling, assignment problems

Convex Optimization

  • Convex objective function
  • Convex feasible region
  • Global optimum guaranteed

Global Optimization

  • Multiple local minima suspected
  • Non-convex problems
  • Requires global search strategies

Least Squares

  • Minimize sum of squared residuals
  • Parameter estimation, curve fitting
  • Special structure exploited by dedicated solvers

Dynamic Optimization / Optimal Control

  • Time-dependent variables
  • Differential equations as constraints
  • Trajectory optimization

Step 3: Characterize Problem Scale

Small problems: < 100 variables

  • Most methods work well
  • scipy.optimize is sufficient

Medium problems: 100-1,000 variables

  • Need efficient algorithms
  • Consider specialized solvers

Large problems: > 1,000 variables

  • Requires sparse matrix techniques
  • Use pyomo or specialized solvers
  • Exploit problem structure

Other characteristics:

  • Are derivatives available? Analytical or numerical?
  • Smooth or non-smooth?
  • Sparse or dense?
  • Special structure (separable, etc.)?

Library Selection Guide

scipy.optimize - Default Choice

Use when:

  • Small to medium problems (<1,000 variables)
  • Unconstrained or smooth constrained NLP
  • Quick prototyping and development
  • Least squares / curve fitting
  • Python-native solution preferred

Strengths:

  • Part of scipy (widely available)
  • Easy to use, good documentation
  • Multiple algorithms available
  • No additional dependencies

Limitations:

  • Not ideal for large-scale problems
  • Limited support for mixed-integer
  • Less sophisticated than commercial solvers

pyomo - Algebraic Modeling

Use when:

  • Large-scale problems (>1,000 variables)
  • Mixed-integer programming
  • Need multiple solver backends
  • Algebraic modeling preferred
  • Production environments

Strengths:

  • Scales to very large problems
  • Supports many external solvers
  • Clean mathematical notation
  • Active development and community

Limitations:

  • Requires external solvers for many problem types
  • Steeper learning curve
  • Additional installation complexity

cvxpy - Convex Optimization

Use when:

  • Problem is (or might be) convex
  • Want automatic convexity verification
  • Prefer disciplined convex programming
  • Portfolio optimization, control

Strengths:

  • Automatic convexity detection
  • Mathematical notation syntax
  • Multiple solver backends
  • Excellent for convex problems

Limitations:

  • Only for convex problems
  • Less flexible for non-convex
  • Learning curve for DCP rules

GEKKO - Dynamic Optimization

Use when:

  • Black-box functions (no derivatives)
  • Dynamic optimization / optimal control
  • Differential equations involved
  • Process control, trajectory optimization

Strengths:

  • Handles differential equations naturally
  • Derivative-free optimization
  • Good for dynamic systems
  • Time-dependent problems

Limitations:

  • Specialized use case
  • Less common than scipy
  • Requires GEKKO server

Comparison Table

| Library | Best For | Problem Types | Scale | |---------|----------|---------------|-------| | scipy.optimize | General NLP, prototyping | LP, QP, NLP, LS | Small-Medium | | pyomo | Large-scale, MIP | LP, MILP, NLP, MINLP | Any | | cvxpy | Convex problems | LP, QP, SOCP, SDP | Medium-Large | | GEKKO | Dynamic optimization | NLP, DAE, MPC | Small-Medium |

scipy.optimize - Method Selection

Unconstrained Optimization

`minimize(f, x0, method='BFGS', jac=gradient)`

  • Use for: Smooth unconstrained problems
  • Requires: Gradient (or uses finite differences)
  • Pros: Fast convergence, robust
  • Cons: Can get stuck in local minima

`minimize(f, x0, method='L-BFGS-B', bounds=bounds)`

  • Use for: Large-scale with box constraints
  • Pros: Memory efficient, handles bounds
  • Cons: Only box constraints (no general constraints)

`minimize(f, x0, method='Nelder-Mead')`

  • Use for: Derivative-free, non-smooth
  • Pros: No derivatives needed
  • Cons: Slow convergence, unreliable for large problems

`minimize(f, x0, method='Powell')`

  • Use for: Derivative-free, better than Nelder-Mead
  • Pros: More robust than Nelder-Mead
  • Cons: Still derivative-free (slower)

Constrained Optimization

`minimize(f, x0, method='SLSQP', constraints=cons)`

  • Use for: General constraints (equality + inequality)
  • Pros: Handles all constraint types
  • Cons: Less robust than trust-constr

`minimize(f, x0, method='trust-constr', constraints=cons)`

  • Use for: Difficult constrained problems
  • Pros: Most robust, can use Hessian
  • Cons: Slower than SLSQP

`minimize(f, x0, method='COBYLA', constraints=cons)`

  • Use for: Derivative-free with constraints
  • Pros: No derivatives needed
  • Cons: Slow, less accurate

Special-Purpose Functions

`least_squares(residual, x0, bounds=bounds)`

  • Use for: Nonlinear least squares
  • Pros: Exploits sum-of-squares structure
  • Cons: Only for least squares problems

`curve_fit(model, xdata, ydata, p0=initial)`

  • Use for: Parameter estimation, curve fitting
  • Pros: Simple interface for fitting
  • Cons: Just a wrapper for least_squares

`differential_evolution(f, bounds)`

  • Use for: Global optimization, multiple local minima
  • Pros: Finds global optimum, derivative-free
  • Cons: Slow, must specify bounds

`linprog(c, A_ub, b_ub)`

  • Use for: Linear programming only
  • Pros: Specialized for LP, efficient
  • Cons: Only linear problems

Implementation Patterns

Pattern 1: Unconstrained Optimization

from scipy.optimize import minimize
import numpy as np

def objective(x):
    """
    Objective function to minimize.

    Example: Rosenbrock function
    f(x) = sum((1 - x[i])^2 + 100*(x[i+1] - x[i]^2)^2)
    """
    return sum((1 - x[:-1])**2 + 100*(x[1:] - x[:-1]**2)**2)

def gradient(x):
    """
    Analytical gradient - ALWAYS provide if possible!
    Dramatically improves convergence speed and reliability.
    """
    grad = np.zeros_like(x)
    grad[:-1] = -2*(1 - x[:-1]) - 400*x[:-1]*(x[1:] - x[:-1]**2)
    grad[1:] += 200*(x[1:] - x[:-1]**2)
    return grad

# Initial guess
x0 = np.array([0.5, 0.5])

# Optimize
result = minimize(objective, x0, method='BFGS', jac=gradient)

# Check results
print(f"Success: {result.success}")
print(f"Message: {result.message}")
print(f"Optimal x: {result.x}")
print(f"Optimal value: {result.fun}")
print(f"Iterations: {result.nit}")
print(f"Function evaluations: {result.nfev}")

Pattern 2: Constrained Optimization

from scipy.optimize import minimize
import numpy as np

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

def constraint_ineq(x):
    """Inequality constraint: x[0] + x[1] - 1 >= 0"""
    return x[0] + x[1] - 1

def constraint_eq(x):
    """Equality constraint: x[0]^2 + x[1]^2 - 1 = 0"""
    return x[0]**2 + x[1]**2 - 1

# Define constraints (can have multiple)
constraints = [
    {'type': 'ineq', 'fun': constraint_ineq},  # g(x) >= 0
    {'type': 'eq', 'fun': constraint_eq}       # h(x) = 0
]

# Bounds: [(lower, upper), ...], use None for no bound
bounds = [(-2, 2), (-2, 2)]

# Initial guess (should be feasible if possible)
x0 = np.array([0.5, 0.5])

# Optimize
result = minimize(
    objective,
    x0,
    method='SLSQP',
    constraints=constraints,
    bounds=bounds,
    options={'ftol': 1e-9, 'maxiter': 1000}
)

print(f"Optimal x: {result.x}")
print(f"Optimal value: {result.fun}")

# Verify constraints are satisfied
print(f"\nConstraint verification:")
print(f"Inequality (should be >= 0): {constraint_ineq(result.x):.6f}")
print(f"Equality (should be ~0): {constraint_eq(result.x):.6e}")

Pattern 3: Parameter Estimation (Curve Fitting)

from scipy.optimize import curve_fit
import numpy as np

def model(x, a, b, c):
    """
    Model function: f(x; parameters)

    Example: Exponential decay + offset
    """
    return a * np.exp(-b * x) + c

# Generate synthetic data (in practice, this is your measured data)
x_data = np.linspace(0, 10, 50)
y_true = 2.5 * np.exp(-0.3 * x_data) + 0.5
y_data = y_true + 0.1 * np.random.randn(len(x_data))  # Add noise

# Fit model to data
# p0 = initial parameter guess (optional but recommended)
params, covariance = curve_fit(
    model,
    x_data,
    y_data,
    p0=[2, 0.5, 0]  # Initial guess: [a, b, c]
)

# Extract parameters and uncertainties
a_opt, b_opt, c_opt = params
uncertainties = np.sqrt(np.diag(covariance))

print(f"Optimal parameters:")
print(f"  a = {a_opt:.3f} ± {uncertainties[0]:.3f}")
print(f"  b = {b_opt:.3f} ± {uncertainties[1]:.3f}")
print(f"  c = {c_opt:.3f} ± {uncertainties[2]:.3f}")

# Calculate R-squared
y_pred = model(x_data, *params)
ss_res = np.sum((y_data - y_pred)**2)
ss_tot = np.sum((y_data - np.mean(y_data))**2)
r_squared = 1 - (ss_res / ss_tot)
print(f"\nR² = {r_squared:.4f}")

Pattern 4: Least Squares (Residuals)

from scipy.optimize import least_squares
import numpy as np

def residuals(params, x, y):
    """
    Residual function for least squares.

    Returns: array of residuals (model - data)
    """
    a, b, c = params
    model = a * np.exp(-b * x) + c
    return model - y

# Data
x_data = np.linspace(0, 10, 50)

Preview shortened. The full SKILL.md is in the pack.