Pyomo Optimization Modeling Framework

6.10.0 · active · verified Sat Apr 11

Pyomo is an open-source Python-based optimization modeling language that allows users to formulate optimization problems in a high-level, object-oriented fashion. It supports a wide range of problem types including linear, mixed-integer, nonlinear, and generalized disjunctive programming. Pyomo provides interfaces to numerous commercial and open-source solvers. It is currently at version 6.10.0 and sees frequent releases with bug fixes, performance enhancements, and new solver interfaces.

Warnings

Install

Imports

Quickstart

This quickstart defines and solves a simple linear programming problem using Pyomo. It demonstrates the creation of a concrete model, defining variables with bounds, an objective function, and constraints. To run this, you need a compatible solver (e.g., GLPK) installed on your system and accessible via Pyomo's SolverFactory.

import pyomo.environ as pyo

# Create a concrete model
model = pyo.ConcreteModel()

# Define variables
model.x = pyo.Var(bounds=(0, 10), within=pyo.Reals)
model.y = pyo.Var(bounds=(0, 10), within=pyo.Reals)

# Define objective function: Maximize x + y
model.obj = pyo.Objective(expr=model.x + model.y, sense=pyo.maximize)

# Define constraints
model.con1 = pyo.Constraint(expr=2*model.x + model.y <= 15)
model.con2 = pyo.Constraint(expr=model.x + 3*model.y <= 20)

# Solve the model (requires a solver, 'glpk' is a common choice)
# Ensure 'glpk' or another solver is installed and accessible in your system PATH.
# For example, on Ubuntu: 'sudo apt-get install glpk-utils'
# On macOS: 'brew install glpk'
# On Windows: download GLPK binaries and add to PATH.

try:
    solver = pyo.SolverFactory('glpk')
    results = solver.solve(model, tee=False) # tee=True shows solver output

    # Check solver status and print results
    if (results.solver.status == pyo.SolverStatus.ok) and \
       (results.solver.termination_condition == pyo.TerminationCondition.optimal):
        print(f"Optimization successful!")
        print(f"Objective value: {pyo.value(model.obj)}")
        print(f"x = {pyo.value(model.x)}")
        print(f"y = {pyo.value(model.y)}")
    else:
        print(f"Solver did not find an optimal solution. Status: {results.solver.status}, Termination: {results.solver.termination_condition}")
except Exception as e:
    print(f"Error solving model: {e}")
    print("Please ensure a solver like 'glpk' is installed and configured for Pyomo.")

view raw JSON →