0

I'm solving an LP using pulp. I want to add constraints to my model. Most friendly way is :

model += lhs == rhs

When we want to add constraints using apply method in pandas.DataFrame, since lambda methods don't take += sign in them, we need to do something like this:

df['variable'].apply(lambda x: model.__iadd__(lhs==rhs))

Now, I don't want to use __iadd__() method directly, rather I want to make a function for this. What I'm trying to achieve is something like this:

`expression is our constraint`: lhs == rhs

def add_to_model(model, expression):
    return model.__iadd__(expression)

An example:

def add_to_model(model, x==0)
    return model.__iadd__(x==0)

Because in the above function, expression variable will be treated as Boolean, this is not serving the purpose. Any suggestions on how to achieve this?

mufassir
  • 406
  • 5
  • 16
  • "*def add_to_model(model, x==0)*" An expression as formal parameter? Not sure what that means. Must be a novel concept. – Erwin Kalvelagen Feb 20 '22 at 18:48
  • Expressions can't be lazily evaluated. You could store the expressions as strings and `eval()` them as you say, but it's not really clear why you want to store boolean expressions. They will always just evaluate to `True` or `False` so why not use those booleans? The effect is adding 1 or 0 to your model, but that doesn't seem particularly useful -- so it's not really clear what you're actually trying to do. – ddejohn Feb 20 '22 at 21:23
  • 1
    @ddejohn == is overloaded. Operator overloading allows PuLP to work. Instead of evaluating its builds a data structure that can be used to generate the complete LP/MIP later on. – Erwin Kalvelagen Feb 20 '22 at 22:28

1 Answers1

1

I suspect you should use LpProblem.addConstraint() to do this

https://github.com/coin-or/pulp/blob/d1ab490c156a7932aca44cfd346ec754fdda96bc/pulp/pulp.py#L1643

Stuart Mitchell
  • 1,060
  • 6
  • 7