HELP: How to transform the continuous variable matrix x into binary variable x', and then create constraints about the summation of x' ?
Answeredsuch as I have a MVars x = [x1，x2, x3, x4]
i want create a constraint like: np.where(x>0, 1, 0).sum() > 5 , actually, i hope the count of nonzero vars must >= 5
How can I linearize this constraint?

oh, i've got a solution:
create y as a binary MVars
and x = bigM * y
y.sum() >= 5
0 
To linearize the constraint that the count of nonzero elements in the continuous variable matrix must be greater than or equal to 5, you can follow these steps using Gurobi:

Binary Variables: Introduce binary variables \(x_i'\)
for each \(x_i\) . Each will be 1 if \( and 0 otherwise. 
Linking Constraints: For each \(i\), add constraints to link \(
and \( . Since Gurobi does not support "not equal" directly in a linear model, you use a small tolerance \(\epsilon\) to define nonzero: \( where \(M\) is a sufficiently large number.
Here, \(M\) should be an upper bound on the possible values of \(x_i\)
(this can sometimes be set based on the problem context), and \(\epsilon\) is a small positive value, like \(10^{−5}\), assuming \(x_i\) cannot naturally be this small if it is considered "nonzero." 
Summation Constraint: Add a constraint that the sum of all binary variables \(x_i'\) should be greater than or equal to 5:
This way, you are enforcing that at least five of the \(x_i\) variables must be nonzero, translating that into a linear constraint suitable for Gurobi's solver. This method does not count how many are exactly zero but rather ensures at least a certain number are nonzero, which matches your requirements.
Here's a small example in Python using Gurobi:
import gurobipy as gp
from gurobipy import GRB
# Create a new model
m = gp.Model("model")
# Add continuous variables x1, x2, x3, x4
x = m.addVars(4, lb=GRB.INFINITY, name="x")
# Add binary variables x1', x2', x3', x4'
x_prime = m.addVars(4, vtype=GRB.BINARY, name="x_prime")
# Big M and small epsilon
M = 100
epsilon = 1e5
# Add linking constraints
for i in range(4):
m.addConstr(x[i] <= M * x_prime[i], name=f"link_upper_{i}")
m.addConstr(x[i] >= epsilon * x_prime[i], name=f"link_lower_{i}")
# Add summation constraint
m.addConstr(x_prime.sum() >= 5, "count_nonzero")
# Set objective (if any specific objective is needed)
m.setObjective(1, GRB.MAXIMIZE) # Dummy objective
# Optimize model
m.optimize()This code creates variables and constraints in a Gurobi model to ensure that at least five of the continuous variables x are nonzero according to the linearized constraint approach.
0 
Please sign in to leave a comment.
Comments
2 comments