我有一个CVXPY问题,定义了一个卷数组和一个成本数组来匹配每个卷。这个问题有我定义的192个变量和3个约束。
我的目标是在这个问题中最小化成本,以交付特定的体积,并避免多次获得0, 1, 0, 1
。
我当前的输出可能如下所示:
[0, 0, 1, 1, 0, 1... 0, 1, 0, 1]
理想的解决方案将避免一个量。因此,如果选择在某一点上是1,那么接下来的2点应该是0。例如:
[0, 0, 1, 1, 0, 0... 0, 1, 0, 0]
我不确定如何编写这样一个约束,以包括我的选择与我目前编程的问题,可以在这里看到:
import cvxpy as cp
import numpy as np
# Volume and cost
full_cost = [[0, data] for data in [0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45,0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4]]
cost_ = np.array(full_cost)
ex = np.array([[0, 17100] for data in [i for i in range(0, 96)]])
# Minimum volume required
v_min = 300000
# Selection variable
selection = cp.Variable(shape=ex.shape, boolean=True)
# Constraints
assignment_constraint = cp.sum(selection,axis=1) == 1
volume_= cp.sum(cp.multiply(ex,selection))
volume_constraint = volume_ >= v_min
cost_constraint = cp.sum(cp.multiply(cost_, selection))
constraints = [assignment_constraint, volume_constraint, cost_constraint]
cost_ = cp.sum(cp.multiply(cost_,selection))
# Problem definition
assign_problem = cp.Problem(cp.Minimize(cost_), constraints)
assign_problem.solve(solver=cp.CPLEX, verbose=True)
# Find solution in ex variable
assignments = [np.where(r==1)[0][0] for r in selection.value]
c = [ ex[i][assignments[i]] for i in range(len(assignments)) ]
best_volume = np.sum(np.multiply(ex,selection.value))
best_cost = np.sum(np.multiply(cost_,selection.value))
print(best_cost)
print(c)
我认为约束应该基于我的选择变量,但我正在努力看到如何将其包含为约束。
如果我理解正确的话看起来你想要施加条件
if x[i]==1 and x[i+1]==0 then x[i+2]==0
对于二元变量x
。这相当于
x[i+2] <= 1 - x[i] + x[i+1]