Technical

Reading the size curve

How is a store's size curve read from its sales? The correction for the days the rail stood empty, shrinkage for a store with few sales, three size profiles and the new store with no sales at all. And why we keep replenishment's ratios out of the curve.

Size and Pack · 3 / 6

In the first article, as Pars brought Konya 3’s and Istanbul 18’s size curvesHow a store's sales are spread across sizes; each size's share of sales. The size mix of a pack is built on this curve. up on screen, Pars said: “I divide the sales by the days the size was on the rail, and read the curve from that.” In this article we open up that reading: which part of the sales is looked at, how are the days the rail stood empty corrected, what does the curve of a store with few sales lean on, and which curve does a new store with no sales at all get? The curve itself is not a decision; but in the next article we will build the pack (the prepack, or ratio pack) on it.

The Python extracts below are taken from the working code under cases/size-and-pack/; docstrings have been shortened. Every number in the article comes from the case’s report. The module that builds the curve is a decision module: it reads only the sales and stock tables published before the decision day. It cannot see the answer key I described in the first article, that is, each store’s hidden size shift. We use that only to measure afterwards, and a test checks that the module cannot reach it.

Which sales

The curve is read from the sales of the last two years before the decision day, from five-size products only. But not all of every product’s history is equally useful. Collection products are seasonal, and the pack serves mostly their first weeks; so for a Collection option only the first eight weeks after its launch are read. Basic and NOS are continuity products. They have no “first weeks”; the whole two years are read.

# size_and_pack/curve.py (option_windows)
start0, end0 = clustering_features.window(decision_day, constants.HISTORY_WINDOW_WEEKS)
u = source.five_size(products)
u = u[u["line"].astype(str).isin(lines)]
o = (u.assign(option_id=u["option_id"].astype(str), line=u["line"].astype(str))
     .groupby("option_id", sort=True).agg(line=("line", "first"), launch=("launch_date", "min"))
     .reset_index())
# the Turkish groupby sorts the option ids as text: the canonical option order
o = ordering.sort_frame(o, [("option_id", "option_id")]).reset_index(drop=True)
lw = _monday(o["launch"])
seasonal = (o["line"] == SEASONAL).to_numpy()
o["start"] = lw.where(lw > start0, start0)
last = (lw + constants.CURVE_WINDOW_WEEKS * _WEEK).where(seasonal, end0)
o["end"] = last.where(last < end0, end0)
o = o[o["start"] < o["end"]]

Every option gets a start week and an end week. For Collection the end is eight weeks after launch; for Basic and NOS, the week of the decision day. No window goes past the decision day.

Sales are counted in gross units. Sizes are referred to by their position in the set: in the women’s alpha set the fourth size is L, in the men’s numeric set 36. That way the sales of the six size sets add up in the same five columns. Dividing a store’s sales in each size by its total sales gives the raw share.

We can measure how far the raw share is from true demand, because in the data’s design we know each store’s true size demand. The measure is the L1 distance from the first article: the differences between two shares in the five sizes are added up, regardless of sign; 0 means the same distribution, 2 two distributions that do not overlap at all. Across the 68 stores whose curve can be read, the raw share is on average 0.0530 from true demand.

The days the rail stood empty

“In Konya 3 the 36 was missing on 37 days of the eight weeks,” says Pelin. “On those days sales were zero. Won’t the raw share read that as the 36 selling badly?”

“It will,” says Pars. “Sales aren’t demand itself; they’re the smaller of demand and the stock on the rail. That’s why I divide each size’s sales by the number of days it was on the rail. A size that was on the rail for five days and sold five sells at the same rate as one that was there for thirty days and sold thirty.”

This is the correction for censored demandDemand that arrives while the shelf is empty and is never recorded. Sales data show not demand but the smaller of demand and stock.. The code does it cell by cell; a cell is one store, one option and one size:

# size_and_pack/curve.py
def cell_demand(cell: pd.DataFrame, chain_curve) -> np.ndarray:
    z = np.asarray(chain_curve, dtype="float64")
    s = cell["s"].to_numpy(dtype="float64")
    f = cell["f"].to_numpy(dtype="float64")
    L = cell["L"].to_numpy(dtype="float64")
    observed = f > 0
    demand = np.where(f >= MIN_IN_STOCK_DAYS, np.divide(s * L, f, out=np.zeros_like(s), where=f > 0), s)
    demand = np.where(observed, demand, 0.0)
    zb = z[cell["size_order"].to_numpy(dtype=int) - 1]
    group = pd.MultiIndex.from_arrays([cell["store_id"].to_numpy(), cell["option_id"].to_numpy()])
    code, _ = pd.factorize(group)          # order of appearance: independent of the id text
    T = np.bincount(code, weights=demand)
    Z = np.bincount(code, weights=np.where(observed, zb, 0.0))
    has = Z[code] > 0
    filled = np.divide(T[code] * zb, Z[code], out=np.zeros_like(s), where=has)
    return np.where(~has, np.nan, np.where(observed, demand, filled))

Every cell has three numbers. s is the sales in the window, f the number of days the size was in stock on the rail, L the number of days the option was observed in that store. If the size has at least three in-stock days its demand is s / f × L: the whole window at the rate it sold on the days it was on the rail. If it has one or two in-stock days its sales are taken as they are; building a rate from so few days would magnify the noise. If it has no in-stock days at all, the size was never observed. Then its demand is filled in from the observed sizes of the same store and option, in the chain’s size ratios.

The number of in-stock days comes from the weekly stock snapshotA day on which a product open for sale in a store or channel was not on the shelf at all. Lost sales happen on these days.. Each snapshot says on how many of the previous seven days the product was on the rail. That is why the function that gathers sales and stock into cells shifts the stock back by a week.

The corrected share is on average 0.0337 from true demand. The raw share’s was 0.0530; the correction cuts the distance by 0.0193.

That is a good result, but its size needs reading correctly. The correction moves a size’s share by only 0.53 points on average, 2.01 points at most. The raw curve and the corrected curve are on average 0.0265 from each other, 0.0584 at most. We said it in the second article too: so small a difference does not change the design of the pack. The two-type design built with the raw curve is the same as the one built with the corrected curve.

The correction has its costs too, and the report counts them. There are 5 cells with sales even though the stock snapshot shows the rail empty: either the record is dirty or the stock came and went between two snapshots. These cells’ sales drop out of the corrected demand and the chain fill comes in their place; only 34 of 11,682,214 units in all. 22 cells have only one or two in-stock days. And there are the sparse cells: when the rate of a size that was in stock on only a few days of a long window is spread over the whole window, a small sale turns into a large demand. There are 143 such cells, and they carry 0.09% of the corrected demand. That is why we did not change the three-day threshold; it stayed the same as the rule in the Initial Allocation series.

The pool, or Collection alone

We read the curve from the sales of Collection, Basic and NOS together, from a single pool. But the pack will go to Collection’s first allocation. Wouldn’t reading the curve from Collection alone be more accurate?

The report measures all three ways. The first two columns are the distance to true demand, that is, measured with the answer key. The third column has no key: the distance from the corrected curve built on the decision day a year earlier, with the data up to that day, to the share actually realised in that season’s Collection products in their first eight weeks. The realised share comes from the published data; it is a measure you have in real life too.

SalesRaw → trueCorrected → trueCorrected → realisedCensoring, meanCensoring, max
Pool0.05300.03370.02790.53 pts2.01 pts
Collection only0.08440.02910.03021.30 pts4.89 pts
Basic and NOS only0.05240.03580.02900.47 pts2.02 pts

The two measures point different ways. By the answer key the curve read from Collection alone is better: 0.0291. By the measure without the key the pool is better: 0.0279. We chose the pool, because we had decided from the start to make choices of this kind without looking at the answer key; we did the same in the Store Grouping series. The cost is this: our final curve is a little further from the truth than it could be. Without the key in hand we could not have known that; in a real chain you cannot know it either.

The table says one more thing. Censoring is much bigger in Collection: it moves a size’s share by 1.30 points on average, 4.89 points at most. The days the rail stood empty shift the curve far more in Collection’s first weeks; the two-year window of Basic and NOS dilutes the effect. Part of the reason the correction comes out small in this data is the pool.

A store with few sales

“Konya 3’s curve is read from 89,409 units,” says Pars. “With that many sales a size’s share hardly moves. But not every store sells that much; the curve of a store that sells little is noisy. I pull it towards the average of the stores that resemble it. The fewer it has sold, the harder.”

This is shrinkage. The store’s own corrected curve and the curve of its profile are mixed; I explain the profile shortly. The weight comes from the sample:

# size_and_pack/curve.py (shrink; check and set-up lines left out)
empty = E.isna().any(axis=1).to_numpy() | (nn.to_numpy() <= 0)
denominator = nn.to_numpy() + kappa
w = np.divide(nn.to_numpy(), denominator, out=np.zeros(len(nn)), where=denominator > 0)
w = np.where(empty, 0.0, w)[:, None]
X = w * np.nan_to_num(E.to_numpy()) + (1 - w) * O
X = X / X.sum(axis=1, keepdims=True)

The store’s weight is w = n / (n + κ); n is the units sold in the window. You can read κ as how many units of sales the profile curve stands in for: a store whose sales are κ takes half its own curve and half its profile’s.

κ is chosen without looking at the answer key. We go back to the decision day a year earlier and rebuild the whole method with the data up to that day; for each κ, the mean distance from the curves to the share realised in that season’s first eight weeks is measured:

# size_and_pack/curve.py (choose_kappa; check and set-up lines left out)
scope_cal = source.scope(tables, cal)
target = realised_share(tables, cal, decision_day, scope_cal).dropna()
setup = _assemble(tables, scope_cal, cal, lines, k, seed, min_units, fallback=False)
ids = [m for m in setup.readable if m in target.index]
H = target.loc[ids].to_numpy()
rows = []
for kp in grid:
    E = shrink(setup.corrected.loc[ids], setup.n, setup.prior.loc[ids], kappa=kp)
    rows.append({"kappa": kp, "l1": float(np.abs(E.to_numpy() - H).sum(axis=1).mean()), "stores": len(ids)})
table = pd.DataFrame(rows)
best = table["l1"].round(12).min()
chosen = table.loc[table["l1"].round(12) == best, "kappa"].min()

The grid starts at 0 and 25, then doubles at every step up to 12,800. Some of the results:

κMean L1 to the realised share
00.027899
1000.027896
1,6000.027853
3,2000.027812
6,4000.027743
12,8000.027646

Here I need to say two things plainly. First, the best κ came out at the end of the grid: 12,800. The distance keeps falling as κ grows; had the grid been wider, a larger κ could have been chosen. We did not widen the grid after seeing the result, because then we would have chosen the grid by the result. Second, the table is almost flat. The difference between the best and the worst κ is 0.000253; which κ is chosen hardly matters in this data.

Even with κ at 12,800 the stores’ weights stay high, because the samples are large. Among the stores whose curve can be read, median sales are 126,481 units, the lowest 34,898. The median weight is 0.908, the lowest 0.732. Konya 3’s weight is 0.875.

That is also why shrinkage has little effect by the answer key: the corrected curve’s distance is 0.0337, the shrunk final curve’s 0.0333. In this data shrinkage gains nothing. It stays in the method all the same; in a chain with stores that sell little and new categories, this is the step that will earn its keep.

One more detail. Had we used the profile’s curve directly instead of the store’s own, the distance would have been 0.0329; slightly closer even than the final curve. It seems that at Lumoda the true size demand of stores in the same profile is almost the same, and most of what sets a store’s curve apart from its profile is noise. That comes from the simplicity of the data’s design. In a real chain there is no reason to assume it.

Three profiles

A profile is a group of stores whose size curves resemble each other. The curves of the stores whose curve can be read are clustered with k-means:

# size_and_pack/curve.py
def profiles(curve: pd.DataFrame, k: int = 3, seed: int = constants.SEED) -> pd.Series:
    E = curve[COLUMNS].astype("float64")
    e = learn.cluster(E, "kmeans", k, seed=seed)
    # cluster numbers (0..k−1, canonical by the smallest store id): the same in both editions
    mean = mean_size(E.groupby(e.to_numpy()).mean())
    rank = list(mean.sort_values(kind="stable").index)
    names = profile_names(k)
    labels = {g: names[i] for i, g in enumerate(rank)}
    return pd.Series([labels[g] for g in e.to_numpy()], index=pd.Index(E.index.astype(str), name="store_id"),
                     name="profile")

The clusterer is the cluster function we built in the Store Grouping series. This time there is no standardisation: all five columns are shares, all on the same scale, and standardising would distort the differences between sizes. The clusters are ranked and named by mean size position: small, medium, large. A profile’s curve is the mean of its member stores’ corrected curves.

ProfileStores12345
Small1915.8%27.7%30.4%18.1%8.1%
Medium229.6%21.4%33.9%23.5%11.5%
Large277.1%16.2%28.2%30.6%18.0%

These are the 68 stores whose curve can be read. The new store that the first article put in the large group is not in this table; I come to it below. In the pack design the large profile has 28 stores with it.

We did not choose the number of profiles by a rule. While exploring we saw that the stores’ mean size position had three peaks, and we said three. We could have chosen it with a measure that needs no key, such as the silhouette; we did not. I say so because, as someone who knows the data’s design, I also know where the number three comes from.

We measure agreement with the answer key with the measure from the Store Grouping series: the ARI, where 1 means a split identical to the key and 0 a random split. The three profiles’ ARI with the hidden shift is 1.000.

Profile \ hidden shiftTowards smallMiddleTowards large
Small1900
Medium0220
Large0027

In the first article I said we would discuss how much of this match comes from the method and how much from the simplicity of the data. The honest answer: most of it from the data. In the data’s design the shift is at store level, takes three values and does not depend on the category; and every store’s curve is read from tens of thousands of units. Separating three groups in so clear a structure does not take a very good method. The method’s part is not to spoil the structure: not to take sales for demand, not to put shipments into the curve, not to let the answer key into any choice.

Let me also mention an oddity of the design here. The code that generates the data draws the shift from four values: one step towards small, the middle, one or two steps towards large. But demand clips the shift at one step; the demand of the 13 stores drawn two steps is the same as that of the stores drawn one step. As the answer key we use the clipped value, the one that actually drives demand. Had we measured with the unclipped value these 13 stores would look like a separate group, and the profiles would part from the key on paper; but what they would part on would not be the store’s demand.

The new store

The curve cannot be read in every store. The rule is a threshold set before seeing the result: if the five-size sales in the window are at least 500 units, the curve can be read.

# size_and_pack/curve.py
def readable(corrected_: pd.DataFrame, n: pd.Series, min_units: float = constants.CURVE_MIN_UNITS) -> pd.Series:
    nn = n.reindex(corrected_.index).fillna(0.0)
    return ((nn >= min_units) & ~corrected_.isna().any(axis=1)).rename("readable")

The threshold is in units, not weeks. In the Store Grouping series Kocaeli 1 counted as new, because its 19 weeks of sales did not make up half a year. That threshold was for the sales mix; how precise a size share is depends on how many units it is read from. Kocaeli 1 has 46,580 units of sales in 19 weeks. Its curve can be read, its weight is 0.784 and its final curve is 0.0334 from its true demand; about the average of the 68 stores.

The one store left is Izmir 2. It opens on the first day of the season and has no sales at all. There are two candidates for its curve: the chain curve, or the profile of the five stores that most resemble Izmir 2 in their static attributes. A static attribute is something known before the store opens: region, climate, store type, square metres and the like. We built this assignment in the Store Grouping series. Which of the two is chosen is again decided by a rule that needs no key:

# size_and_pack/curve.py (new_choice)
for m in readable_ids:
    others = [i for i in readable_ids if i != m]
    p = profiles(corrected_.loc[others], k, seed)
    P = profile_curves(corrected_.loc[others], p)
    a = new_store.assign(st.loc[[m]], st.loc[others], p, neighbours=NEIGHBOURS).iloc[0]
    own = corrected_.loc[m, COLUMNS].to_numpy(dtype="float64")
    l1_p.append(np.abs(P.loc[a].to_numpy() - own).sum())
    l1_z.append(np.abs(z - own).sum())
    hit.append(a == full[m])
lp, lz = float(np.mean(l1_p)), float(np.mean(l1_z))
return {"choice": "profile" if lp < lz else "chain", "l1_profile": lp, "l1_chain": lz,
        "hit_rate": float(np.mean(hit)), "stores": len(readable_ids)}

Each store whose curve can be read is treated in turn “as if it were new”. The profiles are rebuilt without it, the store is assigned to a profile on its static attributes alone, and the two candidates’ distances to the store’s own curve are measured. Whichever has the smaller mean, the new store gets it.

The result is a hair’s breadth. The profile’s mean distance is 0.17421, the chain’s 0.17511. The rule chose the profile. The assignment made on static attributes hits the store’s actual profile 51.5% of the time; a little more than half, across three profiles.

“You’ve likened Izmir 2 to the stores that lean towards large sizes,” says Pelin.

“The stores it resembles do,” says Pars. “I can’t know without seeing its sales. The rule chose the profile, but there’s almost nothing between it and the chain. When the first sales come in, this is the first store I’ll look at.”

In truth Izmir 2’s customers lean towards small sizes. The profile it was assigned is large, and its curve is 0.4344 from its true demand. Had the rule chosen the chain it would have been 0.2451. By the answer key, a bad choice. We did not change the rule after this result: had we done so, we would have chosen a rule by a single store’s result. But the lesson is clear: a fallback chosen by a hair’s breadth can turn out costly in a single store.

Replenishment’s ratios

“There’s another way,” says Pelin. “Let’s look at the stock going from the warehouse to the stores. How much of each size replenishment sends to each store is known.”

“It’s known,” says Pars. “But those ratios don’t show demand, they show what the pack left short.”

We counted this mistake among the trade’s mistakes in the second article: 41.6% of replenishment is the fourth size, while in the chain’s sales it is 24.5%. In the data’s design there is another reason, and a weightier one. Lumoda’s replenishment plan knows the store’s hidden size shift. A curve that read the size mix of the shipments would read the answer key through the back door; the accuracy we measured would be the accuracy of the leak, not of the method. That is why the curve module never reads the shipment table, and a test checks it: not a single line asking for the shipment table may appear in the module’s code.

In a real chain the replenishment plan knows no such key. But it knows your plan. Your own replenishment’s ratios are a mirror of your plan, not of demand.

With and without the referee

The result of every step against the answer key, in one table:

CurveMean L1 to true demand
Raw share of sales0.0530
Days off the rail corrected0.0337
Shrunk (final curve)0.0333
Profile curve0.0329
Chain0.1634

Almost all of the gain comes from two steps: looking at the store’s own sales instead of the chain’s, and correcting the days the rail stood empty. Shrinkage has no effect in this data.

None of the choices was made with the answer key. The windows, the 500-unit threshold and the three-day threshold are constants set before seeing the result. κ, the pool and the new store’s fallback curve were chosen with measures that need no key. In two places the report shows that the key would choose something else: Collection alone instead of the pool, and the chain instead of the profile for Izmir 2. I have written both above. We did not measure what κ would have come out had we chosen it with the key.

There is one more measure without the key: how long does the curve hold? Two corrected curves built a year apart are on average 0.0061 from each other across the 66 stores where both can be read. As I said in the second article, since the two curves share one year of the past, this figure is a little optimistic.

What is hard in your data

The first is the record of stockout days. Everything in this article rests on knowing, for every store, every product and every size, on how many days the rail was stocked. Lumoda’s weekly stock snapshot says so. Many systems keep only the stock count at the end of the week; they do not say whether a size that shows zero ran out on the Monday or on the Saturday. The first job of the correction is to build that record.

The second is size sets. At Lumoda a store’s shift is the same in every category, so we gathered the six size sets into one curve. A real store’s customers can lean towards large sizes in jeans and small ones in T-shirts. Then you need a curve per set, perhaps per category. Each curve’s sample gets smaller; that is exactly where shrinkage, which gains nothing in this data, earns its keep.

The third is the new store. Static attributes hit the size profile a little more than half the time. A new store gets its initial allocation with its curve at its least known.

The fourth is having no referee to measure against. In this article we could measure every step with an answer key. You will have the next season’s realised share; and it is censored too, whenever the rail stands empty. We saw it in the question of which sales to read: the measure with the key and the measure without it do not always choose the same thing. Write down which one you will look at before you see the result.

In the next article we design the pack with these curves: how many pack types, what content, which goes to which store, and is there enough stock of each size in the warehouse?

By Sabri Suyunu