简体   繁体   English

添加约束 CPLEX Python API

[英]Adding constraints CPLEX Python API

The data that I am handling is not as simple as the ones in the documentation.我正在处理的数据并不像文档中的数据那么简单。 As my variables basically depends on the data input file, I will use the following simple example to explain what I am trying to achieve.由于我的变量基本上取决于数据输入文件,我将使用以下简单示例来解释我要实现的目标。 I have following constraints:我有以下限制:

x1 + x2 + x3 = 1
x4 + x5 + x6 + x7 =1
x8 + x9 = 1

I am thinking of using a for loop to repeatedly call the c.linear_constraints.add() function.我正在考虑使用 for 循环重复调用c.linear_constraints.add()函数。 Is there a better way in doing this?有没有更好的方法来做到这一点?

In general, you'll get better performance if you create batches of linear constraints rather than creating them one at a time.一般来说,如果您创建一批线性约束而不是一次创建一个,您将获得更好的性能。 For example (using your example above), it's better to do the following:例如(使用上面的示例),最好执行以下操作:

import cplex
c = cplex.Cplex()
c.variables.add(names=["x{0}".format(i+1) for i in range(9)])
c.linear_constraints.add(lin_expr=[[[0, 1, 2], [1.0, 1.0, 1.0]],
                                   [[3, 4, 5, 6], [1.0, 1.0, 1.0, 1.0]],
                                   [[7, 8], [1.0, 1.0]]],
                         rhs=[1.0, 1.0, 1.0],
                         names=["c{0}".format(i+1) for i in range(3)])
c.write("example.lp")

This produces the following LP file:这将生成以下 LP 文件:

Minimize
 obj:
Subject To
 c1: x1 + x2 + x3  = 1
 c2: x4 + x5 + x6 + x7  = 1
 c3: x8 + x9  = 1
End

So, it would be better to read in your input file, save the constraint information in some data structure (lists or whatever), and then call c.linear_constraints.add once at the end (or every X constraints if your input file is very large).因此,最好读入您的输入文件,将约束信息保存在某些数据结构(列表或其他)中,然后在最后调用c.linear_constraints.add一次(如果您的输入文件非常大的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM