obtain variable values from a program inside a function
AnsweredHello guys, I have created a function named SP_define and inside I have formed an optimization model named SPmodel = gp.Model('SP'). On the final line of the function, I have written: return SPmodel. How could I obtain the model variable values after optimizing the model? by the way I optimize it by the line subproblem.optimize(). But I do not know how to get the variable values after that. Could you help me?
Kind regards
Iason
-
Hi Iason,
The solution values are stored in the X attribute of variables. If you have a variable v, then you can use v.X. If you would prefer to retrieve many values at once, for a collection of variables "vars", then you can use the getAttr method:
sol_values = my_model.getAttr("X", vars)- Riley
0 -
Thank you so much Riley
0 -
Another way just for future reference is: where subproblem is the name of the model.
# Define the prefix to match your variable naming pattern
# This should match the variable name pattern used when adding variables to the model.
# For example, if you named them like 'T[k,i][rs]', use that pattern here.
prefix = "T_{k,i}^{rs}[" # This is a simplified prefix, adjust it to match your exact names
# Assuming 'subproblem' is your Gurobi Model object and it's been optimized
subproblem.optimize()
# Check the optimization status before trying to access variable values
if subproblem.status == GRB.OPTIMAL:
# Get the list of all variable objects in the subproblem
variables = subproblem.getVars()
# Filter variables whose name starts with the specific pattern
# Replace v.varName.startswith(prefix) with the appropriate pattern matching for your problem
filtered_variables = [(v.varName, v.x) for v in variables if v.varName.startswith(prefix)]
# Print the filtered variables
for name, value in filtered_variables:
print(f"Variable {name} has value {value}")0
Please sign in to leave a comment.
Comments
3 comments