Python cvxpy-重用一些约束

问题描述

我目前正在使用cvxpy优化一个非常大的问题,但现在面临当前问题。 我运行求解器的多次迭代(每次迭代都会降低某些变量的灵活性)。 每次运行总共有50个约束,其中每次运行只有2个不同。其余48个约束条件相同。 在每次迭代期间,我从头开始重建这两个约束,问题和obj函数。 如果我不重建其余(相同)的48个约束,那么最终的解决方案将毫无意义。

我阅读了这篇文章CVXPY: how to efficiently solve a series of similar problems,但就我而言,我不需要更改参数并重新进行优化。

我只是设法准备了一个显示此问题的示例:

    x = cvx.Variable(3)
    y = cvx.Variable(3)

    tc = np.array([1.0,1.0,1.0])
    constraints2 = [x >= 2]
    constraints3 = [x <= 4]
    constraints4 = [y >= 0]
    
    for i in range(2):
        if i == 0:
            constraints1 = [x - y >= 0]
            
        else:
            x = cvx.Variable(3)
            y = cvx.Variable(3)
            constraints1 = [x + y == 1,x - y >= 1,x - y >= 0,x >= 0]
    
        
        
        constraints = constraints1 + constraints2 + constraints3 + constraints4
        # Form objective.
        obj = cvx.Minimize( (tc.T @ x ) - (tc.T @ y ) )
        
        # Form and solve problem.
        prob = cvx.Problem(obj,constraints)
        prob.solve()
        

        solution_value = prob.value
        solution = str(prob.status).lower() 
        print("\n\n** SOLUTION:  {}     Value: {} ".format(solution,solution_value))
        print("* optimal (x + y == 1) dual variable",constraints[0].dual_value)
        print("optimal (x - y >= 1) dual variable",constraints[1].dual_value)
        print("x - y value:",(x - y).value)
        print("x = {}".format(x.value))
        print("y = {}".format(y.value))

如您所见,constraints2要求x向量中的所有值都大于2。constraints2在两次迭代中都添加到求解器中使用的“ constraints”。 第二种解决方案应为您提供小于2的向量x值。 为什么?如何避免这个问题? 谢谢

解决方法

您需要使用linked post中所述的参数。假设您有约束rhs >= lhs,该约束有时会使用,而有时不使用,其中rhslhs的尺寸为m x n。编写以下代码:

param = cp.Parameter((m,n))
slack = cp.Variable((m,n))
param_constraint = [rhs >= lhs + cp.multiply(param,slack)]

现在要关闭约束,设置param.values = np.ones((m,n))。要打开约束,请设置param.values = np.zeros((m,n))。您可以通过将param的某些条目设置为1,将其他条目设置为0,来打开/关闭约束的某些条目。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...