Hello
I want to add a constraint that says the number of nonzero elements of a variable couldn’t be more than a certain value.
So following constraints passed through my mind (By defining an extra variable counting nonzero elements of a variable called “attack”):

Optimization programs are not sequentially executed as your usual codes. Therefore when you say attack(bus)=0, it makes no sense to the program because attack(bus) does not have any value until it is solved. With such a condition, it is not possible to create defined equation blocks beforehand that can be passed on to the solver.

A common technique to address this is big-M constraints. Is attack a binary variables? if yes, you can do it by simply sum(bus, attack(bus)) =l= 2;

If it is not, you have to define a binary variable (say y(bus))which is 1 if attack(bus) is nonzero and 0 otherwise. You can then impose a constraint sum(bus, y(bus)) =l= 2;

To connect y(bus) and attack(bus) you use big-M constraint

attack(bus) =l= M*y(bus);

where M is a big constant (not too big). Better read about formulating big-M constraints before doing this.

Hello, thank you for your answer. Attack is not a binary variable, and as I wrote, I had tried to define a binary variable related to attack, but nonlinear solvers threw the error.

Two issues. Even if you define a binary variable using $(binary_variable eq 0) is not allowed. Second, if you have defined binary variables, you should then be using a MIP or MINLP solver instead of an NLP solver.

Hope this helps. If none of the above two issues are relevant, provide exact constraints and variables that you defined and the error message that you get.