IBMDecisionOptimization / docplex-examples

These samples demonstrate how to use the DOcplex library to model and solve optimization problems.
https://ibmdecisionoptimization.github.io/
Apache License 2.0
396 stars 228 forks source link

Docplex MP: How to translate logical implication #52

Closed Julia000199 closed 3 years ago

Julia000199 commented 3 years ago

Hi everybody! Currently I am writing cplex to python docplex conversion model and I have cplex side binding as follows:

forall (i in point: i == 0, j in point: j != 0, k in truck) x[0][j][k] == 1 && f[j][k] >= 0 => sl[j][k] - sl[0][k] + f[j][k] > = 0;

I want to convert this binding to docplex, however I don't know how to write it. Can you help me? Thanks.

PhilippeCouronne commented 3 years ago

Hello, You're not mentioning the original format of the model you want to convert to docplex, seems like OPL?

To explain how to map the constraint syntax you posted to Docplex, let me proceed in steps:

if [ C1 and C2 are satisfied] then C3 must be satisfied.

This can be mapped to docplex easily. The essential point here is that DOcplex provides a binary variable mirroring the "truth value" of a constraint, that is, equal to 1 if and only if the constraint is satisfied. Of course the constraints should not be added to the model, otherwise they would always be satisfied. Let me illustrate with a small simple code:


from docplex.mp.model import Model
m = Model()
x = m.integer_var()
y = m.integer_var()
z = m.integer_var(lb=1, ub=10)
ctx3 = (x == 3)
cty5 = (y == 5)
ctz7 = (z == 7)
m.add(x == 3)
m.add(y == 5)
m.add((ctx3 & cty5) <= ctz7)
m.minimize(x + y)
s1 = m.solve()
s1.display()

Here I create two constraints ctx3 and cty5; note they are NOT added to the model, so we don't know in advance what their status will be .

The syntax:

m.add((ctx3 & cty5) <= ctz7)

illustrates several points:

Applied to your (simplified) case , this would look like: m.add( ( (X == 1) & (F >= 0)) <= (S2 -S1 + F >=0))

To summarize:

Julia000199 commented 3 years ago

Hi, I understand what you mean, thank you very much for your support. Best regards