I am doing an optimization problem for the filling and extraction of a warehouse. One of the constraints is that the filling volume cannot exceed a given limit for one day: For example, on the 3rd of April a maximum of 60 kg, on the 8th of May, 70 kg.

Using pandas I import the column with the maximum inventory profile for each day and impose the restriction as follows (For the lower limit I also have a profile that I impose for each day):

$$\sum_{i=0}^i X_i \le H_i$$ $$\sum_{i=0}^i X_i \ge L_i$$

m.addConstrs(sum(x[i] for i in dias)<=Hvol[i] for i in dias)

m.addConstrs(sum(x[i] for i in dias)>= Lvol[i] for i in dias)

Days is a list associated with the index $i$, representing each day. What python does is that the sum of 365 days is always less than $H_i$, instead of the sum up to day $i$ being less than $H_i$.

What python does: $$\min \sum_{i=0}^n X_i \le H_i$$ $$n=365$$ $$X_1+X_2+X_3+\ldots+X_{365} \le H_1$$

$$X_1+X_2+X_3+\ldots+X_{365} \le H_2$$

Instead of:

\begin{align}X_1&\le H_1\\X_1+X_2&\le H_2\\\cdots\end{align}


1 Answer 1


Firstly, your constraint should rather look this this: $$\sum_{j=0}^{i}X_j \leq H_i \quad \forall i \in I$$ $$\sum_{j=0}^{i}X_j \geq L_i \quad \forall i \in I$$

In your code this should translate to:

m.addConstrs(sum(x[j] for j in range(0,i))<=Hvol[i] for i in dias)

m.addConstrs(sum(x[j] for j in range(0, i))>= Lvol[i] for i in dias)

In case dias starts with index 1, then it should be range(1,i+1)

  • $\begingroup$ I'm getting an error again with what you are telling me: KeyError: 0 $\endgroup$
    – ADMGYP
    May 9, 2022 at 15:52
  • $\begingroup$ @ADMGYP Can you try to change range(i) to range(0,i+1)? Does dias start with 1 or 0? $\endgroup$
    – PeterD
    May 9, 2022 at 16:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.