def optimize_scenario(
forecaster_or_df: Any,
*,
config: RunConfig | Mapping[str, Any] | None = None,
cfg: RunConfig | Mapping[str, Any] | None = None,
predictions_df: pd.DataFrame | None = None,
forecasts_df: pd.DataFrame | None = None,
oof_df: pd.DataFrame | None = None,
history_df: pd.DataFrame | None = None,
data: pd.DataFrame | None = None,
future_covariates_df: pd.DataFrame | None = None,
trajectories_df: pd.DataFrame | None = None,
model_name: str | None = None,
model_type: str | None = None,
objective: Literal[
"gross_profit",
"gross_margin",
"revenue",
"units",
"risk_adjusted_profit",
"target_demand",
] = "gross_profit",
price_col: str | None = None,
promo_col: str | None = None,
price_bounds: tuple[float, float] | Mapping[str, tuple[float, float]] = (-0.15, 0.15),
price_grid: Sequence[float] | Mapping[str, Sequence[float]] | None = None,
promo_bounds: tuple[float, float] = (0.0, 1.0),
binary_promo: bool = True,
max_promo_days: int | Mapping[str, int] | None = None,
min_cooldown_days: int = 0,
cooldown_days: int | None = None,
unit_cost: float | Mapping[str, float] | None = None,
promo_fixed_cost: float | Mapping[str, float] = 0.0,
min_margin_pct: float | None = None,
min_gross_margin_pct: float | None = None,
min_gross_margin: float | None = None,
min_total_units: float | None = None,
max_total_units: float | None = None,
target_total_units: float | None = None,
max_promo_budget: float | None = None,
inventory_cap: float | Mapping[str, float] | None = None,
risk_aversion_lambda: float = 0.0,
risk_aversion: float | None = None,
cvar_alpha: float = 0.95,
risk_alpha: float | None = None,
pull_forward_lags: int = 3,
cannibalization_weight: float = 1.0,
use_similarity_priors: bool = True,
similarity_matrix: pd.DataFrame | np.ndarray | None = None,
similarity_method: str = "hybrid",
reconcile: bool = True,
hier_spec: HierarchySpec | None = None,
temp_spec: Any = None,
include_inventory_impact: bool = True,
lead_time: float = 7.0,
lead_time_std: float = 0.0,
service_level: float | None = 0.95,
n_paths: int = 250,
copula_type: str = "auto",
seed: int = 42,
ts_id_col: str = "ts_id",
date_col: str = "ds",
target_col: str = "y",
horizon: int | None = None,
freq: str | None = None,
strict_feasibility: bool = False,
) -> ScenarioOptimizationResult:
"""Prescribe the optimal future price and promotional calendar across a forecast horizon.
Solves a two-phase mixed-integer / continuous optimization problem over causal response
surfaces (`@monotone` price elasticity, Double-ML `promo_elasticity_df` promotional lift,
post-promotion `pull_forward_dip` lags, and cross-SKU cannibalization), enforcing operational
guardrails (`price_bounds` / `price_grid`, `max_promo_days`, `min_cooldown_days`,
`min_margin_pct`, `min_total_units`, `max_total_units`, `max_promo_budget`, and CVaR
risk-adjusted profit), then propagates the optimal schedule through 3-mode hierarchy
reconciliation and `(s, S)` inventory policy deltas.
"""
eff_cfg = config if config is not None else cfg
eff_preds_in = predictions_df if predictions_df is not None else forecasts_df
eff_hist_in = history_df if history_df is not None else data
eff_cooldown = int(cooldown_days) if cooldown_days is not None else int(min_cooldown_days)
eff_min_margin_pct = (
float(min_margin_pct)
if min_margin_pct is not None
else (float(min_gross_margin_pct) if min_gross_margin_pct is not None else None)
)
if eff_min_margin_pct is not None and eff_min_margin_pct > 1.0:
eff_min_margin_pct = eff_min_margin_pct / 100.0
eff_risk_lambda = (
float(risk_aversion) if risk_aversion is not None else float(risk_aversion_lambda)
)
eff_cvar_alpha = float(risk_alpha) if risk_alpha is not None else float(cvar_alpha)
obj_norm = str(objective).strip().lower()
if obj_norm == "gross_margin":
obj_norm = "gross_profit"
if obj_norm not in (
"gross_profit",
"revenue",
"units",
"risk_adjusted_profit",
"target_demand",
):
raise _ScenarioOptimizerError(
f"Unsupported objective={objective!r}; expected 'gross_profit', 'revenue', "
"'units', or 'risk_adjusted_profit'."
)
if obj_norm == "risk_adjusted_profit" and eff_risk_lambda <= 0.0:
eff_risk_lambda = 0.35
if eff_cooldown < 0:
raise _ScenarioOptimizerError(f"min_cooldown_days={eff_cooldown!r} must be >= 0.")
if not (0.0 < eff_cvar_alpha < 1.0):
raise _ScenarioOptimizerError(f"cvar_alpha={eff_cvar_alpha!r} must lie strictly in (0, 1).")
if eff_min_margin_pct is not None and not (-1.0 < eff_min_margin_pct < 1.0):
raise _ScenarioOptimizerError(
f"min_margin_pct={min_margin_pct!r} must lie strictly in (-1.0, 1.0)."
)
if (
min_total_units is not None
and max_total_units is not None
and float(min_total_units) > float(max_total_units) + 1e-9
):
raise GoalSeekInfeasibleError(
f"Infeasible unit bounds: min_total_units={min_total_units} > "
f"max_total_units={max_total_units}."
)
pred_df, resolved_oof, resolved_hist, parsed_cfg = _resolve_inputs(
forecaster_or_df,
config=eff_cfg,
predictions_df=eff_preds_in,
oof_df=oof_df,
history_df=eff_hist_in,
ts_id_col=ts_id_col,
date_col=date_col,
target_col=target_col,
horizon=horizon,
freq=freq,
)
if pred_df is None or pred_df.empty:
empty_sched = pd.DataFrame(columns=SCENARIO_OPTIMIZATION_COLUMNS)
empty_sum = pd.DataFrame(columns=SCENARIO_OPTIMIZATION_SUMMARY_COLUMNS)
empty_inv = pd.DataFrame(
columns=[
"ts_id",
"model_type",
"baseline_reorder_point",
"optimal_reorder_point",
"delta_reorder_point",
"baseline_safety_stock",
"optimal_safety_stock",
"delta_safety_stock",
"baseline_order_qty",
"optimal_order_qty",
"delta_order_qty",
]
)
return ScenarioOptimizationResult(
schedule_df=empty_sched,
summary_df=empty_sum,
inventory_delta_df=empty_inv,
objective=obj_norm,
feasibility_status="empty",
baseline_objective_value=0.0,
optimal_objective_value=0.0,
objective_improvement=0.0,
objective_improvement_pct=0.0,
baseline_total_units=0.0,
optimal_total_units=0.0,
delta_units_pct=0.0,
baseline_total_revenue=0.0,
optimal_total_revenue=0.0,
revenue_delta=0.0,
revenue_delta_pct=0.0,
baseline_total_gross_margin=0.0,
optimal_total_gross_margin=0.0,
gross_margin_delta=0.0,
gross_margin_delta_pct=0.0,
cvar_profit=0.0,
baseline_cvar_profit=0.0,
promo_budget_used=0.0,
coherence_max_abs_error=0.0,
recommended_shocks={},
)
work = pred_df.copy()
if "segment" in work.columns and (work["segment"] == "forecast").any():
work = work[work["segment"] == "forecast"].copy()
p_tid_col = (
ts_id_col if ts_id_col in work.columns else ("ts_id" if "ts_id" in work.columns else None)
)
if p_tid_col is None:
work["ts_id"] = "series_0"
p_tid_col = "ts_id"
elif p_tid_col != "ts_id":
work["ts_id"] = work[p_tid_col].astype(str)
p_dt_col = (
"forecast_date"
if "forecast_date" in work.columns
else (
date_col
if date_col in work.columns
else ("ds" if "ds" in work.columns else "target_date")
)
)
work["_dt"] = pd.to_datetime(work[p_dt_col])
if "model_type" not in work.columns:
work["model_type"] = model_name or model_type or "model"
eff_model = model_name or model_type
if eff_model is not None and str(eff_model).lower() not in ("all", "*"):
sub_m = work[work["model_type"].astype(str) == str(eff_model)]
if not sub_m.empty:
work = sub_m.copy()
else:
# Select single primary model_type if multiple models exist in predictions_df
unique_models = [str(x) for x in work["model_type"].drop_duplicates().tolist()]
if len(unique_models) > 1:
ens_models = [m for m in unique_models if m.startswith("ensemble_")]
chosen_m = ens_models[0] if ens_models else unique_models[0]
work = work[work["model_type"].astype(str) == chosen_m].copy()
chosen_model_type = str(work["model_type"].iloc[0])
work = work.sort_values(["ts_id", "_dt"]).reset_index(drop=True)
# Resolve hierarchy specification (`HierarchySpec`) if hierarchical reconciliation is active
resolved_hier: HierarchySpec | None = hier_spec
if (
resolved_hier is None
and parsed_cfg is not None
and (
parsed_cfg.hierarchy.levels
or getattr(parsed_cfg.hierarchy, "similarity_hierarchy", False)
)
and resolved_hist is not None
and not resolved_hist.empty
):
needed_cols = {c for lvl in parsed_cfg.hierarchy.levels for c in lvl} - {
"similarity_cluster_id"
}
if needed_cols.issubset(resolved_hist.columns):
try:
_, resolved_hier = build_hierarchy(resolved_hist, parsed_cfg)
except Exception: # noqa: BLE001 - fallback if hierarchy build fails
resolved_hier = None
all_present_ids = [str(x) for x in work["ts_id"].drop_duplicates().tolist()]
if resolved_hier is not None:
bottom_ids = [bid for bid in resolved_hier.bottom_ids if bid in all_present_ids]
if not bottom_ids:
bottom_ids = [tid for tid in all_present_ids if tid != TOTAL_NODE_ID]
else:
if TOTAL_NODE_ID in all_present_ids and len(all_present_ids) > 1:
bottom_ids = [tid for tid in all_present_ids if tid != TOTAL_NODE_ID]
n_b = len(bottom_ids)
s_mat = np.vstack([np.ones((1, n_b), dtype=float), np.eye(n_b, dtype=float)])
resolved_hier = HierarchySpec(
node_ids=(TOTAL_NODE_ID, *bottom_ids),
bottom_ids=tuple(bottom_ids),
level_nodes={TOTAL_NODE_ID: (TOTAL_NODE_ID,), "__bottom__": tuple(bottom_ids)},
summing_matrix=s_mat,
)
else:
bottom_ids = list(all_present_ids)
n_bottom = len(bottom_ids)
# Build aligned date grid across bottom_ids
first_grp = work[work["ts_id"].astype(str) == bottom_ids[0]].sort_values("_dt")
dates_grid = first_grp["_dt"].to_numpy()
h_steps = len(dates_grid)
# Detect price_col and promo_col from future_covariates_df, work, or resolved_hist
search_df = (
future_covariates_df
if (future_covariates_df is not None and not future_covariates_df.empty)
else (resolved_hist if (resolved_hist is not None and not resolved_hist.empty) else work)
)
det_promo, det_price = detect_treatment_cols(
search_df,
promo_col=promo_col,
price_col=price_col,
exclude_cols={
"ts_id",
"ds",
"forecast_date",
"target_date",
"y",
"yhat",
"yhat_lower",
"yhat_upper",
},
)
eff_promo_col = promo_col or det_promo or "promo"
eff_price_col = price_col or det_price or "price"
# Extract baseline yhat, lower/upper intervals, baseline price, baseline promo, and unit cost
base_yhat = np.zeros((n_bottom, h_steps), dtype=float)
base_lo = np.zeros((n_bottom, h_steps), dtype=float)
base_hi = np.zeros((n_bottom, h_steps), dtype=float)
base_price = np.zeros((n_bottom, h_steps), dtype=float)
base_promo = np.zeros((n_bottom, h_steps), dtype=float)
cost_vec = np.zeros(n_bottom, dtype=float)
promo_cost_vec = np.zeros(n_bottom, dtype=float)
inv_cap_vec = np.full(n_bottom, np.inf, dtype=float)
yhat_col_name = "yhat" if "yhat" in work.columns else "forecast"
for i, bid in enumerate(bottom_ids):
grp_b = work[work["ts_id"].astype(str) == bid].sort_values("_dt")
yh_b = (
pd.to_numeric(grp_b[yhat_col_name], errors="coerce").fillna(0.0).to_numpy(dtype=float)
)
yh_b = np.resize(yh_b, h_steps) if len(yh_b) < h_steps else yh_b[:h_steps]
yh_b = np.maximum(0.0, yh_b)
base_yhat[i, :] = yh_b
if "yhat_lower" in grp_b.columns:
yl_raw = pd.to_numeric(grp_b["yhat_lower"], errors="coerce").to_numpy(dtype=float)[
:h_steps
]
yl_b = np.where(np.isfinite(yl_raw), yl_raw, 0.8 * yh_b)
else:
yl_b = np.maximum(0.0, 0.85 * yh_b)
if "yhat_upper" in grp_b.columns:
yu_raw = pd.to_numeric(grp_b["yhat_upper"], errors="coerce").to_numpy(dtype=float)[
:h_steps
]
yu_b = np.where(np.isfinite(yu_raw), yu_raw, 1.2 * yh_b)
else:
yu_b = 1.15 * yh_b
base_lo[i, :] = yl_b
base_hi[i, :] = yu_b
# Resolve unit_cost first so default baseline_price is always profitable (> unit_cost)
if isinstance(unit_cost, Mapping):
uc_i = float(unit_cost.get(bid, 4.50))
elif unit_cost is not None:
uc_i = float(unit_cost)
elif "unit_cost" in grp_b.columns:
uc_i = float(pd.to_numeric(grp_b["unit_cost"], errors="coerce").fillna(4.50).iloc[0])
else:
uc_i = 4.50
cost_vec[i] = max(0.0, uc_i)
default_p0 = max(10.0, cost_vec[i] * 2.2)
p_arr: np.ndarray | None = None
for src_df in (future_covariates_df, grp_b, resolved_hist):
if src_df is not None and not src_df.empty and eff_price_col in src_df.columns:
sub_s = (
src_df[src_df["ts_id"].astype(str) == bid]
if "ts_id" in src_df.columns
else src_df
)
if not sub_s.empty:
vals_p = (
pd.to_numeric(sub_s[eff_price_col], errors="coerce")
.dropna()
.to_numpy(dtype=float)
)
if vals_p.size > 0:
if src_df is resolved_hist:
p_arr = np.full(
h_steps, float(np.nanpercentile(vals_p, 75)), dtype=float
)
else:
p_arr = np.resize(vals_p, h_steps).astype(float)
break
base_price[i, :] = np.maximum(
1e-3, p_arr if p_arr is not None else np.full(h_steps, default_p0)
)
# If unit_cost was not explicitly provided and default cost >= base_price,
# set cost = 0.45 * base_price
if unit_cost is None and cost_vec[i] >= 0.85 * float(np.mean(base_price[i, :])):
cost_vec[i] = 0.45 * float(np.mean(base_price[i, :]))
d_arr: np.ndarray | None = None
for src_df in (future_covariates_df, grp_b):
if src_df is not None and not src_df.empty and eff_promo_col in src_df.columns:
sub_s = (
src_df[src_df["ts_id"].astype(str) == bid]
if "ts_id" in src_df.columns
else src_df
)
if not sub_s.empty:
vals_d = (
pd.to_numeric(sub_s[eff_promo_col], errors="coerce")
.fillna(0.0)
.to_numpy(dtype=float)
)
if vals_d.size > 0:
d_arr = np.clip(np.resize(vals_d, h_steps), 0.0, 1.0)
break
base_promo[i, :] = d_arr if d_arr is not None else np.zeros(h_steps, dtype=float)
if isinstance(promo_fixed_cost, Mapping):
pc_i = float(promo_fixed_cost.get(bid, 0.0))
else:
pc_i = float(promo_fixed_cost)
if pc_i <= 0.0 and max_promo_budget is not None:
pc_i = 1.0
promo_cost_vec[i] = max(0.0, pc_i)
if isinstance(inventory_cap, Mapping) and bid in inventory_cap:
inv_cap_vec[i] = float(inventory_cap[bid])
elif isinstance(inventory_cap, (int, float)):
inv_cap_vec[i] = float(inventory_cap)
# Estimate structural elasticity parameters (own-price elasticity, promo lift,
# pull-forward lags, and cross-SKU cannibalization)
eps_vec, promo_lift_rate, lag_dip_rates, cannib_matrix = _estimate_sku_structural_params(
bottom_ids=bottom_ids,
horizon=h_steps,
base_yhat=base_yhat,
base_price=base_price,
base_promo=base_promo,
history_df=resolved_hist,
ts_id_col=ts_id_col,
date_col=date_col,
target_col=target_col,
promo_col=eff_promo_col,
price_col=eff_price_col,
pull_forward_lags=pull_forward_lags,
cannibalization_weight=cannibalization_weight,
use_similarity_priors=use_similarity_priors,
similarity_matrix=similarity_matrix,
similarity_method=similarity_method,
)
n_lags = lag_dip_rates.shape[1]
# Build candidate price grids per SKU `i` and step `h`
price_candidates_per_sku: list[np.ndarray] = []
price_bounds_per_sku: list[tuple[float, float]] = []
for i, bid in enumerate(bottom_ids):
p0_mean = float(np.mean(base_price[i, :]))
if price_grid is not None:
raw_grid = (
price_grid[bid]
if isinstance(price_grid, Mapping) and bid in price_grid
else (
next(iter(price_grid.values()))
if isinstance(price_grid, Mapping)
else price_grid
)
)
g_arr = np.asarray(list(raw_grid), dtype=float)
if g_arr.size == 0:
raise _ScenarioOptimizerError(f"Empty price_grid for ts_id={bid!r}.")
# If grid values look like relative percentage shifts in [-0.8, 0.8]
if float(np.max(np.abs(g_arr))) <= 0.80 and p0_mean > 1.5:
rel_grid = np.sort(np.unique(np.append(g_arr, 0.0)))
else:
rel_grid = np.sort((g_arr - p0_mean) / max(p0_mean, 1e-6))
price_candidates_per_sku.append(rel_grid)
price_bounds_per_sku.append((float(np.min(rel_grid)), float(np.max(rel_grid))))
else:
b_tuple = (
price_bounds[bid]
if isinstance(price_bounds, Mapping) and bid in price_bounds
else (
next(iter(price_bounds.values()))
if isinstance(price_bounds, Mapping)
else price_bounds
)
)
lo_b, hi_b = float(b_tuple[0]), float(b_tuple[1])
if lo_b > hi_b:
raise _ScenarioOptimizerError(
f"Invalid price_bounds=({lo_b}, {hi_b}) for ts_id={bid!r}: lower > upper."
)
# Interpret bounds as relative shifts if within [-0.95, 2.0] and lo_b < 0 or hi_b < 1.0,
# else convert literal price bounds to relative shifts
if lo_b >= 0.5 and hi_b > 1.0 and p0_mean > 1.0 and lo_b > 0.2 * p0_mean:
rel_lo = (lo_b - p0_mean) / p0_mean
rel_hi = (hi_b - p0_mean) / p0_mean
else:
rel_lo, rel_hi = lo_b, hi_b
rel_grid = np.sort(np.unique(np.append(np.linspace(rel_lo, rel_hi, 11), 0.0)))
price_candidates_per_sku.append(rel_grid)
price_bounds_per_sku.append((rel_lo, rel_hi))
# Resolve per-SKU max_promo_days
max_promo_per_sku = np.full(n_bottom, h_steps, dtype=int)
for i, bid in enumerate(bottom_ids):
if isinstance(max_promo_days, Mapping) and bid in max_promo_days:
max_promo_per_sku[i] = max(0, int(max_promo_days[bid]))
elif isinstance(max_promo_days, (int, float)):
max_promo_per_sku[i] = max(0, int(max_promo_days))
# Sample zero-mean demand residual paths for CVaR calculation
rng = np.random.default_rng(int(seed))
half_w = np.maximum(0.5 * (base_hi - base_lo), 0.10 * base_yhat)
sigma_mat = np.maximum(half_w / 1.28155, 1e-4)
n_cvar_paths = max(50, min(int(n_paths), 400))
# AR(1) correlated residual paths across horizon steps
idx_h = np.arange(h_steps)
corr_h = 0.40 ** np.abs(idx_h[:, None] - idx_h[None, :])
chol_h = np.linalg.cholesky(0.98 * corr_h + 0.02 * np.eye(h_steps))
noise_paths = np.zeros((n_cvar_paths, n_bottom, h_steps), dtype=float)
for i in range(n_bottom):
z_draw = rng.standard_normal((n_cvar_paths, h_steps)) @ chol_h.T
noise_paths[:, i, :] = z_draw * sigma_mat[i, None, :]
# Helper: evaluate demand components for a given `(rel_price_mat, promo_mat)`
def _evaluate_schedule(
rel_p: np.ndarray,
promo_m: np.ndarray,
) -> dict[str, Any]:
price_m = base_price * (1.0 + rel_p)
# Price demand lift: downward-sloping `@monotone` response
price_lift_m = base_yhat * (eps_vec[:, None] * rel_p)
# Direct promo lift
promo_lift_m = base_yhat * (promo_lift_rate[:, None] * (promo_m - base_promo))
# Post-promo pull-forward dip lags (lags 1..L)
pf_dip_m = np.zeros((n_bottom, h_steps), dtype=float)
for lag_idx in range(n_lags):
lag_step = lag_idx + 1
if h_steps > lag_step:
pf_dip_m[:, lag_step:] += (
base_yhat[:, lag_step:]
* lag_dip_rates[:, lag_idx : lag_idx + 1]
* promo_m[:, :-lag_step]
)
# Cross-SKU cannibalization dip
cannib_m = np.zeros((n_bottom, h_steps), dtype=float)
if n_bottom >= 2:
for i in range(n_bottom):
for j in range(n_bottom):
if i != j and cannib_matrix[i, j] != 0.0:
cannib_m[i, :] += base_yhat[i, :] * cannib_matrix[i, j] * promo_m[j, :]
raw_yhat = base_yhat + price_lift_m + promo_lift_m + pf_dip_m + cannib_m
opt_yhat = np.maximum(0.0, raw_yhat)
# Apply optional per-SKU horizon inventory cap
for i in range(n_bottom):
if np.isfinite(inv_cap_vec[i]):
tot_i = float(np.sum(opt_yhat[i, :]))
if tot_i > inv_cap_vec[i] and tot_i > 1e-9:
opt_yhat[i, :] *= inv_cap_vec[i] / tot_i
rev_m = price_m * opt_yhat
promo_spend = float(np.sum(promo_cost_vec[:, None] * promo_m))
gm_m = (price_m - cost_vec[:, None]) * opt_yhat - (promo_cost_vec[:, None] * promo_m)
tot_units = float(np.sum(opt_yhat))
tot_rev = float(np.sum(rev_m))
tot_gm = float(np.sum(gm_m))
margin_pct_val = tot_gm / max(tot_rev, 1e-9)
# Compute profit distribution across `noise_paths` for CVaR_(cvar_alpha)
# Downside profit risk increases with unit margin (price - cost) and promo fixed spend
unit_margin_m = price_m - cost_vec[:, None]
path_Demand = np.maximum(0.0, opt_yhat[None, :, :] + noise_paths)
path_profits = np.sum(unit_margin_m[None, :, :] * path_Demand, axis=(1, 2)) - promo_spend
tail_frac = max(1.0 - eff_cvar_alpha, 0.01)
n_tail = max(1, round(tail_frac * n_cvar_paths))
sorted_profits = np.sort(path_profits)
cvar_val = float(np.mean(sorted_profits[:n_tail]))
expected_profit = float(np.mean(path_profits))
if obj_norm == "gross_profit":
obj_val = (
tot_gm
if eff_risk_lambda <= 0.0
else (1.0 - eff_risk_lambda) * tot_gm + eff_risk_lambda * cvar_val
)
elif obj_norm == "revenue":
obj_val = tot_rev
elif obj_norm == "units":
obj_val = tot_units
elif obj_norm == "risk_adjusted_profit":
obj_val = (1.0 - eff_risk_lambda) * expected_profit + eff_risk_lambda * cvar_val
else: # target_demand
target_u = (
float(target_total_units)
if target_total_units is not None
else float(np.sum(base_yhat)) * 1.05
)
obj_val = -abs(tot_units - target_u) + 1e-3 * tot_gm
return {
"rel_p": rel_p,
"promo_m": promo_m,
"price_m": price_m,
"price_lift_m": price_lift_m,
"promo_lift_m": promo_lift_m,
"pf_dip_m": pf_dip_m,
"cannib_m": cannib_m,
"opt_yhat": opt_yhat,
"rev_m": rev_m,
"gm_m": gm_m,
"tot_units": tot_units,
"tot_rev": tot_rev,
"tot_gm": tot_gm,
"margin_pct": margin_pct_val,
"cvar_profit": cvar_val,
"promo_spend": promo_spend,
"obj_val": float(obj_val),
}
baseline_eval = _evaluate_schedule(
np.zeros((n_bottom, h_steps), dtype=float), base_promo.copy()
)
# Phase 1: Solve Mixed-Integer Linear Program (`scipy.optimize.milp` HiGHS) over discrete
# price ladder w_{i,h,k} in {0, 1} and promo calendar z_{i,h} in {0, 1}.
rel_p_milp, promo_milp, milp_status = _solve_phase1_milp(
n_bottom=n_bottom,
h_steps=h_steps,
base_yhat=base_yhat,
base_price=base_price,
base_promo=base_promo,
cost_vec=cost_vec,
promo_cost_vec=promo_cost_vec,
eps_vec=eps_vec,
promo_lift_rate=promo_lift_rate,
lag_dip_rates=lag_dip_rates,
cannib_matrix=cannib_matrix,
sigma_mat=sigma_mat,
price_candidates_per_sku=price_candidates_per_sku,
promo_bounds=promo_bounds,
binary_promo=binary_promo,
max_promo_per_sku=max_promo_per_sku,
cooldown_days=eff_cooldown,
min_margin_pct=eff_min_margin_pct,
min_gross_margin=min_gross_margin,
min_total_units=min_total_units,
max_total_units=max_total_units,
max_promo_budget=max_promo_budget,
obj_norm=obj_norm,
risk_lambda=eff_risk_lambda,
cvar_alpha=eff_cvar_alpha,
strict_feasibility=strict_feasibility,
)
best_eval = _evaluate_schedule(rel_p_milp, promo_milp)
feasibility_status = milp_status
# Phase 2: Continuous SLSQP price refinement when `price_grid is None`
if price_grid is None:
rel_p_slsqp = _polish_prices_slsqp(
init_rel_p=rel_p_milp,
fixed_promo=promo_milp,
price_bounds_per_sku=price_bounds_per_sku,
evaluate_fn=_evaluate_schedule,
min_margin_pct=eff_min_margin_pct,
min_gross_margin=min_gross_margin,
min_total_units=min_total_units,
max_total_units=max_total_units,
)
cand_eval = _evaluate_schedule(rel_p_slsqp, promo_milp)
if (
_is_schedule_feasible(
cand_eval,
min_margin_pct=eff_min_margin_pct,
min_gross_margin=min_gross_margin,
min_total_units=min_total_units,
max_total_units=max_total_units,
)
and cand_eval["obj_val"] >= best_eval["obj_val"] - 1e-9
):
best_eval = cand_eval
# Build bottom-level and reconciled hierarchy rows
opt_yhat_b = best_eval["opt_yhat"]
opt_price_b = best_eval["price_m"]
opt_promo_b = best_eval["promo_m"]
rel_p_b = best_eval["rel_p"]
price_lift_b = best_eval["price_lift_m"]
promo_lift_b = best_eval["promo_lift_m"]
pf_dip_b = best_eval["pf_dip_m"]
cannib_b = best_eval["cannib_m"]
opt_rev_b = best_eval["rev_m"]
opt_gm_b = best_eval["gm_m"]
base_rev_b = base_price * base_yhat
base_gm_b = (base_price - cost_vec[:, None]) * base_yhat - (
promo_cost_vec[:, None] * base_promo
)
# Assemble step-level records for bottom-level series and (when reconcile=True)
# exact bottom-up reconciled aggregate hierarchy nodes (`S @ b_t`)
if reconcile and resolved_hier is not None and resolved_hier.n_aggregated > 0:
s_mat = np.asarray(resolved_hier.summing_matrix, dtype=float)
# Ensure s_mat columns match bottom_ids
if s_mat.shape[1] == n_bottom:
all_node_ids = list(resolved_hier.node_ids)
full_base_yhat = s_mat @ base_yhat
full_opt_yhat = s_mat @ opt_yhat_b
full_base_lo = s_mat @ base_lo
full_base_hi = s_mat @ base_hi
full_price_lift = s_mat @ price_lift_b
full_promo_lift = s_mat @ promo_lift_b
full_pf_dip = s_mat @ pf_dip_b
full_cannib = s_mat @ cannib_b
full_base_rev = s_mat @ base_rev_b
full_opt_rev = s_mat @ opt_rev_b
full_base_gm = s_mat @ base_gm_b
full_opt_gm = s_mat @ opt_gm_b
node_counts = np.maximum(s_mat.sum(axis=1), 1.0)
full_base_promo = (s_mat @ base_promo) / node_counts[:, None]
full_opt_promo = (s_mat @ opt_promo_b) / node_counts[:, None]
full_cost = (s_mat @ cost_vec) / node_counts
full_base_price = np.where(
full_base_yhat > 1e-9,
full_base_rev / np.maximum(full_base_yhat, 1e-9),
(s_mat @ base_price) / node_counts[:, None],
)
full_opt_price = np.where(
full_opt_yhat > 1e-9,
full_opt_rev / np.maximum(full_opt_yhat, 1e-9),
(s_mat @ opt_price_b) / node_counts[:, None],
)
full_rel_p = np.where(
full_base_price > 1e-9,
(full_opt_price - full_base_price) / np.maximum(full_base_price, 1e-9),
0.0,
)
else:
all_node_ids = list(bottom_ids)
full_base_yhat = base_yhat
full_opt_yhat = opt_yhat_b
full_base_lo = base_lo
full_base_hi = base_hi
full_price_lift = price_lift_b
full_promo_lift = promo_lift_b
full_pf_dip = pf_dip_b
full_cannib = cannib_b
full_base_rev = base_rev_b
full_opt_rev = opt_rev_b
full_base_gm = base_gm_b
full_opt_gm = opt_gm_b
full_base_promo = base_promo
full_opt_promo = opt_promo_b
full_cost = cost_vec
full_base_price = base_price
full_opt_price = opt_price_b
full_rel_p = rel_p_b
else:
all_node_ids = list(bottom_ids)
full_base_yhat = base_yhat
full_opt_yhat = opt_yhat_b
full_base_lo = base_lo
full_base_hi = base_hi
full_price_lift = price_lift_b
full_promo_lift = promo_lift_b
full_pf_dip = pf_dip_b
full_cannib = cannib_b
full_base_rev = base_rev_b
full_opt_rev = opt_rev_b
full_base_gm = base_gm_b
full_opt_gm = opt_gm_b
full_base_promo = base_promo
full_opt_promo = opt_promo_b
full_cost = cost_vec
full_base_price = base_price
full_opt_price = opt_price_b
full_rel_p = rel_p_b
# Compute coherence error across hierarchy if applicable
coherence_err = 0.0
if (
reconcile
and resolved_hier is not None
and resolved_hier.n_aggregated > 0
and len(all_node_ids) == resolved_hier.n_nodes
):
s_mat_check = np.asarray(resolved_hier.summing_matrix, dtype=float)
reconstructed = s_mat_check @ full_opt_yhat[resolved_hier.n_aggregated :, :]
coherence_err = float(np.max(np.abs(full_opt_yhat - reconstructed)))
# Compute operational inventory policy deltas (`delta_reorder_point`, `delta_safety_stock`,
# `delta_order_qty`)
inv_delta_by_tid: dict[str, dict[str, float]] = {}
inv_delta_records: list[dict[str, Any]] = []
if include_inventory_impact:
base_pred_rows: list[dict[str, Any]] = []
opt_pred_rows: list[dict[str, Any]] = []
for idx_n, nid in enumerate(all_node_ids):
for h in range(h_steps):
b_yh = float(full_base_yhat[idx_n, h])
o_yh = float(full_opt_yhat[idx_n, h])
half_b = max(
0.5 * float(full_base_hi[idx_n, h] - full_base_lo[idx_n, h]), 0.1 * b_yh
)
scale_ratio = o_yh / b_yh if b_yh > 1e-6 else 1.0
half_o = half_b * max(0.5, scale_ratio)
dt_val = dates_grid[h]
base_pred_rows.append(
{
"ts_id": nid,
"model_type": chosen_model_type,
"ds": dt_val,
"forecast_date": dt_val,
"yhat": b_yh,
"yhat_lower": max(0.0, b_yh - half_b),
"yhat_upper": b_yh + half_b,
}
)
opt_pred_rows.append(
{
"ts_id": nid,
"model_type": chosen_model_type,
"ds": dt_val,
"forecast_date": dt_val,
"yhat": o_yh,
"yhat_lower": max(0.0, o_yh - half_o),
"yhat_upper": o_yh + half_o,
}
)
base_pol_df = compute_inventory_policy(
pd.DataFrame.from_records(base_pred_rows),
oof_df=resolved_oof,
lead_time=float(lead_time),
lead_time_std=float(lead_time_std),
service_level=service_level,
)
opt_pol_df = compute_inventory_policy(
pd.DataFrame.from_records(opt_pred_rows),
oof_df=resolved_oof,
lead_time=float(lead_time),
lead_time_std=float(lead_time_std),
service_level=service_level,
)
base_pol_map = {str(r["ts_id"]): r for r in base_pol_df.to_dict(orient="records")}
opt_pol_map = {str(r["ts_id"]): r for r in opt_pol_df.to_dict(orient="records")}
for nid in all_node_ids:
br = base_pol_map.get(nid, {})
orow = opt_pol_map.get(nid, {})
b_rop = float(br.get("reorder_point", 0.0))
o_rop = float(orow.get("reorder_point", 0.0))
b_ss = float(br.get("safety_stock", 0.0))
o_ss = float(orow.get("safety_stock", 0.0))
b_q = float(br.get("recommended_order_qty", 0.0))
o_q = float(orow.get("recommended_order_qty", 0.0))
inv_delta_by_tid[nid] = {
"baseline_reorder_point": b_rop,
"optimal_reorder_point": o_rop,
"delta_reorder_point": o_rop - b_rop,
"baseline_safety_stock": b_ss,
"optimal_safety_stock": o_ss,
"delta_safety_stock": o_ss - b_ss,
"baseline_order_qty": b_q,
"optimal_order_qty": o_q,
"delta_order_qty": o_q - b_q,
}
inv_delta_records.append(
{
"ts_id": nid,
"model_type": chosen_model_type,
**inv_delta_by_tid[nid],
}
)
else:
for nid in all_node_ids:
inv_delta_by_tid[nid] = {
"baseline_reorder_point": 0.0,
"optimal_reorder_point": 0.0,
"delta_reorder_point": 0.0,
"baseline_safety_stock": 0.0,
"optimal_safety_stock": 0.0,
"delta_safety_stock": 0.0,
"baseline_order_qty": 0.0,
"optimal_order_qty": 0.0,
"delta_order_qty": 0.0,
}
inv_delta_records.append(
{
"ts_id": nid,
"model_type": chosen_model_type,
**inv_delta_by_tid[nid],
}
)
inventory_delta_df = pd.DataFrame.from_records(inv_delta_records)
# Build `schedule_df` and `summary_df`
sched_records: list[dict[str, Any]] = []
summary_records: list[dict[str, Any]] = []
for idx_n, nid in enumerate(all_node_ids):
inv_d = inv_delta_by_tid[nid]
uc_n = float(full_cost[idx_n])
for h in range(h_steps):
b_p = float(full_base_price[idx_n, h])
o_p = float(full_opt_price[idx_n, h])
p_pct = float(full_rel_p[idx_n, h] * 100.0)
b_pr = float(full_base_promo[idx_n, h])
o_pr = float(full_opt_promo[idx_n, h])
b_y = float(full_base_yhat[idx_n, h])
o_y = float(full_opt_yhat[idx_n, h])
dy = o_y - b_y
dy_pct = (100.0 * dy / b_y) if b_y > 1e-9 else 0.0
half_b = max(0.5 * float(full_base_hi[idx_n, h] - full_base_lo[idx_n, h]), 0.1 * b_y)
scale_r = o_y / b_y if b_y > 1e-6 else 1.0
half_o = half_b * max(0.5, scale_r)
plift = float(full_price_lift[idx_n, h])
prlift = float(full_promo_lift[idx_n, h])
pfdip = float(full_pf_dip[idx_n, h])
candip = float(full_cannib[idx_n, h])
net_inc = plift + prlift + pfdip + candip
b_rev = float(full_base_rev[idx_n, h])
o_rev = float(full_opt_rev[idx_n, h])
d_rev = o_rev - b_rev
d_rev_pct = (100.0 * d_rev / abs(b_rev)) if abs(b_rev) > 1e-9 else 0.0
b_gm = float(full_base_gm[idx_n, h])
o_gm = float(full_opt_gm[idx_n, h])
d_gm = o_gm - b_gm
d_gm_pct = (100.0 * d_gm / abs(b_gm)) if abs(b_gm) > 1e-9 else 0.0
m_pct = (o_gm / o_rev) if o_rev > 1e-9 else ((o_p - uc_n) / max(o_p, 1e-9))
dt_ts = pd.Timestamp(dates_grid[h])
sched_records.append(
{
"ts_id": nid,
"model_type": chosen_model_type,
"ds": dt_ts,
"forecast_date": dt_ts,
"horizon_step": int(h + 1),
"baseline_price": b_p,
"optimal_price": o_p,
"price": o_p,
"price_change_pct": p_pct,
"baseline_promo": b_pr,
"optimal_promo": o_pr,
"promo": o_pr,
"baseline_yhat": b_y,
"optimal_yhat": o_y,
"yhat": o_y,
"yhat_lower": max(0.0, o_y - half_o),
"yhat_upper": o_y + half_o,
"delta_yhat": dy,
"delta_pct": dy_pct,
"price_lift": plift,
"incremental_promo_lift": prlift,
"pull_forward_dip": pfdip,
"pull_forward_effect": pfdip,
"cannibalization_effect": candip,
"cannibalization_dip": candip,
"net_incremental_units": net_inc,
"unit_cost": uc_n,
"baseline_revenue": b_rev,
"optimal_revenue": o_rev,
"scenario_revenue": o_rev,
"revenue_delta": d_rev,
"revenue_delta_pct": d_rev_pct,
"baseline_gross_margin": b_gm,
"optimal_gross_margin": o_gm,
"scenario_gross_margin": o_gm,
"gross_margin_delta": d_gm,
"gross_margin_delta_pct": d_gm_pct,
"margin_pct": m_pct,
"baseline_reorder_point": inv_d["baseline_reorder_point"],
"optimal_reorder_point": inv_d["optimal_reorder_point"],
"delta_reorder_point": inv_d["delta_reorder_point"],
"baseline_safety_stock": inv_d["baseline_safety_stock"],
"optimal_safety_stock": inv_d["optimal_safety_stock"],
"delta_safety_stock": inv_d["delta_safety_stock"],
"baseline_order_qty": inv_d["baseline_order_qty"],
"optimal_order_qty": inv_d["optimal_order_qty"],
"delta_order_qty": inv_d["delta_order_qty"],
}
)
b_tot_u = float(np.sum(full_base_yhat[idx_n, :]))
o_tot_u = float(np.sum(full_opt_yhat[idx_n, :]))
du = o_tot_u - b_tot_u
du_pct = (100.0 * du / b_tot_u) if b_tot_u > 1e-9 else 0.0
b_tot_r = float(np.sum(full_base_rev[idx_n, :]))
o_tot_r = float(np.sum(full_opt_rev[idx_n, :]))
dr = o_tot_r - b_tot_r
dr_pct = (100.0 * dr / abs(b_tot_r)) if abs(b_tot_r) > 1e-9 else 0.0
b_tot_gm = float(np.sum(full_base_gm[idx_n, :]))
o_tot_gm = float(np.sum(full_opt_gm[idx_n, :]))
dgm = o_tot_gm - b_tot_gm
dgm_pct = (100.0 * dgm / abs(b_tot_gm)) if abs(b_tot_gm) > 1e-9 else 0.0
summary_records.append(
{
"ts_id": nid,
"model_type": chosen_model_type,
"horizon": int(h_steps),
"promo_days": int(np.sum(full_opt_promo[idx_n, :] >= 0.5)),
"mean_baseline_price": float(np.mean(full_base_price[idx_n, :])),
"mean_optimal_price": float(np.mean(full_opt_price[idx_n, :])),
"mean_price_change_pct": float(np.mean(full_rel_p[idx_n, :]) * 100.0),
"baseline_total_units": b_tot_u,
"optimal_total_units": o_tot_u,
"delta_units": du,
"delta_units_pct": du_pct,
"total_pull_forward_dip": float(np.sum(full_pf_dip[idx_n, :])),
"total_cannibalization_effect": float(np.sum(full_cannib[idx_n, :])),
"baseline_total_revenue": b_tot_r,
"optimal_total_revenue": o_tot_r,
"revenue_delta": dr,
"revenue_delta_pct": dr_pct,
"baseline_total_gross_margin": b_tot_gm,
"optimal_total_gross_margin": o_tot_gm,
"gross_margin_delta": dgm,
"gross_margin_delta_pct": dgm_pct,
"optimal_margin_pct": (o_tot_gm / o_tot_r) if o_tot_r > 1e-9 else 0.0,
"delta_reorder_point": inv_d["delta_reorder_point"],
"delta_safety_stock": inv_d["delta_safety_stock"],
"delta_order_qty": inv_d["delta_order_qty"],
}
)
schedule_df = pd.DataFrame.from_records(sched_records, columns=SCENARIO_OPTIMIZATION_COLUMNS)
summary_df = pd.DataFrame.from_records(
summary_records, columns=SCENARIO_OPTIMIZATION_SUMMARY_COLUMNS
)
# Construct `recommended_shocks` compatible with `simulate_scenarios`
mean_rel_p = float(np.mean(rel_p_b))
promo_rules: list[dict[str, Any]] = []
for h in range(h_steps):
if float(np.mean(opt_promo_b[:, h])) >= 0.5:
dt_str = str(pd.Timestamp(dates_grid[h]).date())
promo_rules.append(
{"op": "set", "value": 1.0, "start_date": dt_str, "end_date": dt_str}
)
recommended_shocks: dict[str, Any] = {
"optimal_scenario": {
eff_price_col: {"op": "mul", "value": round(1.0 + mean_rel_p, 6)},
**(
{eff_promo_col: promo_rules}
if promo_rules
else {eff_promo_col: {"op": "set", "value": 0.0}}
),
}
}
base_obj = float(baseline_eval["obj_val"])
opt_obj = float(best_eval["obj_val"])
obj_imp = opt_obj - base_obj
obj_imp_pct = (100.0 * obj_imp / abs(base_obj)) if abs(base_obj) > 1e-9 else 0.0
b_u = float(baseline_eval["tot_units"])
o_u = float(best_eval["tot_units"])
du_pct_tot = (100.0 * (o_u - b_u) / b_u) if b_u > 1e-9 else 0.0
b_r = float(baseline_eval["tot_rev"])
o_r = float(best_eval["tot_rev"])
dr_tot = o_r - b_r
dr_pct_tot = (100.0 * dr_tot / abs(b_r)) if abs(b_r) > 1e-9 else 0.0
b_gm = float(baseline_eval["tot_gm"])
o_gm = float(best_eval["tot_gm"])
dgm_tot = o_gm - b_gm
dgm_pct_tot = (100.0 * dgm_tot / abs(b_gm)) if abs(b_gm) > 1e-9 else 0.0
schedule_df.attrs["optimization_summary"] = {
"objective": obj_norm,
"feasibility_status": feasibility_status,
"baseline_objective_value": base_obj,
"optimal_objective_value": opt_obj,
"objective_improvement": obj_imp,
"coherence_max_abs_error": coherence_err,
}
if temp_spec is not None:
schedule_df.attrs["temporal_spec"] = temp_spec
return ScenarioOptimizationResult(
schedule_df=schedule_df,
summary_df=summary_df,
inventory_delta_df=inventory_delta_df,
objective=obj_norm,
feasibility_status=feasibility_status,
baseline_objective_value=base_obj,
optimal_objective_value=opt_obj,
objective_improvement=obj_imp,
objective_improvement_pct=obj_imp_pct,
baseline_total_units=b_u,
optimal_total_units=o_u,
delta_units_pct=du_pct_tot,
baseline_total_revenue=b_r,
optimal_total_revenue=o_r,
revenue_delta=dr_tot,
revenue_delta_pct=dr_pct_tot,
baseline_total_gross_margin=b_gm,
optimal_total_gross_margin=o_gm,
gross_margin_delta=dgm_tot,
gross_margin_delta_pct=dgm_pct_tot,
cvar_profit=float(best_eval["cvar_profit"]),
baseline_cvar_profit=float(baseline_eval["cvar_profit"]),
promo_budget_used=float(best_eval["promo_spend"]),
coherence_max_abs_error=coherence_err,
recommended_shocks=recommended_shocks,
)