Using dictionaries as objective coefficients
回答済みI'm fairly new to Gurobi and have been going over the available examples but I'm unsure how to adapt the examples to my specific problem. I have several (100+) dictionaries which I would like to turn into an objective function. As a small toy example:
d = {(111,222,333):20, (111,222,444):30, (111,222,555):10, (111,222,666):0}
k1 = {(111,222,333):0.5, (111,222,444):0.1, (111,222,666):0.25, (111,222,555):0.3}
k2 = {(111,222,333):0.1, (111,222,555):0.3, (111,222,666):0.1, (111,222,444):0.5}
k3 = {(111,222,444):0.4, (111,222,555):0, (111,222,666):0.2, (111,222,333):0.6}
All of the dictionaries are the same size (around 20000 keys), with the same keys. I'd like to formulate an absolute value problem with the dictionaries as the objective coefficients. For the toy example, it would be something like:
where D, K1, K2, K3 refer to the respective dictionaries, i refers to the keys and x are the decision variables. Is there a way to easily do this? Would really appreciate any help or if anyone could point me towards the right direction.
-
Hi Bing,
This should do the trick:
import gurobipy as gp
m = gp.Model()
d = {(111,222,333):20, (111,222,444):30, (111,222,555):10, (111,222,666):0}
k1 = {(111,222,333):0.5, (111,222,444):0.1, (111,222,666):0.25, (111,222,555):0.3}
k2 = {(111,222,333):0.1, (111,222,555):0.3, (111,222,666):0.1, (111,222,444):0.5}
k3 = {(111,222,444):0.4, (111,222,555):0, (111,222,666):0.2, (111,222,333):0.6}
x_d = m.addVars(d, name="d")
x_d_abs = m.addVars(d, name="d_abs")
x_k1 = m.addVars(k1, name="k1")
x_k2 = m.addVars(k2, name="k2")
x_k3 = m.addVars(k2, name="k3")
for i in d.keys():
m.addConstr(x_d[i] == d[i] - k1[i]*x_k1[i] - k2[i]*x_k2[i] - k3[i]*x_k3[i])
m.addGenConstrAbs(x_d_abs[i], x_d[i])
m.setObjective(gp.quicksum(x_d_abs))
m.write("dict.lp")You just have to define a set of auxiliary variables to hold the absolute values for the objective.
I added a call to write() so you can inspect the final model to see whether this is actually correct.
Cheers,
Matthias0
サインインしてコメントを残してください。
コメント
1件のコメント