Technical

Solving it as a MIP — PuLP and CBC

The same candidate table, this time with real optimisation: binary decision variables, opening routes, the minimum shipment. A better total; a time limit and set-up cost thrown in.

Block Transfer · 5 / 7

The last article found 90.9% of the value the solver finds with an SQL query and a short loop. Now we look at what it takes to get the remaining 9.1%: about forty lines of Python and a free solver.

Let me say up front, though, that the real subject of this article is not that 9.1%. One of the last sentences of the previous article was this: we know it is 90.9%, because we built the other one as well and measured it. That is what building the model really pays you: you learn how big your loss is. The part that comes back as profit is a bonus; mind you, this week the bonus is not small either: TRY 3,253,435.

PuLP: writing the maths in Python

Solvers want the model in a standard format; nobody writes that format by hand. A modelling language sits in between. On the Python side the most common one is PuLP:

pip install pulp

That’s it. The solver (CBC, COIN-OR’s open-source branch-and-bound engine) comes in the box too; no separate licence, server or installation. The whole model is set up as below, and above each piece I put the formula from the third article so that you can see the translation.

Variables. xijo∈{0,1}x_{ijo} \in \{0, 1\} for every candidate move, yij∈{0,1}y_{ij} \in \{0, 1\} for every route:

model = pulp.LpProblem("block_transfer", pulp.LpMaximize)
x = {i: pulp.LpVariable(f"x_{i}", cat="Binary") for i in candidates.index}
routes = sorted(set(zip(candidates.donor, candidates.receiver)))
y = {r: pulp.LpVariable(f"y_{r[0]}_{r[1]}", cat="Binary") for r in routes}

Objective function. max⁡∑wijoxijo−R∑yij\max \sum w_{ijo}x_{ijo} - R\sum y_{ij}:

model += (
    pulp.lpSum(candidates.loc[i, "w"] * x[i] for i in candidates.index)
    - p.route_fixed_cost_try * pulp.lpSum(y.values())
)

Constraint 1: a block goes to one destination. ∑jxijo≤1\sum_j x_{ijo} \le 1:

for (donor, option), group in candidates.groupby(["donor", "option_id"]):
    model += pulp.lpSum(x[i] for i in group.index) <= 1          # a block goes to one destination

Constraint 2: capacity at the receiving store. ∑sioxijo≤Qj\sum s_{io}x_{ijo} \le Q_j:

for receiver, group in candidates.groupby("receiver"):
    model += (
        pulp.lpSum(int(candidates.loc[i, "units"]) * x[i] for i in group.index)
        <= capacity.get(receiver, 0)
    )

Constraints 3 and 4: opening a route, and the minimum shipment. xijo≤yijx_{ijo} \le y_{ij} and ∑osioxijo≥Kyij\sum_o s_{io}x_{ijo} \ge K y_{ij}:

for r, group in candidates.groupby(["donor", "receiver"]):
    for i in group.index:
        model += x[i] <= y[r]                                    # no move without an open route
    model += (
        pulp.lpSum(int(candidates.loc[i, "units"]) * x[i] for i in group.index)
        >= p.min_route_units * y[r]                              # an open route fills a shipment
    )

That’s all. The formulas and the code match line for line; what PuLP does is collect the lines you add with += and turn them into a form the solver understands.

A one-line lesson: sorted

There is a small detail in the variables block above:

routes = sorted(set(zip(candidates.donor, candidates.receiver)))

That sorted was not there at first. It was added in code review, and this is why: in Python, the order in which a set is iterated can change from run to run. When the order changes, the order of the variables in the model file changes; and when the order of the variables changes, if there are several best solutions of equal value, the solver returns one of them one time and another the next.

Mathematically both are right; they earn the same money. But for Ali, who gets the report on Monday morning, being right is not enough: a system that said “take it from Malatya” last week saying “take it from Kayseri” this week on the same data is the end of its credibility. In the last article, adding the donor, receiver, option_id tail to the greedy loop’s ranking solved the same problem. Determinism is not a matter of maths but of trust, and it has to be handled separately in each method.

After I wrote this article a second instance of the same lesson turned up, so I am adding it here: sorted on its own was not enough. The SQL queries that produced the candidate table had no order by, and DuckDB does not have to return rows in the same order on every run. When the order changed the names of the variables changed, and when the names changed the solver again landed on a different optimum of equal value: over three runs in a row the objective came out the same to the last kuruş while every run had twenty or so moves in the plan that were different. Sorting the candidate table closed the problem; that is where the order by on the last line of the last article’s query comes from. The lesson: determinism is not secured in one place, it is secured along the whole chain from the data to the solution. And when you miss it somewhere, it comes back to you not as an error but as “last week it said something else”.

Solving it and reading the answer

model.solve(pulp.PULP_CBC_CMD(
    msg=0,
    threads=0,
    gapRel=p.mip_gap_rel,
    timeLimit=p.mip_time_limit_s,
    maxNodes=p.mip_node_limit,
    logPath=log_path,
))

msg and logPath are about what the solver writes; each of the other four settings has a story.

gapRel tells the solver when to stop: when the gap between the plan in hand and the upper bound falls below 0.5%. So we are not saying “find the best”, we are saying “stop the moment you have proven you are close enough to the best”.

maxNodes and timeLimit are safety limits, and the difference between them is the determinism lesson again. A time limit depends on the speed of the machine: a fast computer opens more branches in the same time and finds a different plan. A node limit does not depend on the machine; so it is set to bind before the time limit. A model that hits the safety net then gives the same plan whichever computer it runs on. threads=0 is there for the same reason: parallel search on the same input hung on some runs and crashed on others; serial search walks the same path every time.

There is one thing we deliberately did not do: we did not give the solver the greedy plan as a starting point. We tried; in this version of CBC that path was broken, and once fixed it made the models that hit the limit worse.

When the solver stops, we also have to read from it what it found:

# PuLP's `solve()` return (LpStatus) is LpStatusOptimal also for a CBC run that
# stopped at the time or node limit with a feasible solution: "optimal" does not
# mean proof. The proof is carried by the solution status (`sol_status`).
STATUSES = {
    pulp.LpSolutionOptimal: "optimal",          # within the gap tolerance (see solve)
    pulp.LpSolutionIntegerFeasible: "limit",    # stopped at a safety limit, best feasible solution
}
status = STATUSES.get(model.sol_status, "error")

These three paths are the part most often neglected when a solver is put into production. The solver does not always say “I found the best”:

  • optimal: the solver stopped within the tolerance. The plan is at most 0.5% from the best plan; how far exactly we read from the last upper bound in the log. It does not mean proven best.
  • limit: a safety limit ran out. There is a solution in hand and it is probably good, but it has not even been proven to be within the tolerance.
  • error: the solver could not produce an answer.

It is very easy to fall into this trap: code that looks at what solve() returns will quietly call plans cut off at the time limit “best” too. The right information is in sol_status.

The greedy method has no such distinction; it always gives a list. One of the costs of building a model is that you have to handle this uncertainty in the code. If you don’t, one day the time runs out and you are left with a plan that quietly stopped halfway, and on top of that your report calls it “optimal”.

Exactly where the MIP wins

In the last article we saw that nearly all the difference came from the choice of stock: only TRY 11,000 of the TRY 3,253,435 came from routes. Even so, routes are the visible face of the job. The solver moves more blocks with fewer shipments, and that becomes visible when you look at how many options each route carries:

Options moved on the routeGreedySolver
1268194
23372
3816
479
Total routes340318

The table shows only the first four rows; the tail is long in both plans, and the fullest route carries 17 options in both. In the greedy plan 268 shipments are opened to move a single option. In the solver’s it is 194. The solver moves more stock with fewer lorries, because the −R∑yij-R\sum y_{ij} term in the objective function tells it every new route costs TRY 500. The greedy loop has no such term, and cannot have one: since the loop does not see the next move, it cannot think “if I put this here, the lorry was going anyway”.

A concrete example, one of the solver’s fullest routes:

Kayseri 1 → Izmir 1 · 17 options · 5,722 units

  MDL0540-BGE   569 units   in the greedy plan: Kayseri 1 → Istanbul 2
  MDL0541-TER   236 units   in the greedy plan: Kayseri 1 → Ankara 2
  MDL0543-KHK   478 units   in the greedy plan: Kayseri 1 → Istanbul 2
  MDL0544-IND   372 units   in the greedy plan: Kayseri 1 → Istanbul 2
  MDL0544-GRN   280 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0551-ECR   250 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0551-KHK   233 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0554-BUR   388 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0555-BUR   363 units   in the greedy plan: Kayseri 1 → Istanbul 3
  MDL0556-TER   202 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0557-BLK   607 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0576-BUR   127 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0576-TER   189 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0582-IND   147 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0597-NVY   165 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0601-NVY   597 units   in the greedy plan: Kayseri 1 → Izmir 1
  MDL0603-GRN   519 units   in the greedy plan: Kayseri 1 → Istanbul 3

The solver puts these seventeen blocks on a single lorry; the greedy method spread the same blocks across four different receiving stores: 11 of them to Izmir 1 again, the rest to Istanbul 2, Istanbul 3 and Ankara 2. Note that the greedy method is not doing anything wrong; it sends each block to the best destination left when its turn comes. Why the solver pulls those six blocks to Izmir 1, though, you cannot read off by looking at one route. The route cost may be one reason; leaving the room at the two Istanbul stores for other blocks may be another. The solver never chooses any move on its own, and that will cause us trouble at the end of the article.

There is one more result the table does not show: of the 571 blocks the two plans move in common, the receiving store is different in 193; the solver also places 90 blocks greedy never touched. So the solver does not just reorder greedy’s plan on the cheap; it builds from scratch both which stock moves and who sends to whom.

Where does the solver stop?

In the third article I wrote that this model has 7,730 binary variables, which by brute force means 27,7302^{\text{7,730}} possibilities. I also explained why the solver finishes it in under a minute: branch and bound. Now let’s measure it.

Let’s solve the model twice. First letting the variables be fractions between 0 and 1 (the LP relaxation), then in its real form:

Value
LP relaxation (upper bound)TRY 36,255,104.44
Integer solution (the MIP plan)TRY 35,934,123.10
The gap between themTRY 320,981.34 (0.89%)

Solving the relaxation takes far less time than the integer model. The number it gives is a ceiling: no integer plan can beat TRY 36,255,104.44. In the relaxed solution 105 of the 5,369 xx variables and 56 of the 2,361 yy variables come out fractional; the solver is saying “send half this block, open this route halfway”. Between the ceiling and the plan in hand there is a gap of 0.89%; the rest of the time goes into closing it.

By branching, the solver pulls the ceiling down. When it stops, its last upper bound is TRY 35,997,742.47: it has closed TRY 257,361.97 of the gap the LP left. The plan in hand is 0.18% below that bound; the tolerance is 0.5%, so it stops there. That is why nowhere in this article do I say “the best plan”. The honest sentence is: this plan is at most 0.18% from the best possible plan. It may be the very best; proving it would mean running the solver longer, and we did not spend that time for an improvement of 0.18% at most.

Not every MIP behaves itself

Do not conclude from this that “solvers are always fast”. This model stopped within the tolerance at the reference setting, but turn the dial and that no longer holds. Of the six threshold settings we will compare at the end of the series, in four the solver hit the node limit we set as a safety net and came back with the limit flag. Those plans are somewhere between 1.33% and 5.24% from the optimum at most; they all still earn more than greedy, but we do not know where in that range the true best lies.

What makes a MIP hard is more or less known; two of those things are in this data. The candidate set grows: as the ceiling on the receiving side opens, rails that are not broken can become receiving stores too. Capacities bind: 12 of the 80 stores have no room at all; of the blocks with a positive score left out of the reference plan, 194 do not fit in the remaining room at their receiving store. The more the constraints lock one another, the slower the ceiling comes down.

In that situation the thing to do is not to throw the solution away but to learn to work with the limit flag: the solution is good, it is not proven, and the report should say so. Our report writes the status and the gap next to every MIP line. In your data this is most likely where it will be hard: explaining the solver’s “limit” to the person who will use the plan not as “wrong” but as “unproven”.

An honest account of the cost

PuLP is free, CBC is free, a run takes under a minute. More than a thousand times greedy’s 39.7 ms, but nothing at all for a Monday morning. So why is there a debate at all?

Because the real cost is neither in the licence nor in the time. When the person who built the model leaves, what is left behind is not forty lines of Python but nobody knowing why those lines are the way they are. Who will update the constraint when the definition of capacity changes, why the results shift a notch when the solver version goes up, whether to use the plan in a week that comes back with limit, and hardest of all: the answer to give when a store manager asks “why did you take my stock?”

With the greedy method that answer is one line: “it was the highest-scoring match.” With the solver the honest answer is: “the plan chosen was at most 0.18% behind the best of all the plans that met the constraints.” A true answer, but not a persuasive one, because there is no such thing as a reason for a single move; the moves are chosen as one connected whole. That is the most common reason optimisation projects end up on the shelf: not technology, but trust.

In the next article we will put the two methods side by side on every measure: money, time, set-up, explainability. A result came out there that I did not expect: switch to the plan that turns the dial and grows the money by two-thirds, and the share of empty-handed customers rescued barely moves 🙂

By Sabri Suyunu