Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standardize the usage of pyomo.environ imports #3545

Merged
merged 4 commits into from
Mar 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 40 additions & 40 deletions doc/OnlineDocs/explanation/solvers/persistent.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ Using Persistent Solvers
The first step in using a persistent solver is to create a Pyomo model
as usual.

>>> import pyomo.environ as pe
>>> m = pe.ConcreteModel()
>>> m.x = pe.Var()
>>> m.y = pe.Var()
>>> m.obj = pe.Objective(expr=m.x**2 + m.y**2)
>>> m.c = pe.Constraint(expr=m.y >= -2*m.x + 5)
>>> import pyomo.environ as pyo
>>> m = pyo.ConcreteModel()
>>> m.x = pyo.Var()
>>> m.y = pyo.Var()
>>> m.obj = pyo.Objective(expr=m.x**2 + m.y**2)
>>> m.c = pyo.Constraint(expr=m.y >= -2*m.x + 5)

You can create an instance of a persistent solver through the SolverFactory.

>>> opt = pe.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> opt = pyo.SolverFactory('gurobi_persistent') # doctest: +SKIP

This returns an instance of :py:class:`GurobiPersistent`. Now we need
to tell the solver about our model.
Expand All @@ -48,7 +48,7 @@ variables and constraints. We can now solve the model.
We can also add or remove variables, constraints, blocks, and
objectives. For example,

>>> m.c2 = pe.Constraint(expr=m.y >= m.x) # doctest: +SKIP
>>> m.c2 = pyo.Constraint(expr=m.y >= m.x) # doctest: +SKIP
>>> opt.add_constraint(m.c2) # doctest: +SKIP

This tells the solver to add one new constraint but otherwise leave
Expand All @@ -69,29 +69,29 @@ code will run without error, but the solver will have an extra
constraint. The solver will have both y >= -2*x + 5 and y <= x, which
is not what was intended!

>>> m = pe.ConcreteModel() # doctest: +SKIP
>>> m.x = pe.Var() # doctest: +SKIP
>>> m.y = pe.Var() # doctest: +SKIP
>>> m.c = pe.Constraint(expr=m.y >= -2*m.x + 5) # doctest: +SKIP
>>> opt = pe.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> m = pyo.ConcreteModel() # doctest: +SKIP
>>> m.x = pyo.Var() # doctest: +SKIP
>>> m.y = pyo.Var() # doctest: +SKIP
>>> m.c = pyo.Constraint(expr=m.y >= -2*m.x + 5) # doctest: +SKIP
>>> opt = pyo.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> opt.set_instance(m) # doctest: +SKIP
>>> # WRONG:
>>> del m.c # doctest: +SKIP
>>> m.c = pe.Constraint(expr=m.y <= m.x) # doctest: +SKIP
>>> m.c = pyo.Constraint(expr=m.y <= m.x) # doctest: +SKIP
>>> opt.add_constraint(m.c) # doctest: +SKIP

The correct way to do this is:

>>> m = pe.ConcreteModel() # doctest: +SKIP
>>> m.x = pe.Var() # doctest: +SKIP
>>> m.y = pe.Var() # doctest: +SKIP
>>> m.c = pe.Constraint(expr=m.y >= -2*m.x + 5) # doctest: +SKIP
>>> opt = pe.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> m = pyo.ConcreteModel() # doctest: +SKIP
>>> m.x = pyo.Var() # doctest: +SKIP
>>> m.y = pyo.Var() # doctest: +SKIP
>>> m.c = pyo.Constraint(expr=m.y >= -2*m.x + 5) # doctest: +SKIP
>>> opt = pyo.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> opt.set_instance(m) # doctest: +SKIP
>>> # Correct:
>>> opt.remove_constraint(m.c) # doctest: +SKIP
>>> del m.c # doctest: +SKIP
>>> m.c = pe.Constraint(expr=m.y <= m.x) # doctest: +SKIP
>>> m.c = pyo.Constraint(expr=m.y <= m.x) # doctest: +SKIP
>>> opt.add_constraint(m.c) # doctest: +SKIP

.. warning:: Components removed from a pyomo model must be removed
Expand All @@ -100,14 +100,14 @@ The correct way to do this is:
Additionally, unexpected behavior may result if a component is
modified before being removed.

>>> m = pe.ConcreteModel() # doctest: +SKIP
>>> m.b = pe.Block() # doctest: +SKIP
>>> m.b.x = pe.Var() # doctest: +SKIP
>>> m.b.y = pe.Var() # doctest: +SKIP
>>> m.b.c = pe.Constraint(expr=m.b.y >= -2*m.b.x + 5) # doctest: +SKIP
>>> opt = pe.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> m = pyo.ConcreteModel() # doctest: +SKIP
>>> m.b = pyo.Block() # doctest: +SKIP
>>> m.b.x = pyo.Var() # doctest: +SKIP
>>> m.b.y = pyo.Var() # doctest: +SKIP
>>> m.b.c = pyo.Constraint(expr=m.b.y >= -2*m.b.x + 5) # doctest: +SKIP
>>> opt = pyo.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> opt.set_instance(m) # doctest: +SKIP
>>> m.b.c2 = pe.Constraint(expr=m.b.y <= m.b.x) # doctest: +SKIP
>>> m.b.c2 = pyo.Constraint(expr=m.b.y <= m.b.x) # doctest: +SKIP
>>> # ERROR: The constraint referenced by m.b.c2 does not
>>> # exist in the solver model.
>>> opt.remove_block(m.b) # doctest: +SKIP
Expand All @@ -117,12 +117,12 @@ the solver instance, modify it with Pyomo, and then add it back to the
solver instance. The only exception is with variables. Variables may
be modified and then updated with with solver:

>>> m = pe.ConcreteModel() # doctest: +SKIP
>>> m.x = pe.Var() # doctest: +SKIP
>>> m.y = pe.Var() # doctest: +SKIP
>>> m.obj = pe.Objective(expr=m.x**2 + m.y**2) # doctest: +SKIP
>>> m.c = pe.Constraint(expr=m.y >= -2*m.x + 5) # doctest: +SKIP
>>> opt = pe.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> m = pyo.ConcreteModel() # doctest: +SKIP
>>> m.x = pyo.Var() # doctest: +SKIP
>>> m.y = pyo.Var() # doctest: +SKIP
>>> m.obj = pyo.Objective(expr=m.x**2 + m.y**2) # doctest: +SKIP
>>> m.c = pyo.Constraint(expr=m.y >= -2*m.x + 5) # doctest: +SKIP
>>> opt = pyo.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> opt.set_instance(m) # doctest: +SKIP
>>> m.x.setlb(1.0) # doctest: +SKIP
>>> opt.update_var(m.x) # doctest: +SKIP
Expand Down Expand Up @@ -160,13 +160,13 @@ Persistent Solver Performance
In order to get the best performance out of the persistent solvers, use the
"save_results" flag:

>>> import pyomo.environ as pe
>>> m = pe.ConcreteModel()
>>> m.x = pe.Var()
>>> m.y = pe.Var()
>>> m.obj = pe.Objective(expr=m.x**2 + m.y**2)
>>> m.c = pe.Constraint(expr=m.y >= -2*m.x + 5)
>>> opt = pe.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> import pyomo.environ as pyo
>>> m = pyo.ConcreteModel()
>>> m.x = pyo.Var()
>>> m.y = pyo.Var()
>>> m.obj = pyo.Objective(expr=m.x**2 + m.y**2)
>>> m.c = pyo.Constraint(expr=m.y >= -2*m.x + 5)
>>> opt = pyo.SolverFactory('gurobi_persistent') # doctest: +SKIP
>>> opt.set_instance(m) # doctest: +SKIP
>>> results = opt.solve(save_results=False) # doctest: +SKIP

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Relevant imports
.. doctest::
:skipif: not numpy_available or not scipy_available or not asl_available

>>> import pyomo.environ as pe
>>> import pyomo.environ as pyo
>>> from pyomo.contrib.pynumero.interfaces.pyomo_nlp import PyomoNLP
>>> import numpy as np

Expand All @@ -19,12 +19,12 @@ Create a Pyomo model
.. doctest::
:skipif: not numpy_available or not scipy_available or not asl_available

>>> m = pe.ConcreteModel()
>>> m.x = pe.Var(bounds=(-5, None))
>>> m.y = pe.Var(initialize=2.5)
>>> m.obj = pe.Objective(expr=m.x**2 + m.y**2)
>>> m.c1 = pe.Constraint(expr=m.y == (m.x - 1)**2)
>>> m.c2 = pe.Constraint(expr=m.y >= pe.exp(m.x))
>>> m = pyo.ConcreteModel()
>>> m.x = pyo.Var(bounds=(-5, None))
>>> m.y = pyo.Var(initialize=2.5)
>>> m.obj = pyo.Objective(expr=m.x**2 + m.y**2)
>>> m.c1 = pyo.Constraint(expr=m.y == (m.x - 1)**2)
>>> m.c2 = pyo.Constraint(expr=m.y >= pyo.exp(m.x))

Create a :py:class:`pyomo.contrib.pynumero.interfaces.pyomo_nlp.PyomoNLP` instance

Expand Down
26 changes: 13 additions & 13 deletions pyomo/contrib/alternative_solutions/aos_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import numpy.random
from numpy.linalg import norm

import pyomo.environ as pe
import pyomo.environ as pyo
from pyomo.common.modeling import unique_component_name
from pyomo.common.collections import ComponentSet
import pyomo.util.vars_from_expressions as vfe
Expand Down Expand Up @@ -56,7 +56,7 @@ def get_active_objective(model):
assume that there is exactly one active objective.
"""

active_objs = list(model.component_data_objects(pe.Objective, active=True))
active_objs = list(model.component_data_objects(pyo.Objective, active=True))
assert (
len(active_objs) == 1
), "Model has {} active objective functions, exactly one is required.".format(
Expand All @@ -68,7 +68,7 @@ def get_active_objective(model):

def _add_aos_block(model, name="_aos_block"):
"""Adds an alternative optimal solution block with a unique name."""
aos_block = pe.Block()
aos_block = pyo.Block()
model.add_component(unique_component_name(model, name), aos_block)
return aos_block

Expand Down Expand Up @@ -103,11 +103,11 @@ def _add_objective_constraint(
)

if objective_is_min:
aos_block.optimality_tol_rel = pe.Constraint(
aos_block.optimality_tol_rel = pyo.Constraint(
expr=objective_expr <= objective_cutoff
)
else:
aos_block.optimality_tol_rel = pe.Constraint(
aos_block.optimality_tol_rel = pyo.Constraint(
expr=objective_expr >= objective_cutoff
)
objective_constraints.append(aos_block.optimality_tol_rel)
Expand All @@ -116,11 +116,11 @@ def _add_objective_constraint(
objective_cutoff = objective_value + objective_sense * abs_opt_gap

if objective_is_min:
aos_block.optimality_tol_abs = pe.Constraint(
aos_block.optimality_tol_abs = pyo.Constraint(
expr=objective_expr <= objective_cutoff
)
else:
aos_block.optimality_tol_abs = pe.Constraint(
aos_block.optimality_tol_abs = pyo.Constraint(
expr=objective_expr >= objective_cutoff
)
objective_constraints.append(aos_block.optimality_tol_abs)
Expand Down Expand Up @@ -219,7 +219,7 @@ def get_model_variables(

"""

component_list = (pe.Objective, pe.Constraint)
component_list = (pyo.Objective, pyo.Constraint)
variable_set = ComponentSet()
if components == None:
var_generator = vfe.get_vars_from_components(
Expand All @@ -235,7 +235,7 @@ def get_model_variables(
)
else:
for comp in components:
if hasattr(comp, "ctype") and comp.ctype == pe.Block:
if hasattr(comp, "ctype") and comp.ctype == pyo.Block:
blocks = comp.values() if comp.is_indexed() else (comp,)
for item in blocks:
variables = vfe.get_vars_from_components(
Expand All @@ -252,10 +252,10 @@ def get_model_variables(
elif (
isinstance(comp, tuple)
and hasattr(comp[0], "ctype")
and comp[0].ctype == pe.Block
and comp[0].ctype == pyo.Block
):
block = comp[0]
descend_into = pe.Block if comp[1] else False
descend_into = pyo.Block if comp[1] else False
blocks = block.values() if block.is_indexed() else (block,)
for item in blocks:
variables = vfe.get_vars_from_components(
Expand All @@ -275,7 +275,7 @@ def get_model_variables(
elif hasattr(comp, "ctype") and comp.ctype in component_list:
constraints = comp.values() if comp.is_indexed() else (comp,)
for item in constraints:
variables = pe.expr.identify_variables(
variables = pyo.expr.identify_variables(
item.expr, include_fixed=include_fixed
)
_filter_model_variables(
Expand All @@ -286,7 +286,7 @@ def get_model_variables(
include_integer,
include_fixed,
)
elif hasattr(comp, "ctype") and comp.ctype == pe.Var:
elif hasattr(comp, "ctype") and comp.ctype == pyo.Var:
variables = comp.values() if comp.is_indexed() else (comp,)
_filter_model_variables(
variable_set,
Expand Down
24 changes: 13 additions & 11 deletions pyomo/contrib/alternative_solutions/balas.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

logger = logging.getLogger(__name__)

import pyomo.environ as pe
import pyomo.environ as pyo
from pyomo.common.collections import ComponentSet
from pyomo.contrib.alternative_solutions import Solution
import pyomo.contrib.alternative_solutions.aos_utils as aos_utils
Expand Down Expand Up @@ -124,7 +124,7 @@ def enumerate_binary_solutions(
#
# Setup solver
#
opt = pe.SolverFactory(solver)
opt = pyo.SolverFactory(solver)
opt.available()
for parameter, value in solver_options.items():
opt.options[parameter] = value
Expand Down Expand Up @@ -159,7 +159,7 @@ def enumerate_binary_solutions(
logger.info("Performing initial solve of model.")
results = opt.solve(model, tee=tee, load_solutions=False)
status = results.solver.status
if not pe.check_optimal_termination(results):
if not pyo.check_optimal_termination(results):
condition = results.solver.termination_condition
raise Exception(
(
Expand All @@ -170,7 +170,7 @@ def enumerate_binary_solutions(
)

model.solutions.load_from(results)
orig_objective_value = pe.value(orig_objective)
orig_objective_value = pyo.value(orig_objective)
logger.info("Found optimal solution, value = {}.".format(orig_objective_value))
solutions = [Solution(model, all_variables, objective=orig_objective)]
#
Expand All @@ -181,7 +181,7 @@ def enumerate_binary_solutions(

aos_block = aos_utils._add_aos_block(model, name="_balas")
logger.info("Added block {} to the model.".format(aos_block))
aos_block.no_good_cuts = pe.ConstraintList()
aos_block.no_good_cuts = pyo.ConstraintList()
aos_utils._add_objective_constraint(
aos_block, orig_objective, orig_objective_value, rel_opt_gap, abs_opt_gap
)
Expand All @@ -207,7 +207,9 @@ def enumerate_binary_solutions(
if use_appsi and opt.update_config.check_for_new_objective:
opt.update_config.check_for_new_objective = False
else:
aos_block.hamming_objective = pe.Objective(expr=expr, sense=pe.maximize)
aos_block.hamming_objective = pyo.Objective(
expr=expr, sense=pyo.maximize
)

elif search_mode == "random":
if hasattr(aos_block, "random_objective"):
Expand All @@ -218,22 +220,22 @@ def enumerate_binary_solutions(
for var in binary_variables:
expr += vector[idx] * var
idx += 1
aos_block.random_objective = pe.Objective(expr=expr, sense=pe.maximize)
aos_block.random_objective = pyo.Objective(expr=expr, sense=pyo.maximize)

results = opt.solve(model, tee=tee, load_solutions=False)
status = results.solver.status
condition = results.solver.termination_condition
if pe.check_optimal_termination(results):
if pyo.check_optimal_termination(results):
model.solutions.load_from(results)
orig_obj_value = pe.value(orig_objective)
orig_obj_value = pyo.value(orig_objective)
logger.info(
"Iteration {}: objective = {}".format(solution_number, orig_obj_value)
)
solutions.append(Solution(model, all_variables, objective=orig_objective))
solution_number += 1
elif (
condition == pe.TerminationCondition.infeasibleOrUnbounded
or condition == pe.TerminationCondition.infeasible
condition == pyo.TerminationCondition.infeasibleOrUnbounded
or condition == pyo.TerminationCondition.infeasible
):
logger.info(
"Iteration {}: Infeasible, no additional binary solutions.".format(
Expand Down
Loading
Loading