rasinmuhammed's picture
Retail star schema v1
7e5adcc verified
Raw History Blame Contribute Delete
9.28 kB
"""Returns after the engine draws them: Apparel's sales-cohort rate checked against the brief's rounding, and each
return on a day its channel takes returns.
The engine holds every matured Apparel sale month at round(0.18 x units sold) returned units (a cohort claim). Its round
is half to even, on a float; the brief's, like ClickHouse's on decimals, is half away from zero. The two differ by one
unit in a month whose 0.18 x units ends in exactly .5 (525 units: 94 against 95). This checks every matured month against
the half-away-from-zero target and moves the difference, if any: a unit onto a partial return with room first, else a
return added to an unreturned line, drawn as the engine draws them; a unit too many comes off a return with more than
one, else a whole return goes. Every move is recorded. Cohorts still open at the as-of date are left as drawn.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from . import catalog as C
@dataclass
class Held:
returns: pd.DataFrame # order_line_id, return_date, returned_qty, reason
moves: list[dict] = field(default_factory=list)
def target_units(units_sold: int) -> int:
"""round(0.18 x units), half away from zero, in whole-number arithmetic."""
pct = int(round(C.APPAREL_RETURN_RATE * 100))
return (2 * pct * units_sold + 100) // 200
def _lags(rng: np.random.Generator, n: int) -> np.ndarray:
d = C.RETURN_LAG_MEDIAN * np.exp(rng.normal(0.0, C.RETURN_LAG_SIGMA, n))
return np.floor(np.clip(d, 1, C.RETURN_MAX_LAG_DAYS)).astype(np.int64)
def _units(rng: np.random.Generator, q: np.ndarray) -> np.ndarray:
full = rng.random(len(q)) < C.FULL_RETURN_SHARE
return np.where(full, q, 1 + np.floor(rng.random(len(q)) * q).astype(np.int64))
def hold_apparel(drawn: pd.DataFrame, lines: pd.DataFrame, products: pd.DataFrame, seed: int) -> Held:
"""`drawn`: the engine's returns. `lines`: delivered order lines. `products`: dim_product."""
r = drawn[["order_line_id", "return_date", "returned_qty", "reason"]].reset_index(drop=True)
r["return_date"] = pd.to_datetime(r.return_date).dt.normalize()
r["returned_qty"] = r.returned_qty.astype(np.int64)
bought = r.order_line_id.map(lines.set_index("order_line_id").quantity).to_numpy(dtype=np.int64)
apparel = set(products.loc[products.category == "Apparel", "product_id"])
ln = lines.loc[lines.product_id.isin(apparel), ["order_line_id", "order_date", "quantity"]].copy()
ln["cohort"] = ln.order_date.dt.to_period("M")
reasons = C.RETURN_REASONS["Apparel"]
names, weights = list(reasons), np.asarray(list(reasons.values()), dtype=float)
weights /= weights.sum()
moves = []
keep = np.ones(len(r), dtype=bool)
added = []
for cohort, cl in ln.groupby("cohort", sort=True):
if str(cohort) > C.MATURE_THROUGH:
continue
rng = np.random.default_rng([seed, cohort.ordinal])
sold = int(cl.quantity.sum())
want = target_units(sold)
mine = r.order_line_id.isin(cl.order_line_id) & keep
have = int(r.loc[mine, "returned_qty"].sum())
move = {"cohort": str(cohort), "units_sold": sold, "drawn_units": have, "held_units": want, "units_added": 0,
"added_returns": 0, "removed_returns": 0, "units_trimmed": 0}
if have < want:
short, rows = want - have, []
room = r.index[mine & (r.returned_qty < bought)].to_numpy()
for i in room[rng.permutation(len(room))]:
if short <= 0:
break
up = int(min(short, bought[i] - r.at[i, "returned_qty"]))
r.at[i, "returned_qty"] += up
short -= up
move["units_added"] += up
free = cl.loc[~cl.order_line_id.isin(r.loc[mine, "order_line_id"])].sample(frac=1.0, random_state=rng)
q = free.quantity.to_numpy(dtype=np.int64)
units = _units(rng, q)
lags = _lags(rng, len(free))
picks = rng.choice(len(names), size=len(free), p=weights)
for i in range(len(free) if short > 0 else 0):
if short <= 0:
break
u = int(min(units[i], short))
rows.append((int(free.order_line_id.iat[i]), free.order_date.iat[i] + pd.Timedelta(days=int(lags[i])), u, names[picks[i]]))
short -= u
if short > 0:
raise RuntimeError(f"Apparel cohort {cohort}: not enough unreturned units to reach {want}")
added += rows
move["added_returns"] = len(rows)
elif have > want:
excess = have - want
idx = r.index[mine].to_numpy()
idx = idx[rng.permutation(len(idx))]
for i in idx: # units off returns of more than one first, so the engine's returns stay
if excess <= 0:
break
if r.at[i, "returned_qty"] > 1:
cut = int(min(excess, r.at[i, "returned_qty"] - 1))
r.at[i, "returned_qty"] -= cut
excess -= cut
move["units_trimmed"] += cut
for i in idx:
if excess <= 0:
break
if keep[i]:
keep[i] = False
excess -= int(r.at[i, "returned_qty"])
move["removed_returns"] += 1
if excess > 0:
raise RuntimeError(f"Apparel cohort {cohort}: could not take back {excess} units")
moves.append(move)
out = pd.concat([r.loc[keep], pd.DataFrame(added, columns=["order_line_id", "return_date", "returned_qty", "reason"])], ignore_index=True)
return Held(returns=out, moves=moves)
def _closed(days: pd.DatetimeIndex, online: np.ndarray) -> np.ndarray:
"""Thanksgiving and Christmas Day close every channel; New Year's Day closes the warehouse."""
thanksgiving = (days.month == 11) & (days.dayofweek == 3) & (days.day >= 22) & (days.day <= 28)
christmas = (days.month == 12) & (days.day == 25)
new_year = (days.month == 1) & (days.day == 1)
return thanksgiving | christmas | (new_year & online)
def _choices(base: np.ndarray, dow: np.ndarray, online: np.ndarray, week: dict[bool, np.ndarray]) -> np.ndarray:
"""Each return's chance of each candidate day: the shift's weight, the open day's factor, its weekday's weight."""
w = base * np.where(online[:, None], week[True][dow], week[False][dow])
total = w.sum(axis=1, keepdims=True)
return np.divide(w, total, out=np.zeros_like(w), where=total > 0)
def on_return_days(held: pd.DataFrame, lines: pd.DataFrame, stores: pd.DataFrame, seed: int) -> tuple[pd.DataFrame, dict]:
"""Each return moved at most two days from its drawn day onto a day its channel takes returns, so each channel's
weekdays carry their stated shares. The lag stays within 1 to 90 days and the day on or before the as-of date, so
every return stays in its sale's cohort and none is lost. Returns `held` with new dates and a record of the moves."""
r = held.reset_index(drop=True).copy()
on = lines.set_index("order_line_id").loc[r.order_line_id.to_numpy(), ["order_date", "store_id"]]
online = on.store_id.map(stores.set_index("store_id").channel).to_numpy() == "Online"
sale = pd.DatetimeIndex(pd.to_datetime(on.order_date.to_numpy()))
drawn = pd.DatetimeIndex(pd.to_datetime(r.return_date.to_numpy()))
as_of = pd.Timestamp(C.AS_OF)
shifts = np.asarray(list(C.RETURN_DAY_SHIFT))
base = np.empty((len(r), len(shifts)))
dow = np.empty((len(r), len(shifts)), dtype=np.int64)
for j, k in enumerate(shifts):
day = drawn + pd.Timedelta(days=int(k))
lag = (day - sale).days.to_numpy()
w = np.where(online, C.ONLINE_RETURN_DAY_SHIFT[int(k)], C.RETURN_DAY_SHIFT[int(k)])
w = w * np.where(~online & (day.month == 12) & (day.day == 26), C.DAY_AFTER_CHRISTMAS_RETURNS, 1.0)
w = np.where(_closed(day, online), 0.0, w)
base[:, j] = np.where((lag >= 1) & (lag <= C.RETURN_MAX_LAG_DAYS) & (day <= as_of), w, 0.0)
dow[:, j] = day.dayofweek.to_numpy()
stuck = base.sum(axis=1) == 0 # no open day within reach: the drawn day stands
base[stuck, list(shifts).index(0)] = 1.0
# weekday weights fitted so each channel's expected weekday shares meet the stated ones
target = {False: np.asarray(C.STORE_RETURN_DAYS), True: np.asarray(C.ONLINE_RETURN_DAYS)}
week = {False: np.ones(7), True: np.ones(7)}
for _ in range(40):
p = _choices(base, dow, online, week)
for ch in (False, True):
got = np.bincount(dow[online == ch].ravel(), weights=p[online == ch].ravel(), minlength=7)
week[ch] = week[ch] * target[ch] / np.maximum(got / got.sum(), 1e-9)
cum = np.cumsum(_choices(base, dow, online, week), axis=1)
u = np.random.default_rng([seed, 6]).random(len(r))[:, None]
moved = shifts[np.minimum((u > cum).sum(axis=1), len(shifts) - 1)]
r["return_date"] = drawn + pd.to_timedelta(moved, unit="D")
record = {"days_moved": {str(int(k)): int((moved == k).sum()) for k in shifts}, "left_on_drawn_day": int(stuck.sum())}
return r, record