SQL for the candidates, greedy for the decision
How the trade does it today: DuckDB SQL finds the candidate pairs, and a greedy match in score order makes the decision. Easy to write, an answer in every case, and the price is shown too.
Block Transfer · 4 / 7
In the previous article we built a mixed integer programme with 7,730 binary variables. Now let me confess something: most of the chains I have seen in the field do not solve this problem that way. They write SQL. A query, a ranking, a loop.
This article is not a defence of that method but a recipe for it. Before the recipe, though, I have to say this, because articles about optimisation usually skip it and are unfair as a result: solving it with SQL is not a foolish choice. There are three sound reasons for it.
First, the SQL is already there. The chain has a data warehouse, the reports come out of it, the team speaks the language. There is no new solver to install, no licence to buy, no library versions to manage. Second, it is readable. A planning manager can read a query too and point at the bit to argue with; to argue with the output of a mixed integer model you first have to understand the model. Third, and most important: it gives an answer in every case. A solver can hit its time limit and say “I couldn’t find the best”; a query that ranks always gives you a list.
By the end of this article we will see how good this method is and exactly where it loses money, down to the last lira.
Step 1: SQL finds the candidates
The thesis of the last article was this: the most important part of a model is the constraints you do not write. Business knowledge goes into the solver not as constraints but as the definition of the candidate set. The good news is that the definition is already an SQL query.
The query below runs directly on the Lumoda dataset and produces exactly the same candidate list as the Python side of the pipeline:
-- bt_* views: open stores and cleaned stock, sales and shipment rows
with decision as (select cast($decision as date) as t),
-- 1. The decision-day snapshot, at option level: stocked rails, and is the set broken?
snapshot as (
select st.store_id, p.option_id,
sum(st.units) as stock,
count(*) filter (where st.units = 0 and p.size_order between 2 and 4) > 0 as broken
from bt_stock st join product p using (product_id), decision
where st.date = decision.t
group by 1, 2
having sum(st.units) > 0
),
-- 2. Rate of sale: the mean of the weeks the stock was on the rail only
stocked_week as (
select st.date as week, st.store_id, p.option_id
from bt_stock st join product p using (product_id), decision
where st.date >= decision.t - interval 8 week and st.date < decision.t
group by 1, 2, 3
having sum(st.units) > 0
),
weekly_sales as (
select date_trunc('week', s.date) as week, s.store_id, p.option_id, sum(s.units) as units
from bt_sales s join product p using (product_id), decision
where s.date >= decision.t - interval 8 week and s.date < decision.t
group by 1, 2, 3
),
rate as (
select sw.store_id, sw.option_id,
coalesce(sum(ws.units), 0)::double / count(*) as rate
from stocked_week sw
left join weekly_sales ws
on ws.week = sw.week and ws.store_id = sw.store_id and ws.option_id = sw.option_id
group by 1, 2
),
-- 3. Rails that are cooling: stock arrived in the last two weeks (from the warehouse or a store)
cooling as (
select distinct sh.store_id, p.option_id
from bt_shipment sh join product p using (product_id), decision
where sh.date > decision.t - interval 2 week and sh.date <= decision.t
),
-- 4. Donor candidate: has stock, set not broken (core sizes on the rail), cover over the floor, not cooling
donor as (
select n.store_id, n.option_id, n.stock, n.broken, coalesce(r.rate, 0) as rate,
case when coalesce(r.rate, 0) > 0 then n.stock / r.rate else 999 end as cover
from snapshot n
left join rate r using (store_id, option_id)
),
donor_candidate as (
select d.* from donor d
where d.cover >= 6
and not d.broken
and not exists (select 1 from cooling c
where c.store_id = d.store_id and c.option_id = d.option_id)
),
-- 5. Receiver candidate: set broken or out of stock, but selling
receiver_candidate as (
select r.store_id, r.option_id, r.rate
from rate r
left join snapshot n using (store_id, option_id)
where r.rate >= 1
and (n.broken or n.stock is null)
),
option_summary as (
select option_id, any_value(line) as line,
any_value(list_price) as list_price, any_value(cost_price) as cost_price
from product group by 1
)
-- 6. Pair up and filter: no sending to yourself, outlet stock does not go to a full-price store
select d.store_id as donor, r.store_id as receiver, d.option_id,
d.stock as units, d.rate as donor_rate, r.rate as receiver_rate,
o.list_price, o.cost_price
from donor_candidate d
join receiver_candidate r using (option_id)
join option_summary o using (option_id)
join bt_store s on s.store_id = r.store_id
where d.store_id <> r.store_id
and (o.line <> 'Outlet' or s.type = 'Outlet')
order by donor, receiver, option_id
Eighty-odd lines, and every one of them a business rule. In the fourth
block, cover >= 6 defines a sending store (donor in the code); in the
fifth, n.broken or n.stock is null defines a receiving store (receiver); and in the sixth,
o.line <> 'Outlet' or s.type = 'Outlet' is the trade’s ban. Ali’s second
number, the maximum cover at the receiving store, does not appear in this query at
all: the third gate is shut in the reference scenario, so
receiver_candidate collects only rails that are broken or out of stock. In
the repository this logic is split across a few functions; here I have put
it into one query for readability.
The query’s only input is $decision at the top: which Monday’s snapshot to
look at. The rate of sale, cooling and the snapshot are all measured from it,
and none of them looks beyond it; no sale or arrival after the decision gets
into the query. Nor does the query look at the raw tables; it looks at the
views starting with bt_: the physical stores open that Monday and their
cleaned rows. Lumoda’s data has sales rows written twice, too, and phantom
stock that shows up one Monday without ever selling and then disappears. In
your data the hard part will most likely not be this query but what sits
behind those views.
The and not d.broken line in the fourth block is the code version of the
trap Pelin caught in the second article. A broken set stops selling and its
cover heads for infinity; delete that line and the query ranks broken rails
as the best sending stores, and the scales work backwards.
Look once more at the second block, too: having sum(st.units) > 0. That
single line is what makes the rate of sale be measured only on in-stock
weeks. Delete it and the query still runs, raises no error, and brands every
product that could not sell because it was out of stock a “slow seller”. It
is the most dangerous line in this article, because the broken-set line’s
mistake jumps out when you look at the plan, and this one’s does not.
The order by on the last line is not decoration either; I will explain why
it is there in the next article.
On Lumoda’s real snapshot the query returns 5,369 candidates. The “exactly the same” claim is held up by a test: the test reads this query out of the article, runs it and compares it with the Python side’s list. If the article and the code drift apart, the test fails.
Step 2: the score on the scales
We have the candidate list. Now every row needs a score: the scales of the second article, the of the third:
No solver is needed for this; it is just arithmetic. Adding three expressions to the query’s select line, or writing four lines of Python, is enough:
df["gain"] = np.minimum(df.units, df.receiver_rate * H) * unit
df["donor_loss"] = np.minimum(df.units, df.donor_rate * H) * unit
df["transport_cost"] = p.unit_cost_try * df.units
df["w"] = df.gain - df.donor_loss - df.transport_cost
unit here is the list price. Anyone who wants to set up the scales with
profit replaces it with price less cost; the query’s cost_price column is
there for that. We measured it in the third article: the plan changes a
little, and profit moves by a few tenths of a per cent.
Note that nothing we have done so far is specific to optimisation. The candidate set and the scoring are exactly the same in both methods. The split starts at the next step.
Step 3: the greedy decision
Take the highest-scoring move, strike out what clashes with it, move on to the next. That is the whole recipe, and the code is as short as the recipe:
ranked = candidates.sort_values(
by=["w", "donor", "receiver", "option_id"],
ascending=[False, True, True, True],
)
for row in ranked.itertuples(index=False):
if row.w <= 0:
break # all the rest are worse
counters["positive"] += 1
if (row.donor, row.option_id) in given:
counters["block"] += 1
continue # a block goes to one destination
if left.get(row.receiver, 0) < row.units:
counters["capacity"] += 1
continue # receiver capacity
given.add((row.donor, row.option_id))
left[row.receiver] -= row.units
counters["selected"] += 1
chosen.append({k: getattr(row, k) for k in MOVE_COLUMNS})
Three checks, three constraints. The counters lines only count; the table
below comes from them. The break looks bold at first sight, but it is
right: the list is sorted by score, so once you reach the first negative
score everything after it is worse.
The donor, receiver, option_id tail in the ranking is not decoration.
When scores come out equal, if nothing decides the order, two runs on the
same data produce two different plans. And nobody trusts a system that
“suggests one thing yesterday and another today”.
What actually happened
The numbers, on Lumoda’s real snapshot:
| Step | Result |
|---|---|
| Candidates found by the SQL | 5,369 |
| With a positive score | 3,337 |
| Skipped as “this block has already gone” | 1,895 |
| Skipped for capacity | 852 |
| Moves selected | 590 |
| Cut by the minimum shipment filter | 4 |
| Plan left | 586 moves · 99,029 units · 340 routes |
Time: 39.7 ms. Net gain: TRY 32,680,688. (The solve times in this series are the ones measured in the Turkish edition’s run. The plans here are proven identical to that run’s, and a rerun never repeats a time exactly.)
Let’s look at that 1,895 for a second, because the nature of the greedy method is right there. Several stores want the same block; the highest-scoring one gets it, and the other requests are turned away at the door. The method never thinks about the turned-away requests again. Yet perhaps giving that block to the store in second place, and finding the highest-scoring store stock from somewhere else, would have been better overall. That is the definition of the greedy method: at every step it picks the best of the moment and does not look at what that choice shuts off later.
The 852 just below it is the other side of the same story. A positive score, a block not yet given to anyone, but not enough room left at the receiving store: mostly because blocks chosen earlier have eaten it up, sometimes because the store has no room at all. Capacity does not stay on paper here: at the moment of the decision 12 of the 80 stores have no room at all. When the loop meets a receiving store with no room left it cannot ask “if I undid one of my earlier choices, would this fit better?”; going back is not in its recipe.
Where it loses money
Now the real point. Let’s run the solver on the same data too and put the two plans side by side:
| Moves | Units | Routes | Net gain | |
|---|---|---|---|---|
| Greedy | 586 | 99,029 | 340 | TRY 32,680,688 |
| Solver (MIP) | 661 | 109,100 | 318 | TRY 35,934,123 |
Looking at this table, the first thing I asked was: are they moving the same stock? No. The two plans move 571 blocks in common, but in 193 of them the receiving store is different. There are 15 blocks greedy moves that the solver does not touch; and 90 blocks the solver moves that greedy does not touch, 12,580 units in all.
Let’s do the arithmetic and split the difference in two: the of the moves and the route cost.
The solver opens 22 fewer routes, and that is worth TRY 11,000. The remaining TRY 3,242,435 comes from which block goes where. The loop gives a block to its best destination when its turn comes; that choice both eats up that receiving store’s room and shuts the door on the other stores that wanted the block. Blocks that come later, each with a lower score but together worth more, may no longer fit there; the loop cannot go back and share them out again. The solver weighs all the blocks and all the gaps at once. The traces show: when the plans are done, 270 of the blocks with a positive score do not fit in the remaining room at their receiving store under greedy, 194 under the solver. We did not measure separately how much of the difference comes from room and how much from blocks clashing.
In one sentence: the difference is not in the lorries but in which carton goes to which rail.
A crude patch: the minimum shipment
There is one more thing I have to tell you honestly. The minimum shipment rule (“you don’t send a lorry for two units”) does not fit naturally into the greedy flow, because a route’s total load is only known once every choice has been made. The fix is crude: once the selection is over, we look at each route’s load and delete those that fall short.
route_units = df.groupby(["donor", "receiver"]).units.transform("sum")
df = df[route_units >= p.min_route_units].reset_index(drop=True)
What is bad about this? It stops at deleting and does not look for anything in its place. When the moves on that route are cancelled, those blocks are freed up, but the method does not go back to the start and ask “since this route won’t be opened, where else could I give this block?”
This week the patch cut 4 moves: four of the 590 moves the loop selected were deleted because they sat on routes that could not reach the minimum shipment, and nothing was put in their place. Four moves looks like few; the real trouble is not the number but the silence. That is the way of patches like this: most of the time they cut nothing and get forgotten as “it never kicks in anyway”; then the data or the parameters change a little and they cut without telling anyone. This week it cut, and nobody looking at the plan would have noticed. The solver has no such patch: there the minimum shipment is a constraint line inside the model, and the solver also considers the option of combining moves without breaking it.
So when is this enough?
Let’s look at the figures: the greedy method finds 90.9% of the value the solver finds, in less than a thousandth of the time and at zero set-up cost.
That is easy to sniff at, and wrong. This method really is the right answer under these conditions: if fixed costs are small (the route cost is negligible next to the total), if decisions constrain one another little, if nobody in the team can look after optimisation, and if the difference between “good” and “best” is too small to be worth a meeting. This week at Lumoda is not like that. Several stores want the same block, room at the receiving stores binds, and the gap is 9.1%: more than three million lira.
But note: we know it is 90.9%, because we built the other one as well and measured it. A chain that runs only the greedy method cannot know whether its result is 90.9% or 70%. Intuition is no use here; how big the loss is depends on the shape of the problem, and the shape changes every week.
In the next article we will set up the same problem with a solver: writing the model with PuLP, running CBC, and what to do when the solver hits a limit. In the sixth article we will put the two side by side on every measure. There is a surprise there: turn the dial and grow the money by two-thirds, and the customer who cannot find what they came for barely notices 🙂