Search code examples
pythonpython-3.xoptimizationcvxpyconvex-optimization

Remainder operation in cvxpy


Is there any built in function to compute the remainder of a variable in cvxpy? For instance, the following example code:

m = 3
n = 2
k = 5
A = cp.Variable((m,n),boolean=True)
B = np.ones((1,m))
C = np.ones(n)
constraints = []
objective = cp.Maximize((B@A%2)@C)
prob = cp.Problem(objective, constraints)
optimal_value = prob.solve()

gives error:

Exception has occurred: TypeError
unsupported operand type(s) for %: 'MulExpression' and 'int'

Because of the % operation


Solution

  • The remainder r = a mod n, with a ≥ 0, can be found as:

      a = q*n + r      (assume n is constant) 
      q ∈ {0,1,...}    (integer variable, non-negative}
      r ∈ {0,..,n-1}   (integer variable between 0 and n-1)
    

    This is just a linear constraint. See also: https://en.wikipedia.org/wiki/Modulo_operation.