Decision Optimization

Decision Optimization

Delivers prescriptive analytics capabilities and decision intelligence to improve decision-making.


#Analytics
#DecisionOptimization
#DecisionOptimization
 View Only
Expand all | Collapse all

How to model simple constraints x_{kn} <= y_n in Python with CPLEX

  • 1.  How to model simple constraints x_{kn} <= y_n in Python with CPLEX

    Posted 11/28/16 03:20 PM

    Originally posted by: Zoubeir


    I have a simple constraints of the form

     

    x_{kn} <= y_n for all k, n
    

    I need to write this in Python. I did this

     

    
    import cplex
    x = []
    y = []
    xy = []
    
    for n 
    in 
    range(
    N):
        yname = 
    "y_" + 
    str(n)
        y.append(yname) 
    for k 
    in 
    range(
    K):
            xname = 
    "x_" + 
    str(k) + 
    str(n)
            
    x.append(xname)
    xy.append(
    x)
    xy.append(y)
    prob.variables.add(
    names=y, 
    lb=[
    0] * 
    len(y), 
    ub=[
    1] * 
    len(y), 
    types=[
    "B"] * 
    len(y), 
    obj=[
    1] * 
    len(y))
    prob.variables.add(
    names=
    x, 
    lb=[
    0] * 
    len(
    x), 
    ub=[
    1] * 
    len(
    x), 
    types=[
    "B"] * 
    len(
    x))
    
    for k 
    in 
    range(
    K):    
       for n 
    in 
    range(
    N):
            prob.linear_constraints.add(
    lin_expr=[cplex.SparsePair(
    x[n][k]-y[n], [
    1])], 
    senses=[
    "L"], 
    rhs=
    0)
    

    I get an error message

     

    prob.linear_constraints.add(lin_expr=[cplex.SparsePair(x[n][k]-y[n], [1])],
    TypeError: unsupported operand type(s) for -: 'str' and 'str'
    

     


    #CPLEXOptimizers
    #DecisionOptimization


  • 2.  Re: How to model simple constraints x_{kn} <= y_n in Python with CPLEX

    Posted 12/06/16 12:41 AM

    Maybe take a look at the various Python examples that are shipped with CPLEX and at the reference manual.

    The correct code to add your constraint is

    prob.linear_constraints.add(lin_expr = [cplex.SparsePair([ x[n][k], y[n] ], [1, -1])], senses = ['L'], rhs = [0.0])
    

     


    #CPLEXOptimizers
    #DecisionOptimization