Solution of optimization saved as array.
回答済みHello everyone. I am new at programming and I've been struggling with this piece of code. I am working with a modified version of the Knapsack Problem.
- #Data
n = n. of items
weights =[...]
v = [...]
sigma =[...]
knapsack_model = Model('knapsack')
x = knapsack_model.addVars(n, vtype = GRB.BINARY, name="x")
# constraint on capacity
knapsack_model.addConstr(sum(weights[i]*x[i] for i in range(n)) <= C)
estimation = [ ]
for i in range(n):
values = np.random.normal(v[i], sigma[i])
estimation.append(values)
# Objective function
obj_fn = sum((estimation[i]*x[i]) for i in range(n))
knapsack_model.setObjective(obj_fn, GRB.MAXIMIZE)
knapsack_model.optimize()
print('Optimization is done. Objective Function Value: %.2f' % knapsack_model.objVal)
#Piece of code that gives me an error
total = [ ]
for v in knapsack_model.getVars():
total.append(v.x)
final_objective = sum((total[ i ]*v[ i ]) for i in range(n))
Here I get an error saying: 'Var' object is not subscriptable
I need to use the x that gurobi produced and multiply it with v[i], but I am having a hard time putting the x in an array that i can use.
If anyone could help me I would really appreciate it.
Thank you in advance!
0
-
正式なコメント
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 try Gurobot, our chatbot interface offering instant, expert-level support. -
You are using the variable \(\texttt{v}\) in the \(\texttt{for}\)-loop
for v in knapsack_model.getVars():
total.append(v.x)but you have already defined and used \(\texttt{v}\) before. Using a different iterator in the above \(\texttt{for}\)-loop should solve the issue.
for var in knapsack_model.getVars():
total.append(var.x)Best regards,
Jaromił1
投稿コメントは受け付けていません。
コメント
2件のコメント