简体   繁体   English

如何在PuLP中添加逻辑约束

[英]How to add Logical constraints in PuLP

I am trying to solve FLP using PuLP. 我正在尝试使用PuLP解决FLP。 I want to add logical constraint for variable value. 我想为变量值添加逻辑约束。

I have LpVariable f and C is list of LpVariables . 我有LpVariable f,C是LpVariables的列表。 I want to add f to the constraint of problem and which depends on values of c[i]. 我想将f添加到问题的约束中,这取决于c [i]的值。

Below is code snippet > 以下是代码段>

prob = LpProblem("The MILP problem", LpMinimize)

Added 1st constraint : 添加了第一个约束:

prob += lpSum(c[i] for i in range (len(c))) == 2

Now I want to add following constraint: 现在,我想添加以下约束:

  if`lpSum(c[i] for i in range (len(c))) > 1:
`     prob += f == 1  
  else:
      prob += f == 0


prob += lpSum(c[i] for i in range (len(c)) + f )

Now problem is LpVariables c[i] are initialized with None and hence it throws error while calculating lpSum() . 现在的问题是LpVariables c [i]被初始化为None ,因此在计算lpSum()时抛出错误。

I hope I am clear. 我希望我清楚。 Let me know if need any help in understanding this query but I think given code snippet is sufficient enough. 让我知道是否需要任何帮助来理解此查询,但我认为给定的代码片段就足够了。

Three points: 三点:

(1) Your first constraint forces the lpsum to be equal to 2, so f will always be 1 in your example - are you sure your formulation is correct? (1)您的第一个约束迫使lpsum等于2,因此在您的示例中f始终为1-您确定公式正确吗?

(2) If statements can't be used in combination with the lpSum - you should formulate it as an actual constraint. (2)如果语句不能与lpSum结合使用-您应将其公式化为实际约束。

For example, you could define f as a binary variable and add this constraint: 例如,您可以将f定义为二进制变量并添加以下约束:

prob += lpSum(c[i] for i in range (len(c))) - 1 <= M*f 

where M is a sufficiently large number. 其中M是足够大的数字。 Then, if f==0 we have that "lpsum() <= 1" and if f==1 we have that lpsum can be anything. 然后,如果f == 0,则我们的“ lpsum()<= 1”;如果f == 1,则我们的lpsum可以是任何值。 Play around with that type of constraints to get f to behave the way you want. 尝试使用这种约束,使f表现出所需的行为。

(3) The constraint "prob += lpSum(c[i] for i in range (len(c)) + f )" does nothing unless it's supposed to be the objective of your MILP? (3)约束“ prob + = lpSum(c [i] for i in range(len(c))+ f)”不做任何事情,除非它被认为是您的MILP的目标? If so, you should add it immediately after prob = LpProblem("The MILP problem", LpMinimize) 如果是这样,您应该在prob = LpProblem(“ MILP问题”,LpMinimize)之后立即添加它

Good luck 祝好运

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

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