I'm using a toolbox that internally calls Pyomo to solve an optimization problem. I am interested in accessing the Pyomo model it constructs so I can modify the constraints/objective. So my question is, suppose I get the following output:
Problem:
Name: unknown Lower bound: 6250.0 Upper bound: 6250.0 Number of objectives: 1 Number of constraints: 11 Number of variables: 8 Number of nonzeros: 17 Sense: minimize
Solver:
Status: ok Termination condition: optimal Statistics: Branch and bound: Number of bounded subproblems: 0 Number of created subproblems: 0 Error rc: 0 Time: 0.015599727630615234
Solution:
number of solutions: 0 number of solutions displayed: 0
So the problem works well and I get a solution, the modeling was done internally via another too. Is it possible to access the constraints/objective so I can freely modify the optimization model in Pyomo syntax?
I tried to call the model and got something like this:
<pyomo.core.base.PyomoModel.ConcreteModel at xxxxxxx>
It sounds like network.model
is the Pyomo model and yes, if you have access to it, you can modify it. Try printing the model or individual model components using the pprint()
method:
network.model.pprint()
network.model.con1.pprint()
or you can loop over specific types of components in the model:
for c in network.model.component_objects(Constraint):
print(c) # Prints the name of every constraint on the model
The easiest way to modify the objective would be to find the existing one, deactivate it, and add a new one
network.model.obj.deactivate()
network.model.new_obj = Objective(expr=network.model.x**2)
There are ways to modify constraints/objectives in place but they are not well-documented. I'd recommend using Python's dir()
function and playing around with some of the component attributes and methods to get a feel for how they work.
dir(network.model.obj)