Search code examples
pythonoptimizationconstraintscplexdocplex

Error while writing optimization constraint in cplex python api


My goal is to write the following model using docplex.mp.model in python. which ptj takes binary variable {0,1}.

[summation from of Ptj from j=1 to t][t = 1,.....,8]

here is the code I wrote:

N = 8 
(period_list = [t for t in range(1, no_of_period+1)])
(j = period_list)
p = Mode.binary_var_dict(period_list, name = 'p')
for t in period_list:
    for j in range(1,t+1):
        Model.add_constraints(Model.sum(p[t,j]) == 1) 

but I got an error. Could anyone help me with this problem please?


Solution

  • Your code has numerous issues.

    First, you need to create one instance of docplex.mp.model.Model to add constraints to: all your calls to Model.<fn> should be rewritten as mdl.<fn> as they are instance methods.

    Second, the variable dict you create has periods as keys, that is, 1,2,..P so querying p[t,j] is sure to crash with KeyError. If you need a square matrix of variables for each couple of periods, use Model.binary_var_matrix.

    Third: Model.add_constraints (with a final S) expects an iterable, but you are passing one constraint, this is also sure to crash.

    Lastly, using ranges starting at 1 is not the simplest nor the safest choice with Docplex.

    Here is a code, freely derived from your sample, which I guess is close to what you need:

    pr = range(1, no_of_period+1)
    from docplex.mp.model import Model
    m = Model()
    p = m.binary_var_matrix(pr, pr, name = 'p')
    m.add_constraints( (m.sum(p[t,j] for j in pr) == 1) for t in pr)
    print(m.lp_string)
    

    and the output is:

    Minimize
     obj:
    Subject To
     c1: p_1_1 + p_1_2 + p_1_3 = 1
     c2: p_2_1 + p_2_2 + p_2_3 = 1
     c3: p_3_1 + p_3_2 + p_3_3 = 1
    

    [..snip..]