I am new to or-tools and I struggle to use it, here is my problem:
Let say we have a map with 3 points '1', '2', '3' and that we have 3 names 'a', 'b', 'c'. Each points can take all name but must have one name. With that we have a matrix that says the distance between all points and another that say how many time you have to go from one name to another. The goal is to find which name to set to each point to have the least distance to do.
With code:
'Distance matrix' 'Planning matrix'
'1' '2' '3' 'a' 'b' 'c'
'1' 0 10 20 'a' 0 1 3
'2' 10 0 30 'b' 1 0 2
'3' 20 30 0 'c' 3 2 0
Here we need to go from a to b 1 time. Here how i create my variables and constraints:
for x in range(len(planning)):
for y in range(len(planning)):
var_list[x, y] = model.NewBoolVar('')
for x in range(len(planning)):
model.AddExactlyOne(var_list[x, y] for y in range(len(planning)))
for y in range(len(planning)):
model.AddExactlyOne(var_list[x, y] for x in range(len(planning)))
We have a matrix where each row and column have only one 1 My idea is to use this matrix to define which name is set to each point. The matrix can be this for example:
'a''b''c'
'1' 0 1 0
'2' 0 0 1
'3' 1 0 0
And here is how i try to solve optimization, I use my var as an index for my distance matrix:
terms = []
for index_x in range(len(planning)):
for index_y in range(len(planning)):
terms.append(planning[index_x, index_y] * distance[np.where(var_list[index_x] == True)[0][0]][np.where(var_list[index_y] == True)[0][0]])
model.Minimize(sum(terms))
But it won't run because it can't find the index where var_list is True
terms.append(planning[index_x, index_y] * distance[np.where(var_list[index_x] == True)[0][0]][np.where(var_list[index_y] == True)[0][0]])
IndexError: index 0 is out of bounds for axis 0 with size 0
I had another idea where I use directly my variables but my problem was no longer linear:
terms = []
for index_x in range(len(planning)):
for index_y in range(len(planning)):
terms.append(
planning[index_x, index_y] *
sum(
distance[i, j] * var_list[index_x, i] * var_list[index_y, j] for i in range(len(planning)) for j in range(len(planning))
)
)
model.Minimize(sum(terms))
Anyone know how could I change my code to make it work ? Even if I have to use another library.
for x in range(len(planning)): for y in range(len(planning)): var_list[x, y] = model.NewBoolVar('') for x in range(len(planning)): model.AddExactlyOne(var_list[x, y] for y in range(len(planning))) for y in range(len(planning)): model.AddExactlyOne(var_list[x, y] for x in range(len(planning)))