下面是一個例子:
>>> 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])
我建議你看看了隨CPLEX示例腳本(如lpex1.py,等等。)。 – rkersh