PuLP:将 LpVariable 或 LpAffineExpression 转换为整数
PuLP: casting LpVariable or LpAffineExpression to integer
在我的优化问题中,我有一个条件,即特定组中的项目数量 (LpInteger) 不得超过项目总数的百分比。为此,我编写了以下代码:
total = lpSum([num[i].varValue for i in ind])
for d in length:
# get list of items that satisfy the conditional
items_length_d = list(compress(items,[work[i]==work_group[d] for i in items]))
# use that list to calculate the amount of items in the group (an item can occur multiple times)
amount[d] = lpSum([num[dl] for dl in items_length_d])
max_d[d] = total*perc_max[d] + 1
min_d[d] = total*perc_min[d] - 1
prob += max_d[d] >= amount[d]
prob += min_d[d] <= amount[d]
这种方法的问题是我的最大值和最小值变成浮点数 (LpContinuous)。这反过来使解决方案 infeasible
。
如何确保每个 max_d 和 min_d 值都是整数? 最好,我也想四舍五入 max_d,同时截断 min_d。
编辑
我通过将 total = lpSum([num[i].varValue for i in ind])
更改为 total = lpSum([num[i] for i in ind])
解决了 infeasible
解决方案的问题。但是,最小值和最大值仍然是浮点数。如果有人知道如何将这些转换为整数,仍然会非常感激答案。
您似乎误解了构造和求解线性规划问题的原理。
应该设置整个问题,然后求解并提取解值。
设置问题时无法获取变量的LpVariable.varValue。
所以对于分数约束,如果我们将组定义为 i /in G,然后将总数定义为 i /in T
我们得到 f 是所需的分数
如果重新排列这个等式。
所以在你的代码中
prob += perc_max[d] * lpSum([num[i] for i in ind]) <= lpSum([num[dl] for dl in items_length_d])
在我的优化问题中,我有一个条件,即特定组中的项目数量 (LpInteger) 不得超过项目总数的百分比。为此,我编写了以下代码:
total = lpSum([num[i].varValue for i in ind])
for d in length:
# get list of items that satisfy the conditional
items_length_d = list(compress(items,[work[i]==work_group[d] for i in items]))
# use that list to calculate the amount of items in the group (an item can occur multiple times)
amount[d] = lpSum([num[dl] for dl in items_length_d])
max_d[d] = total*perc_max[d] + 1
min_d[d] = total*perc_min[d] - 1
prob += max_d[d] >= amount[d]
prob += min_d[d] <= amount[d]
这种方法的问题是我的最大值和最小值变成浮点数 (LpContinuous)。这反过来使解决方案 infeasible
。
如何确保每个 max_d 和 min_d 值都是整数? 最好,我也想四舍五入 max_d,同时截断 min_d。
编辑
我通过将 total = lpSum([num[i].varValue for i in ind])
更改为 total = lpSum([num[i] for i in ind])
解决了 infeasible
解决方案的问题。但是,最小值和最大值仍然是浮点数。如果有人知道如何将这些转换为整数,仍然会非常感激答案。
您似乎误解了构造和求解线性规划问题的原理。
应该设置整个问题,然后求解并提取解值。
设置问题时无法获取变量的LpVariable.varValue。
所以对于分数约束,如果我们将组定义为 i /in G,然后将总数定义为 i /in T
我们得到 f 是所需的分数
如果重新排列这个等式。
所以在你的代码中
prob += perc_max[d] * lpSum([num[i] for i in ind]) <= lpSum([num[dl] for dl in items_length_d])