How to print a variable value
回答済みDear Sir/Madam,
Can you help me? I have a python with gurobi optimization code as below?
When I print the output, it only print A.. and B... but did not print ATOTAL and BTOTAL,
I undersatnd that ATOTAL and BTOTAL is in my objective function. How can I print out ATOTAL and BTOTAL? Thank you, Robert
** Sample Code as below:
set_T = range(1,31)
A = scm.addVars(range(1,31), lb=0, vtype=GRB.INTEGER, name="A")
B = scm.addVars(range(1,31), lb=0, vtype=GRB.INTEGER, name="B")
ATOTAL = scm.addVar(lb=0, name="ATOTAL")
BTOTAL = scm.addVar(lb=0, name="BTOTAL")
ATOTAL = quicksum( 3 * A[TT] for TT in set_T)
BTOTAL= quicksum( 5 * B[TT] for TT in set_T)
TCB= ATOTAL + BTOTAL
scm.addConstrs((A[TT] >= 10) for T in set_T, name='constraint1')
scm.addConstrs((B[TT] >= 20) for T in set_T, name='constraint2')
scm.update()
obj= TCB
# Set objective
scm.setObjective( obj, GRB.MINIMIZE)
for v in scm.getVars():
print('%s %g' % (v.varName, v.x))
-
正式なコメント
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi,
There are a few issues in your code: I assume that the lines that add the constraints "constraint1" and "constraint2" should read "for TT in set_T" and the closing parantheses should be put after "set_T" instead. Moreover, you need to call "scm.optimize()" before you can access the variables' X attribute. Also note that your call to scm.update() is not necessary.
With these fixes, your code should print all variable names (including ATOTAL and BTOTAL) and their values in the optimal solution. However, the values of ATOTAL and BTOTAL will likely be 0 since these variables are not used in your constraints.
In fact, you first define ATOTAL and BTOTAL to be decision variables in your model, directly afterwards you override them to be linear expressions that you then use to build the objective function. However, you only used the Python variables (and not the model's decision variables) to build the objective. You need to add constraints if you want your decision variables ATOTAL and BTOTAL to be equal to those quicksum expressions. E. g.:
scm.addConstr(ATOTAL == quicksum( 3 * A[TT] for TT in set_T))
scm.addConstr(BTOTAL == quicksum( 5 * B[TT] for TT in set_T))
0 -
Hi Silke,
Thank you for your help. I got it working to print a variable value.
Robert
0
投稿コメントは受け付けていません。
コメント
3件のコメント