Reputation: 21
I want to set a binary four-dimensions variable, like X[a][b][c][d], bur docplex only have function binary_var_cube
to set a three-dimension. How can I to create a four-dimension?
I have found that someone use this to create a three-dimension and said it could extend to more dimensions.But it isn't useful.
binary_var_dict((a,b,c) for a in ... for b in ... for c in ...)
Upvotes: 0
Views: 1465
Reputation: 10062
Let me share a tiny example:
from docplex.mp.model import Model
# Data
r=range(1,3)
i=[(a,b,c,d) for a in r for b in r for c in r for d in r]
print(i)
mdl = Model(name='model')
#decision variables
mdl.x=mdl.integer_var_dict(i,name="x")
# Constraint
for it in i:
mdl.add_constraint(mdl.x[it] == it[0]+it[1]+it[2]+it[3], 'ct')
mdl.solve()
# Dislay solution
for it in i:
print(" x ",it," --> ",mdl.x[it].solution_value);
which gives
[(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 1, 2, 2), (1, 2, 1, 1), (1, 2, 1, 2), (1, 2, 2, 1), (1, 2, 2, 2), (2, 1, 1, 1), (2, 1, 1, 2), (2, 1, 2, 1), (2, 1, 2, 2), (2, 2, 1, 1), (2, 2, 1, 2), (2, 2, 2, 1), (2, 2, 2, 2)]
x (1, 1, 1, 1) --> 4.0
x (1, 1, 1, 2) --> 5.0
x (1, 1, 2, 1) --> 5.0
x (1, 1, 2, 2) --> 6.0
x (1, 2, 1, 1) --> 5.0
x (1, 2, 1, 2) --> 6.0
x (1, 2, 2, 1) --> 6.0
x (1, 2, 2, 2) --> 7.0
x (2, 1, 1, 1) --> 5.0
x (2, 1, 1, 2) --> 6.0
x (2, 1, 2, 1) --> 6.0
x (2, 1, 2, 2) --> 7.0
x (2, 2, 1, 1) --> 6.0
x (2, 2, 1, 2) --> 7.0
x (2, 2, 2, 1) --> 7.0
x (2, 2, 2, 2) --> 8.0
Upvotes: 2
Reputation: 5105
Here's an answer from Daniel Junglas, copied almost verbatim from https://developer.ibm.com/answers/questions/385771/decision-matrices-with-more-than-3-variables-for-d/
You can use tuples of any arity as keys to access the variables from a dictionary:
x = m.binary_var_dict((i, l, t, v, r)
for i in types
for l in locations
for t in times
for v in vehicles
for r in routes)
You can then access the variables using:
for i in types:
for l in locations:
for t in times:
for v in vehicles:
for r in routes:
print x[i, l, t, v, r]
You could as well use:
x = [[[[[m.binary_var('%d_%d_%d_%d_%d' % (i, l, t, v, r))
for r in routes]
for v in vehicles]
for t in times]
for l in locations]
for i in types]
for i in types:
for l in locations:
for t in times:
for v in vehicles:
for r in routes:
print x[i][l][t][v][r]
but this method doesn't support sparse dimensions, and requires many more brackets to express.
Upvotes: 2