在CPLEX python API

时间:2016-01-08 11:15:15

标签: python constraints linear cplex

线性程序:

Decision Variables:
x[]

Maximize:  Sum(i to n) (fare[i] * x[i])

subject to:
x[i] <= demand[i]

我正在尝试使用python在cplex中添加线性约束。

但无法使语法正确。困扰我一段时间。请忽略变量和值的硬编码。

fare = [400.0, 700.0, 600.0]
dmd= [2, 4, 3]
itins = []
for count in range(3):
        i = Itinerary(count, 1, dmd[count], fare[count])
        itins.append(i)


# problem variables
X=[] * len(itins)

def setupproblem(c):

    c.objective.set_sense(c.objective.sense.maximize)
    num_x = range(len(itins))
    print (num_x)

    varnames = ["X"+str(j) for j in range(len(itins))]
    c.variables.add(names = varnames, lb=[0.0, 0, 0], ub=[10.0, 10, 10])
    x = [c.variables.add(obj=fare)  for i in num_x]

 i_iten = range(len(itins))

    c.linear_constraints.add(lin_expr  = [cplex.SparsePair(ind = i_iten,
                                                     val = X[i])
                                          for i in range(len(itins) -1 )],
                             senses = ["L"],
                             rhs   = capacity,
                             names = ["capacity_"+str(i)
                                      for i in i_iten])

出现此错误:

raise CplexError(" %d: Invalid name -- '%s'\n" % tuple(self._mat))
cplex.exceptions.errors.CplexError:  1210: Invalid name -- 'X'

2 个答案:

答案 0 :(得分:2)

cplex.SparcePair中,您需要在val下指定非零元素,并在ind下指定相应的变量。另外,从您的线性程序中,您的右侧应为dmd

c.linear_constraints.add(lin_expr  = [cplex.SparsePair(ind = xname,
                                                 val = [1.0])
                                      for xname in varnames],
                         senses = ["L"],
                         rhs   = dmd,
                         names = ["capacity_"+str(i)
                                  for i in i_iten])

另外,我建议在添加变量时指明目标函数:

c.variables.add(obj = fare, names = varnames, lb=[0.0, 0, 0], ub=[10.0, 10, 10])

答案 1 :(得分:0)

c.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=[xname], val=[1.0]) for xname in varn], senses=["L"] * len(varnames), rhs=dmd)

但是在对变量添加约束之前,请记住应该将变量名添加到函数中。我花了4个小时四处走动才弄清楚出了什么问题。

这条线应该是第一位的。 c.variables.add(varnames)

感谢serge_k的初步指示!!