0

I'm playing with docplex on Python and I'm facing some difficulties. I wanto to code the Mathematical expressions attached in the image as constraints, but it is quite hard for me. I know that t and T are fixed values. I coded the first constraint without considering v1≠v, I don't know if it is even possible to add it. For the second constraint I tried to write a code but I'm pretty confident it is wrong because it does not consider the part of the summation which says fv,v1=i

My code is:

from docplex.mp.model import Model
mdl = Model('Optimization model')

#For matrix G, columns represent v, rows represent t
G = ((0, 2, 2, 1),
     (1, 0, 5, 4),
     (2, 5, 0, 3),
     (3, 0, 5, 4),
     (4, 5, 0, 7),
     (5, 6, 4, 0))

#For matrix f, rows represent v and columns represent v1 (it is a time matrix, for travelling from v to v1)
f = ((0, 1, 2, 1),
    (1, 0, 2, 1),
    (2, 2, 0, 2),
    (1, 1, 2, 0))

E = (2, 1, 1, 0)

t=2  # t is given
T=len(G)
V=len(E)

# Define the variable
X = mdl.integer_var_matrix(V, V, lb=0, name="X")

# Define the constraints
Constraint1 = mdl.add_constraints([sum(x[v,v1] for v1 in range(V) if v != v1) <= E[v] for v in range(V)])

Constraint2 = mdl.add_constraints([sum(x[v,v1] for v1 in range(V)) <= G[v,t+i] for v in range(V) for i in range(T-t)])

Any idea? Thanks!

Edit:

  • I added the answer I received for the first constraint and it works.
  • I made the code more readable and added the import part.
  • For the second constraint I'm still struggling. I tried adding the fv,v1=i part to the code but without success. Any help is more than welcome!

Edit1: I solved the second constraint as follow, but not sure if it is really right:

for i in range(T-t):
    for v in range(V): 
        temp = (sum(x[v1,v] for v1 in range(V) if (i+1) == f[v1][v]))
        mdl.add_constraint(temp <= G[t+i][v])
Fab
  • 1
  • 3

1 Answers1

0

I coded the first constraint without considering v'≠v, I don't know if it is even possible to add it

For this, just change

sum(x[v,v1] for v1 in range(V))

to

sum(x[v,v1] for v1 in range(V) if v != v1)

(assuming v' is v1 in your code).

For the second constraint I tried to write a code but I'm pretty confident it is wrong because it does not consider the part of the summation which says f_v_v'=i

You should be able to add a similar if clause to the second generator expression. There is nothing in your formulas that indicate where f_v_v' comes from, so I can't give any exact code.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Thanks for the fast reply and excellent advice! f_v_v' is coming from the f matrix, in Excel I would use something like a vlookup function but here I really don't know how to call specific value of f in the constraint code – Fab Jan 11 '22 at 20:32
  • @Fab Probably just `f[v][v']` or something similar. If you are unfamiliar with this syntax, I suggest you read more about lists and tuples in Python. – Code-Apprentice Jan 11 '22 at 20:46