Isando
Isando

Reputation: 13

cplex Python sum constraint

I just get started with cplex Python API and I got problem with creating linear_constraints for my model.

I want to do something like that:

dvar float+ x[]

Minimize:  Sum(i in I) C[i] * x[i]

subject to:
sum(i in I) x[i] <= constantValue

And my problem is that I don't know how to make constraint in Python API

  cpx.linear_constraints.add(
            lin_expr=  1,
            senses=["L"],
            rhs=constantValue,
            range_values= 2,

What do I need to type in 1) and 2) to get SUM of x[i] table which also need to be a decision variable?

Upvotes: 0

Views: 2993

Answers (1)

serge_k
serge_k

Reputation: 1772

Here is an example:

>>> import cplex
>>> c = cplex.Cplex()
>>> c.variables.add(names = ["x1", "x2", "x3"])
>>> c.linear_constraints.add(lin_expr = [cplex.SparsePair(ind = ["x1", "x3"], val = [1.0, -1.0]),
                                 cplex.SparsePair(ind = ["x1", "x2"], val = [1.0, 1.0]),
                                 cplex.SparsePair(ind = ["x1", "x2", "x3"], val = [-1.0] * 3),
                                 cplex.SparsePair(ind = ["x2", "x3"], val = [10.0, -2.0])],
                         senses = ["E", "L", "G", "R"],
                         rhs = [0.0, 1.0, -1.0, 2.0],
                         range_values = [0.0, 0.0, 0.0, -10.0],
                         names = ["c0", "c1", "c2", "c3"],)
>>> c.linear_constraints.get_rhs()
[0.0, 1.0, -1.0, 2.0]

where range_values is a list of floats, specifying the difference between lefthand side and righthand side of each linear constraint. If range_values[i] > 0 (zero) then the constraint i is defined as rhs[i] <= rhs[i] + range_values[i]. If range_values[i] < 0 (zero) then constraint i is defined as rhs[i] + range_value[i] <= a*x <= rhs[i]. I would suggest to leave it to default value (blank).

To define a sum just indicate all variables and vector of ones, e.g.,

NumCols = 10
vars = [ 'x'+str(n) for n in xrange(1,NumCols+1) ]
coef = [1]*NumCols
cpx.linear_constraints.add(
        lin_expr= [cplex.SparsePair(ind = vars, val = coef)] ,
        senses=["L"],
        rhs=[constantValue] )

Upvotes: 2

Related Questions