Skip to content

Top-Down Goal-Seek & Constrained Target Allocation

flowchart TD
    G1["1. Declare Top-Down Targets, Node Locks & Physical Bounds<br/>target_total / targets · locked_nodes · lower_bounds / upper_bounds · floor / cap"] --> G2["2. Build Precision & Temporal Smoothness Objective<br/>W^-1 (mint_shrink · wls_var · wls_struct · ols) + smoothness_weight * ||D(b - b_hat)||_2^2"]
    G2 --> G3["3. Pre-Check Feasibility & Solve Constrained Convex QP<br/>min_b 0.5*(b - b_hat)^T H (b - b_hat) s.t. C*b = d, l <= b <= u (GoalSeekInfeasibleError)"]
    G3 --> G4["4. Propagate Hierarchy Rollups, Gross Margin & Inventory Impact<br/>GoalSeekResult · summarize_goal_seek · plot_goal_seek · gross_margin_delta · delta_reorder_point"]

goal_seek

Top-Down Goal-Seek and Constrained Minimum-Trace Target Disaggregation (allocate_target).

Implements constrained quadratic programming (QP) target allocation across hierarchical and flat time-series panels:

  1. Constrained Minimum-Trace QP (allocate_target) — Given a top-level, regional, or per-period target override (in units or revenue dollars), solves the equality- and box-constrained Minimum-Trace quadratic program

min_b 0.5 * sum_t (b_t - b_hat_t)^T W_t^{-1} (b_t - b_hat_t) s.t. A_eq b = c_target, l <= b <= u

to distribute adjustments across bottom-level leaf series and horizon timestamps proportional to forecast error covariance W_t while respecting hard capacity/floor bounds [l, u] and user-locked nodes (locked_nodes / locks). 2. Pre- and Post-Solve Feasibility Verification (GoalSeekInfeasibleError) — Analytically verifies box bounds, locked-node equality compatibility, and subset complement bounds before and after solving the QP, raising GoalSeekInfeasibleError (ConfigError, ValueError) with actionable diagnostics whenever constraints are mathematically infeasible. 3. Scenario, Gross-Margin & Inventory Policy Chaining — Accepts either standard forecast frames (yhat) or simulate_scenarios frames (scenario_yhat), computes revenue and gross-margin deltas when price_col / prices / unit_cost are supplied, and propagates allocated demand into (s, S) inventory policy deltas (delta_reorder_point, delta_safety_stock, delta_order_qty) when include_inventory_impact=True. 4. Horizon Summary & Visualization (summarize_goal_seek, plot_goal_seek) — Rolls up per-series baseline vs. allocated units, revenue, gross margin, and constraint status across the horizon and renders a publication-grade horizontal bar/interval comparison chart.

GoalSeekResult dataclass

GoalSeekResult(
    allocations,
    summary,
    target_node,
    target_total,
    baseline_total,
    allocated_total,
    coherence_max_abs_error,
    active_bound_count=0,
    locked_count=0,
    hierarchy_spec=None,
)

Container for constrained top-down target allocation results and diagnostics.

dataframe property

dataframe

Alias for allocations DataFrame.

max_coherence_discrepancy property

max_coherence_discrepancy

Alias for coherence_max_abs_error.

max_coherence_error property

max_coherence_error

Alias for coherence_max_abs_error.

max_target_discrepancy property

max_target_discrepancy

Absolute discrepancy between allocated_total and target_total.

allocate_target

allocate_target(
    forecasts_df=None,
    target_total=None,
    *,
    predictions_df=None,
    target=None,
    targets=None,
    target_sum=None,
    horizon_total=None,
    node_id=None,
    target_node=TOTAL_NODE_ID,
    period=None,
    target_dates=None,
    target_mode="auto",
    target_metric="auto",
    locked_nodes=None,
    locks=None,
    lower_bounds=None,
    upper_bounds=None,
    bounds=None,
    floor=0.0,
    cap=None,
    ceiling=None,
    nonneg=True,
    method="mint_shrink",
    weights=None,
    smoothness_weight=0.0,
    hier_spec=None,
    spec=None,
    cfg=None,
    history_df=None,
    oof_df=None,
    price_col=None,
    prices=None,
    unit_cost=None,
    include_inventory_impact=False,
    lead_time=7.0,
    lead_time_std=0.0,
    service_level=0.95,
    inventory_params=None,
    model_type=None,
    scenario=None,
    date_col="ds",
    ts_id_col="ts_id",
    target_col="y",
    similarity_hierarchy=False,
    similarity_n_clusters="auto",
    similarity_method="hybrid",
    return_result=False,
)

Optimally disaggregate a top-down or regional target across leaf series and dates (pure).

Solves the equality- and box-constrained Minimum-Trace quadratic program over the bottom-level forecast trajectory while respecting locked_nodes / locks and [lower_bounds, upper_bounds], then rolls up the coherent hierarchy y_tilde = S @ b_tilde and optionally propagates the allocated forecast into revenue, gross margin, and (s, S) inventory policy deltas.

Source code in src/scale_forecasting/goal_seek.py
 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
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
def allocate_target(
    forecasts_df: pd.DataFrame | None = None,
    target_total: float | Sequence[float] | Mapping[Any, float] | pd.DataFrame | None = None,
    *,
    predictions_df: pd.DataFrame | None = None,
    target: float | Sequence[float] | Mapping[Any, float] | pd.DataFrame | None = None,
    targets: float | Sequence[float] | Mapping[Any, float] | pd.DataFrame | None = None,
    target_sum: float | Sequence[float] | Mapping[Any, float] | None = None,
    horizon_total: float | None = None,
    node_id: str | None = None,
    target_node: str = TOTAL_NODE_ID,
    period: Sequence[Any] | str | None = None,
    target_dates: Sequence[Any] | str | None = None,
    target_mode: Literal["auto", "per_step", "horizon_sum", "proportional"] = "auto",
    target_metric: Literal["auto", "units", "revenue"] = "auto",
    locked_nodes: Sequence[str] | Mapping[str, float] | None = None,
    locks: Sequence[str] | Mapping[str, float] | None = None,
    lower_bounds: Mapping[str, float] | Sequence[float] | np.ndarray | float | None = None,
    upper_bounds: Mapping[str, float] | Sequence[float] | np.ndarray | float | None = None,
    bounds: (
        Mapping[str, tuple[float | None, float | None]]
        | tuple[float | None, float | None]
        | pd.DataFrame
        | None
    ) = None,
    floor: float | None = 0.0,
    cap: float | None = None,
    ceiling: float | None = None,
    nonneg: bool = True,
    method: str = "mint_shrink",
    weights: str | Mapping[str, float] | Sequence[float] | np.ndarray | None = None,
    smoothness_weight: float = 0.0,
    hier_spec: HierarchySpec | None = None,
    spec: HierarchySpec | None = None,
    cfg: RunConfig | Mapping[str, Any] | None = None,
    history_df: pd.DataFrame | None = None,
    oof_df: pd.DataFrame | None = None,
    price_col: str | Mapping[str, float] | float | None = None,
    prices: Mapping[str, float] | float | pd.DataFrame | None = None,
    unit_cost: float | Mapping[str, float] | str | None = None,
    include_inventory_impact: bool = False,
    lead_time: float = 7.0,
    lead_time_std: float = 0.0,
    service_level: float | None = 0.95,
    inventory_params: Mapping[str, Any] | None = None,
    model_type: str | None = None,
    scenario: str | None = None,
    date_col: str = "ds",
    ts_id_col: str = "ts_id",
    target_col: str = "y",
    similarity_hierarchy: bool = False,
    similarity_n_clusters: int | Literal["auto"] = "auto",
    similarity_method: str = "hybrid",
    return_result: bool = False,
) -> pd.DataFrame | GoalSeekResult:
    """Optimally disaggregate a top-down or regional target across leaf series and dates (pure).

    Solves the equality- and box-constrained Minimum-Trace quadratic program over the bottom-level
    forecast trajectory while respecting ``locked_nodes`` / ``locks`` and
    ``[lower_bounds, upper_bounds]``, then rolls up the coherent hierarchy
    ``y_tilde = S @ b_tilde`` and optionally propagates the allocated forecast into revenue,
    gross margin, and `(s, S)` inventory policy deltas.
    """
    raw_df = forecasts_df if forecasts_df is not None else predictions_df
    if raw_df is None or not isinstance(raw_df, pd.DataFrame) or raw_df.empty:
        raise DataError(
            "allocate_target requires a non-empty forecasts_df / predictions_df DataFrame"
        )

    df = raw_df.copy()

    # Support scenario simulation outputs directly (`scenario_yhat` -> `yhat`).
    if "scenario" in df.columns:
        if scenario is not None:
            df = df[df["scenario"].astype(str) == str(scenario)].copy()
        else:
            non_base = df[df["scenario"].astype(str) != "baseline"]
            if not non_base.empty:
                first_scen = str(non_base["scenario"].iloc[0])
                df = non_base[non_base["scenario"].astype(str) == first_scen].copy()
        if df.empty:
            raise DataError(f"No rows found for scenario='{scenario}' in forecasts_df")

    if "yhat" not in df.columns and "scenario_yhat" in df.columns:
        df["yhat"] = df["scenario_yhat"].astype(float)
    if "yhat" not in df.columns:
        raise DataError("forecasts_df must contain a 'yhat' or 'scenario_yhat' column")

    if ts_id_col not in df.columns:
        df[ts_id_col] = "series_0"
    dcol = (
        date_col
        if date_col in df.columns
        else ("forecast_date" if "forecast_date" in df.columns else "ds")
    )
    if dcol not in df.columns:
        df[dcol] = pd.date_range("2026-01-01", periods=len(df), freq="D")

    if model_type is not None and "model_type" in df.columns:
        df = df[df["model_type"].astype(str) == str(model_type)].copy()
        if df.empty:
            raise DataError(f"No forecast rows found for model_type='{model_type}'")
    elif "model_type" in df.columns and df["model_type"].nunique() > 1:
        first_m = str(df["model_type"].iloc[0])
        df = df[df["model_type"].astype(str) == first_m].copy()
    elif "model_type" not in df.columns:
        df["model_type"] = model_type or "default"

    eff_model_type = str(df["model_type"].iloc[0])

    # Resolve target specification.
    raw_target = (
        target_total
        if target_total is not None
        else (
            target
            if target is not None
            else (
                targets
                if targets is not None
                else (target_sum if target_sum is not None else horizon_total)
            )
        )
    )
    if raw_target is None:
        raise ConfigError(
            "allocate_target requires target_total "
            "(or target / targets / target_sum / horizon_total)"
        )
    if (
        isinstance(smoothness_weight, bool)
        or not isinstance(smoothness_weight, (int, float, np.number))
        or not np.isfinite(float(smoothness_weight))
        or float(smoothness_weight) < 0.0
    ):
        raise ConfigError(
            f"smoothness_weight must be a finite float >= 0.0; got {smoothness_weight!r}"
        )
    smooth_w = float(smoothness_weight)

    eff_cap = cap if cap is not None else ceiling
    eff_hier_spec = hier_spec if hier_spec is not None else spec
    eff_target_node = str(node_id if node_id is not None else target_node)
    resolved_spec, include_agg_in_out = _infer_hierarchy_spec_from_frame(
        df,
        hier_spec=eff_hier_spec,
        cfg=cfg,
        history_df=history_df,
        ts_id_col=ts_id_col,
        date_col=dcol,
        target_node=eff_target_node,
        raw_target=raw_target,
        similarity_hierarchy=similarity_hierarchy,
        similarity_n_clusters=similarity_n_clusters,
        similarity_method=similarity_method,
    )
    bottom_ids = list(resolved_spec.bottom_ids)
    n_b = len(bottom_ids)
    b_to_idx = {bid: i for i, bid in enumerate(bottom_ids)}
    node_to_idx = {nid: i for i, nid in enumerate(resolved_spec.node_ids)}

    all_dates = sorted(df[dcol].drop_duplicates().tolist())
    h_total = len(all_dates)
    date_to_t = {dt: t for t, dt in enumerate(all_dates)}

    # Resolve active period / target_dates subset.
    raw_period = period if period is not None else target_dates
    if raw_period is not None:
        if isinstance(raw_period, (str, pd.Timestamp, int)):
            raw_period_seq: Sequence[Any] = [raw_period]
        else:
            raw_period_seq = list(raw_period)
        active_t_indices: list[int] = []
        for item in raw_period_seq:
            if isinstance(item, int) and 0 <= item < h_total and item not in date_to_t:
                active_t_indices.append(item)
            elif item in date_to_t:
                active_t_indices.append(date_to_t[item])
            else:
                ts_item = pd.Timestamp(item)
                for dt_cand, t_cand in date_to_t.items():
                    if pd.Timestamp(dt_cand) == ts_item:
                        active_t_indices.append(t_cand)
                        break
        if not active_t_indices:
            raise ConfigError(
                f"None of the requested target_dates / period {raw_period_seq} "
                "matched forecast dates"
            )
        active_t_indices = sorted(set(active_t_indices))
    else:
        active_t_indices = list(range(h_total))

    # Pivot bottom-level baseline yhat (n_b, H) and intervals.
    piv_yhat = (
        df.pivot_table(index=ts_id_col, columns=dcol, values="yhat", aggfunc="first")
        .reindex(index=bottom_ids, columns=all_dates)
        .fillna(0.0)
    )
    b_hat = piv_yhat.to_numpy(dtype=float)

    b_var_intervals: np.ndarray | None = None
    lo_col_name = (
        "yhat_lower"
        if "yhat_lower" in df.columns
        else ("yhat_lower_80" if "yhat_lower_80" in df.columns else None)
    )
    hi_col_name = (
        "yhat_upper"
        if "yhat_upper" in df.columns
        else ("yhat_upper_80" if "yhat_upper_80" in df.columns else None)
    )
    if lo_col_name and hi_col_name:
        piv_lo = (
            df.pivot_table(index=ts_id_col, columns=dcol, values=lo_col_name, aggfunc="first")
            .reindex(index=bottom_ids, columns=all_dates)
            .fillna(piv_yhat)
            .to_numpy(dtype=float)
        )
        piv_hi = (
            df.pivot_table(index=ts_id_col, columns=dcol, values=hi_col_name, aggfunc="first")
            .reindex(index=bottom_ids, columns=all_dates)
            .fillna(piv_yhat)
            .to_numpy(dtype=float)
        )
        hw_mat = np.maximum(0.0, 0.5 * (piv_hi - piv_lo))
        b_var_intervals = np.maximum((hw_mat / _Z_80) ** 2, _VAR_FLOOR)

    # Resolve prices and unit_cost per (bottom_i, t).
    eff_price_source = prices if prices is not None else price_col
    has_price = eff_price_source is not None or (
        "price" in df.columns and target_metric == "revenue"
    )
    price_mat = np.ones((n_b, h_total), dtype=float)
    if isinstance(eff_price_source, str):
        if eff_price_source in df.columns:
            p_piv = (
                df.pivot_table(
                    index=ts_id_col, columns=dcol, values=eff_price_source, aggfunc="first"
                )
                .reindex(index=bottom_ids, columns=all_dates)
                .fillna(1.0)
            )
            price_mat = p_piv.to_numpy(dtype=float)
        elif history_df is not None and eff_price_source in history_df.columns:
            last_p = (
                history_df.sort_values(dcol if dcol in history_df.columns else "ds")
                .groupby(ts_id_col)[eff_price_source]
                .last()
                .to_dict()
            )
            for i, bid in enumerate(bottom_ids):
                price_mat[i, :] = float(last_p.get(bid, 1.0))
        else:
            raise ConfigError(
                f"price_col '{eff_price_source}' not found in forecasts_df or history_df"
            )
    elif isinstance(eff_price_source, (int, float)):
        price_mat.fill(float(eff_price_source))
    elif isinstance(eff_price_source, Mapping):
        for i, bid in enumerate(bottom_ids):
            if bid in eff_price_source:
                price_mat[i, :] = float(eff_price_source[bid])
    elif isinstance(eff_price_source, pd.DataFrame):
        p_col = "price" if "price" in eff_price_source.columns else eff_price_source.columns[-1]
        if ts_id_col in eff_price_source.columns:
            p_map = eff_price_source.groupby(ts_id_col)[p_col].last().to_dict()
            for i, bid in enumerate(bottom_ids):
                price_mat[i, :] = float(p_map.get(bid, 1.0))
    elif "price" in df.columns:
        has_price = True
        p_piv = (
            df.pivot_table(index=ts_id_col, columns=dcol, values="price", aggfunc="first")
            .reindex(index=bottom_ids, columns=all_dates)
            .fillna(1.0)
        )
        price_mat = p_piv.to_numpy(dtype=float)

    cost_mat = np.zeros((n_b, h_total), dtype=float)
    has_cost = unit_cost is not None or "unit_cost" in df.columns
    if isinstance(unit_cost, (int, float)):
        cost_mat.fill(float(unit_cost))
    elif isinstance(unit_cost, str):
        if unit_cost in df.columns:
            c_piv = (
                df.pivot_table(index=ts_id_col, columns=dcol, values=unit_cost, aggfunc="first")
                .reindex(index=bottom_ids, columns=all_dates)
                .fillna(0.0)
            )
            cost_mat = c_piv.to_numpy(dtype=float)
        elif history_df is not None and unit_cost in history_df.columns:
            last_c = (
                history_df.sort_values(dcol if dcol in history_df.columns else "ds")
                .groupby(ts_id_col)[unit_cost]
                .last()
                .to_dict()
            )
            for i, bid in enumerate(bottom_ids):
                cost_mat[i, :] = float(last_c.get(bid, 0.0))
        else:
            raise ConfigError(
                f"unit_cost column '{unit_cost}' not found in forecasts_df or history_df"
            )
    elif isinstance(unit_cost, Mapping):
        for i, bid in enumerate(bottom_ids):
            if bid in unit_cost:
                cost_mat[i, :] = float(unit_cost[bid])
    elif "unit_cost" in df.columns:
        c_piv = (
            df.pivot_table(index=ts_id_col, columns=dcol, values="unit_cost", aggfunc="first")
            .reindex(index=bottom_ids, columns=all_dates)
            .fillna(0.0)
        )
        cost_mat = c_piv.to_numpy(dtype=float)

    use_revenue_weights = target_metric == "revenue"

    # Build box bounds [lo_mat, hi_mat] of shape (n_b, H).
    default_lo = float(floor) if floor is not None else (0.0 if nonneg else -np.inf)
    default_hi = float(eff_cap) if eff_cap is not None else np.inf
    lo_mat = np.full((n_b, h_total), default_lo, dtype=float)
    hi_mat = np.full((n_b, h_total), default_hi, dtype=float)
    locked_mat = np.zeros((n_b, h_total), dtype=bool)

    if isinstance(bounds, tuple) and len(bounds) == 2:
        if bounds[0] is not None:
            lo_mat = np.maximum(lo_mat, float(bounds[0]))
        if bounds[1] is not None:
            hi_mat = np.minimum(hi_mat, float(bounds[1]))
    elif isinstance(bounds, Mapping):
        for k_id, b_pair in bounds.items():
            k_str = str(k_id)
            if k_str in b_to_idx and isinstance(b_pair, tuple) and len(b_pair) == 2:
                idx = b_to_idx[k_str]
                if b_pair[0] is not None:
                    lo_mat[idx, :] = float(b_pair[0])
                if b_pair[1] is not None:
                    hi_mat[idx, :] = float(b_pair[1])
    elif isinstance(bounds, pd.DataFrame) and not bounds.empty:
        for brow in bounds.to_dict(orient="records"):
            bid_s = str(brow.get(ts_id_col, ""))
            if bid_s in b_to_idx:
                idx = b_to_idx[bid_s]
                l_v = brow.get("lower_bound", brow.get("lower", brow.get("min")))
                u_v = brow.get("upper_bound", brow.get("upper", brow.get("max")))
                if dcol in brow and brow[dcol] in date_to_t:
                    t_i = date_to_t[brow[dcol]]
                    if l_v is not None and pd.notna(l_v):
                        lo_mat[idx, t_i] = float(l_v)
                    if u_v is not None and pd.notna(u_v):
                        hi_mat[idx, t_i] = float(u_v)
                else:
                    if l_v is not None and pd.notna(l_v):
                        lo_mat[idx, :] = float(l_v)
                    if u_v is not None and pd.notna(u_v):
                        hi_mat[idx, :] = float(u_v)

    if lower_bounds is not None:
        if isinstance(lower_bounds, (int, float)):
            lo_mat = np.full((n_b, h_total), float(lower_bounds), dtype=float)
        elif isinstance(lower_bounds, Mapping):
            for k_id, l_val in lower_bounds.items():
                if str(k_id) in b_to_idx and l_val is not None:
                    lo_mat[b_to_idx[str(k_id)], :] = float(l_val)
        else:
            arr_l = np.asarray(lower_bounds, dtype=float)
            if arr_l.shape == (n_b, h_total):
                lo_mat = arr_l.copy()
            elif arr_l.size == n_b:
                lo_mat = np.repeat(arr_l.reshape(n_b, 1), h_total, axis=1)

    if upper_bounds is not None:
        if isinstance(upper_bounds, (int, float)):
            hi_mat = np.full((n_b, h_total), float(upper_bounds), dtype=float)
        elif isinstance(upper_bounds, Mapping):
            for k_id, u_val in upper_bounds.items():
                if str(k_id) in b_to_idx and u_val is not None:
                    hi_mat[b_to_idx[str(k_id)], :] = float(u_val)
        else:
            arr_u = np.asarray(upper_bounds, dtype=float)
            if arr_u.shape == (n_b, h_total):
                hi_mat = arr_u.copy()
            elif arr_u.size == n_b:
                hi_mat = np.repeat(arr_u.reshape(n_b, 1), h_total, axis=1)

    # Inactive dates (outside `period` / `target_dates`) stay locked to their baseline forecasts.
    active_set = set(active_t_indices)
    for t_idx in range(h_total):
        if t_idx not in active_set:
            lo_mat[:, t_idx] = b_hat[:, t_idx]
            hi_mat[:, t_idx] = b_hat[:, t_idx]
            locked_mat[:, t_idx] = True

    # Build linear equality constraints A_eq @ b_flat = c_eq
    # (where b_flat is ordered by t then i: k = t * n_b + i).
    eq_rows: list[np.ndarray] = []
    eq_rhs: list[float] = []

    def _node_s_row(nid_raw: str) -> np.ndarray:
        nid = _canonicalize_sim_cluster_node_id(str(nid_raw), bottom_ids=set(b_to_idx))
        if nid in node_to_idx:
            return resolved_spec.summing_matrix[node_to_idx[nid]].copy()
        # Allow shorthand like "North" matching "region=North".
        for cand_nid, r_idx in node_to_idx.items():
            if cand_nid.endswith(f"={nid}") or cand_nid == nid:
                return resolved_spec.summing_matrix[r_idx].copy()
        if nid in b_to_idx:
            r = np.zeros(n_b, dtype=float)
            r[b_to_idx[nid]] = 1.0
            return r
        raise ConfigError(
            f"Unknown hierarchy node '{nid_raw}'; available nodes: {list(resolved_spec.node_ids)}"
        )

    # Process locked_nodes and locks.
    for lock_arg in (locked_nodes, locks):
        if lock_arg is None:
            continue
        if isinstance(lock_arg, Mapping):
            for k_lock, val_lock in lock_arg.items():
                s_r = _node_s_row(str(k_lock))
                member_indices = np.flatnonzero(s_r > 0.5).tolist()
                if len(member_indices) == 1 and (
                    target_mode == "per_step" or len(active_t_indices) == 1
                ):
                    idx_b = member_indices[0]
                    for t_idx in active_t_indices:
                        lo_mat[idx_b, t_idx] = float(val_lock)
                        hi_mat[idx_b, t_idx] = float(val_lock)
                        locked_mat[idx_b, t_idx] = True
                elif len(member_indices) == 1:
                    # Single leaf locked to explicit horizon total val_lock across active_t_indices.
                    idx_b = member_indices[0]
                    base_slice = np.maximum(b_hat[idx_b, active_t_indices], 0.0)
                    base_sum = float(np.sum(base_slice))
                    shares = (
                        base_slice / base_sum
                        if base_sum > 1e-12
                        else np.full(
                            len(active_t_indices), 1.0 / len(active_t_indices), dtype=float
                        )
                    )
                    for pos_t, t_idx in enumerate(active_t_indices):
                        v_step = float(val_lock) * float(shares[pos_t])
                        if (
                            v_step < lo_mat[idx_b, t_idx] - _FEAS_TOL
                            or v_step > hi_mat[idx_b, t_idx] + _FEAS_TOL
                        ):
                            raise GoalSeekInfeasibleError(
                                f"Locked value {val_lock} for '{k_lock}' violates its box bounds "
                                f"[{lo_mat[idx_b, t_idx]}, {hi_mat[idx_b, t_idx]}] at step {t_idx}."
                            )
                        lo_mat[idx_b, t_idx] = v_step
                        hi_mat[idx_b, t_idx] = v_step
                        locked_mat[idx_b, t_idx] = True
                else:
                    # Aggregate node locked to explicit value val_lock across active_t_indices.
                    row_flat = np.zeros(n_b * h_total, dtype=float)
                    for t_idx in active_t_indices:
                        row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r
                    eq_rows.append(row_flat)
                    eq_rhs.append(float(val_lock))
        else:
            for k_lock in lock_arg:
                s_r = _node_s_row(str(k_lock))
                member_indices = np.flatnonzero(s_r > 0.5).tolist()
                if len(member_indices) == 1:
                    idx_b = member_indices[0]
                    for t_idx in active_t_indices:
                        val_b = float(b_hat[idx_b, t_idx])
                        if (
                            val_b < lo_mat[idx_b, t_idx] - _FEAS_TOL
                            or val_b > hi_mat[idx_b, t_idx] + _FEAS_TOL
                        ):
                            raise GoalSeekInfeasibleError(
                                f"Locked baseline value {val_b:.4f} for '{k_lock}' violates "
                                f"its box bounds [{lo_mat[idx_b, t_idx]:.4f}, "
                                f"{hi_mat[idx_b, t_idx]:.4f}]."
                            )
                        lo_mat[idx_b, t_idx] = val_b
                        hi_mat[idx_b, t_idx] = val_b
                        locked_mat[idx_b, t_idx] = True
                else:
                    # Aggregate node locked to its baseline forecast at each active timestamp.
                    for t_idx in active_t_indices:
                        row_flat = np.zeros(n_b * h_total, dtype=float)
                        row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r
                        eq_rows.append(row_flat)
                        eq_rhs.append(float(s_r @ b_hat[:, t_idx]))

    # Add target equality constraint(s).
    n_lock_eq = len(eq_rhs)
    if isinstance(raw_target, pd.DataFrame):
        if raw_target.empty:
            raise ConfigError("target_total DataFrame cannot be empty")
        val_col = (
            "target"
            if "target" in raw_target.columns
            else ("yhat" if "yhat" in raw_target.columns else raw_target.columns[-1])
        )
        for trow in raw_target.to_dict(orient="records"):
            nid_t = str(trow.get(ts_id_col, eff_target_node))
            s_r = _node_s_row(nid_t)
            if dcol in trow and trow[dcol] in date_to_t:
                t_idx = date_to_t[trow[dcol]]
                row_flat = np.zeros(n_b * h_total, dtype=float)
                w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
                row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
                eq_rows.append(row_flat)
                eq_rhs.append(float(trow[val_col]))
            else:
                row_flat = np.zeros(n_b * h_total, dtype=float)
                for t_idx in active_t_indices:
                    w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
                    row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
                eq_rows.append(row_flat)
                eq_rhs.append(float(trow[val_col]))
    elif isinstance(raw_target, Mapping):
        if not raw_target:
            raise ConfigError("target_total mapping cannot be empty")
        # Determine whether keys are hierarchy node IDs or dates/steps.
        sample_keys = list(raw_target.keys())
        is_node_mapping = all(
            _canonicalize_sim_cluster_node_id(str(k), bottom_ids=set(b_to_idx)) in node_to_idx
            or str(k) in b_to_idx
            or any(cand.endswith(f"={k}") for cand in node_to_idx)
            for k in sample_keys
        )
        if is_node_mapping:
            for k_node, v_targ in raw_target.items():
                s_r = _node_s_row(str(k_node))
                if target_mode == "per_step":
                    for t_idx in active_t_indices:
                        row_flat = np.zeros(n_b * h_total, dtype=float)
                        w_m = (
                            price_mat[:, t_idx]
                            if use_revenue_weights
                            else np.ones(n_b, dtype=float)
                        )
                        row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
                        eq_rows.append(row_flat)
                        eq_rhs.append(float(v_targ))
                else:
                    row_flat = np.zeros(n_b * h_total, dtype=float)
                    for t_idx in active_t_indices:
                        w_m = (
                            price_mat[:, t_idx]
                            if use_revenue_weights
                            else np.ones(n_b, dtype=float)
                        )
                        row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
                    eq_rows.append(row_flat)
                    eq_rhs.append(float(v_targ))
        else:
            s_r = _node_s_row(eff_target_node)
            for k_dt, v_targ in raw_target.items():
                matched_t: int | None = None
                if isinstance(k_dt, int) and 0 <= k_dt < h_total and k_dt not in date_to_t:
                    matched_t = k_dt
                elif k_dt in date_to_t:
                    matched_t = date_to_t[k_dt]
                else:
                    ts_k = pd.Timestamp(k_dt)
                    for dt_cand, t_cand in date_to_t.items():
                        if pd.Timestamp(dt_cand) == ts_k:
                            matched_t = t_cand
                            break
                if matched_t is None:
                    raise ConfigError(
                        f"Target key '{k_dt}' did not match any hierarchy node or forecast date"
                    )
                row_flat = np.zeros(n_b * h_total, dtype=float)
                w_m = price_mat[:, matched_t] if use_revenue_weights else np.ones(n_b, dtype=float)
                row_flat[matched_t * n_b : (matched_t + 1) * n_b] = s_r * w_m
                eq_rows.append(row_flat)
                eq_rhs.append(float(v_targ))
    elif isinstance(raw_target, (Sequence, np.ndarray)) and not isinstance(
        raw_target, (str, bytes)
    ):
        seq_vals = [float(x) for x in raw_target]
        if len(seq_vals) != len(active_t_indices):
            raise ConfigError(
                f"Target sequence length ({len(seq_vals)}) must match "
                f"active horizon length ({len(active_t_indices)})."
            )
        s_r = _node_s_row(eff_target_node)
        for pos_t, t_idx in enumerate(active_t_indices):
            row_flat = np.zeros(n_b * h_total, dtype=float)
            w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
            row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
            eq_rows.append(row_flat)
            eq_rhs.append(seq_vals[pos_t])
    else:
        scalar_target = float(raw_target)
        if not np.isfinite(scalar_target):
            raise ConfigError(f"target_total must be finite; got {raw_target!r}")
        s_r = _node_s_row(eff_target_node)
        if target_mode == "per_step":
            for t_idx in active_t_indices:
                row_flat = np.zeros(n_b * h_total, dtype=float)
                w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
                row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
                eq_rows.append(row_flat)
                eq_rhs.append(scalar_target)
        else:
            row_flat = np.zeros(n_b * h_total, dtype=float)
            for t_idx in active_t_indices:
                w_m = price_mat[:, t_idx] if use_revenue_weights else np.ones(n_b, dtype=float)
                row_flat[t_idx * n_b : (t_idx + 1) * n_b] = s_r * w_m
            eq_rows.append(row_flat)
            eq_rhs.append(scalar_target)

    a_eq = np.vstack(eq_rows)
    c_eq = np.asarray(eq_rhs, dtype=float)

    # Build covariance blocks W_t across horizon steps t = 0..H-1.
    w_cs = _resolve_bottom_covariance(
        resolved_spec,
        method,
        weights,
        b_hat=b_hat,
        b_var_from_intervals=b_var_intervals,
        oof_df=oof_df,
        ts_id_col=ts_id_col,
    )
    eff_mode_str = str(weights if isinstance(weights, str) else method).strip().lower()
    w_blocks: list[np.ndarray] = []
    for t_idx in range(h_total):
        if eff_mode_str in {"proportional", "baseline"}:
            w_blocks.append(np.diag(np.maximum(np.abs(b_hat[:, t_idx]), 1e-4)))
        elif (
            b_var_intervals is not None
            and oof_df is None
            and not isinstance(weights, (Mapping, Sequence, np.ndarray))
        ):
            w_blocks.append(np.diag(np.maximum(b_var_intervals[:, t_idx], _VAR_FLOOR)))
        elif (
            oof_df is None
            and b_var_intervals is None
            and eff_mode_str not in {"ols", "wls_struct", "struc", "uniform", "equal"}
            and not isinstance(weights, (Mapping, Sequence, np.ndarray))
        ):
            w_blocks.append(np.diag(np.maximum(np.abs(b_hat[:, t_idx]), 1.0) ** 2))
        else:
            w_blocks.append(w_cs)

    # Flatten column-major by timestamp t: flat index k = t * n_b + i.
    b_hat_flat = b_hat.T.reshape(-1)
    lo_flat = lo_mat.T.reshape(-1)
    hi_flat = hi_mat.T.reshape(-1)

    b_alloc_flat = _solve_constrained_qp(
        b_hat_flat,
        w_blocks,
        a_eq,
        c_eq,
        lo_flat,
        hi_flat,
        smoothness_weight=smooth_w,
    )
    b_alloc = b_alloc_flat.reshape(h_total, n_b).T  # shape (n_b, H)

    # Full hierarchy rollup Y_tilde = S @ B_alloc and Y_hat = S @ B_hat of shape (n_nodes, H).
    s_mat = resolved_spec.summing_matrix
    y_base_all = s_mat @ b_hat
    y_alloc_all = s_mat @ b_alloc
    lo_all = s_mat @ lo_mat
    hi_all = np.where(
        (s_mat @ np.where(np.isfinite(hi_mat), 0.0, 1.0)) > 0.0,
        np.inf,
        s_mat @ np.where(np.isfinite(hi_mat), hi_mat, 0.0),
    )

    # Normalized bottom-series allocation weights for transparency.
    raw_series_w = np.diag(w_cs).copy()
    w_sum = float(np.sum(raw_series_w))
    norm_b_weights = raw_series_w / w_sum if w_sum > 1e-12 else np.full(n_b, 1.0 / n_b, dtype=float)
    node_weights = s_mat @ norm_b_weights

    # Determine which nodes to include in output DataFrame.
    output_node_ids = (
        list(resolved_spec.node_ids) if include_agg_in_out else list(resolved_spec.bottom_ids)
    )

    # Index original rows for interval extraction.
    orig_by_key: dict[tuple[str, Any], dict[str, Any]] = {}
    for r in df.to_dict(orient="records"):
        orig_by_key[(str(r[ts_id_col]), r[dcol])] = {str(k): v for k, v in r.items()}

    canon_tn = _canonicalize_sim_cluster_node_id(eff_target_node, bottom_ids=set(b_to_idx))
    if canon_tn in node_to_idx:
        target_node_idx = node_to_idx[canon_tn]
    else:
        target_node_idx = 0
        for cand_nid, r_idx in node_to_idx.items():
            if cand_nid.endswith(f"={canon_tn}") or cand_nid == canon_tn:
                target_node_idx = r_idx
                break
    records: list[dict[str, Any]] = []
    for nid in output_node_ids:
        n_idx = node_to_idx[nid]
        is_bottom = nid in b_to_idx
        b_idx_opt = b_to_idx.get(nid)
        for t_idx, dt_val in enumerate(all_dates):
            base_v = float(y_base_all[n_idx, t_idx])
            alloc_v = float(y_alloc_all[n_idx, t_idx])
            d_v = alloc_v - base_v
            d_pct = (100.0 * d_v / abs(base_v)) if abs(base_v) > 1e-12 else 0.0
            lo_v = (
                float(lo_mat[b_idx_opt, t_idx])
                if b_idx_opt is not None
                else float(lo_all[n_idx, t_idx])
            )
            hi_v = (
                float(hi_mat[b_idx_opt, t_idx])
                if b_idx_opt is not None
                else float(hi_all[n_idx, t_idx])
            )
            is_lck = bool(locked_mat[b_idx_opt, t_idx]) if b_idx_opt is not None else False

            if is_lck or abs(hi_v - lo_v) <= 1e-9:
                c_status = "LOCKED"
            elif np.isfinite(lo_v) and abs(alloc_v - lo_v) <= 1e-6 * max(1.0, abs(lo_v)):
                c_status = "AT_FLOOR"
            elif np.isfinite(hi_v) and abs(alloc_v - hi_v) <= 1e-6 * max(1.0, abs(hi_v)):
                c_status = "AT_CAP"
            else:
                c_status = "FREE"

            orig_r = orig_by_key.get((nid, dt_val), {})
            base_lo = float(
                orig_r.get(
                    "yhat_lower", orig_r.get("yhat_lower_80", base_v - 0.1 * max(abs(base_v), 1.0))
                )
            )
            base_hi = float(
                orig_r.get(
                    "yhat_upper", orig_r.get("yhat_upper_80", base_v + 0.1 * max(abs(base_v), 1.0))
                )
            )
            hw = max(0.0, 0.5 * (base_hi - base_lo))
            alloc_lo = alloc_v - hw
            alloc_hi = alloc_v + hw
            if np.isfinite(lo_v):
                alloc_lo = max(lo_v, alloc_lo)
            if np.isfinite(hi_v):
                alloc_hi = min(hi_v, alloc_hi)
            alloc_lo = min(alloc_lo, alloc_v)
            alloc_hi = max(alloc_hi, alloc_v)

            root_tot_t = float(y_alloc_all[target_node_idx, t_idx])
            share_t = (
                (alloc_v / root_tot_t)
                if abs(root_tot_t) > 1e-12
                else (
                    float(norm_b_weights[b_idx_opt])
                    if b_idx_opt is not None
                    else float(node_weights[n_idx])
                )
            )

            rec: dict[str, Any] = {
                ts_id_col: nid,
                "model_type": eff_model_type,
                "ds": pd.Timestamp(dt_val) if not isinstance(dt_val, (int, np.integer)) else dt_val,
                "forecast_date": pd.Timestamp(dt_val)
                if not isinstance(dt_val, (int, np.integer))
                else dt_val,
                "horizon_step": int(orig_r.get("horizon_step", t_idx + 1)),
                "baseline_yhat": base_v,
                "allocated_yhat": alloc_v,
                "yhat": alloc_v,
                "yhat_lower": alloc_lo,
                "yhat_upper": alloc_hi,
                "delta_yhat": d_v,
                "delta_units": d_v,
                "delta_pct": d_pct,
                "lower_bound": lo_v,
                "upper_bound": hi_v,
                "is_locked": is_lck,
                "allocation_weight": float(norm_b_weights[b_idx_opt])
                if b_idx_opt is not None
                else float(node_weights[n_idx]),
                "constraint_status": c_status,
                "yhat_baseline": base_v,
                "yhat_allocated": alloc_v,
                "y_allocated": alloc_v,
                "bound_active": c_status != "FREE",
                "allocation_share": share_t,
            }

            # Shift any explicit quantile columns (`yhat_lower_80`, `yhat_upper_95`, etc.).
            for col_k, col_v in orig_r.items():
                if col_k.startswith("yhat_lower_") and col_v is not None and pd.notna(col_v):
                    q_suf = col_k[len("yhat_lower_") :]
                    u_k = f"yhat_upper_{q_suf}"
                    u_v = orig_r.get(u_k)
                    if u_v is not None and pd.notna(u_v):
                        q_hw = max(0.0, 0.5 * (float(u_v) - float(col_v)))
                        q_lo = min(
                            alloc_v, max(lo_v if np.isfinite(lo_v) else -np.inf, alloc_v - q_hw)
                        )
                        q_hi = max(
                            alloc_v, min(hi_v if np.isfinite(hi_v) else np.inf, alloc_v + q_hw)
                        )
                        rec[col_k] = q_lo
                        rec[u_k] = q_hi
                        rec[f"allocated_{col_k}"] = q_lo
                        rec[f"allocated_{u_k}"] = q_hi

            if has_price or has_cost:
                s_row_n = s_mat[n_idx]
                b_rev_vec = price_mat[:, t_idx] * b_hat[:, t_idx]
                a_rev_vec = price_mat[:, t_idx] * b_alloc[:, t_idx]
                b_rev = (
                    float(b_rev_vec[b_idx_opt])
                    if is_bottom and b_idx_opt is not None
                    else float(s_row_n @ b_rev_vec)
                )
                a_rev = (
                    float(a_rev_vec[b_idx_opt])
                    if is_bottom and b_idx_opt is not None
                    else float(s_row_n @ a_rev_vec)
                )
                rev_d = a_rev - b_rev
                rev_pct = (100.0 * rev_d / abs(b_rev)) if abs(b_rev) > 1e-12 else 0.0
                eff_p = (
                    float(price_mat[b_idx_opt, t_idx])
                    if is_bottom and b_idx_opt is not None
                    else ((a_rev / alloc_v) if abs(alloc_v) > 1e-12 else 1.0)
                )
                rec.update(
                    {
                        "price": eff_p,
                        "baseline_revenue": b_rev,
                        "allocated_revenue": a_rev,
                        "scenario_revenue": a_rev,
                        "revenue_delta": rev_d,
                        "delta_revenue": rev_d,
                        "revenue_delta_pct": rev_pct,
                    }
                )
                if has_cost:
                    b_gm_vec = (price_mat[:, t_idx] - cost_mat[:, t_idx]) * b_hat[:, t_idx]
                    a_gm_vec = (price_mat[:, t_idx] - cost_mat[:, t_idx]) * b_alloc[:, t_idx]
                    b_gm = (
                        float(b_gm_vec[b_idx_opt])
                        if is_bottom and b_idx_opt is not None
                        else float(s_row_n @ b_gm_vec)
                    )
                    a_gm = (
                        float(a_gm_vec[b_idx_opt])
                        if is_bottom and b_idx_opt is not None
                        else float(s_row_n @ a_gm_vec)
                    )
                    gm_d = a_gm - b_gm
                    gm_pct = (100.0 * gm_d / abs(b_gm)) if abs(b_gm) > 1e-12 else 0.0
                    eff_c = (
                        float(cost_mat[b_idx_opt, t_idx])
                        if is_bottom and b_idx_opt is not None
                        else (((a_rev - a_gm) / alloc_v) if abs(alloc_v) > 1e-12 else 0.0)
                    )
                    rec.update(
                        {
                            "unit_cost": eff_c,
                            "baseline_gross_margin": b_gm,
                            "allocated_gross_margin": a_gm,
                            "scenario_gross_margin": a_gm,
                            "gross_margin_delta": gm_d,
                            "delta_gross_margin": gm_d,
                            "gross_margin_delta_pct": gm_pct,
                        }
                    )

            records.append(rec)

    out_df = pd.DataFrame.from_records(records)

    # Optional inventory replenishment policy delta via diagnostics.compute_inventory_policy.
    if (include_inventory_impact or inventory_params is not None) and not out_df.empty:
        from .diagnostics import compute_inventory_policy

        inv_kw: dict[str, Any] = {
            "lead_time": float(lead_time),
            "lead_time_std": float(lead_time_std),
            "service_level": service_level,
        }
        if inventory_params:
            inv_kw.update(dict(inventory_params))

        base_for_inv = out_df.copy()
        base_for_inv["yhat"] = base_for_inv["baseline_yhat"]
        hw_curr = 0.5 * (
            out_df["yhat_upper"].to_numpy(dtype=float) - out_df["yhat_lower"].to_numpy(dtype=float)
        )
        base_for_inv["yhat_lower"] = base_for_inv["baseline_yhat"] - hw_curr
        base_for_inv["yhat_upper"] = base_for_inv["baseline_yhat"] + hw_curr

        base_pol = compute_inventory_policy(base_for_inv, oof_df=oof_df, **inv_kw)
        alloc_pol = compute_inventory_policy(out_df, oof_df=oof_df, **inv_kw)

        base_inv_map = {str(r["ts_id"]): r for r in base_pol.to_dict(orient="records")}
        alloc_inv_map = {str(r["ts_id"]): r for r in alloc_pol.to_dict(orient="records")}

        b_rop: list[float] = []
        a_rop: list[float] = []
        d_rop: list[float] = []
        b_ss: list[float] = []
        a_ss: list[float] = []
        d_ss: list[float] = []
        b_q: list[float] = []
        a_q: list[float] = []
        d_q: list[float] = []

        for tid_val in out_df[ts_id_col].astype(str):
            br = base_inv_map.get(tid_val, {})
            ar = alloc_inv_map.get(tid_val, {})
            rop_0 = float(br.get("reorder_point", 0.0))
            rop_1 = float(ar.get("reorder_point", rop_0))
            ss_0 = float(br.get("safety_stock", 0.0))
            ss_1 = float(ar.get("safety_stock", ss_0))
            q_0 = float(br.get("recommended_order_qty", 0.0))
            q_1 = float(ar.get("recommended_order_qty", q_0))
            b_rop.append(rop_0)
            a_rop.append(rop_1)
            d_rop.append(rop_1 - rop_0)
            b_ss.append(ss_0)
            a_ss.append(ss_1)
            d_ss.append(ss_1 - ss_0)
            b_q.append(q_0)
            a_q.append(q_1)
            d_q.append(q_1 - q_0)

        out_df["baseline_reorder_point"] = b_rop
        out_df["allocated_reorder_point"] = a_rop
        out_df["scenario_reorder_point"] = a_rop
        out_df["delta_reorder_point"] = d_rop
        out_df["baseline_safety_stock"] = b_ss
        out_df["allocated_safety_stock"] = a_ss
        out_df["scenario_safety_stock"] = a_ss
        out_df["delta_safety_stock"] = d_ss
        out_df["baseline_order_qty"] = b_q
        out_df["allocated_order_qty"] = a_q
        out_df["scenario_order_qty"] = a_q
        out_df["delta_order_qty"] = d_q

    coh_err = float(np.max(np.abs(a_eq @ b_alloc_flat - c_eq)))
    target_eq_rhs = eq_rhs[n_lock_eq:]
    target_tot_val = float(np.sum(target_eq_rhs)) if target_eq_rhs else float(np.sum(c_eq))
    out_df.attrs["hierarchy_spec"] = resolved_spec
    out_df.attrs["target_node"] = eff_target_node
    out_df.attrs["target_total"] = target_tot_val
    out_df.attrs["coherence_max_abs_error"] = coh_err
    out_df.attrs["smoothness_weight"] = smooth_w
    if return_result:
        sum_df = summarize_goal_seek(out_df, ts_id_col=ts_id_col)
        return GoalSeekResult(
            allocations=out_df,
            summary=sum_df,
            target_node=eff_target_node,
            target_total=target_tot_val,
            baseline_total=float(np.sum(y_base_all[target_node_idx, active_t_indices])),
            allocated_total=float(np.sum(y_alloc_all[target_node_idx, active_t_indices])),
            coherence_max_abs_error=coh_err,
            active_bound_count=int(np.sum(out_df["bound_active"])),
            locked_count=int(np.sum(out_df["is_locked"])),
        )
    return out_df

plot_goal_seek

plot_goal_seek(
    goal_seek_df,
    *,
    ts_id=None,
    top_n=10,
    ax=None,
    title=None,
)

Plot baseline vs. goal-seek allocated forecasts (bar summary or single-series trajectory).

Source code in src/scale_forecasting/goal_seek.py
def plot_goal_seek(
    goal_seek_df: pd.DataFrame | GoalSeekResult,
    *,
    ts_id: str | None = None,
    top_n: int = 10,
    ax: Any = None,
    title: str | None = None,
) -> Any:
    """Plot baseline vs. goal-seek allocated forecasts (bar summary or single-series trajectory)."""
    import matplotlib.pyplot as plt

    if isinstance(goal_seek_df, GoalSeekResult):
        goal_seek_df = goal_seek_df.allocations
    if goal_seek_df is None or goal_seek_df.empty:
        raise DataError("plot_goal_seek requires a non-empty goal_seek_df DataFrame")

    created_fig = False
    if ax is None:
        fig, ax = plt.subplots(figsize=(9, 4.5))
        created_fig = True
    else:
        fig = ax.figure

    id_col = "ts_id" if "ts_id" in goal_seek_df.columns else goal_seek_df.columns[0]
    dcol = (
        "ds"
        if "ds" in goal_seek_df.columns
        else ("forecast_date" if "forecast_date" in goal_seek_df.columns else None)
    )

    unique_ids = goal_seek_df[id_col].astype(str).unique().tolist()
    if ts_id is not None or len(unique_ids) == 1:
        target_id = str(ts_id) if ts_id is not None else unique_ids[0]
        sub = goal_seek_df[goal_seek_df[id_col].astype(str) == target_id].copy()
        if sub.empty:
            raise DataError(f"ts_id='{target_id}' not found in goal_seek_df")
        x_vals: Any
        if dcol is not None:
            sub = sub.sort_values(dcol, kind="mergesort")
            x_vals = sub[dcol]
        else:
            x_vals = np.arange(len(sub))

        ax.plot(
            x_vals,
            sub["baseline_yhat"],
            label="Baseline Forecast",
            linestyle="--",
            color="#64748b",
            linewidth=1.8,
        )
        ax.plot(
            x_vals,
            sub["allocated_yhat"],
            label="Goal-Seek Allocated",
            color="#2563eb",
            linewidth=2.2,
        )
        if "yhat_lower" in sub.columns and "yhat_upper" in sub.columns:
            ax.fill_between(
                x_vals,
                sub["yhat_lower"].to_numpy(dtype=float),
                sub["yhat_upper"].to_numpy(dtype=float),
                color="#2563eb",
                alpha=0.15,
                label="Allocated 80% PI",
            )
        ax.set_title(title or f"Top-Down Goal-Seek Allocation — {target_id}")
        ax.set_ylabel("Forecast Units")
        ax.legend(loc="best")
        ax.grid(True, alpha=0.25)
    else:
        summary = summarize_goal_seek(goal_seek_df, ts_id_col=id_col)
        non_total = summary[summary[id_col] != TOTAL_NODE_ID]
        if not non_total.empty:
            summary = non_total
        summary = summary.reindex(
            summary["delta_units"].abs().sort_values(ascending=False).index
        ).head(max(1, int(top_n)))

        y_pos = np.arange(len(summary))
        height = 0.36
        ax.barh(
            y_pos - height / 2,
            summary["baseline_total_units"],
            height=height,
            label="Baseline Total",
            color="#94a3b8",
        )
        ax.barh(
            y_pos + height / 2,
            summary["allocated_total_units"],
            height=height,
            label="Allocated Total",
            color="#2563eb",
        )
        ax.set_yticks(y_pos)
        ax.set_yticklabels(summary[id_col].tolist())
        ax.invert_yaxis()
        ax.set_xlabel("Horizon Total Units")
        ax.set_title(title or "Top-Down Goal-Seek Disaggregation across Series")
        ax.legend(loc="best")
        ax.grid(True, axis="x", alpha=0.25)

    if created_fig:
        fig.tight_layout()
    return fig

summarize_goal_seek

summarize_goal_seek(goal_seek_df, *, ts_id_col='ts_id')

Aggregate per-series goal-seek allocations across the forecast horizon (pure).

Source code in src/scale_forecasting/goal_seek.py
def summarize_goal_seek(
    goal_seek_df: pd.DataFrame | GoalSeekResult,
    *,
    ts_id_col: str = "ts_id",
) -> pd.DataFrame:
    """Aggregate per-series goal-seek allocations across the forecast horizon (pure)."""
    if isinstance(goal_seek_df, GoalSeekResult):
        goal_seek_df = goal_seek_df.allocations
    if goal_seek_df is None or goal_seek_df.empty:
        return pd.DataFrame(
            columns=[
                ts_id_col,
                "model_type",
                "baseline_total_units",
                "allocated_total_units",
                "y_allocated_sum",
                "delta_units",
                "delta_pct",
                "allocation_weight",
                "constraint_status",
            ]
        )

    id_col = ts_id_col if ts_id_col in goal_seek_df.columns else "ts_id"
    rows: list[dict[str, Any]] = []
    for tid, grp in goal_seek_df.groupby(id_col, sort=False):
        b_tot = float(grp["baseline_yhat"].sum())
        a_tot = float(grp["allocated_yhat"].sum())
        d_u = a_tot - b_tot
        d_pct = (100.0 * d_u / abs(b_tot)) if abs(b_tot) > 1e-12 else 0.0
        statuses = (
            set(grp["constraint_status"].astype(str).tolist())
            if "constraint_status" in grp.columns
            else {"FREE"}
        )
        if "LOCKED" in statuses:
            dom_status = "LOCKED"
        elif "AT_CAP" in statuses:
            dom_status = "AT_CAP"
        elif "AT_FLOOR" in statuses:
            dom_status = "AT_FLOOR"
        else:
            dom_status = "FREE"

        rec: dict[str, Any] = {
            id_col: str(tid),
            "model_type": str(grp["model_type"].iloc[0])
            if "model_type" in grp.columns
            else "default",
            "baseline_total_units": b_tot,
            "allocated_total_units": a_tot,
            "y_allocated_sum": a_tot,
            "baseline_yhat": b_tot,
            "allocated_yhat": a_tot,
            "delta_units": d_u,
            "delta_yhat": d_u,
            "delta_pct": d_pct,
            "allocation_weight": float(grp["allocation_weight"].mean())
            if "allocation_weight" in grp.columns
            else 0.0,
            "constraint_status": dom_status,
        }
        if "baseline_revenue" in grp.columns and "allocated_revenue" in grp.columns:
            b_rev = float(grp["baseline_revenue"].sum())
            a_rev = float(grp["allocated_revenue"].sum())
            rec["baseline_revenue"] = b_rev
            rec["allocated_revenue"] = a_rev
            rec["revenue_delta"] = a_rev - b_rev
            rec["delta_revenue"] = a_rev - b_rev
        if "baseline_gross_margin" in grp.columns and "allocated_gross_margin" in grp.columns:
            b_gm = float(grp["baseline_gross_margin"].sum())
            a_gm = float(grp["allocated_gross_margin"].sum())
            rec["baseline_gross_margin"] = b_gm
            rec["allocated_gross_margin"] = a_gm
            rec["gross_margin_delta"] = a_gm - b_gm
            rec["delta_gross_margin"] = a_gm - b_gm
        if "delta_reorder_point" in grp.columns:
            rec["baseline_reorder_point"] = float(grp["baseline_reorder_point"].iloc[0])
            rec["allocated_reorder_point"] = float(grp["allocated_reorder_point"].iloc[0])
            rec["delta_reorder_point"] = float(grp["delta_reorder_point"].iloc[0])
            rec["baseline_safety_stock"] = float(grp["baseline_safety_stock"].iloc[0])
            rec["allocated_safety_stock"] = float(grp["allocated_safety_stock"].iloc[0])
            rec["delta_safety_stock"] = float(grp["delta_safety_stock"].iloc[0])
            rec["baseline_order_qty"] = float(grp["baseline_order_qty"].iloc[0])
            rec["allocated_order_qty"] = float(grp["allocated_order_qty"].iloc[0])
            rec["delta_order_qty"] = float(grp["delta_order_qty"].iloc[0])
        rows.append(rec)

    return pd.DataFrame.from_records(rows)