|
24 | 24 | from pyomo.common.deprecation import relocated_module_attribute
|
25 | 25 | from pyomo.common.dependencies import attempt_import, numpy as np, numpy_available
|
26 | 26 | from pyomo.common.tee import redirect_fd, TeeStream
|
| 27 | +from pyomo.common.modeling import unique_component_name |
| 28 | +from pyomo.core.base.objective import Objective |
27 | 29 |
|
28 | 30 | # Because pynumero.interfaces requires numpy, we will leverage deferred
|
29 | 31 | # imports here so that the solver can be registered even when numpy is
|
@@ -332,11 +334,22 @@ def solve(self, model, **kwds):
|
332 | 334 | grey_box_blocks = list(
|
333 | 335 | model.component_data_objects(egb.ExternalGreyBoxBlock, active=True)
|
334 | 336 | )
|
335 |
| - if grey_box_blocks: |
336 |
| - # nlp = pyomo_nlp.PyomoGreyBoxNLP(model) |
337 |
| - nlp = pyomo_grey_box.PyomoNLPWithGreyBoxBlocks(model) |
338 |
| - else: |
339 |
| - nlp = pyomo_nlp.PyomoNLP(model) |
| 337 | + # if there is no objective, add one temporarily so we can construct an NLP |
| 338 | + objectives = list(model.component_data_objects(Objective, active=True)) |
| 339 | + if not objectives: |
| 340 | + objname = unique_component_name(model, "_obj") |
| 341 | + objective = model.add_component(objname, Objective(expr=0.0)) |
| 342 | + try: |
| 343 | + if grey_box_blocks: |
| 344 | + # nlp = pyomo_nlp.PyomoGreyBoxNLP(model) |
| 345 | + nlp = pyomo_grey_box.PyomoNLPWithGreyBoxBlocks(model) |
| 346 | + else: |
| 347 | + nlp = pyomo_nlp.PyomoNLP(model) |
| 348 | + finally: |
| 349 | + # We only need the objective to construct the NLP, so we delete |
| 350 | + # it from the model ASAP |
| 351 | + if not objectives: |
| 352 | + model.del_component(objective) |
340 | 353 |
|
341 | 354 | problem = cyipopt_interface.CyIpoptNLP(
|
342 | 355 | nlp,
|
|
0 commit comments