Accessing the values of Mvars during optimization
AnsweredHi everyone,
I am currently working on a project where I need to solve optimization models defined using PyCUTEst with Gurobi. My primary objective is to transfer PyCUTEst models to Gurobi models.
I am facing a challenge in that the objective function provided by PyCUTEst accepts input arguments as a NumPy array. Therefore, I need a method to extract the values of Gurobi decision variables (mvars) at any given instant to calculate the objective function. Essentially, I need to:
- Transfer the values of mvars to the PyCUTEst objective function during the optimization process.
- Alternatively, incorporate the PyCUTEst objective function directly into the Gurobi model.
So far I have tried Mvar.tolist(), model.m.getVarByName and model.cbGetSolution(x) methods which didn't work.
I would greatly appreciate any suggestions or guidance on achieving this, including relevant materials or documentation that could assist in this process.
Thank you for your help!
-
Try using this:
from gurobipy import Model, GRB
import numpy as np
# Create Gurobi model and define variables
model = Model()
mvars = model.addVars(n, vtype=GRB.CONTINUOUS, name="vars")
# Define your PyCUTEst objective function
def pycutest_objective_function(x):
return np.sum(x**2)
# Optimize the model and extract values
model.optimize()
if model.status == GRB.OPTIMAL:
values = np.array(model.getAttr('X', mvars.values()))
objective_value = pycutest_objective_function(values)
print(f"Objective Value: {objective_value}")0 -
"'gurobipy.MVar' object has no attribute 'values'", I also checked Gurobi python API documentation the method values() is not listed there for the Mvars.
0 -
Hi Harsh,
I think it may be worthwhile familiarizing yourself with how models are formulated in our solver (and mixed integer programs more generally).
Some quick examples can be found here: Functional Code Examples
More thorough examples here: Resouce Center: Demos
I need a method to extract the values of Gurobi decision variables (mvars) at any given instant to calculate the objective function... Transfer the values of mvars to the PyCUTEst objective function during the optimization process.
It is not possible to transfer values to an external function to be evaluated as the objective during the optimization.
Alternatively, incorporate the PyCUTEst objective function directly into the Gurobi model.
This is the right way to do it. You need to examine what the PyCUTEst objective function is doing with the inputs and formulate it as an expression in Gurobi (before the optimization is run).
- Riley
0
Please sign in to leave a comment.
Comments
3 comments