Skip to content

Prescriptive Counterfactual Scenario & Promotional Calendar Optimizer

flowchart TD
    S1["1. Estimate Causal Elasticity & Cross-Item Cannibalization<br/>compute_promo_elasticity_decomposition · pull_forward_dip_ratio"] --> S2["2. Declare Decision Levers & Business Guardrails<br/>price_bounds_pct · max_promo_days · min_cooldown_days · min_gross_margin_pct"]
    S2 --> S3["3. Solve Mixed-Integer / Continuous Prescriptive Schedule<br/>optimize_scenario (gross_profit · revenue · units · cvar_profit)"]
    S3 --> S4["4. Round-Trip Optimal Shocks into Scenarios & Goal-Seek<br/>ScenarioOptimizationResult.optimal_scenarios_dict · plot_optimal_scenario"]

scenario_optimizer

Prescriptive Price & Promotional Calendar Optimizer — pure DataFrame analytics.

Solves mixed continuous/discrete prescriptive optimization problems over causal demand response surfaces (@monotone price guardrails, Robinson / Double-ML promo_elasticity_df promotional lifts, post-promotion pull_forward_dip pantry-loading lags, and cross-SKU cannibalization):

  1. Structural Response Surface Extraction: Estimates per-SKU own-price elasticity $\epsilon_i < 0$ (strictly monotone downward-sloping demand per :mod:~scale_forecasting.monotonicity), direct promotional lift $\beta_{\text{promo}, i} \ge 0$, post-promo pull-forward lag penalties $\gamma_{i, 1 \dots L} \le 0$, and cross-SKU cannibalization $\Gamma_{i,j} \le 0$ via :func:~scale_forecasting.elasticity.compute_promo_elasticity_decomposition.
  2. Phase 1 — Mixed-Integer Linear Programming via C++ HiGHS (scipy.optimize.milp): Optimizes discrete price ladders ($w_{i,h,k} \in {0, 1}$) and promotional pulse calendars ($z_{i,h} \in {0, 1}$) subject to promotional frequency caps (max_promo_days), minimum inter-promo cooldown spacing (min_cooldown_days clique inequalities $\sum_{\tau=h}^{h+d} z_{i,\tau} \le 1$), portfolio gross-margin percentage floors (min_margin_pct), volume capacity bounds (min_total_units, max_total_units), promotional spend caps (max_promo_budget), and Rockafellar–Uryasev $\text{CVaR}_\alpha$ downside profit risk.
  3. Phase 2 — Continuous Price Refinement (scipy.optimize.minimize(method="SLSQP")) & Full-Chain Propagation: When price_grid is None, polishes continuous prices $P_{i,h} \in [P_{\min}, P_{\max}]$ with the optimal promotional calendar fixed, then propagates the winning schedule through spatial/temporal hierarchy reconciliation (< 1e-6 coherence error) and (s, S) inventory policy shifts (delta_reorder_point, delta_safety_stock, delta_order_qty).

ScenarioOptimizationResult dataclass

ScenarioOptimizationResult(
    schedule_df,
    summary_df,
    inventory_delta_df,
    objective,
    feasibility_status,
    baseline_objective_value,
    optimal_objective_value,
    objective_improvement,
    objective_improvement_pct,
    baseline_total_units,
    optimal_total_units,
    delta_units_pct,
    baseline_total_revenue,
    optimal_total_revenue,
    revenue_delta,
    revenue_delta_pct,
    baseline_total_gross_margin,
    optimal_total_gross_margin,
    gross_margin_delta,
    gross_margin_delta_pct,
    cvar_profit,
    baseline_cvar_profit,
    promo_budget_used,
    coherence_max_abs_error,
    recommended_shocks,
)

Container for prescriptive price and promotional calendar optimization results.

Provides both structured attributes (.schedule_df, .summary_df, .inventory_delta_df, .optimal_objective_value, .recommended_shocks) and DataFrame-like delegation (len(res), res["optimal_price"], res.columns, res.head()) for ergonomic interactive and programmatic use.

attrs property

attrs

Delegate .attrs to self.schedule_df.attrs.

baseline_profit property

baseline_profit

Alias for self.baseline_total_gross_margin.

columns property

columns

Delegate .columns to self.schedule_df.

dataframe property

dataframe

Return the step-level optimal schedule DataFrame (self.schedule_df).

df property

df

Alias for self.schedule_df.

empty property

empty

Delegate .empty to self.schedule_df.

optimal_profit property

optimal_profit

Alias for self.optimal_total_gross_margin.

shape property

shape

Delegate .shape to self.schedule_df.

head

head(n=5)

Return the first n rows of self.schedule_df.

Source code in src/scale_forecasting/scenario_optimizer.py
def head(self, n: int = 5) -> pd.DataFrame:
    """Return the first ``n`` rows of ``self.schedule_df``."""
    return self.schedule_df.head(n)

summary_text

summary_text()

Render a concise plain-English executive summary of the optimal prescription.

Source code in src/scale_forecasting/scenario_optimizer.py
def summary_text(self) -> str:
    """Render a concise plain-English executive summary of the optimal prescription."""
    return (
        f"ScenarioOptimizationResult(objective={self.objective!r}, "
        f"status={self.feasibility_status!r}): "
        f"objective {self.baseline_objective_value:,.2f} -> "
        f"{self.optimal_objective_value:,.2f} "
        f"({self.objective_improvement:+,.2f}, {self.objective_improvement_pct:+.2f}%), "
        f"units {self.baseline_total_units:,.1f} -> {self.optimal_total_units:,.1f} "
        f"({self.delta_units_pct:+.2f}%), "
        f"revenue ${self.baseline_total_revenue:,.2f} -> ${self.optimal_total_revenue:,.2f} "
        f"({self.revenue_delta_pct:+.2f}%), "
        f"gross_margin ${self.baseline_total_gross_margin:,.2f} -> "
        f"${self.optimal_total_gross_margin:,.2f} ({self.gross_margin_delta_pct:+.2f}%), "
        f"CVaR=${self.cvar_profit:,.2f}, coherence_err={self.coherence_max_abs_error:.2e}"
    )

tail

tail(n=5)

Return the last n rows of self.schedule_df.

Source code in src/scale_forecasting/scenario_optimizer.py
def tail(self, n: int = 5) -> pd.DataFrame:
    """Return the last ``n`` rows of ``self.schedule_df``."""
    return self.schedule_df.tail(n)

to_dict

to_dict()

Serialize scalar summary metrics and recommended shocks to a plain dictionary.

Source code in src/scale_forecasting/scenario_optimizer.py
def to_dict(self) -> dict[str, Any]:
    """Serialize scalar summary metrics and recommended shocks to a plain dictionary."""
    return {
        "objective": self.objective,
        "feasibility_status": self.feasibility_status,
        "baseline_objective_value": float(self.baseline_objective_value),
        "optimal_objective_value": float(self.optimal_objective_value),
        "objective_improvement": float(self.objective_improvement),
        "objective_improvement_pct": float(self.objective_improvement_pct),
        "baseline_total_units": float(self.baseline_total_units),
        "optimal_total_units": float(self.optimal_total_units),
        "delta_units_pct": float(self.delta_units_pct),
        "baseline_total_revenue": float(self.baseline_total_revenue),
        "optimal_total_revenue": float(self.optimal_total_revenue),
        "revenue_delta": float(self.revenue_delta),
        "revenue_delta_pct": float(self.revenue_delta_pct),
        "baseline_total_gross_margin": float(self.baseline_total_gross_margin),
        "optimal_total_gross_margin": float(self.optimal_total_gross_margin),
        "gross_margin_delta": float(self.gross_margin_delta),
        "gross_margin_delta_pct": float(self.gross_margin_delta_pct),
        "cvar_profit": float(self.cvar_profit),
        "baseline_cvar_profit": float(self.baseline_cvar_profit),
        "promo_budget_used": float(self.promo_budget_used),
        "coherence_max_abs_error": float(self.coherence_max_abs_error),
        "recommended_shocks": dict(self.recommended_shocks),
    }

optimize_scenario

optimize_scenario(
    forecaster_or_df,
    *,
    config=None,
    cfg=None,
    predictions_df=None,
    forecasts_df=None,
    oof_df=None,
    history_df=None,
    data=None,
    future_covariates_df=None,
    trajectories_df=None,
    model_name=None,
    model_type=None,
    objective="gross_profit",
    price_col=None,
    promo_col=None,
    price_bounds=(-0.15, 0.15),
    price_grid=None,
    promo_bounds=(0.0, 1.0),
    binary_promo=True,
    max_promo_days=None,
    min_cooldown_days=0,
    cooldown_days=None,
    unit_cost=None,
    promo_fixed_cost=0.0,
    min_margin_pct=None,
    min_gross_margin_pct=None,
    min_gross_margin=None,
    min_total_units=None,
    max_total_units=None,
    target_total_units=None,
    max_promo_budget=None,
    inventory_cap=None,
    risk_aversion_lambda=0.0,
    risk_aversion=None,
    cvar_alpha=0.95,
    risk_alpha=None,
    pull_forward_lags=3,
    cannibalization_weight=1.0,
    use_similarity_priors=True,
    similarity_matrix=None,
    similarity_method="hybrid",
    reconcile=True,
    hier_spec=None,
    temp_spec=None,
    include_inventory_impact=True,
    lead_time=7.0,
    lead_time_std=0.0,
    service_level=0.95,
    n_paths=250,
    copula_type="auto",
    seed=42,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    horizon=None,
    freq=None,
    strict_feasibility=False,
)

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.

Source code in src/scale_forecasting/scenario_optimizer.py
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
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,
    )

plot_optimal_scenario

plot_optimal_scenario(
    result_or_df, *, ts_id=None, ax=None, title=None
)

Plot Baseline vs. Optimal Scenario Demand, Price Schedule, and Promotional Pulses.

Source code in src/scale_forecasting/scenario_optimizer.py
def plot_optimal_scenario(
    result_or_df: ScenarioOptimizationResult | pd.DataFrame,
    *,
    ts_id: str | None = None,
    ax: Any = None,
    title: str | None = None,
) -> Any:
    """Plot Baseline vs. Optimal Scenario Demand, Price Schedule, and Promotional Pulses."""
    require_extra("notebook", purpose="Plotting optimal scenario schedule")
    import matplotlib.pyplot as plt

    if ax is None:
        _, ax = plt.subplots(figsize=(10, 5))

    sched_df = (
        result_or_df.schedule_df
        if isinstance(result_or_df, ScenarioOptimizationResult)
        else result_or_df
    )
    if sched_df is None or sched_df.empty:
        ax.set_title(title or "Optimal Scenario Schedule (no rows)")
        return ax

    sub = sched_df.copy()
    if ts_id is not None and "ts_id" in sub.columns:
        sub = sub[sub["ts_id"].astype(str) == str(ts_id)].copy()
    elif "ts_id" in sub.columns:
        all_ids = [str(x) for x in sub["ts_id"].drop_duplicates().tolist()]
        chosen_id = TOTAL_NODE_ID if TOTAL_NODE_ID in all_ids else all_ids[0]
        sub = sub[sub["ts_id"].astype(str) == chosen_id].copy()

    if sub.empty:
        ax.set_title(title or "Optimal Scenario Schedule (empty selection)")
        return ax

    dt_col = "ds" if "ds" in sub.columns else "forecast_date"
    sub = sub.sort_values(dt_col)
    x_dates = pd.to_datetime(sub[dt_col])
    base_y = sub["baseline_yhat"].to_numpy(dtype=float)
    opt_y = sub["optimal_yhat"].to_numpy(dtype=float)

    ax.plot(
        x_dates, base_y, linestyle="--", linewidth=1.8, color="#64748b", label="Baseline Demand"
    )
    ax.plot(
        x_dates, opt_y, marker="o", linewidth=2.2, color="#2563eb", label="Optimal Scenario Demand"
    )

    if "optimal_promo" in sub.columns:
        promo_mask = sub["optimal_promo"].to_numpy(dtype=float) >= 0.5
        if promo_mask.any():
            ax.scatter(
                x_dates[promo_mask],
                opt_y[promo_mask],
                color="#dc2626",
                s=65,
                zorder=5,
                label="Active Promo Pulse",
            )

    if isinstance(result_or_df, ScenarioOptimizationResult):
        default_title = (
            f"Prescriptive Scenario Optimization ({result_or_df.objective}: "
            f"{result_or_df.objective_improvement_pct:+.1f}% Lift)"
        )
    else:
        default_title = "Prescriptive Scenario Schedule: Baseline vs. Optimal Demand"

    ax.set_xlabel("Date")
    ax.set_ylabel("Forecast Demand (Units)")
    ax.set_title(title or default_title)
    ax.legend(loc="best", frameon=True)
    ax.grid(True, alpha=0.25)
    return ax