2

I am totally new to pulp, and am wondering that if I need to optimize the following:

x = pulp.LpVariable.dicts("Volume", range(0, 7), cat='Binary')

where whenever there is a 0, it needs to be at least 3 of them.

so the solution can be [0,0,0,0,0,0,1], [0,0,0,1,0,0,0], [1,1,1,0,0,0,1] but not [1,0,1,0,1,0,0].

I tried to add a constraint as follows:

prob += min([len(list(g)) for k, g in itertools.groupby(x.values()) if k == 0]) >= 3

but it didn't work.

How can I formulate that?

1 Answer 1

5

No. PuLP is for linear programming, so all constraints need to be linear. So it is not allowed to use if statements and similar programming constructs.

The requirement to have at least three consecutive zeros can be expressed in different ways. One rather interesting way is to forbid patterns 101 and 1001. This can be stated as:

 x[i] - x[i+1] + x[i+2] <= 1             for i=0,1,2,....
 x[i] - x[i+1] - x[i+2] + x[i+3] <= 1    for i=0,1,2,....

These constraints very precisely exclude the patterns 101 and 1001 but allow any other bit pattern. In addition, they don't require any additional variables (some other approaches do).

As mentioned in the comments, what happens near the boundaries needs some attention. The precise implementation of this depends a bit on the details of the problem. Like is 01 or 001 allowed at the beginning and whether 10,100 is allowed at the end. So it is a bit difficult to show how this must be done (I would have to enumerate several possible scenarios).

In any case, this is easily expressed in Pulp.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice! Much more elegant than what I would've come up with. There might need to be a few additional constraints to prevent fewer-than-three-zeros and the start/end; such as [01...], [001...], and [...10], [....100].
Good point about these boundary issues. The question does not really address this. Often for the first period, I have historic data for periods -1,-2,.. I usually do not restrict the last period the way you suggest (unless we are looking for a steady-state solution).
@ErwinKalvelagen Is is possible that you help me on my question? thank you a lot math.stackexchange.com/questions/3920008/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.