# Create constraint when variable is within a given range MILP

What is the best way to specify whether a given variable is within a given range in Pyomo? Here I have a binary decision variable assign[t, e] which I want to initialise with 0 when t is within some range specified as below. I read that this might not be the best way to do so and might cause solvers to violate this constraint. Is that the case?

def rule1(model, t, e):
if t < model.start[e] or t >= model.end[e]:
return model.assign[t, e] == 0
else:
return pyo.Constraint.Skip
model.rule1 = pyo.Constraint(model.times, model.elements, rule=rule1)
• Not a promo expert but can try using usual binary-MILP type constraint like b=0 if $a<x<b$. But are a,b, x continuous and positive? Nov 29, 2022 at 18:33
• @Sutanu sounds interesting. Can you elaborate more so I can get a better idea what do you mean? Nov 29, 2022 at 18:34
• Like this: or.stackexchange.com/questions/33/… Nov 29, 2022 at 18:36
• @Sutanu I meant by expanding on my code as I feel this is a Pyomo specific issue. (Does it work? Why doesn't it work? Alternative suggestion?) Nov 29, 2022 at 18:46

## 1 Answer

When you say:

initialise with 0 when t is within some range specified

I'm assuming you mean that you want to fix the variable to 0 given your code snippet. Instead of using a constraint for this I would recommend just fixing the variable using something like:

for t in model.times:
for e in model.elements:
if t < pyo.value(model.start[e]) or t >= pyo.value(model.end[e]):
model.assign[t,e].fix(0)

Also, it looks like you might have a typo in your constraint rule. You implemented model.end[w] but w is not defined.

• Very good suggestion. Do you know why my code does not work?In terms of fixing the variable. Does it make difference where do I “fix it“ or it should work as long as it is after the variable definition and before solving the model? Nov 29, 2022 at 19:15
• What do you mean by "does not work"? Are you seeing an error message? Is the solver not converging? Is the solution not what you expected? You can fix variables any time after the variable is defined and before the solver is called. Nov 29, 2022 at 19:18
• TypeError ‘>=’ not supported between instances on ‘int’ and ‘IndexedParam Nov 29, 2022 at 19:54
• Oh, you just need to use the pyo.value function to get the value of the params. I've updated the code snippet in my answer. Nov 29, 2022 at 20:55
• can I contact you over email? I feel your answer is correct but I need advise on it and don't want to spam the post. Nov 29, 2022 at 23:03