Search code examples
cplexdocplex

What is the efficient way to add new variables using docplex python API?


I have a basic question about docplex library. Does anyone know what is the best way to add/delete variables from existing model? I am using the following code to create decision variables

self.model.continuous_var_dict(self.N, lb=0)

Can I run this line again by just increasing the size of self.N?

I also want to know if there is an efficient way for updating existing constraints, right now, I am deleting all the constraints and adding new ones back using the following code

self.model.remove_constraints(self.constrains)
self.constrains = self.model.add_constraints(
        self.model.sum(self.cons_coef[(i, k, p)] * self.x_mp[(k, p)] for k, p in self.N) == 1 for i in range(N))

What if I only want to add new columns in column generation?


Solution

  • The way that you are adding variables (through continuous_var_dict) is fine. Yes, you can call continuous_var_dict repeatedly to add several batches of variables. In terms of performance, docplex should be adding these to CPLEX in the quickest way possible. If you are surprised by slow performance, please share the specifics.

    To remove variables, you remove them from the objective and constraints of the model. For example, using LinearExpr.remove_term.

    To modify constraints, you can do something like the following (see LinearConstraint.lhs):

    for c in contraints:
       c.lhs += model.sum_vars(newvars)
    

    The docplex "incremental modeling" example demonstrates this (see here).