def allocate_target(
forecasts_df: pd.DataFrame | None = None,
target_total: float | Sequence[float] | Mapping[Any, float] | pd.DataFrame | None = None,
*,
predictions_df: pd.DataFrame | None = None,
target: float | Sequence[float] | Mapping[Any, float] | pd.DataFrame | None = None,
targets: float | Sequence[float] | Mapping[Any, float] | pd.DataFrame | None = None,
target_sum: float | Sequence[float] | Mapping[Any, float] | None = None,
horizon_total: float | None = None,
node_id: str | None = None,
target_node: str = TOTAL_NODE_ID,
period: Sequence[Any] | str | None = None,
target_dates: Sequence[Any] | str | None = None,
target_mode: Literal["auto", "per_step", "horizon_sum", "proportional"] = "auto",
target_metric: Literal["auto", "units", "revenue"] = "auto",
locked_nodes: Sequence[str] | Mapping[str, float] | None = None,
locks: Sequence[str] | Mapping[str, float] | None = None,
lower_bounds: Mapping[str, float] | Sequence[float] | np.ndarray | float | None = None,
upper_bounds: Mapping[str, float] | Sequence[float] | np.ndarray | float | None = None,
bounds: (
Mapping[str, tuple[float | None, float | None]]
| tuple[float | None, float | None]
| pd.DataFrame
| None
) = None,
floor: float | None = 0.0,
cap: float | None = None,
ceiling: float | None = None,
nonneg: bool = True,
method: str = "mint_shrink",
weights: str | Mapping[str, float] | Sequence[float] | np.ndarray | None = None,
smoothness_weight: float = 0.0,
hier_spec: HierarchySpec | None = None,
spec: HierarchySpec | None = None,
cfg: RunConfig | Mapping[str, Any] | None = None,
history_df: pd.DataFrame | None = None,
oof_df: pd.DataFrame | None = None,
price_col: str | Mapping[str, float] | float | None = None,
prices: Mapping[str, float] | float | pd.DataFrame | None = None,
unit_cost: float | Mapping[str, float] | str | None = None,
include_inventory_impact: bool = False,
lead_time: float = 7.0,
lead_time_std: float = 0.0,
service_level: float | None = 0.95,
inventory_params: Mapping[str, Any] | None = None,
model_type: str | None = None,
scenario: str | None = None,
date_col: str = "ds",
ts_id_col: str = "ts_id",
target_col: str = "y",
similarity_hierarchy: bool = False,
similarity_n_clusters: int | Literal["auto"] = "auto",
similarity_method: str = "hybrid",
return_result: bool = False,
) -> pd.DataFrame | GoalSeekResult:
"""Optimally disaggregate a top-down or regional target across leaf series and dates (pure).
Solves the equality- and box-constrained Minimum-Trace quadratic program over the bottom-level
forecast trajectory while respecting ``locked_nodes`` / ``locks`` and
``[lower_bounds, upper_bounds]``, then rolls up the coherent hierarchy
``y_tilde = S @ b_tilde`` and optionally propagates the allocated forecast into revenue,
gross margin, and `(s, S)` inventory policy deltas.
"""
raw_df = forecasts_df if forecasts_df is not None else predictions_df
if raw_df is None or not isinstance(raw_df, pd.DataFrame) or raw_df.empty:
raise DataError(
"allocate_target requires a non-empty forecasts_df / predictions_df DataFrame"
)
df = raw_df.copy()
# Support scenario simulation outputs directly (`scenario_yhat` -> `yhat`).
if "scenario" in df.columns:
if scenario is not None:
df = df[df["scenario"].astype(str) == str(scenario)].copy()
else:
non_base = df[df["scenario"].astype(str) != "baseline"]
if not non_base.empty:
first_scen = str(non_base["scenario"].iloc[0])
df = non_base[non_base["scenario"].astype(str) == first_scen].copy()
if df.empty:
raise DataError(f"No rows found for scenario='{scenario}' in forecasts_df")
if "yhat" not in df.columns and "scenario_yhat" in df.columns:
df["yhat"] = df["scenario_yhat"].astype(float)
if "yhat" not in df.columns:
raise DataError("forecasts_df must contain a 'yhat' or 'scenario_yhat' column")
if ts_id_col not in df.columns:
df[ts_id_col] = "series_0"
dcol = (
date_col
if date_col in df.columns
else ("forecast_date" if "forecast_date" in df.columns else "ds")
)
if dcol not in df.columns:
df[dcol] = pd.date_range("2026-01-01", periods=len(df), freq="D")
if model_type is not None and "model_type" in df.columns:
df = df[df["model_type"].astype(str) == str(model_type)].copy()
if df.empty:
raise DataError(f"No forecast rows found for model_type='{model_type}'")
elif "model_type" in df.columns and df["model_type"].nunique() > 1:
first_m = str(df["model_type"].iloc[0])
df = df[df["model_type"].astype(str) == first_m].copy()
elif "model_type" not in df.columns:
df["model_type"] = model_type or "default"
eff_model_type = str(df["model_type"].iloc[0])
# Resolve target specification.
raw_target = (
target_total
if target_total is not None
else (
target
if target is not None
else (
targets
if targets is not None
else (target_sum if target_sum is not None else horizon_total)
)
)
)
if raw_target is None:
raise ConfigError(
"allocate_target requires target_total "
"(or target / targets / target_sum / horizon_total)"
)
if (
isinstance(smoothness_weight, bool)
or not isinstance(smoothness_weight, (int, float, np.number))
or not np.isfinite(float(smoothness_weight))
or float(smoothness_weight) < 0.0
):
raise ConfigError(
f"smoothness_weight must be a finite float >= 0.0; got {smoothness_weight!r}"
)
smooth_w = float(smoothness_weight)
eff_cap = cap if cap is not None else ceiling
eff_hier_spec = hier_spec if hier_spec is not None else spec
eff_target_node = str(node_id if node_id is not None else target_node)
resolved_spec, include_agg_in_out = _infer_hierarchy_spec_from_frame(
df,
hier_spec=eff_hier_spec,
cfg=cfg,
history_df=history_df,
ts_id_col=ts_id_col,
date_col=dcol,
target_node=eff_target_node,
raw_target=raw_target,
similarity_hierarchy=similarity_hierarchy,
similarity_n_clusters=similarity_n_clusters,
similarity_method=similarity_method,
)
bottom_ids = list(resolved_spec.bottom_ids)
n_b = len(bottom_ids)
b_to_idx = {bid: i for i, bid in enumerate(bottom_ids)}
node_to_idx = {nid: i for i, nid in enumerate(resolved_spec.node_ids)}
all_dates = sorted(df[dcol].drop_duplicates().tolist())
h_total = len(all_dates)
date_to_t = {dt: t for t, dt in enumerate(all_dates)}
# Resolve active period / target_dates subset.
raw_period = period if period is not None else target_dates
if raw_period is not None:
if isinstance(raw_period, (str, pd.Timestamp, int)):
raw_period_seq: Sequence[Any] = [raw_period]
else:
raw_period_seq = list(raw_period)
active_t_indices: list[int] = []
for item in raw_period_seq:
if isinstance(item, int) and 0 <= item < h_total and item not in date_to_t:
active_t_indices.append(item)
elif item in date_to_t:
active_t_indices.append(date_to_t[item])
else:
ts_item = pd.Timestamp(item)
for dt_cand, t_cand in date_to_t.items():
if pd.Timestamp(dt_cand) == ts_item:
active_t_indices.append(t_cand)
break
if not active_t_indices:
raise ConfigError(
f"None of the requested target_dates / period {raw_period_seq} "
"matched forecast dates"
)
active_t_indices = sorted(set(active_t_indices))
else:
active_t_indices = list(range(h_total))
# Pivot bottom-level baseline yhat (n_b, H) and intervals.
piv_yhat = (
df.pivot_table(index=ts_id_col, columns=dcol, values="yhat", aggfunc="first")
.reindex(index=bottom_ids, columns=all_dates)
.fillna(0.0)
)
b_hat = piv_yhat.to_numpy(dtype=float)
b_var_intervals: np.ndarray | None = None
lo_col_name = (
"yhat_lower"
if "yhat_lower" in df.columns
else ("yhat_lower_80" if "yhat_lower_80" in df.columns else None)
)
hi_col_name = (
"yhat_upper"
if "yhat_upper" in df.columns
else ("yhat_upper_80" if "yhat_upper_80" in df.columns else None)
)
if lo_col_name and hi_col_name:
piv_lo = (
df.pivot_table(index=ts_id_col, columns=dcol, values=lo_col_name, aggfunc="first")
.reindex(index=bottom_ids, columns=all_dates)
.fillna(piv_yhat)
.to_numpy(dtype=float)
)
piv_hi = (
df.pivot_table(index=ts_id_col, columns=dcol, values=hi_col_name, aggfunc="first")
.reindex(index=bottom_ids, columns=all_dates)
.fillna(piv_yhat)
.to_numpy(dtype=float)
)
hw_mat = np.maximum(0.0, 0.5 * (piv_hi - piv_lo))
b_var_intervals = np.maximum((hw_mat / _Z_80) ** 2, _VAR_FLOOR)
# Resolve prices and unit_cost per (bottom_i, t).
eff_price_source = prices if prices is not None else price_col
has_price = eff_price_source is not None or (
"price" in df.columns and target_metric == "revenue"
)
price_mat = np.ones((n_b, h_total), dtype=float)
if isinstance(eff_price_source, str):
if eff_price_source in df.columns:
p_piv = (
df.pivot_table(
index=ts_id_col, columns=dcol, values=eff_price_source, aggfunc="first"
)
.reindex(index=bottom_ids, columns=all_dates)
.fillna(1.0)
)
price_mat = p_piv.to_numpy(dtype=float)
elif history_df is not None and eff_price_source in history_df.columns:
last_p = (
history_df.sort_values(dcol if dcol in history_df.columns else "ds")
.groupby(ts_id_col)[eff_price_source]
.last()
.to_dict()
)
for i, bid in enumerate(bottom_ids):
price_mat[i, :] = float(last_p.get(bid, 1.0))
else:
raise ConfigError(
f"price_col '{eff_price_source}' not found in forecasts_df or history_df"
)
elif isinstance(eff_price_source, (int, float)):
price_mat.fill(float(eff_price_source))
elif isinstance(eff_price_source, Mapping):
for i, bid in enumerate(bottom_ids):
if bid in eff_price_source:
price_mat[i, :] = float(eff_price_source[bid])
elif isinstance(eff_price_source, pd.DataFrame):
p_col = "price" if "price" in eff_price_source.columns else eff_price_source.columns[-1]
if ts_id_col in eff_price_source.columns:
p_map = eff_price_source.groupby(ts_id_col)[p_col].last().to_dict()
for i, bid in enumerate(bottom_ids):
price_mat[i, :] = float(p_map.get(bid, 1.0))
elif "price" in df.columns:
has_price = True
p_piv = (
df.pivot_table(index=ts_id_col, columns=dcol, values="price", aggfunc="first")
.reindex(index=bottom_ids, columns=all_dates)
.fillna(1.0)
)
price_mat = p_piv.to_numpy(dtype=float)
cost_mat = np.zeros((n_b, h_total), dtype=float)
has_cost = unit_cost is not None or "unit_cost" in df.columns
if isinstance(unit_cost, (int, float)):
cost_mat.fill(float(unit_cost))
elif isinstance(unit_cost, str):
if unit_cost in df.columns:
c_piv = (
df.pivot_table(index=ts_id_col, columns=dcol, values=unit_cost, aggfunc="first")
.reindex(index=bottom_ids, columns=all_dates)
.fillna(0.0)
)
cost_mat = c_piv.to_numpy(dtype=float)
elif history_df is not None and unit_cost in history_df.columns:
last_c = (
history_df.sort_values(dcol if dcol in history_df.columns else "ds")
.groupby(ts_id_col)[unit_cost]
.last()
.to_dict()
)
for i, bid in enumerate(bottom_ids):
cost_mat[i, :] = float(last_c.get(bid, 0.0))
else:
raise ConfigError(
f"unit_cost column '{unit_cost}' not found in forecasts_df or history_df"
)
elif isinstance(unit_cost, Mapping):
for i, bid in enumerate(bottom_ids):
if bid in unit_cost:
cost_mat[i, :] = float(unit_cost[bid])
elif "unit_cost" in df.columns:
c_piv = (
df.pivot_table(index=ts_id_col, columns=dcol, values="unit_cost", aggfunc="first")
.reindex(index=bottom_ids, columns=all_dates)
.fillna(0.0)
)
cost_mat = c_piv.to_numpy(dtype=float)
use_revenue_weights = target_metric == "revenue"
# Build box bounds [lo_mat, hi_mat] of shape (n_b, H).
default_lo = float(floor) if floor is not None else (0.0 if nonneg else -np.inf)
default_hi = float(eff_cap) if eff_cap is not None else np.inf
lo_mat = np.full((n_b, h_total), default_lo, dtype=float)
hi_mat = np.full((n_b, h_total), default_hi, dtype=float)
locked_mat = np.zeros((n_b, h_total), dtype=bool)
if isinstance(bounds, tuple) and len(bounds) == 2:
if bounds[0] is not None:
lo_mat = np.maximum(lo_mat, float(bounds[0]))
if bounds[1] is not None:
hi_mat = np.minimum(hi_mat, float(bounds[1]))
elif isinstance(bounds, Mapping):
for k_id, b_pair in bounds.items():
k_str = str(k_id)
if k_str in b_to_idx and isinstance(b_pair, tuple) and len(b_pair) == 2:
idx = b_to_idx[k_str]
if b_pair[0] is not None:
lo_mat[idx, :] = float(b_pair[0])
if b_pair[1] is not None:
hi_mat[idx, :] = float(b_pair[1])
elif isinstance(bounds, pd.DataFrame) and not bounds.empty:
for brow in bounds.to_dict(orient="records"):
bid_s = str(brow.get(ts_id_col, ""))
if bid_s in b_to_idx:
idx = b_to_idx[bid_s]
l_v = brow.get("lower_bound", brow.get("lower", brow.get("min")))
u_v = brow.get("upper_bound", brow.get("upper", brow.get("max")))
if dcol in brow and brow[dcol] in date_to_t:
t_i = date_to_t[brow[dcol]]
if l_v is not None and pd.notna(l_v):
lo_mat[idx, t_i] = float(l_v)
if u_v is not None and pd.notna(u_v):
hi_mat[idx, t_i] = float(u_v)
else:
if l_v is not None and pd.notna(l_v):
lo_mat[idx, :] = float(l_v)
if u_v is not None and pd.notna(u_v):
hi_mat[idx, :] = float(u_v)
if lower_bounds is not None:
if isinstance(lower_bounds, (int, float)):
lo_mat = np.full((n_b, h_total), float(lower_bounds), dtype=float)
elif isinstance(lower_bounds, Mapping):
for k_id, l_val in lower_bounds.items():
if str(k_id) in b_to_idx and l_val is not None:
lo_mat[b_to_idx[str(k_id)], :] = float(l_val)
else:
arr_l = np.asarray(lower_bounds, dtype=float)
if arr_l.shape == (n_b, h_total):
lo_mat = arr_l.copy()
elif arr_l.size == n_b:
lo_mat = np.repeat(arr_l.reshape(n_b, 1), h_total, axis=1)
if upper_bounds is not None:
if isinstance(upper_bounds, (int, float)):
hi_mat = np.full((n_b, h_total), float(upper_bounds), dtype=float)
elif isinstance(upper_bounds, Mapping):
for k_id, u_val in upper_bounds.items():
if str(k_id) in b_to_idx and u_val is not None:
hi_mat[b_to_idx[str(k_id)], :] = float(u_val)
else:
arr_u = np.asarray(upper_bounds, dtype=float)
if arr_u.shape == (n_b, h_total):
hi_mat = arr_u.copy()
elif arr_u.size == n_b:
hi_mat = np.repeat(arr_u.reshape(n_b, 1), h_total, axis=1)
# Inactive dates (outside `period` / `target_dates`) stay locked to their baseline forecasts.
active_set = set(active_t_indices)
for t_idx in range(h_total):
if t_idx not in active_set:
lo_mat[:, t_idx] = b_hat[:, t_idx]
hi_mat[:, t_idx] = b_hat[:, t_idx]
locked_mat[:, t_idx] = True
# Build linear equality constraints A_eq @ b_flat = c_eq
# (where b_flat is ordered by t then i: k = t * n_b + i).
eq_rows: list[np.ndarray] = []
eq_rhs: list[float] = []
def _node_s_row(nid_raw: str) -> np.ndarray:
nid = _canonicalize_sim_cluster_node_id(str(nid_raw), bottom_ids=set(b_to_idx))
if nid in node_to_idx:
return resolved_spec.summing_matrix[node_to_idx[nid]].copy()
# Allow shorthand like "North" matching "region=North".
for cand_nid, r_idx in node_to_idx.items():
if cand_nid.endswith(f"={nid}") or cand_nid == nid:
return resolved_spec.summing_matrix[r_idx].copy()
if nid in b_to_idx:
r = np.zeros(n_b, dtype=float)
r[b_to_idx[nid]] = 1.0
return r
raise ConfigError(
f"Unknown hierarchy node '{nid_raw}'; available nodes: {list(resolved_spec.node_ids)}"
)
# Process locked_nodes and locks.
for lock_arg in (locked_nodes, locks):
if lock_arg is None:
continue
if isinstance(lock_arg, Mapping):
for k_lock, val_lock in lock_arg.items():
s_r = _node_s_row(str(k_lock))
member_indices = np.flatnonzero(s_r > 0.5).tolist()
if len(member_indices) == 1 and (
target_mode == "per_step" or len(active_t_indices) == 1
):
idx_b = member_indices[0]
for t_idx in active_t_indices:
lo_mat[idx_b, t_idx] = float(val_lock)
hi_mat[idx_b, t_idx] = float(val_lock)
locked_mat[idx_b, t_idx] = True
elif len(member_indices) == 1:
# Single leaf locked to explicit horizon total val_lock across active_t_indices.
idx_b = member_indices[0]
base_slice = np.maximum(b_hat[idx_b, active_t_indices], 0.0)
base_sum = float(np.sum(base_slice))
shares = (
base_slice / base_sum
if base_sum > 1e-12
else np.full(
len(active_t_indices), 1.0 / len(active_t_indices), dtype=float
)
)
for pos_t, t_idx in enumerate(active_t_indices):
v_step = float(val_lock) * float(shares[pos_t])
if (
v_step < lo_mat[idx_b, t_idx] - _FEAS_TOL
or v_step > hi_mat[idx_b, t_idx] + _FEAS_TOL
):
raise GoalSeekInfeasibleError(
f"Locked value {val_lock} for '{k_lock}' violates its box bounds "
f"[{lo_mat[idx_b, t_idx]}, {hi_mat[idx_b, t_idx]}] at step {t_idx}."
)
lo_mat[idx_b, t_idx] = v_step
hi_mat[idx_b, t_idx] = v_step
locked_mat[idx_b, t_idx] = True
else:
# Aggregate node locked to explicit value val_lock across active_t_indices.
row_flat = np.zeros(n_b * h_total, dtype=float)
for t_idx in active_t_indices:
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r
eq_rows.append(row_flat)
eq_rhs.append(float(val_lock))
else:
for k_lock in lock_arg:
s_r = _node_s_row(str(k_lock))
member_indices = np.flatnonzero(s_r > 0.5).tolist()
if len(member_indices) == 1:
idx_b = member_indices[0]
for t_idx in active_t_indices:
val_b = float(b_hat[idx_b, t_idx])
if (
val_b < lo_mat[idx_b, t_idx] - _FEAS_TOL
or val_b > hi_mat[idx_b, t_idx] + _FEAS_TOL
):
raise GoalSeekInfeasibleError(
f"Locked baseline value {val_b:.4f} for '{k_lock}' violates "
f"its box bounds [{lo_mat[idx_b, t_idx]:.4f}, "
f"{hi_mat[idx_b, t_idx]:.4f}]."
)
lo_mat[idx_b, t_idx] = val_b
hi_mat[idx_b, t_idx] = val_b
locked_mat[idx_b, t_idx] = True
else:
# Aggregate node locked to its baseline forecast at each active timestamp.
for t_idx in active_t_indices:
row_flat = np.zeros(n_b * h_total, dtype=float)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r
eq_rows.append(row_flat)
eq_rhs.append(float(s_r @ b_hat[:, t_idx]))
# Add target equality constraint(s).
n_lock_eq = len(eq_rhs)
if isinstance(raw_target, pd.DataFrame):
if raw_target.empty:
raise ConfigError("target_total DataFrame cannot be empty")
val_col = (
"target"
if "target" in raw_target.columns
else ("yhat" if "yhat" in raw_target.columns else raw_target.columns[-1])
)
for trow in raw_target.to_dict(orient="records"):
nid_t = str(trow.get(ts_id_col, eff_target_node))
s_r = _node_s_row(nid_t)
if dcol in trow and trow[dcol] in date_to_t:
t_idx = date_to_t[trow[dcol]]
row_flat = np.zeros(n_b * h_total, dtype=float)
w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(float(trow[val_col]))
else:
row_flat = np.zeros(n_b * h_total, dtype=float)
for t_idx in active_t_indices:
w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(float(trow[val_col]))
elif isinstance(raw_target, Mapping):
if not raw_target:
raise ConfigError("target_total mapping cannot be empty")
# Determine whether keys are hierarchy node IDs or dates/steps.
sample_keys = list(raw_target.keys())
is_node_mapping = all(
_canonicalize_sim_cluster_node_id(str(k), bottom_ids=set(b_to_idx)) in node_to_idx
or str(k) in b_to_idx
or any(cand.endswith(f"={k}") for cand in node_to_idx)
for k in sample_keys
)
if is_node_mapping:
for k_node, v_targ in raw_target.items():
s_r = _node_s_row(str(k_node))
if target_mode == "per_step":
for t_idx in active_t_indices:
row_flat = np.zeros(n_b * h_total, dtype=float)
w_m = (
price_mat[:, t_idx]
if use_revenue_weights
else np.ones(n_b, dtype=float)
)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(float(v_targ))
else:
row_flat = np.zeros(n_b * h_total, dtype=float)
for t_idx in active_t_indices:
w_m = (
price_mat[:, t_idx]
if use_revenue_weights
else np.ones(n_b, dtype=float)
)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(float(v_targ))
else:
s_r = _node_s_row(eff_target_node)
for k_dt, v_targ in raw_target.items():
matched_t: int | None = None
if isinstance(k_dt, int) and 0 <= k_dt < h_total and k_dt not in date_to_t:
matched_t = k_dt
elif k_dt in date_to_t:
matched_t = date_to_t[k_dt]
else:
ts_k = pd.Timestamp(k_dt)
for dt_cand, t_cand in date_to_t.items():
if pd.Timestamp(dt_cand) == ts_k:
matched_t = t_cand
break
if matched_t is None:
raise ConfigError(
f"Target key '{k_dt}' did not match any hierarchy node or forecast date"
)
row_flat = np.zeros(n_b * h_total, dtype=float)
w_m = price_mat[:, matched_t] if use_revenue_weights else np.ones(n_b, dtype=float)
row_flat[matched_t * n_b : (matched_t + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(float(v_targ))
elif isinstance(raw_target, (Sequence, np.ndarray)) and not isinstance(
raw_target, (str, bytes)
):
seq_vals = [float(x) for x in raw_target]
if len(seq_vals) != len(active_t_indices):
raise ConfigError(
f"Target sequence length ({len(seq_vals)}) must match "
f"active horizon length ({len(active_t_indices)})."
)
s_r = _node_s_row(eff_target_node)
for pos_t, t_idx in enumerate(active_t_indices):
row_flat = np.zeros(n_b * h_total, dtype=float)
w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(seq_vals[pos_t])
else:
scalar_target = float(raw_target)
if not np.isfinite(scalar_target):
raise ConfigError(f"target_total must be finite; got {raw_target!r}")
s_r = _node_s_row(eff_target_node)
if target_mode == "per_step":
for t_idx in active_t_indices:
row_flat = np.zeros(n_b * h_total, dtype=float)
w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(scalar_target)
else:
row_flat = np.zeros(n_b * h_total, dtype=float)
for t_idx in active_t_indices:
w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
eq_rows.append(row_flat)
eq_rhs.append(scalar_target)
a_eq = np.vstack(eq_rows)
c_eq = np.asarray(eq_rhs, dtype=float)
# Build covariance blocks W_t across horizon steps t = 0..H-1.
w_cs = _resolve_bottom_covariance(
resolved_spec,
method,
weights,
b_hat=b_hat,
b_var_from_intervals=b_var_intervals,
oof_df=oof_df,
ts_id_col=ts_id_col,
)
eff_mode_str = str(weights if isinstance(weights, str) else method).strip().lower()
w_blocks: list[np.ndarray] = []
for t_idx in range(h_total):
if eff_mode_str in {"proportional", "baseline"}:
w_blocks.append(np.diag(np.maximum(np.abs(b_hat[:, t_idx]), 1e-4)))
elif (
b_var_intervals is not None
and oof_df is None
and not isinstance(weights, (Mapping, Sequence, np.ndarray))
):
w_blocks.append(np.diag(np.maximum(b_var_intervals[:, t_idx], _VAR_FLOOR)))
elif (
oof_df is None
and b_var_intervals is None
and eff_mode_str not in {"ols", "wls_struct", "struc", "uniform", "equal"}
and not isinstance(weights, (Mapping, Sequence, np.ndarray))
):
w_blocks.append(np.diag(np.maximum(np.abs(b_hat[:, t_idx]), 1.0) ** 2))
else:
w_blocks.append(w_cs)
# Flatten column-major by timestamp t: flat index k = t * n_b + i.
b_hat_flat = b_hat.T.reshape(-1)
lo_flat = lo_mat.T.reshape(-1)
hi_flat = hi_mat.T.reshape(-1)
b_alloc_flat = _solve_constrained_qp(
b_hat_flat,
w_blocks,
a_eq,
c_eq,
lo_flat,
hi_flat,
smoothness_weight=smooth_w,
)
b_alloc = b_alloc_flat.reshape(h_total, n_b).T # shape (n_b, H)
# Full hierarchy rollup Y_tilde = S @ B_alloc and Y_hat = S @ B_hat of shape (n_nodes, H).
s_mat = resolved_spec.summing_matrix
y_base_all = s_mat @ b_hat
y_alloc_all = s_mat @ b_alloc
lo_all = s_mat @ lo_mat
hi_all = np.where(
(s_mat @ np.where(np.isfinite(hi_mat), 0.0, 1.0)) > 0.0,
np.inf,
s_mat @ np.where(np.isfinite(hi_mat), hi_mat, 0.0),
)
# Normalized bottom-series allocation weights for transparency.
raw_series_w = np.diag(w_cs).copy()
w_sum = float(np.sum(raw_series_w))
norm_b_weights = raw_series_w / w_sum if w_sum > 1e-12 else np.full(n_b, 1.0 / n_b, dtype=float)
node_weights = s_mat @ norm_b_weights
# Determine which nodes to include in output DataFrame.
output_node_ids = (
list(resolved_spec.node_ids) if include_agg_in_out else list(resolved_spec.bottom_ids)
)
# Index original rows for interval extraction.
orig_by_key: dict[tuple[str, Any], dict[str, Any]] = {}
for r in df.to_dict(orient="records"):
orig_by_key[(str(r[ts_id_col]), r[dcol])] = {str(k): v for k, v in r.items()}
canon_tn = _canonicalize_sim_cluster_node_id(eff_target_node, bottom_ids=set(b_to_idx))
if canon_tn in node_to_idx:
target_node_idx = node_to_idx[canon_tn]
else:
target_node_idx = 0
for cand_nid, r_idx in node_to_idx.items():
if cand_nid.endswith(f"={canon_tn}") or cand_nid == canon_tn:
target_node_idx = r_idx
break
records: list[dict[str, Any]] = []
for nid in output_node_ids:
n_idx = node_to_idx[nid]
is_bottom = nid in b_to_idx
b_idx_opt = b_to_idx.get(nid)
for t_idx, dt_val in enumerate(all_dates):
base_v = float(y_base_all[n_idx, t_idx])
alloc_v = float(y_alloc_all[n_idx, t_idx])
d_v = alloc_v - base_v
d_pct = (100.0 * d_v / abs(base_v)) if abs(base_v) > 1e-12 else 0.0
lo_v = (
float(lo_mat[b_idx_opt, t_idx])
if b_idx_opt is not None
else float(lo_all[n_idx, t_idx])
)
hi_v = (
float(hi_mat[b_idx_opt, t_idx])
if b_idx_opt is not None
else float(hi_all[n_idx, t_idx])
)
is_lck = bool(locked_mat[b_idx_opt, t_idx]) if b_idx_opt is not None else False
if is_lck or abs(hi_v - lo_v) <= 1e-9:
c_status = "LOCKED"
elif np.isfinite(lo_v) and abs(alloc_v - lo_v) <= 1e-6 * max(1.0, abs(lo_v)):
c_status = "AT_FLOOR"
elif np.isfinite(hi_v) and abs(alloc_v - hi_v) <= 1e-6 * max(1.0, abs(hi_v)):
c_status = "AT_CAP"
else:
c_status = "FREE"
orig_r = orig_by_key.get((nid, dt_val), {})
base_lo = float(
orig_r.get(
"yhat_lower", orig_r.get("yhat_lower_80", base_v - 0.1 * max(abs(base_v), 1.0))
)
)
base_hi = float(
orig_r.get(
"yhat_upper", orig_r.get("yhat_upper_80", base_v + 0.1 * max(abs(base_v), 1.0))
)
)
hw = max(0.0, 0.5 * (base_hi - base_lo))
alloc_lo = alloc_v - hw
alloc_hi = alloc_v + hw
if np.isfinite(lo_v):
alloc_lo = max(lo_v, alloc_lo)
if np.isfinite(hi_v):
alloc_hi = min(hi_v, alloc_hi)
alloc_lo = min(alloc_lo, alloc_v)
alloc_hi = max(alloc_hi, alloc_v)
root_tot_t = float(y_alloc_all[target_node_idx, t_idx])
share_t = (
(alloc_v / root_tot_t)
if abs(root_tot_t) > 1e-12
else (
float(norm_b_weights[b_idx_opt])
if b_idx_opt is not None
else float(node_weights[n_idx])
)
)
rec: dict[str, Any] = {
ts_id_col: nid,
"model_type": eff_model_type,
"ds": pd.Timestamp(dt_val) if not isinstance(dt_val, (int, np.integer)) else dt_val,
"forecast_date": pd.Timestamp(dt_val)
if not isinstance(dt_val, (int, np.integer))
else dt_val,
"horizon_step": int(orig_r.get("horizon_step", t_idx + 1)),
"baseline_yhat": base_v,
"allocated_yhat": alloc_v,
"yhat": alloc_v,
"yhat_lower": alloc_lo,
"yhat_upper": alloc_hi,
"delta_yhat": d_v,
"delta_units": d_v,
"delta_pct": d_pct,
"lower_bound": lo_v,
"upper_bound": hi_v,
"is_locked": is_lck,
"allocation_weight": float(norm_b_weights[b_idx_opt])
if b_idx_opt is not None
else float(node_weights[n_idx]),
"constraint_status": c_status,
"yhat_baseline": base_v,
"yhat_allocated": alloc_v,
"y_allocated": alloc_v,
"bound_active": c_status != "FREE",
"allocation_share": share_t,
}
# Shift any explicit quantile columns (`yhat_lower_80`, `yhat_upper_95`, etc.).
for col_k, col_v in orig_r.items():
if col_k.startswith("yhat_lower_") and col_v is not None and pd.notna(col_v):
q_suf = col_k[len("yhat_lower_") :]
u_k = f"yhat_upper_{q_suf}"
u_v = orig_r.get(u_k)
if u_v is not None and pd.notna(u_v):
q_hw = max(0.0, 0.5 * (float(u_v) - float(col_v)))
q_lo = min(
alloc_v, max(lo_v if np.isfinite(lo_v) else -np.inf, alloc_v - q_hw)
)
q_hi = max(
alloc_v, min(hi_v if np.isfinite(hi_v) else np.inf, alloc_v + q_hw)
)
rec[col_k] = q_lo
rec[u_k] = q_hi
rec[f"allocated_{col_k}"] = q_lo
rec[f"allocated_{u_k}"] = q_hi
if has_price or has_cost:
s_row_n = s_mat[n_idx]
b_rev_vec = price_mat[:, t_idx] * b_hat[:, t_idx]
a_rev_vec = price_mat[:, t_idx] * b_alloc[:, t_idx]
b_rev = (
float(b_rev_vec[b_idx_opt])
if is_bottom and b_idx_opt is not None
else float(s_row_n @ b_rev_vec)
)
a_rev = (
float(a_rev_vec[b_idx_opt])
if is_bottom and b_idx_opt is not None
else float(s_row_n @ a_rev_vec)
)
rev_d = a_rev - b_rev
rev_pct = (100.0 * rev_d / abs(b_rev)) if abs(b_rev) > 1e-12 else 0.0
eff_p = (
float(price_mat[b_idx_opt, t_idx])
if is_bottom and b_idx_opt is not None
else ((a_rev / alloc_v) if abs(alloc_v) > 1e-12 else 1.0)
)
rec.update(
{
"price": eff_p,
"baseline_revenue": b_rev,
"allocated_revenue": a_rev,
"scenario_revenue": a_rev,
"revenue_delta": rev_d,
"delta_revenue": rev_d,
"revenue_delta_pct": rev_pct,
}
)
if has_cost:
b_gm_vec = (price_mat[:, t_idx] - cost_mat[:, t_idx]) * b_hat[:, t_idx]
a_gm_vec = (price_mat[:, t_idx] - cost_mat[:, t_idx]) * b_alloc[:, t_idx]
b_gm = (
float(b_gm_vec[b_idx_opt])
if is_bottom and b_idx_opt is not None
else float(s_row_n @ b_gm_vec)
)
a_gm = (
float(a_gm_vec[b_idx_opt])
if is_bottom and b_idx_opt is not None
else float(s_row_n @ a_gm_vec)
)
gm_d = a_gm - b_gm
gm_pct = (100.0 * gm_d / abs(b_gm)) if abs(b_gm) > 1e-12 else 0.0
eff_c = (
float(cost_mat[b_idx_opt, t_idx])
if is_bottom and b_idx_opt is not None
else (((a_rev - a_gm) / alloc_v) if abs(alloc_v) > 1e-12 else 0.0)
)
rec.update(
{
"unit_cost": eff_c,
"baseline_gross_margin": b_gm,
"allocated_gross_margin": a_gm,
"scenario_gross_margin": a_gm,
"gross_margin_delta": gm_d,
"delta_gross_margin": gm_d,
"gross_margin_delta_pct": gm_pct,
}
)
records.append(rec)
out_df = pd.DataFrame.from_records(records)
# Optional inventory replenishment policy delta via diagnostics.compute_inventory_policy.
if (include_inventory_impact or inventory_params is not None) and not out_df.empty:
from .diagnostics import compute_inventory_policy
inv_kw: dict[str, Any] = {
"lead_time": float(lead_time),
"lead_time_std": float(lead_time_std),
"service_level": service_level,
}
if inventory_params:
inv_kw.update(dict(inventory_params))
base_for_inv = out_df.copy()
base_for_inv["yhat"] = base_for_inv["baseline_yhat"]
hw_curr = 0.5 * (
out_df["yhat_upper"].to_numpy(dtype=float) - out_df["yhat_lower"].to_numpy(dtype=float)
)
base_for_inv["yhat_lower"] = base_for_inv["baseline_yhat"] - hw_curr
base_for_inv["yhat_upper"] = base_for_inv["baseline_yhat"] + hw_curr
base_pol = compute_inventory_policy(base_for_inv, oof_df=oof_df, **inv_kw)
alloc_pol = compute_inventory_policy(out_df, oof_df=oof_df, **inv_kw)
base_inv_map = {str(r["ts_id"]): r for r in base_pol.to_dict(orient="records")}
alloc_inv_map = {str(r["ts_id"]): r for r in alloc_pol.to_dict(orient="records")}
b_rop: list[float] = []
a_rop: list[float] = []
d_rop: list[float] = []
b_ss: list[float] = []
a_ss: list[float] = []
d_ss: list[float] = []
b_q: list[float] = []
a_q: list[float] = []
d_q: list[float] = []
for tid_val in out_df[ts_id_col].astype(str):
br = base_inv_map.get(tid_val, {})
ar = alloc_inv_map.get(tid_val, {})
rop_0 = float(br.get("reorder_point", 0.0))
rop_1 = float(ar.get("reorder_point", rop_0))
ss_0 = float(br.get("safety_stock", 0.0))
ss_1 = float(ar.get("safety_stock", ss_0))
q_0 = float(br.get("recommended_order_qty", 0.0))
q_1 = float(ar.get("recommended_order_qty", q_0))
b_rop.append(rop_0)
a_rop.append(rop_1)
d_rop.append(rop_1 - rop_0)
b_ss.append(ss_0)
a_ss.append(ss_1)
d_ss.append(ss_1 - ss_0)
b_q.append(q_0)
a_q.append(q_1)
d_q.append(q_1 - q_0)
out_df["baseline_reorder_point"] = b_rop
out_df["allocated_reorder_point"] = a_rop
out_df["scenario_reorder_point"] = a_rop
out_df["delta_reorder_point"] = d_rop
out_df["baseline_safety_stock"] = b_ss
out_df["allocated_safety_stock"] = a_ss
out_df["scenario_safety_stock"] = a_ss
out_df["delta_safety_stock"] = d_ss
out_df["baseline_order_qty"] = b_q
out_df["allocated_order_qty"] = a_q
out_df["scenario_order_qty"] = a_q
out_df["delta_order_qty"] = d_q
coh_err = float(np.max(np.abs(a_eq @ b_alloc_flat - c_eq)))
target_eq_rhs = eq_rhs[n_lock_eq:]
target_tot_val = float(np.sum(target_eq_rhs)) if target_eq_rhs else float(np.sum(c_eq))
out_df.attrs["hierarchy_spec"] = resolved_spec
out_df.attrs["target_node"] = eff_target_node
out_df.attrs["target_total"] = target_tot_val
out_df.attrs["coherence_max_abs_error"] = coh_err
out_df.attrs["smoothness_weight"] = smooth_w
if return_result:
sum_df = summarize_goal_seek(out_df, ts_id_col=ts_id_col)
return GoalSeekResult(
allocations=out_df,
summary=sum_df,
target_node=eff_target_node,
target_total=target_tot_val,
baseline_total=float(np.sum(y_base_all[target_node_idx, active_t_indices])),
allocated_total=float(np.sum(y_alloc_all[target_node_idx, active_t_indices])),
coherence_max_abs_error=coh_err,
active_bound_count=int(np.sum(out_df["bound_active"])),
locked_count=int(np.sum(out_df["is_locked"])),
)
return out_df