The Pyomo optimization modeling framework for formulating, analyzing, and solving mathematical optimization problems
—
Contributed modules providing specialized optimization algorithms, solver interfaces, and modeling capabilities in Pyomo. These extensions offer advanced techniques for complex optimization problems including nonlinear decomposition, sensitivity analysis, robust optimization, and specialized solver interfaces.
Advanced optimization algorithms for complex problem types including mixed-integer nonlinear programming and generalized disjunctive programming.
# GDP Optimization (pyomo.contrib.gdpopt)
class GDPoptSolver:
"""GDP optimization solver with multiple solution strategies."""
def __init__(self, **kwargs): ...
def solve(self, model, **kwargs): ...
# Mixed-Integer Nonlinear Decomposition (pyomo.contrib.mindtpy)
class MindtPySolver:
"""Mixed-integer nonlinear decomposition algorithm."""
def __init__(self, **kwargs): ...
def solve(self, model, **kwargs): ...
# Multi-start Optimization (pyomo.contrib.multistart)
class MultistartSolver:
"""Multi-start optimization for global optimization."""
def __init__(self, **kwargs): ...
def solve(self, model, **kwargs): ...
# Trust Region Methods (pyomo.contrib.trustregion)
class TrustRegionSolver:
"""Trust region optimization methods."""
def __init__(self, **kwargs): ...
def solve(self, model, **kwargs): ...Next-generation solver interfaces with enhanced performance and capabilities.
# Advanced Solver Interface (pyomo.contrib.appsi)
class AppsiSolver:
"""Advanced solver interface with improved performance."""
def __init__(self, solver_name, **kwargs): ...
def solve(self, model, **kwargs): ...
def update_config(self, **kwargs): ...
# New Solver Framework (pyomo.contrib.solver)
class NewSolverInterface:
"""New solver interface framework."""
def __init__(self, **kwargs): ...
def solve(self, model, **kwargs): ...Extended modeling capabilities for specialized problem types and constraint programming.
# Constraint Programming (pyomo.contrib.cp)
class CPModel:
"""Constraint programming model extensions."""
def __init__(self): ...
def AllDifferent(variables):
"""All different constraint for CP."""
def Circuit(variables):
"""Circuit constraint for routing problems."""
# Preprocessing (pyomo.contrib.preprocessing)
class ModelPreprocessor:
"""Model preprocessing and reformulation."""
def __init__(self): ...
def preprocess(self, model): ...
# Expression Simplification (pyomo.contrib.simplification)
def simplify_expression(expr):
"""
Simplify mathematical expressions.
Args:
expr: Expression to simplify
Returns:
Expression: Simplified expression
"""
# Piecewise Linear Modeling (pyomo.contrib.piecewise)
class PiecewiseLinearFunction:
"""Enhanced piecewise linear function modeling."""
def __init__(self, **kwargs): ...Comprehensive analysis tools for model diagnostics, sensitivity analysis, and feasibility analysis.
# Sensitivity Analysis (pyomo.contrib.sensitivity_toolbox)
class SensitivityInterface:
"""Sensitivity analysis interface."""
def __init__(self, model, **kwargs): ...
def get_dsdp(self, variables, parameters):
"""
Get sensitivity of solution w.r.t. parameters.
Args:
variables: Variables of interest
parameters: Parameters for sensitivity
Returns:
dict: Sensitivity matrix
"""
# Incidence Analysis (pyomo.contrib.incidence_analysis)
def get_incidence_matrix(model):
"""
Get constraint-variable incidence matrix.
Args:
model: Pyomo model
Returns:
scipy.sparse matrix: Incidence matrix
"""
def analyze_structural_singularity(model):
"""
Analyze structural singularity of model.
Args:
model: Pyomo model
Returns:
dict: Analysis results
"""
# Feasibility-Based Bounds Tightening (pyomo.contrib.fbbt)
def fbbt(model, **kwargs):
"""
Perform feasibility-based bounds tightening.
Args:
model: Pyomo model to tighten
**kwargs: FBBT options
Returns:
dict: Bounds tightening results
"""
# Community Detection (pyomo.contrib.community_detection)
def detect_communities(model):
"""
Detect communities in model structure.
Args:
model: Pyomo model
Returns:
dict: Community structure
"""Domain-specific applications for parameter estimation, robust optimization, design of experiments, and model predictive control.
# Parameter Estimation (pyomo.contrib.parmest)
class ParameterEstimation:
"""Parameter estimation interface."""
def __init__(self, model_function, data, **kwargs): ...
def theta_est(self, **kwargs):
"""
Estimate parameters.
Returns:
dict: Estimated parameters
"""
def likelihood_ratio_test(self, **kwargs):
"""
Perform likelihood ratio test.
Returns:
dict: Test results
"""
# Robust Optimization (pyomo.contrib.pyros)
class PyROSSolver:
"""Robust optimization solver."""
def __init__(self): ...
def solve(self, model, uncertain_params, **kwargs):
"""
Solve robust optimization problem.
Args:
model: Nominal model
uncertain_params: Uncertain parameters
**kwargs: Solver options
Returns:
Results: Robust solution
"""
# Design of Experiments (pyomo.contrib.doe)
class DesignOfExperiments:
"""Design of experiments interface."""
def __init__(self, model, **kwargs): ...
def compute_FIM(self, **kwargs):
"""
Compute Fisher Information Matrix.
Returns:
numpy.array: FIM matrix
"""
def optimize_design(self, **kwargs):
"""
Optimize experimental design.
Returns:
dict: Optimal design
"""
# Model Predictive Control (pyomo.contrib.mpc)
class ModelPredictiveController:
"""Model predictive control interface."""
def __init__(self, model, **kwargs): ...
def solve_mpc(self, initial_state, **kwargs):
"""
Solve MPC optimization.
Args:
initial_state: Current state
**kwargs: MPC options
Returns:
dict: Control actions
"""Components for modeling network structures and flows in optimization problems including process networks and supply chains.
# Network Components (pyomo.network)
class Arc:
"""Network arc component for connecting ports."""
def __init__(self, *args, **kwargs): ...
class Port:
"""Connection port component for network modeling."""
def __init__(self, *args, **kwargs): ...
class SequentialDecomposition:
"""Sequential decomposition solver for network problems."""
def __init__(self, **kwargs): ...
def solve(self, model, **kwargs): ...Advanced numerical computing interfaces for integration with external numerical libraries.
# PyNumero (pyomo.contrib.pynumero)
class PyNumeroInterface:
"""Interface to advanced numerical methods."""
def __init__(self, model): ...
def get_jacobian(self):
"""Get constraint Jacobian matrix."""
def get_hessian(self):
"""Get Lagrangian Hessian matrix."""
def evaluate_constraints(self, x):
"""Evaluate constraints at point x."""from pyomo.environ import *
from pyomo.gdp import Disjunct, Disjunction
import pyomo.contrib.gdpopt as gdpopt
# Create GDP model
model = ConcreteModel()
model.x = Var(bounds=(0, 10))
model.y = Var(bounds=(0, 10))
# Disjuncts
model.d1 = Disjunct()
model.d1.c1 = Constraint(expr=model.x >= 8)
model.d1.c2 = Constraint(expr=model.y <= 3)
model.d2 = Disjunct()
model.d2.c1 = Constraint(expr=model.x <= 3)
model.d2.c2 = Constraint(expr=model.y >= 8)
model.disjunction = Disjunction(expr=[model.d1, model.d2])
model.obj = Objective(expr=model.x + model.y, sense=minimize)
# Solve with GDPopt
solver = SolverFactory('gdpopt')
results = solver.solve(model, tee=True, strategy='LOA')from pyomo.environ import *
import pyomo.contrib.mindtpy as mindtpy
# Create MINLP model
model = ConcreteModel()
model.x = Var(bounds=(1, 10))
model.y = Var(domain=Binary)
model.obj = Objective(expr=model.x**2 + model.y, sense=minimize)
model.con1 = Constraint(expr=model.x >= 2*model.y)
model.con2 = Constraint(expr=log(model.x) + model.y <= 3)
# Solve with MindtPy
solver = SolverFactory('mindtpy')
results = solver.solve(
model,
strategy='OA', # Outer approximation
mip_solver='cplex',
nlp_solver='ipopt',
tee=True
)from pyomo.environ import *
from pyomo.contrib.sensitivity_toolbox import sensitivity_calculation
# Create model
model = ConcreteModel()
model.x = Var(initialize=1.5)
model.y = Var(initialize=1.5)
model.p1 = Param(initialize=1.0, mutable=True)
model.p2 = Param(initialize=1.0, mutable=True)
model.obj = Objective(expr=model.x**2 + model.y**2)
model.con1 = Constraint(expr=model.x + model.y >= model.p1)
model.con2 = Constraint(expr=model.x - model.y <= model.p2)
# Solve nominal problem
solver = SolverFactory('ipopt')
solver.solve(model)
# Perform sensitivity analysis
m_sens = sensitivity_calculation(model)
sens_results = m_sens.get_dsdp(
variables=[model.x, model.y],
parameters=[model.p1, model.p2]
)
print("Sensitivity matrix:")
print(sens_results)from pyomo.environ import *
import pyomo.contrib.parmest as parmest
import pandas as pd
# Define model function
def model_function(data, theta):
model = ConcreteModel()
model.x = Var(initialize=1)
model.theta1 = Param(initialize=theta['theta1'])
model.theta2 = Param(initialize=theta['theta2'])
# Model equations
model.response = Expression(
expr=model.theta1 * exp(-model.theta2 * data['time'])
)
return model
# Load experimental data
data = pd.DataFrame({
'time': [0, 1, 2, 3, 4, 5],
'response': [10, 7.4, 5.5, 4.1, 3.0, 2.2]
})
# Create parameter estimation object
pest = parmest.Estimator(
model_function,
data,
theta_names=['theta1', 'theta2'],
obj_function='SSE' # Sum of squared errors
)
# Estimate parameters
theta_est = pest.theta_est()
print("Estimated parameters:", theta_est)
# Bootstrap confidence intervals
bootstrap_results = pest.theta_est_bootstrap(100)from pyomo.environ import *
import pyomo.contrib.pyros as pyros
# Create nominal model
model = ConcreteModel()
model.x = Var(bounds=(0, 10))
model.y = Var(bounds=(0, 10))
# Uncertain parameters
model.p1 = Param(initialize=1.0, mutable=True)
model.p2 = Param(initialize=2.0, mutable=True)
model.obj = Objective(expr=model.x + model.y, sense=minimize)
model.con1 = Constraint(expr=model.p1 * model.x + model.p2 * model.y >= 5)
model.con2 = Constraint(expr=model.x - model.y <= 2)
# Define uncertainty set
uncertainty_set = BoxSet(bounds=[(0.8, 1.2), (1.5, 2.5)])
# Solve robust optimization problem
pyros_solver = pyros.PyROSSolver()
results = pyros_solver.solve(
model=model,
first_stage_variables=[model.x, model.y],
second_stage_variables=[],
uncertain_params=[model.p1, model.p2],
uncertainty_set=uncertainty_set,
local_solver=SolverFactory('ipopt'),
global_solver=SolverFactory('baron')
)from pyomo.environ import *
from pyomo.dae import ContinuousSet, DerivativeVar
import pyomo.contrib.mpc as mpc
# Create dynamic model
def create_control_model():
model = ConcreteModel()
model.time = ContinuousSet(bounds=(0, 1))
# State variables
model.x1 = Var(model.time, bounds=(-10, 10))
model.x2 = Var(model.time, bounds=(-10, 10))
# Control variables
model.u = Var(model.time, bounds=(-1, 1))
# Derivatives
model.dx1dt = DerivativeVar(model.x1, wrt=model.time)
model.dx2dt = DerivativeVar(model.x2, wrt=model.time)
# System dynamics
model.ode1 = Constraint(
model.time,
rule=lambda m, t: m.dx1dt[t] == m.x2[t]
)
model.ode2 = Constraint(
model.time,
rule=lambda m, t: m.dx2dt[t] == m.u[t]
)
return model
# Create MPC controller
model_template = create_control_model()
controller = mpc.ModelPredictiveController(
model_template,
sample_time=0.1,
horizon=10
)
# Simulate closed-loop control
current_state = {'x1': 0, 'x2': 0}
setpoint = {'x1': 1, 'x2': 0}
for step in range(50):
# Solve MPC optimization
control_action = controller.solve_mpc(
initial_state=current_state,
setpoint=setpoint
)
# Apply first control action
u_applied = control_action['u'][0]
# Simulate system response (simplified)
current_state['x1'] += current_state['x2'] * 0.1
current_state['x2'] += u_applied * 0.1
print(f"Step {step}: State = {current_state}, Control = {u_applied}")from pyomo.environ import *
import pyomo.contrib.appsi as appsi
# Create model
model = ConcreteModel()
model.x = Var(bounds=(0, 10))
model.y = Var(bounds=(0, 10))
model.obj = Objective(expr=model.x**2 + model.y**2, sense=minimize)
model.con = Constraint(expr=model.x + model.y >= 3)
# Use advanced solver interface
solver = appsi.solvers.Ipopt()
# Configure solver options
solver.config.stream_solver = True
solver.config.load_solution = True
# Add model to solver
solver.set_instance(model)
# Solve
results = solver.solve()
# Update model and resolve
model.con.set_rhs(5) # Change constraint right-hand side
solver.update_config.check_for_new_or_old_constraints = True
results = solver.solve() # Warm start from previous solutionInstall with Tessl CLI
npx tessl i tessl/pypi-pyomo