@@ -213,7 +213,9 @@ def results(self):
213213 """
214214 return processing .results (self )
215215
216- def solve (self , solver = "cbc" , solver_io = "lp" , ** kwargs ):
216+ def solve (
217+ self , solver = "cbc" , solver_io = "lp" , allow_nonoptimal = True , ** kwargs
218+ ):
217219 r"""Takes care of communication with solver to solve the model.
218220
219221 Parameters
@@ -222,6 +224,9 @@ def solve(self, solver="cbc", solver_io="lp", **kwargs):
222224 solver to be used e.g. "cbc", "glpk", "gurobi", "cplex"
223225 solver_io : string
224226 pyomo solver interface file format: "lp", "python", "nl", etc.
227+ allow_nonoptimal : bool
228+ if set to false, an error will be raised
229+ if no optimal solution is found
225230 \**kwargs : keyword arguments
226231 Possible keys can be set see below:
227232
@@ -248,23 +253,29 @@ def solve(self, solver="cbc", solver_io="lp", **kwargs):
248253
249254 solver_results = opt .solve (self , ** solve_kwargs )
250255
251- status = solver_results ["Solver" ][0 ]["Status" ]
252- termination_condition = solver_results ["Solver" ][0 ][
253- "Termination condition"
254- ]
256+ status = solver_results .Solver .Status
257+ termination_condition = solver_results .Solver .Termination_condition
258+
259+ self .es .results = solver_results
260+ self .solver_results = solver_results
255261
256262 if status == "ok" and termination_condition == "optimal" :
257263 logging .info ("Optimization successful..." )
258264 else :
259265 msg = (
260- "Optimization ended with status {0} and termination "
261- "condition {1}"
262- )
263- warnings .warn (
264- msg .format (status , termination_condition ), UserWarning
266+ f"The solver did not return an optimal solution. "
267+ f"Instead the optimization ended with\n "
268+ f" - status: { status } \n "
269+ f" - termination condition: { termination_condition } "
265270 )
266- self .es .results = solver_results
267- self .solver_results = solver_results
271+
272+ if allow_nonoptimal :
273+ msg += "\n In the future, this will be treated as an error."
274+ warnings .warn (
275+ msg .format (status , termination_condition ), UserWarning
276+ )
277+ else :
278+ raise RuntimeError (msg )
268279
269280 return solver_results
270281
0 commit comments