[英]Constraint Programming, how to add x[i] <= (max(x[:i]) + 1)
I'm building a model using or-tools CP tools.我正在使用 or-tools CP 工具构建一个 model。 The values I want to find are placed in a vector X, and I want to add a constraint that says up to each position of X
, the next position cannot have as a value something bigger than the maximum found until X[:i] + 1
我想找到的值放在向量 X 中,我想添加一个约束,表示X
的每个 position,下一个 position 的值不能大于X[:i] + 1
之前找到的最大值X[:i] + 1
It would be something like this:它会是这样的:
X[i] <= (max(X[:i]) + 1)
Of course, I cannot add this as a linear constraint with a max()
, and creating one extra feature for each value of X upper bound seems excessive and also I would need to minimize each one to make it the "max", otherwise those are just upper bounds that could be huge and not prune my search space (and I already have an objective function).当然,我不能将其添加为带有max()
的线性约束,并且为 X 上限的每个值创建一个额外的特征似乎过多,而且我需要最小化每个特征以使其成为“最大”,否则那些只是上限可能很大并且不会修剪我的搜索空间(而且我已经有一个目标函数)。
I already have an objective function.我已经有一个目标 function。
I know that one trick to add for instance a min-max ( min(max(x[i])
) problem is to create another variable that is an upper bound of each x and minimize that one. It would be sth like this:我知道添加最小 - 最大( min(max(x[i])
)问题的一个技巧是创建另一个变量,它是每个 x 的上限并最小化那个。它会是这样的:
model = cp_model.CpModel()
lb =0; ub=0
model.NewIntVar(z, lb, ub)
for i in domain(X):
model.NewIntVar(X[i], lb, up)
model.Add(X[i] <= z)
model.Minimize(z)
In case you don't want to program this you can use the method in or-tools:如果您不想对此进行编程,您可以使用 or-tools 中的方法:
model.AddMaxEquality(z, X)
Now I want to add a constraint that at each value of X sets an upper limit which is the maximum value found until the previous x.现在我想添加一个约束,在 X 的每个值处设置一个上限,该上限是在前一个 x 之前找到的最大值。 It would be something like this:它会是这样的:
X[i] <= max(X[:i]) + 1
I was thinking of replicating the previous idea but that would require creating a "z" for each x... not sure if that is the best approach and how much it will reduce my space of solutions.我正在考虑复制以前的想法,但这需要为每个 x 创建一个“z”……不确定这是否是最好的方法以及它会减少多少我的解决方案空间。 At the same time couldn't find a method in or-tools to do this.同时无法在 or-tools 中找到执行此操作的方法。
Any suggestions, please?有什么建议吗?
PS: I already have as an objective function min(z)
like it is in the example presented. PS:我已经有一个目标 function min(z)
就像它在给出的例子中一样。
Example:例子:
For instance, you can have as a result of the model: [0, 1, 2, 0, 2, 3]
例如,您可以得到 model 的结果: [0, 1, 2, 0, 2, 3]
But you shouldn't have:但你不应该:
[0, 1, 1, 2, 4]
Since the max until X[:3]
is 2, so the ub of X[4]
should be 2 + 1. [0, 1, 1, 2, 4]
因为X[:3]
之前的最大值是 2,所以X[4]
的 ub 应该是 2 + 1。
Thanks!谢谢!
I have no specific hints except:我没有具体的提示,除了:
X
the array of variables and M
the array of max, ie M[i] = max(X[0], .., X[i - 1])
确保在索引 i - 1 处重复使用 max 变量X
是变量数组, M
是 max 数组,即M[i] = max(X[0], .., X[i - 1])
M[i] = max(M[i - 1], X[i - 1])
X[i] <= M[i] + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.