CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyomo

The Pyomo optimization modeling framework for formulating, analyzing, and solving mathematical optimization problems

Pending
Overview
Eval results
Files

optimization-interface.mddocs/

Optimization Interface

Solver factories, result handling, and optimization problem management in Pyomo. Provides standardized interface to dozens of optimization solvers with comprehensive result analysis capabilities and problem format conversion.

Capabilities

Solver Factory

Factory classes for creating solver instances and managing solver availability with automatic solver detection and configuration.

SolverFactory: object
    """
    Factory instance for creating solver instances.
    Usage: SolverFactory('solver_name', **options)
    
    Args:
        _name (str, optional): Solver name
        **kwds: Solver-specific options
        
    Returns:
        Solver instance
    """

class SolverManagerFactory:
    """Factory for solver managers."""
    def __call__(self, manager_type, **kwargs): ...

class UnknownSolver(Exception):
    """Exception raised for unknown solver names."""

Solver Results and Status

Comprehensive result handling with detailed status information, solution data, and termination condition analysis.

class SolverResults:
    """Container for solver results and metadata."""
    def __init__(self): ...
    
    @property
    def solver_status(self): ...
    
    @property
    def termination_condition(self): ...
    
    def write(self, filename=None): ...

class Solution:
    """Solution container for optimization results."""
    def __init__(self): ...
    
    def load_from(self, results): ...

def check_optimal_termination(results):
    """
    Check if solver terminated with optimal solution.
    
    Args:
        results (SolverResults): Solver results object
        
    Returns:
        bool: True if optimal termination
    """

def assert_optimal_termination(results):
    """
    Assert optimal termination, raise exception if not.
    
    Args:
        results (SolverResults): Solver results object
        
    Raises:
        RuntimeError: If termination is not optimal
    """

Status Enumerations

Standardized enumerations for solver status, termination conditions, and solution status across different solvers.

from enum import Enum, IntEnum

class SolverStatus(Enum):
    """Status of solver execution."""
    ok = 'ok'
    warning = 'warning'
    error = 'error'
    aborted = 'aborted'
    unknown = 'unknown'

class TerminationCondition(Enum):
    """Solver termination conditions."""
    unknown = 'unknown'
    maxTimeLimit = 'maxTimeLimit'
    maxIterations = 'maxIterations'
    minFunctionValue = 'minFunctionValue'
    minStepLength = 'minStepLength'
    globallyOptimal = 'globallyOptimal'
    locallyOptimal = 'locallyOptimal'
    optimal = 'optimal'
    maxEvaluations = 'maxEvaluations'
    other = 'other'
    unbounded = 'unbounded'
    infeasible = 'infeasible'
    feasible = 'feasible'
    infeasibleOrUnbounded = 'infeasibleOrUnbounded'
    intermediateNonInteger = 'intermediateNonInteger'
    noSolution = 'noSolution'
    invalidProblem = 'invalidProblem'
    solverFailure = 'solverFailure'
    internalSolverError = 'internalSolverError'
    error = 'error'
    userInterrupt = 'userInterrupt'
    resourceInterrupt = 'resourceInterrupt'
    licensingProblems = 'licensingProblems'

class ProblemSense(IntEnum):
    """Problem optimization sense (extends IntEnum)."""
    unknown = 0
    minimize = 1
    maximize = -1

class SolutionStatus(Enum):
    """Solution status enumeration."""
    optimal = 'optimal'
    feasible = 'feasible'
    infeasible = 'infeasible'
    unbounded = 'unbounded'
    unsure = 'unsure'
    error = 'error'
    unknown = 'unknown'
    bestSoFar = 'bestSoFar'
    globallyOptimal = 'globallyOptimal'
    locallyOptimal = 'locallyOptimal'
    other = 'other'
    stoppedByLimit = 'stoppedByLimit'

Problem Format Conversion

Utilities for converting between different problem formats and interfacing with various solver file formats.

from enum import Enum

class ProblemFormat(Enum):
    """Supported problem file formats."""
    nl = 'nl'
    cpxlp = 'cpxlp'
    mps = 'mps'
    osil = 'osil' 
    python = 'python'
    pyomo = 'pyomo'
    mod = 'mod'
    lpxlp = 'lpxlp'
    bar = 'bar'
    gams = 'gams'

class ResultsFormat(Enum):
    """Supported results file formats."""
    sol = 'sol'
    osrl = 'osrl'
    results = 'results'
    json = 'json'
    soln = 'soln'
    yaml = 'yaml'

def convert_problem(
    args, 
    problem_format, 
    valid_problem_types,
    **kwargs
):
    """
    Convert problem to specified format.
    
    Args:
        args: Problem arguments
        problem_format: Target format
        valid_problem_types: Valid problem types
        **kwargs: Additional conversion options
        
    Returns:
        Converted problem representation
    """

def check_available_solvers():
    """
    Check which solvers are available on the system.
    
    Returns:
        dict: Dictionary of available solvers and their status
    """

def guess_format(filename):
    """
    Guess problem format from filename.
    
    Args:
        filename (str): Problem filename
        
    Returns:
        str: Guessed format name
    """

I/O Factories

Factory classes for problem readers and writers with support for multiple file formats and solver-specific I/O operations.

class ReaderFactory:
    """Factory for problem readers."""
    def __call__(self, format, **kwargs): ...

class WriterFactory:
    """Factory for problem writers.""" 
    def __call__(self, format, **kwargs): ...

class AbstractProblemWriter:
    """Abstract base class for problem writers."""
    def __init__(self): ...
    def write(self, model, filename, **kwargs): ...

class AbstractResultsReader:
    """Abstract base class for results readers."""
    def __init__(self): ...
    def read(self, filename, **kwargs): ...

Solver Management

Advanced solver management including asynchronous solving and solver configuration options.

class OptSolver:
    """Base optimization solver class."""
    def __init__(self, **kwargs): ...
    
    def solve(self, model, **kwargs):
        """
        Solve optimization model.
        
        Args:
            model: Pyomo model to solve
            **kwargs: Solver options
            
        Returns:
            SolverResults: Solver results object
        """
    
    def available(self):
        """Check if solver is available."""
    
    def set_options(self, **kwargs):
        """Set solver options."""

class AsynchronousSolverManager:
    """Manager for asynchronous solver execution."""
    def __init__(self, **kwargs): ...
    
    def queue(self, model, **kwargs):
        """Queue model for solving."""
    
    def wait_for(self, action_handle):
        """Wait for specific solve to complete."""
    
    def wait_any(self):
        """Wait for any queued solve to complete."""
    
    def wait_all(self):
        """Wait for all queued solves to complete."""

Usage Examples

Basic Solver Usage

from pyomo.environ import *

# Create and solve model
model = ConcreteModel()
model.x = Var(domain=NonNegativeReals)
model.y = Var(domain=NonNegativeReals)
model.obj = Objective(expr=model.x + model.y, sense=minimize)
model.con = Constraint(expr=model.x + 2*model.y >= 3)

# Create solver and solve
solver = SolverFactory('glpk')
results = solver.solve(model)

# Check results
if check_optimal_termination(results):
    print(f"Optimal solution found:")
    print(f"x = {value(model.x)}")
    print(f"y = {value(model.y)}")
    print(f"Objective = {value(model.obj)}")
else:
    print(f"Solver status: {results.solver.status}")
    print(f"Termination: {results.solver.termination_condition}")

Solver Options and Configuration

from pyomo.environ import *

model = ConcreteModel()
# ... define model ...

# Create solver with options
solver = SolverFactory('ipopt')
solver.options['max_iter'] = 1000
solver.options['tol'] = 1e-8
solver.options['print_level'] = 5

# Alternative: pass options to solve
results = solver.solve(
    model, 
    options={'max_iter': 1000, 'tol': 1e-8},
    tee=True  # Show solver output
)

# Check specific termination conditions
if results.solver.termination_condition == TerminationCondition.optimal:
    print("Global optimum found")
elif results.solver.termination_condition == TerminationCondition.locallyOptimal:
    print("Local optimum found") 
elif results.solver.termination_condition == TerminationCondition.maxTimeLimit:
    print("Time limit reached")

Problem Format Conversion

from pyomo.environ import *
from pyomo.opt import convert_problem

model = ConcreteModel()
# ... define model ...

# Convert to different formats
convert_problem(
    (model,), 
    ProblemFormat.lp, 
    [ConcreteModel]
)

# Write model to file
model.write('problem.lp', format='lp')
model.write('problem.nl', format='nl')

Asynchronous Solving

from pyomo.environ import *
from pyomo.opt import SolverManagerFactory

models = [create_model(i) for i in range(10)]  # Create multiple models

# Create asynchronous solver manager
manager = SolverManagerFactory('serial')

# Queue all models for solving
action_handles = []
for model in models:
    handle = manager.queue(model, opt=SolverFactory('glpk'))
    action_handles.append(handle)

# Wait for all to complete
results = manager.wait_all()

# Process results
for i, result in enumerate(results):
    if check_optimal_termination(result):
        print(f"Model {i}: Optimal solution found")
    else:
        print(f"Model {i}: {result.solver.termination_condition}")

Install with Tessl CLI

npx tessl i tessl/pypi-pyomo

docs

advanced-extensions.md

core-modeling.md

dae.md

data-management.md

domain-sets.md

gdp.md

index.md

mathematical-functions.md

mpec.md

optimization-interface.md

tile.json