How to make the operation != in cvxpy?

67 Views Asked by At

I am currently working on cvxpy and I have the following constraint:

constraints.append(z[p][offices.index(office), offices.index(linked_office)]  != 3/M)

I need each value of z to belong to [0,3/M[ U ]3/M,1], how can I proceed ?

Here is the definition of my variable z, with e a matrix n*p which take values between 0 and M-1

    z = [] 
    for p in range(P):
        z.append(cp.Variable((n, n)))

    for p in range(P):
        for i in range(n):
            for j in range(n):
                constraints.append(z[p][i, j] >= 0)

    for p in range(P):
        for office in offices:
            for linked_office in linked_offices[office]:
                constraints.append(z[p][offices.index(office), offices.index(linked_office)]
                                   <= e[offices.index(office), p] / M)
                constraints.append(z[p][offices.index(office), offices.index(linked_office)]
                                   <= e[offices.index(linked_office), p] / M)
                constraints.append(z[p][offices.index(office), offices.index(linked_office)]
                                   >= e[offices.index(office), p] / M + e[offices.index(linked_office), p] / M - 1)
1

There are 1 best solutions below

5
A10 On

CVXPY doesn't explicitly allow for not equal to constraints, and instead the (simple) constraints it allows are ==, >= and <=, but that's okay! It just means you instead need to get a little tricky with how you formulate the problem.

For ease of notation, let's say we want to ensure that some value x is not equal to some value, N, say. In this case we can write our constraint of x != N as follows

eps = 1e-3 # may need to be tuned to your problem's precision
constraint = abs(x - N) >= eps

Where this will work if N is either an integer, or a floating point value.

So, for your problem you would need to modify your code to something like


# Will depend on the precision of your problem and the value of 3/M
# if you're using big M notation, I imagine 3/M is a very small float 
# and you may need to adjust eps
eps = 1e-3
constraint = abs(z[p][offices.index(office), offices.index(linked_office)] - 3/M) >= eps
constraints.append(constraint)

However, for more efficient constraint formulations for CVXPY, you may find this thread to be helpful