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

Allow CyIpopt to solve problems without objectives #3163

Merged
merged 2 commits into from
Feb 27, 2024
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
23 changes: 18 additions & 5 deletions pyomo/contrib/pynumero/algorithms/solvers/cyipopt_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from pyomo.common.deprecation import relocated_module_attribute
from pyomo.common.dependencies import attempt_import, numpy as np, numpy_available
from pyomo.common.tee import redirect_fd, TeeStream
from pyomo.common.modeling import unique_component_name
from pyomo.core.base.objective import Objective

# Because pynumero.interfaces requires numpy, we will leverage deferred
# imports here so that the solver can be registered even when numpy is
Expand Down Expand Up @@ -332,11 +334,22 @@ def solve(self, model, **kwds):
grey_box_blocks = list(
model.component_data_objects(egb.ExternalGreyBoxBlock, active=True)
)
if grey_box_blocks:
# nlp = pyomo_nlp.PyomoGreyBoxNLP(model)
nlp = pyomo_grey_box.PyomoNLPWithGreyBoxBlocks(model)
else:
nlp = pyomo_nlp.PyomoNLP(model)
# if there is no objective, add one temporarily so we can construct an NLP
objectives = list(model.component_data_objects(Objective, active=True))
if not objectives:
objname = unique_component_name(model, "_obj")
objective = model.add_component(objname, Objective(expr=0.0))
try:
if grey_box_blocks:
# nlp = pyomo_nlp.PyomoGreyBoxNLP(model)
nlp = pyomo_grey_box.PyomoNLPWithGreyBoxBlocks(model)
else:
nlp = pyomo_nlp.PyomoNLP(model)
finally:
# We only need the objective to construct the NLP, so we delete
# it from the model ASAP
if not objectives:
model.del_component(objective)

problem = cyipopt_interface.CyIpoptNLP(
nlp,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,13 @@ def test_hs071_evalerror_old_cyipopt(self):
msg = "Error in AMPL evaluation"
with self.assertRaisesRegex(PyNumeroEvaluationError, msg):
res = solver.solve(m, tee=True)

def test_solve_without_objective(self):
m = create_model1()
m.o.deactivate()
m.x[2].fix(0.0)
m.x[3].fix(4.0)
solver = pyo.SolverFactory("cyipopt")
res = solver.solve(m, tee=True)
pyo.assert_optimal_termination(res)
self.assertAlmostEqual(m.x[1].value, 9.0)