Specifying complex constraints in cvxpy yields strict inequalities error

我的梦境 提交于 2021-01-29 08:11:30

问题


I am trying to recreate an integer linear optimization problem using cvxpy that I have outlined in Excel - . Note that this is a dummy example, the actual dataset will have thousands of variables. Please ignore the solution in cell K5 of the spreadsheet, as Excel Solver isn't able to provide integer solutions.

Consider that the 9 variables are split into 3 buckets. Note my goal with constraints 1-3 is that either there are at least 2 out of 3 1's for a bucket of variables, or all of the values are 0. For example, a,b,c should be either 1,1,1 or 1, 1, 0 or 1,0,1 or 0, 1, 1, or 0, 0, 0.

import numpy as np
import cvxpy as cp
import cvxopt 

coefs= np.array([0.7, 0.95, 0.3, 2, 1.05, 2.2, 4, 1, 3])

dec_vars = cp.Variable(len(coefs), boolean = True)

constr1 = np.array([1,1,1,0,0,0,0,0,0]) @ dec_vars == 2 * max(dec_vars[0:3]) 
constr2 = np.array([0,0,0,1,1,1,0,0,0]) @ dec_vars == 2 * max(dec_vars[3:6])
constr3 = np.array([0,0,0,0,0,0,1,1,1]) @ dec_vars == 2 * max(dec_vars[6:9])
constr4 = np.ones(len(coefs)) @ dec_vars >= 2

When I run up to here, I get a NotImplementedError: Strict inequalities are not allowed. error


回答1:


The core issue is your usage of python's max which is tried to be evaluated before reaching cvxpy. You cannot use just any python-native function on cvxpy-objects. max(cvx_vars) is not supported as is abs(cvx_vars) and much more.

There is max-function in cvxpy, namely: cp.max(...), but i don't get what you are trying to do or how you would achieve this by exploiting max. See below...

Note my goal with constraints 1-3 is that either there are at least 2 out of 3 1's for a bucket of variables, or all of the values are 0. For example, a,b,c should be either 1,1,1 or 1, 1, 0 or 1,0,1 or 0, 1, 1, or 0, 0, 0.

This, in general, needs some kind of disjunctive reasoning.

Approach A

The general approach would be using a binary indicator variable together with a big-M based expression:

is_zero = binary aux-var

sum(dec_vars) <= 3 * is_zero
sum(dec_vars) >= 2 * is_zero

Approach B

Alternatively, one could also model this by (without aux-vars):

a -> b || c
b -> a || c
c -> a || b

meaning: if there is a non-zero, there is at least one more non-zero needed. This would look like:

(1-a) + b + c >= 1
(1-b) + a + c >= 1
(1-c) + a + b >= 1


来源:https://stackoverflow.com/questions/65416823/specifying-complex-constraints-in-cvxpy-yields-strict-inequalities-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!