集合中的CVXPY等式约束

时间:2019-03-14 19:40:15

标签: python optimization constraints cvxpy

我有一个ILP问题,我需要将变量矩阵的值约束在{0,1}中。我尝试使用以下(简化)代码进行此操作,但不允许我使用“ |”操作员。我该怎么办?

def test_ILP(scores):
    N = scores.shape[0]
    eye_bool = np.eye(N)
    zero_when_equal = np.abs(np.eye(N) - 1)


    opt = cp.Variable(scores.shape)
    objective = cp.Maximize(
        cp.sum(cp.multiply(scores, opt * zero_when_equal))
    )


    constraints = [(opt == 0) | (opt == 1) | eye_bool]

    prob = cp.Problem(objective, constraints)
    prob.solve()
    return opt.value

1 个答案:

答案 0 :(得分:0)

基于@sascha的注释,对于布尔(或整数)约束,可以在Variable构造函数中使用该参数。对于这种情况:

def test_ILP(scores):
    N = scores.shape[0]
    eye_bool = np.eye(N)
    zero_when_equal = np.abs(np.eye(N) - 1)
    boolean_constraint = [(x, y) for x in range(N) for y in range(N) if x != y]

    opt = cp.Variable(scores.shape, boolean=boolean_constraint)
    objective = cp.Maximize(
        cp.sum(cp.multiply(scores, opt * zero_when_equal))
    )


    constraints = [#Rest of the constraints]

    prob = cp.Problem(objective, constraints)
    prob.solve()
    return opt.value