pythonpython-3.xlinear-programmingcplexdocplex

Docplex use for timeseries based variables


I am trying to model an optimisation problem where each item in a list is essentially power generated at that hour. I am trying to minimise the amount of energy stored while still getting the same energy over the course of the time series, and as such am modelling it as a linear programming problem.

I am trying to add a constraint, but am running into problems. The important bits look like this:

var_1 = model.continuous_var_list(1000, name = 'var_1')
var_2 = model.continuous_var_list(1000, name = 'var_2')
var_3 = model.continuous_var_list(1000, name = 'var_3')

model.add_constraint(var_1[i] - var+2[i] == var_3[i] for i in range(1000))

Where I am trying to say that at timestep i, var_3 should always equal the difference between var_1 and var_2. Is there a good example for this kind of problem I can learn from, or does anyone have any advice? Either in Docplex, or a similar thing in CPLEX I can use to understand. This code results in the error:

Expecting constraint, got: <generator object Home.linearlySolve.<locals>.<genexpr> at 0x0000013F2BBBA940> with type: <class 'generator'>

Thanks!


Solution

  • You could use add_constraints with an "s"

    from docplex.mp.model import Model
    
    model = Model(name='model')
    
    var_1 = model.continuous_var_list(1000, name = 'var_1')
    var_2 = model.continuous_var_list(1000, name = 'var_2')
    var_3 = model.continuous_var_list(1000, name = 'var_3')
    
    model.add_constraints(var_1[i] - var_2[i] == var_3[i] for i in range(1000))
    
    sol=model.solve(log_output=True)
    
    for v in model.iter_continuous_vars():
        print(v," = ",v.solution_value)
    

    works fine