0
# Optimization Interface
1
2
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.
3
4
## Capabilities
5
6
### Solver Factory
7
8
Factory classes for creating solver instances and managing solver availability with automatic solver detection and configuration.
9
10
```python { .api }
11
SolverFactory: object
12
"""
13
Factory instance for creating solver instances.
14
Usage: SolverFactory('solver_name', **options)
15
16
Args:
17
_name (str, optional): Solver name
18
**kwds: Solver-specific options
19
20
Returns:
21
Solver instance
22
"""
23
24
class SolverManagerFactory:
25
"""Factory for solver managers."""
26
def __call__(self, manager_type, **kwargs): ...
27
28
class UnknownSolver(Exception):
29
"""Exception raised for unknown solver names."""
30
```
31
32
### Solver Results and Status
33
34
Comprehensive result handling with detailed status information, solution data, and termination condition analysis.
35
36
```python { .api }
37
class SolverResults:
38
"""Container for solver results and metadata."""
39
def __init__(self): ...
40
41
@property
42
def solver_status(self): ...
43
44
@property
45
def termination_condition(self): ...
46
47
def write(self, filename=None): ...
48
49
class Solution:
50
"""Solution container for optimization results."""
51
def __init__(self): ...
52
53
def load_from(self, results): ...
54
55
def check_optimal_termination(results):
56
"""
57
Check if solver terminated with optimal solution.
58
59
Args:
60
results (SolverResults): Solver results object
61
62
Returns:
63
bool: True if optimal termination
64
"""
65
66
def assert_optimal_termination(results):
67
"""
68
Assert optimal termination, raise exception if not.
69
70
Args:
71
results (SolverResults): Solver results object
72
73
Raises:
74
RuntimeError: If termination is not optimal
75
"""
76
```
77
78
### Status Enumerations
79
80
Standardized enumerations for solver status, termination conditions, and solution status across different solvers.
81
82
```python { .api }
83
from enum import Enum, IntEnum
84
85
class SolverStatus(Enum):
86
"""Status of solver execution."""
87
ok = 'ok'
88
warning = 'warning'
89
error = 'error'
90
aborted = 'aborted'
91
unknown = 'unknown'
92
93
class TerminationCondition(Enum):
94
"""Solver termination conditions."""
95
unknown = 'unknown'
96
maxTimeLimit = 'maxTimeLimit'
97
maxIterations = 'maxIterations'
98
minFunctionValue = 'minFunctionValue'
99
minStepLength = 'minStepLength'
100
globallyOptimal = 'globallyOptimal'
101
locallyOptimal = 'locallyOptimal'
102
optimal = 'optimal'
103
maxEvaluations = 'maxEvaluations'
104
other = 'other'
105
unbounded = 'unbounded'
106
infeasible = 'infeasible'
107
feasible = 'feasible'
108
infeasibleOrUnbounded = 'infeasibleOrUnbounded'
109
intermediateNonInteger = 'intermediateNonInteger'
110
noSolution = 'noSolution'
111
invalidProblem = 'invalidProblem'
112
solverFailure = 'solverFailure'
113
internalSolverError = 'internalSolverError'
114
error = 'error'
115
userInterrupt = 'userInterrupt'
116
resourceInterrupt = 'resourceInterrupt'
117
licensingProblems = 'licensingProblems'
118
119
class ProblemSense(IntEnum):
120
"""Problem optimization sense (extends IntEnum)."""
121
unknown = 0
122
minimize = 1
123
maximize = -1
124
125
class SolutionStatus(Enum):
126
"""Solution status enumeration."""
127
optimal = 'optimal'
128
feasible = 'feasible'
129
infeasible = 'infeasible'
130
unbounded = 'unbounded'
131
unsure = 'unsure'
132
error = 'error'
133
unknown = 'unknown'
134
bestSoFar = 'bestSoFar'
135
globallyOptimal = 'globallyOptimal'
136
locallyOptimal = 'locallyOptimal'
137
other = 'other'
138
stoppedByLimit = 'stoppedByLimit'
139
```
140
141
### Problem Format Conversion
142
143
Utilities for converting between different problem formats and interfacing with various solver file formats.
144
145
```python { .api }
146
from enum import Enum
147
148
class ProblemFormat(Enum):
149
"""Supported problem file formats."""
150
nl = 'nl'
151
cpxlp = 'cpxlp'
152
mps = 'mps'
153
osil = 'osil'
154
python = 'python'
155
pyomo = 'pyomo'
156
mod = 'mod'
157
lpxlp = 'lpxlp'
158
bar = 'bar'
159
gams = 'gams'
160
161
class ResultsFormat(Enum):
162
"""Supported results file formats."""
163
sol = 'sol'
164
osrl = 'osrl'
165
results = 'results'
166
json = 'json'
167
soln = 'soln'
168
yaml = 'yaml'
169
170
def convert_problem(
171
args,
172
problem_format,
173
valid_problem_types,
174
**kwargs
175
):
176
"""
177
Convert problem to specified format.
178
179
Args:
180
args: Problem arguments
181
problem_format: Target format
182
valid_problem_types: Valid problem types
183
**kwargs: Additional conversion options
184
185
Returns:
186
Converted problem representation
187
"""
188
189
def check_available_solvers():
190
"""
191
Check which solvers are available on the system.
192
193
Returns:
194
dict: Dictionary of available solvers and their status
195
"""
196
197
def guess_format(filename):
198
"""
199
Guess problem format from filename.
200
201
Args:
202
filename (str): Problem filename
203
204
Returns:
205
str: Guessed format name
206
"""
207
```
208
209
### I/O Factories
210
211
Factory classes for problem readers and writers with support for multiple file formats and solver-specific I/O operations.
212
213
```python { .api }
214
class ReaderFactory:
215
"""Factory for problem readers."""
216
def __call__(self, format, **kwargs): ...
217
218
class WriterFactory:
219
"""Factory for problem writers."""
220
def __call__(self, format, **kwargs): ...
221
222
class AbstractProblemWriter:
223
"""Abstract base class for problem writers."""
224
def __init__(self): ...
225
def write(self, model, filename, **kwargs): ...
226
227
class AbstractResultsReader:
228
"""Abstract base class for results readers."""
229
def __init__(self): ...
230
def read(self, filename, **kwargs): ...
231
```
232
233
### Solver Management
234
235
Advanced solver management including asynchronous solving and solver configuration options.
236
237
```python { .api }
238
class OptSolver:
239
"""Base optimization solver class."""
240
def __init__(self, **kwargs): ...
241
242
def solve(self, model, **kwargs):
243
"""
244
Solve optimization model.
245
246
Args:
247
model: Pyomo model to solve
248
**kwargs: Solver options
249
250
Returns:
251
SolverResults: Solver results object
252
"""
253
254
def available(self):
255
"""Check if solver is available."""
256
257
def set_options(self, **kwargs):
258
"""Set solver options."""
259
260
class AsynchronousSolverManager:
261
"""Manager for asynchronous solver execution."""
262
def __init__(self, **kwargs): ...
263
264
def queue(self, model, **kwargs):
265
"""Queue model for solving."""
266
267
def wait_for(self, action_handle):
268
"""Wait for specific solve to complete."""
269
270
def wait_any(self):
271
"""Wait for any queued solve to complete."""
272
273
def wait_all(self):
274
"""Wait for all queued solves to complete."""
275
```
276
277
## Usage Examples
278
279
### Basic Solver Usage
280
281
```python
282
from pyomo.environ import *
283
284
# Create and solve model
285
model = ConcreteModel()
286
model.x = Var(domain=NonNegativeReals)
287
model.y = Var(domain=NonNegativeReals)
288
model.obj = Objective(expr=model.x + model.y, sense=minimize)
289
model.con = Constraint(expr=model.x + 2*model.y >= 3)
290
291
# Create solver and solve
292
solver = SolverFactory('glpk')
293
results = solver.solve(model)
294
295
# Check results
296
if check_optimal_termination(results):
297
print(f"Optimal solution found:")
298
print(f"x = {value(model.x)}")
299
print(f"y = {value(model.y)}")
300
print(f"Objective = {value(model.obj)}")
301
else:
302
print(f"Solver status: {results.solver.status}")
303
print(f"Termination: {results.solver.termination_condition}")
304
```
305
306
### Solver Options and Configuration
307
308
```python
309
from pyomo.environ import *
310
311
model = ConcreteModel()
312
# ... define model ...
313
314
# Create solver with options
315
solver = SolverFactory('ipopt')
316
solver.options['max_iter'] = 1000
317
solver.options['tol'] = 1e-8
318
solver.options['print_level'] = 5
319
320
# Alternative: pass options to solve
321
results = solver.solve(
322
model,
323
options={'max_iter': 1000, 'tol': 1e-8},
324
tee=True # Show solver output
325
)
326
327
# Check specific termination conditions
328
if results.solver.termination_condition == TerminationCondition.optimal:
329
print("Global optimum found")
330
elif results.solver.termination_condition == TerminationCondition.locallyOptimal:
331
print("Local optimum found")
332
elif results.solver.termination_condition == TerminationCondition.maxTimeLimit:
333
print("Time limit reached")
334
```
335
336
### Problem Format Conversion
337
338
```python
339
from pyomo.environ import *
340
from pyomo.opt import convert_problem
341
342
model = ConcreteModel()
343
# ... define model ...
344
345
# Convert to different formats
346
convert_problem(
347
(model,),
348
ProblemFormat.lp,
349
[ConcreteModel]
350
)
351
352
# Write model to file
353
model.write('problem.lp', format='lp')
354
model.write('problem.nl', format='nl')
355
```
356
357
### Asynchronous Solving
358
359
```python
360
from pyomo.environ import *
361
from pyomo.opt import SolverManagerFactory
362
363
models = [create_model(i) for i in range(10)] # Create multiple models
364
365
# Create asynchronous solver manager
366
manager = SolverManagerFactory('serial')
367
368
# Queue all models for solving
369
action_handles = []
370
for model in models:
371
handle = manager.queue(model, opt=SolverFactory('glpk'))
372
action_handles.append(handle)
373
374
# Wait for all to complete
375
results = manager.wait_all()
376
377
# Process results
378
for i, result in enumerate(results):
379
if check_optimal_termination(result):
380
print(f"Model {i}: Optimal solution found")
381
else:
382
print(f"Model {i}: {result.solver.termination_condition}")
383
```