簡體   English   中英

cplex Python和約束

[英]cplex Python sum constraint

我剛開始使用cplex Python API,但在為模型創建linear_constraints遇到問題。

我想做這樣的事情:

dvar float+ x[]

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

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

我的問題是我不知道如何在Python API中進行約束

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

我需要在1)和2)中鍵入什么來獲得x[i]表的SUM,它也需要是一個決策變量?

這是一個例子:

>>> 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]

其中range_values是浮點列表,指定每個線性約束的左側和右側之間的差。 如果range_values [i]> 0(零),則約束i定義為rhs [i] <= rhs [i] + range_values [i]。 如果range_values [i] <0(零),則約束i定義為rhs [i] + range_value [i] <= a * x <= rhs [i]。 我建議將其保留為默認值(空白)。

要定義總和,只需指出所有變量和矢量,例如,

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] )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM