如果您使用set_quadratic
可分离的二次目标函数进行调用,则它对应于CPXXcopyqpsep。如果您使用不可分set_quadratic
的二次目标函数进行调用,则它对应于CPXXcopyquad。我同意你得到的错误并不是特别有用,但如果你知道它来自 Callable C Library 的哪里,它会更有意义。
话虽如此,这是一个完整的示例,使用您的代码段,并带有一些虚拟输入:
import cplex
class MockTarget(object):
pass
# Dummy data for testing
numB = 3
numQ = 3
deltas = [0.1, 0.1, 0.1]
problem = cplex.Cplex()
target = MockTarget()
target.v = [1, 2, 3]
# Build the problem
varCoefs = [1]*(numB + numQ)
varLower = [0]*(numB + numQ)
varNames = [(x,"b%s"%x) for x in range( numB )]
varNames += [(len(varNames) + x,"q%s"%x) for x in range( numQ )]
varCoefs += [10]*len(deltas)
varLower += [1]*len(deltas)
varNames += [(len(varNames) + x,"delta%s"%x) for x in range( len(deltas) )]
varCoefs += [0]*len(target.v)
varLower += [0]*len(target.v)
sContent = [(len(varNames) + x,"s%s"%x) for x in range( len(target.v) )]
varNames += sContent
varCoefs += [-1]
varLower += [0]
varNames += [(len(varNames),'mu')]
problem.variables.add(obj = varCoefs, lb = varLower)
problem.variables.set_names(varNames)
# Print without quadratic terms so you can see the progression.
problem.write('test1.lp')
# Separable Q
qsepvec = []
for tpl in varNames:
if tpl in sContent:
qsepvec.append(1.0)
else:
qsepvec.append(0.0)
print qsepvec
problem.objective.set_quadratic(qsepvec)
problem.write('test2.lp')
# Inseparable Q (overwrites previous Q)
qmat = []
for tpl in varNames:
if tpl in sContent:
sp = cplex.SparsePair(ind=[tpl[0]], val=[1.0])
qmat.append(sp)
else:
sp = cplex.SparsePair(ind=[], val=[])
qmat.append(sp)
print qmat
problem.objective.set_quadratic(qmat)
problem.write('test3.lp')
我已经把它写成很长的形式,而不是使用列表推导来使它更清楚一点。LP文件的内容如下:
测试1.lp:
\ENCODING=ISO-8859-1
\Problem name:
Minimize
obj: b0 + b1 + b2 + q0 + q1 + q2 + 10 delta0 + 10 delta1 + 10 delta2 + 0 s0
+ 0 s1 + 0 s2 - mu
Bounds
delta0 >= 1
delta1 >= 1
delta2 >= 1
End
测试2.lp
\ENCODING=ISO-8859-1
\Problem name:
Minimize
obj: b0 + b1 + b2 + q0 + q1 + q2 + 10 delta0 + 10 delta1 + 10 delta2 + 0 s0
+ 0 s1 + 0 s2 - mu + [ s0 ^2 + s1 ^2 + s2 ^2 ] / 2
Bounds
delta0 >= 1
delta1 >= 1
delta2 >= 1
End
测试3.lp
\ENCODING=ISO-8859-1
\Problem name:
Minimize
obj: b0 + b1 + b2 + q0 + q1 + q2 + 10 delta0 + 10 delta1 + 10 delta2 + 0 s0
+ 0 s1 + 0 s2 - mu + [ s0 ^2 + s1 ^2 + s2 ^2 ] / 2
Bounds
delta0 >= 1
delta1 >= 1
delta2 >= 1
End
您可以看到 test2.lp 和 test3.lp 是相同的(后者覆盖了前者,但做同样的事情)。希望这使它更容易理解。一般来说,使用这种打印出 LP 的技术来解决非常简单的问题,是更有用的调试技术之一。
您还应该查看 CPLEX 附带的 python 示例。例如,qpex1.py、miqpex1.py、indefqpex1.py。