[英]How can I specify the objective in a CP-SAT formulation (in python) to be the minimization of the max of all decision variable values?
I am attempting to implement a simple CP-SAT where the objective is to minimize the largest value assigned across all decision variables.我正在尝试实现一个简单的 CP-SAT,其目标是最小化分配给所有决策变量的最大值。 I can minimize any individual variable or a linear function of variables, but it seems I am unable to minimize the maximum of variables.我可以最小化任何单个变量或变量的线性 function,但似乎我无法最小化变量的最大值。 Is there a way to achieve this?有没有办法做到这一点? Perhaps a way to linearize a max() function?也许是一种线性化 max() function 的方法?
Note: I do have constraints in my model, but I'm omitting them here as I do not believe they are relevant to my question.注意:我的 model 确实有限制,但我在这里省略了它们,因为我认为它们与我的问题无关。
from ortools.sat.python import cp_model
model = cp_model.CpModel()
num_vars = 50
variables = {}
for i in range(num_vars):
variables[i] = model.NewIntVar(0,i,'n_%i'% i)
The following line always results in an error, as does alternative arguments, eg, an iterator.以下行总是导致错误,替代 arguments 也是如此,例如,迭代器。
model.Minimize(max(variables))
I've discovered a solution to this problem.我发现了解决这个问题的方法。 I needed to declare a new decision variable, representing the objective value, and then I needed an AddMaxEquality constraint, equating the new variable to the max of other decision variables.我需要声明一个新的决策变量,代表目标值,然后我需要一个 AddMaxEquality 约束,将新变量等同于其他决策变量的最大值。 Finally, I pass the new objective variable to the model.Minimize() command.最后,我将新的目标变量传递给 model.Minimize() 命令。
obj = model.NewIntVar(0,num_vars,'obj')
# Impose a constraint equating the new variable to the max of other vars.
model.AddMaxEquality(obj, [variables[i] for i in range(num_vars)])
# Minimize objective.
model.Minimize(obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.