Skip to content

Lifecycle Markdown, Shelf-Space Reclamation, Vendor Contract Volume & Assortment Transference Optimizer

flowchart TD
    subgraph Inputs["1. Inputs, Similarity & Digital-Twin Elasticity Priors"]
        direction TB
        C1["Baseline Forecasts & Inventory<br/>predictions_df · initial_inventory · expiry_step · shelf_space"]
        C2["Own-Price & Digital-Twin Elasticity / Similarity<br/>history_df · similarity_df · use_digital_twin_elasticity · walk_rate"]
    end
    subgraph Solvers["2. HiGHS Mixed-Integer Linear Programs (scipy.optimize.milp)"]
        direction TB
        S1["Lifecycle Markdown & Space Reclamation<br/>optimize_clearance · target_space_freed · reclaim_by_step"]
        S2["Vendor Contract Rebate & Take-or-Pay<br/>optimize_contract_volume · contract_tiers · min_contract_volume"]
        S3["Assortment Delisting & Demand Transference<br/>optimize_assortment · max_skus · max_shelf_space · walk_rate"]
    end
    subgraph Outputs["3. Prescriptive Schedules & Diagnostics"]
        direction TB
        O1["ClearanceOptimizationResult<br/>schedule_df · summary_df · plot_clearance_schedule"]
        O2["ContractVolumeOptimizationResult<br/>rebate_earned · shortfall_penalty · cvar_shortfall_units"]
        O3["AssortmentOptimizationResult<br/>assortment_df · transference_df · category_retention_pct"]
    end
    C1 & C2 --> S1 & S2 & S3
    S1 --> O1
    S2 --> O2
    S3 --> O3

clearance_optimizer

Lifecycle markdown & perishable clearance MILP, shelf-space reclamation, and vendor contract volume optimization.

Provides three coupled prescriptive optimization capabilities built on scipy.optimize.milp (HiGHS) and Track P digital-twin similarity priors:

  1. Lifecycle Markdown & Perishable Expiry Optimization (:func:optimize_clearance, :func:optimize_clearance_df): Solves for a monotone markdown discount ladder across the forecast horizon ($d_{i,t} \le d_{i,t+1}$) subject to finite starting on-hand inventory $I_{i,0}$, per-SKU shelf-life / end-of-season expiry deadlines $T_{\text{expiry},i}$, terminal salvage value or spoilage disposal cost, cross-SKU cannibalization penalties, and digital-twin deep-discount elasticity borrowing when a SKU has never been marked down before.
  2. Warehouse & Shelf Space Reclamation (target_space_freed, unit_volume, reclaim_by_step): Adds a linear cubic-volume / shelf-facing reclamation constraint $\sum_i v_i \sum_{t=1}^{T_{\text{reclaim}}} q_{i,t}(d_{i,t}) \ge V_{\text{target}}$ so the solver finds the minimum-margin-erosion clearance schedule that frees target capacity for incoming high-velocity SKUs.
  3. Vendor Contract Volume & Tiered Rebate / Take-or-Pay Optimization (:func:optimize_contract_volume, :func:optimize_contract_volume_df): Allocates discounts across a multi-SKU vendor portfolio to cross cumulative all-units rebate tiers $(\tau_m, R_m)$ or satisfy Take-or-Pay minimum volume commitments $Q_{\min}$ while accounting for Copula $\text{CVaR}_{\alpha}$ demand shortfall risk.

AssortmentOptimizationResult dataclass

AssortmentOptimizationResult(
    assortment_df,
    transference_df,
    status,
    is_feasible,
    total_candidate_skus,
    retained_skus,
    delisted_skus,
    baseline_category_units,
    post_assortment_units,
    transferred_units,
    lost_walk_units,
    category_retention_pct,
    mean_walk_rate,
    baseline_net_profit,
    optimal_net_profit,
    net_profit_lift,
    shelf_space_used,
    relaxation_hint=None,
    hierarchy_rollup_df=None,
)

Structured output of :func:optimize_assortment.

Attributes:

Name Type Description
assortment_df DataFrame

Per-SKU assortment decision ("KEEP" vs. "DELIST"), walk rate, transferred demand, and profit contribution (ASSORTMENT_OPTIMIZER_COLUMNS).

transference_df DataFrame

Pairwise demand transference flows from delisted SKUs to retained substitute SKUs (ASSORTMENT_TRANSFERENCE_COLUMNS).

status str

Solver status ("optimal", "feasible", or "infeasible").

is_feasible bool

True when all SKU count, shelf space, and category retention constraints are satisfied.

total_candidate_skus int

Total candidate SKUs evaluated.

retained_skus int

Count of SKUs kept (action == "KEEP").

delisted_skus int

Count of SKUs delisted (action == "DELIST").

baseline_category_units float

Total baseline demand across all candidate SKUs.

post_assortment_units float

Total retained + transferred demand after assortment rationalization.

transferred_units float

Total demand transferred from delisted SKUs to retained substitutes.

lost_walk_units float

Total category demand lost to shopper walk-away (walk_rate).

category_retention_pct float

Fraction of baseline category demand retained ([0, 1]).

mean_walk_rate float

Mean intrinsic walk rate across candidate SKUs.

baseline_net_profit float

Net profit of keeping all candidate SKUs (margin minus slot costs).

optimal_net_profit float

Net profit of the optimized assortment including demand transference.

net_profit_lift float

optimal_net_profit - baseline_net_profit.

shelf_space_used float

Total shelf space / facings consumed by retained SKUs.

relaxation_hint str | None

Actionable diagnostic message when constraints are infeasible.

hierarchy_rollup_df DataFrame | None

Optional bottom-up hierarchy rollup of assortment metrics.

ClearanceOptimizationResult dataclass

ClearanceOptimizationResult(
    schedule_df,
    summary_df,
    status,
    is_feasible,
    total_baseline_profit,
    total_optimal_profit,
    total_profit_lift,
    total_space_freed,
    target_space_freed,
    overall_sell_through_pct,
    relaxation_hint=None,
    hierarchy_rollup_df=None,
)

Structured output of :func:optimize_clearance.

Attributes:

Name Type Description
schedule_df DataFrame

Step-by-step markdown schedule with columns :data:CLEARANCE_SCHEDULE_COLUMNS.

summary_df DataFrame

Per-SKU clearance & space-reclamation summary with columns :data:CLEARANCE_SUMMARY_COLUMNS.

status str

Solver status ("optimal", "feasible", "infeasible", or "empty").

is_feasible bool

True when all sell-through and warehouse space targets were met without relaxation.

total_baseline_profit float

Portfolio net profit under a $0\%$ discount policy (including terminal salvage minus spoilage).

total_optimal_profit float

Portfolio net profit under the optimized markdown schedule.

total_profit_lift float

total_optimal_profit - total_baseline_profit.

total_space_freed float

Total warehouse/shelf volume freed by reclaim_by_step.

target_space_freed float | None

Requested warehouse/shelf volume target (or None).

overall_sell_through_pct float

Portfolio-wide fraction of initial inventory sold before expiry.

relaxation_hint str | None

Diagnostic message explaining which constraint was unreachable when is_feasible is False.

ContractVolumeOptimizationResult dataclass

ContractVolumeOptimizationResult(
    schedule_df,
    summary_df,
    status,
    is_feasible,
    baseline_portfolio_units,
    optimal_portfolio_units,
    target_contract_units,
    achieved_tier_units,
    rebate_earned,
    shortfall_units,
    shortfall_penalty,
    cvar_shortfall_units,
    baseline_net_value,
    optimal_net_value,
    net_value_lift,
    relaxation_hint=None,
    hierarchy_rollup_df=None,
)

Structured output of :func:optimize_contract_volume.

Attributes:

Name Type Description
schedule_df DataFrame

Step-by-step promotional discount schedule with columns :data:CONTRACT_VOLUME_COLUMNS.

summary_df DataFrame

Per-SKU volume, margin, and rebate allocation summary with columns :data:CONTRACT_VOLUME_SUMMARY_COLUMNS.

status str

Solver status ("optimal", "feasible", "infeasible", or "empty").

is_feasible bool

True when the contract optimization solved cleanly.

baseline_portfolio_units float

Cumulative portfolio volume at $0\%$ discount.

optimal_portfolio_units float

Cumulative portfolio volume under the optimal discount plan.

target_contract_units float

Highest active target volume threshold ($\tau_m$ or $Q_{\min}$).

achieved_tier_units float

Volume threshold of the rebate tier unlocked by the optimal plan.

rebate_earned float

Lump-sum vendor rebate unlocked ($R_m$).

shortfall_units float

Remaining volume shortfall below min_contract_volume.

shortfall_penalty float

Total Take-or-Pay shortfall penalty incurred.

cvar_shortfall_units float

Expected tail shortfall at cvar_alpha across demand paths.

baseline_net_value float

Baseline gross margin plus baseline rebate minus baseline penalty.

optimal_net_value float

Optimal gross margin plus earned rebate minus shortfall penalty.

net_value_lift float

optimal_net_value - baseline_net_value.

relaxation_hint str | None

Optional diagnostic hint if min_contract_volume exceeds maximum physical demand.

optimize_assortment

optimize_assortment(
    predictions_df,
    *,
    history_df=None,
    oof_df=None,
    similarity_df=None,
    elasticity_df=None,
    similarity_method="hybrid",
    max_skus=None,
    min_skus=1,
    max_shelf_space=None,
    shelf_space=1.0,
    base_price=20.0,
    unit_cost=10.0,
    fixed_slot_cost=0.0,
    walk_rate=None,
    retention_scale=0.85,
    min_walk_rate=0.05,
    max_walk_rate=0.95,
    min_similarity=0.1,
    top_k_substitutes=5,
    walk_penalty_weight=0.0,
    min_category_retention=None,
    must_keep_skus=None,
    must_delist_skus=None,
    text_cols=None,
    attribute_cols=None,
    covariate_cols=None,
    hierarchy_cols="auto",
    model_type=None,
    reconciliation_method=None,
    prefer_reconciled=True,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    horizon=14,
    freq="D",
)

Solve the assortment rationalization & delisting demand-transference MILP (HiGHS).

Given $N$ candidate SKUs with horizon demand $D_i$, unit margin $m_i = p_i - c_i$, fixed slot cost $F_i$, and shelf space $s_i$, selects which SKUs to retain ($z_i = 1$) vs. delist ($z_i = 0$). When SKU $i$ is delisted, a fraction $t_{ij}$ of its demand transfers to retained substitute SKUs $j$ based on the multi-modal similarity matrix $\mathbf{S}{ij}$, while the remaining fraction $w_i^{\text{walk}} = 1 - \sum$ walks away from the category (}} t_{ijlost_walk_units).

Source code in src/scale_forecasting/clearance_optimizer.py
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
def optimize_assortment(
    predictions_df: pd.DataFrame,
    *,
    history_df: pd.DataFrame | None = None,
    oof_df: pd.DataFrame | None = None,
    similarity_df: pd.DataFrame | None = None,
    elasticity_df: pd.DataFrame | None = None,
    similarity_method: str = "hybrid",
    max_skus: int | None = None,
    min_skus: int = 1,
    max_shelf_space: float | None = None,
    shelf_space: float | Mapping[str, float] | str = 1.0,
    base_price: float | Mapping[str, float] | str = 20.0,
    unit_cost: float | Mapping[str, float] | str = 10.0,
    fixed_slot_cost: float | Mapping[str, float] | str = 0.0,
    walk_rate: float | Mapping[str, float] | str | None = None,
    retention_scale: float = 0.85,
    min_walk_rate: float = 0.05,
    max_walk_rate: float = 0.95,
    min_similarity: float = 0.10,
    top_k_substitutes: int = 5,
    walk_penalty_weight: float = 0.0,
    min_category_retention: float | None = None,
    must_keep_skus: Sequence[str] | None = None,
    must_delist_skus: Sequence[str] | None = None,
    text_cols: Sequence[str] | None = None,
    attribute_cols: Sequence[str] | None = None,
    covariate_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | str | None = "auto",
    model_type: str | None = None,
    reconciliation_method: str | None = None,
    prefer_reconciled: bool = True,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    horizon: int = 14,
    freq: str = "D",
) -> AssortmentOptimizationResult:
    """Solve the assortment rationalization & delisting demand-transference MILP (`HiGHS`).

    Given $N$ candidate SKUs with horizon demand $D_i$, unit margin $m_i = p_i - c_i$, fixed slot
    cost $F_i$, and shelf space $s_i$, selects which SKUs to retain ($z_i = 1$) vs. delist
    ($z_i = 0$). When SKU $i$ is delisted, a fraction $t_{ij}$ of its demand transfers to retained
    substitute SKUs $j$ based on the multi-modal similarity matrix $\\mathbf{S}_{ij}$, while the
    remaining fraction $w_i^{\\text{walk}} = 1 - \\sum_{j \\text{ kept}} t_{ij}$ walks away from the
    category (`lost_walk_units`).
    """
    preds, eff_hist = _prepare_forecast_frame(
        predictions_df,
        history_df=history_df,
        oof_df=oof_df,
        model_type=model_type,
        reconciliation_method=reconciliation_method,
        prefer_reconciled=prefer_reconciled,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        horizon=horizon,
        freq=freq,
    )
    if preds.empty:
        return AssortmentOptimizationResult(
            assortment_df=pd.DataFrame(columns=ASSORTMENT_OPTIMIZER_COLUMNS),
            transference_df=pd.DataFrame(columns=ASSORTMENT_TRANSFERENCE_COLUMNS),
            status="optimal",
            is_feasible=True,
            total_candidate_skus=0,
            retained_skus=0,
            delisted_skus=0,
            baseline_category_units=0.0,
            post_assortment_units=0.0,
            transferred_units=0.0,
            lost_walk_units=0.0,
            category_retention_pct=1.0,
            mean_walk_rate=0.0,
            baseline_net_profit=0.0,
            optimal_net_profit=0.0,
            net_profit_lift=0.0,
            shelf_space_used=0.0,
        )

    ts_ids = sorted(preds["ts_id"].astype(str).unique().tolist())
    n_skus = len(ts_ids)
    sku_to_idx = {ts: idx for idx, ts in enumerate(ts_ids)}
    ref_df = eff_hist if (eff_hist is not None and not eff_hist.empty) else preds

    demand_series = preds.groupby("ts_id")["yhat"].sum()
    base_demand = {ts: float(max(0.0, demand_series.get(ts, 0.0))) for ts in ts_ids}
    price_map = _resolve_sku_param(base_price, ts_ids, 20.0, df=ref_df, ts_id_col="ts_id")
    cost_map = _resolve_sku_param(unit_cost, ts_ids, 10.0, df=ref_df, ts_id_col="ts_id")
    slot_map = _resolve_sku_param(fixed_slot_cost, ts_ids, 0.0, df=ref_df, ts_id_col="ts_id")
    space_map = _resolve_sku_param(shelf_space, ts_ids, 1.0, df=ref_df, ts_id_col="ts_id")
    for ts in ts_ids:
        price_map[ts] = max(0.01, price_map[ts])
        cost_map[ts] = max(0.0, min(cost_map[ts], price_map[ts] * 0.98))
        space_map[ts] = max(1e-6, space_map[ts])

    pair_sim = _build_pairwise_similarity_map(
        ts_ids,
        similarity_df=similarity_df,
        history_df=eff_hist,
        preds_df=preds,
        similarity_method=similarity_method,
        text_cols=text_cols,
        attribute_cols=attribute_cols,
        covariate_cols=covariate_cols,
        hierarchy_cols=hierarchy_cols,
    )

    # Integrate Double-ML cross-SKU cannibalization (gamma < 0) and positive Halo lift (gamma > 0)
    # when `elasticity_df` is supplied.
    halo_units_map: dict[str, float] = dict.fromkeys(ts_ids, 0.0)
    if elasticity_df is not None and not elasticity_df.empty and "ts_id" in elasticity_df.columns:
        ts_set = set(ts_ids)
        for _, erow in elasticity_df.iterrows():
            ts_e = str(erow["ts_id"])
            if ts_e not in ts_set:
                continue
            # Positive complementary Halo units driven by SKU `ts_e` across the category.
            for h_col in ("total_halo_units", "halo_lift", "halo_units"):
                if h_col in erow.index and pd.notna(erow[h_col]):
                    val_h = float(erow[h_col])
                    if np.isfinite(val_h) and val_h > 0.0:
                        halo_units_map[ts_e] = max(halo_units_map[ts_e], val_h)
            # Substitute cannibalization target boosts transference similarity when delisted.
            for c_col in ("top_cannibalized_ts_id", "substitute_ts_id"):
                if c_col in erow.index and pd.notna(erow[c_col]):
                    peer_c = str(erow[c_col])
                    if peer_c in ts_set and peer_c != ts_e:
                        boosted = min(1.0, pair_sim.get((ts_e, peer_c), 0.35) + 0.20)
                        pair_sim[(ts_e, peer_c)] = max(pair_sim.get((ts_e, peer_c), 0.0), boosted)
                        pair_sim[(peer_c, ts_e)] = max(pair_sim.get((peer_c, ts_e), 0.0), boosted)

    # Resolve intrinsic walk_rate and candidate substitute transference edges.
    explicit_walk: dict[str, float] | None = None
    if walk_rate is not None:
        explicit_walk = _resolve_sku_param(walk_rate, ts_ids, 0.30, df=ref_df, ts_id_col="ts_id")

    ret_scale = float(np.clip(retention_scale, 0.0, 1.0))
    w_lo = float(np.clip(min_walk_rate, 0.0, 1.0))
    w_hi = float(np.clip(max_walk_rate, w_lo, 1.0))
    sim_floor = float(np.clip(min_similarity, 0.0, 1.0))
    top_k = max(1, int(top_k_substitutes))

    walk_map: dict[str, float] = {}
    max_sim_map: dict[str, float] = {}
    primary_sub_map: dict[str, str] = {}
    # Directed edges: (i_idx, j_idx, similarity, transfer_share_t_ij)
    edges: list[tuple[int, int, float, float]] = []

    for i_idx, ts_i in enumerate(ts_ids):
        peers = [
            (ts_j, pair_sim.get((ts_i, ts_j), 0.0))
            for ts_j in ts_ids
            if ts_j != ts_i and pair_sim.get((ts_i, ts_j), 0.0) >= sim_floor
        ]
        peers.sort(key=lambda item: (-item[1], item[0]))
        top_peers = peers[:top_k]
        max_s = float(top_peers[0][1]) if top_peers else 0.0
        max_sim_map[ts_i] = max_s
        primary_sub_map[ts_i] = str(top_peers[0][0]) if top_peers else ""

        if explicit_walk is not None and ts_i in explicit_walk:
            w_i = float(np.clip(explicit_walk[ts_i], 0.0, 1.0))
        elif not top_peers:
            w_i = 1.0
        else:
            w_i = float(np.clip(1.0 - ret_scale * max_s, w_lo, w_hi))
        walk_map[ts_i] = w_i

        transfer_budget = max(0.0, 1.0 - w_i)
        if top_peers and transfer_budget > 0.0:
            weights = np.array([max(s, 1e-6) ** 1.5 for _, s in top_peers], dtype=float)
            w_sum = float(np.sum(weights))
            for (ts_j, s_val), w_raw in zip(top_peers, weights, strict=True):
                t_ij = float(transfer_budget * (w_raw / max(w_sum, 1e-9)))
                edges.append((i_idx, sku_to_idx[ts_j], float(s_val), t_ij))

    n_edges = len(edges)
    n_vars = n_skus + n_edges  # z_0..z_{N-1} in {0,1}, y_0..y_{E-1} in [0,1]

    keep_set = {str(s) for s in (must_keep_skus or []) if str(s) in sku_to_idx}
    delist_set = {str(s) for s in (must_delist_skus or []) if str(s) in sku_to_idx}
    conflict_set = keep_set & delist_set

    eff_min_skus = max(0, int(min_skus)) if n_skus > 0 else 0
    eff_max_skus = int(max_skus) if max_skus is not None else n_skus
    total_base_units = float(sum(base_demand.values()))

    # Feasibility pre-checks and relaxation hints.
    is_feasible = True
    relaxation_hint: str | None = None
    if conflict_set:
        is_feasible = False
        relaxation_hint = (
            f"Conflicting must_keep_skus and must_delist_skus on {sorted(conflict_set)}."
        )
    elif eff_max_skus < len(keep_set):
        is_feasible = False
        relaxation_hint = (
            f"max_skus={eff_max_skus} is smaller than len(must_keep_skus)={len(keep_set)}. "
            f"Increase max_skus to at least {len(keep_set)}."
        )
    elif eff_min_skus > n_skus - len(delist_set):
        is_feasible = False
        relaxation_hint = (
            f"min_skus={eff_min_skus} exceeds available non-delisted SKUs "
            f"({n_skus - len(delist_set)}). Lower min_skus to <= {n_skus - len(delist_set)}."
        )
    elif eff_max_skus < eff_min_skus:
        is_feasible = False
        relaxation_hint = (
            f"max_skus={eff_max_skus} < min_skus={eff_min_skus}. Set max_skus >= {eff_min_skus}."
        )
    elif max_shelf_space is not None:
        keep_space = sum(space_map[s] for s in keep_set)
        sorted_spaces = sorted(
            space_map[s] for s in ts_ids if s not in keep_set and s not in delist_set
        )
        need_more = max(0, eff_min_skus - len(keep_set))
        min_possible_space = keep_space + sum(sorted_spaces[:need_more])
        if float(max_shelf_space) + 1e-9 < min_possible_space:
            is_feasible = False
            relaxation_hint = (
                f"max_shelf_space={float(max_shelf_space):.2f} is below the minimum required "
                f"shelf space {min_possible_space:.2f} for min_skus={eff_min_skus} and "
                f"must_keep_skus. Increase max_shelf_space to >= {min_possible_space:.2f}."
            )

    # Build MILP objective (scipy.optimize.milp minimizes c^T x).
    c_vec = np.zeros(n_vars, dtype=float)
    lb_vars = np.zeros(n_vars, dtype=float)
    ub_vars = np.ones(n_vars, dtype=float)
    integrality = np.zeros(n_vars, dtype=int)
    integrality[:n_skus] = 1  # z_i binary

    for i_idx, ts_i in enumerate(ts_ids):
        m_i = price_map[ts_i] - cost_map[ts_i]
        d_i = base_demand[ts_i]
        f_i = slot_map[ts_i]
        halo_bonus = m_i * halo_units_map.get(ts_i, 0.0)
        walk_pen = float(walk_penalty_weight) * m_i * d_i
        # Retaining SKU i yields (m_i * d_i + halo_bonus - f_i) and avoids walk_pen.
        c_vec[i_idx] = -(m_i * d_i + halo_bonus - f_i + walk_pen)
        if ts_i in keep_set:
            lb_vars[i_idx] = 1.0
            ub_vars[i_idx] = 1.0
        elif ts_i in delist_set and ts_i not in keep_set:
            lb_vars[i_idx] = 0.0
            ub_vars[i_idx] = 0.0

    for e_idx, (i_idx, j_idx, _sim, t_ij) in enumerate(edges):
        ts_i = ts_ids[i_idx]
        ts_j = ts_ids[j_idx]
        d_i = base_demand[ts_i]
        m_i = price_map[ts_i] - cost_map[ts_i]
        m_j = price_map[ts_j] - cost_map[ts_j]
        walk_saved = float(walk_penalty_weight) * m_i * d_i * t_ij
        c_vec[n_skus + e_idx] = -(m_j * d_i * t_ij + walk_saved)

    rows_a: list[np.ndarray] = []
    rows_lb: list[float] = []
    rows_ub: list[float] = []

    # 1. Edge coupling constraints:
    #    y_{i->j} + z_i <= 1  (only transfers if i is delisted)
    #    y_{i->j} - z_j <= 0  (only transfers to j if j is kept)
    for e_idx, (i_idx, j_idx, _sim, _t_ij) in enumerate(edges):
        row1 = np.zeros(n_vars, dtype=float)
        row1[i_idx] = 1.0
        row1[n_skus + e_idx] = 1.0
        rows_a.append(row1)
        rows_lb.append(-np.inf)
        rows_ub.append(1.0)

        row2 = np.zeros(n_vars, dtype=float)
        row2[j_idx] = -1.0
        row2[n_skus + e_idx] = 1.0
        rows_a.append(row2)
        rows_lb.append(-np.inf)
        rows_ub.append(0.0)

    # 2. SKU count bounds: min_skus <= sum_i z_i <= max_skus
    if is_feasible:
        row_cnt = np.zeros(n_vars, dtype=float)
        row_cnt[:n_skus] = 1.0
        rows_a.append(row_cnt)
        rows_lb.append(float(eff_min_skus))
        rows_ub.append(float(eff_max_skus))

    # 3. Shelf space cap: sum_i s_i z_i <= max_shelf_space
    if is_feasible and max_shelf_space is not None:
        row_sp = np.zeros(n_vars, dtype=float)
        for i_idx, ts_i in enumerate(ts_ids):
            row_sp[i_idx] = space_map[ts_i]
        rows_a.append(row_sp)
        rows_lb.append(-np.inf)
        rows_ub.append(float(max_shelf_space))

    # 4. Category retention floor: sum_i D_i z_i + sum_e D_i t_ij y_e >= rho_min * sum_i D_i
    if is_feasible and min_category_retention is not None and total_base_units > 0.0:
        rho = float(np.clip(min_category_retention, 0.0, 1.0))
        row_ret = np.zeros(n_vars, dtype=float)
        for i_idx, ts_i in enumerate(ts_ids):
            row_ret[i_idx] = base_demand[ts_i]
        for e_idx, (i_idx, _j_idx, _sim, t_ij) in enumerate(edges):
            row_ret[n_skus + e_idx] = base_demand[ts_ids[i_idx]] * t_ij
        rows_a.append(row_ret)
        rows_lb.append(rho * total_base_units)
        rows_ub.append(np.inf)

    z_sol = np.ones(n_skus, dtype=float)
    y_sol = np.zeros(n_edges, dtype=float)
    solver_ok = False

    if is_feasible:
        constraints = LinearConstraint(np.vstack(rows_a), rows_lb, rows_ub) if rows_a else None
        res = milp(
            c=c_vec,
            integrality=integrality,
            bounds=Bounds(lb_vars, ub_vars),
            constraints=constraints,
        )
        if res.success and res.x is not None:
            solver_ok = True
            z_sol = np.round(np.clip(res.x[:n_skus], 0.0, 1.0))
            y_sol = np.clip(res.x[n_skus:], 0.0, 1.0)
        elif min_category_retention is not None:
            is_feasible = False
            relaxation_hint = (
                f"min_category_retention={float(min_category_retention):.2f} is infeasible under "
                f"max_skus={eff_max_skus} / max_shelf_space={max_shelf_space} because delisted "
                f"SKUs incur walk_rate losses. Lower min_category_retention or increase max_skus."
            )

    if not solver_ok:
        # Deterministic greedy fallback ranking by net standalone profit per unit of shelf space.
        scores = []
        for i_idx, ts_i in enumerate(ts_ids):
            m_i = price_map[ts_i] - cost_map[ts_i]
            prof = m_i * base_demand[ts_i] - slot_map[ts_i]
            scores.append((prof / max(space_map[ts_i], 1e-6), i_idx))
        scores.sort(key=lambda item: (-item[0], item[1]))
        z_sol = np.zeros(n_skus, dtype=float)
        used_sp = 0.0
        kept_cnt = 0
        for ts_k in keep_set:
            idx_k = sku_to_idx[ts_k]
            z_sol[idx_k] = 1.0
            used_sp += space_map[ts_k]
            kept_cnt += 1
        for _sc, idx_cand in scores:
            ts_c = ts_ids[idx_cand]
            if z_sol[idx_cand] > 0.5 or ts_c in delist_set:
                continue
            if kept_cnt >= eff_max_skus:
                break
            if (
                max_shelf_space is not None
                and used_sp + space_map[ts_c] > float(max_shelf_space) + 1e-9
            ):
                continue
            if (_sc > 0.0) or (kept_cnt < eff_min_skus):
                z_sol[idx_cand] = 1.0
                used_sp += space_map[ts_c]
                kept_cnt += 1
        for e_idx, (i_idx, j_idx, _sim, _t_ij) in enumerate(edges):
            y_sol[e_idx] = 1.0 if (z_sol[i_idx] < 0.5 and z_sol[j_idx] > 0.5) else 0.0

    # Assemble transference_df and assortment_df.
    trans_out_units = dict.fromkeys(ts_ids, 0.0)
    trans_in_units = dict.fromkeys(ts_ids, 0.0)
    trans_rows: list[dict[str, Any]] = []

    for e_idx, (i_idx, j_idx, s_val, t_ij) in enumerate(edges):
        act = float(y_sol[e_idx])
        if act > 1e-6 and z_sol[i_idx] < 0.5 and z_sol[j_idx] > 0.5:
            ts_i = ts_ids[i_idx]
            ts_j = ts_ids[j_idx]
            u_flow = float(base_demand[ts_i] * t_ij * act)
            m_j = price_map[ts_j] - cost_map[ts_j]
            trans_out_units[ts_i] += u_flow
            trans_in_units[ts_j] += u_flow
            trans_rows.append(
                {
                    "delisted_ts_id": ts_i,
                    "recipient_ts_id": ts_j,
                    "similarity": float(s_val),
                    "transfer_share": float(t_ij * act),
                    "transferred_units": u_flow,
                    "transferred_margin": float(u_flow * m_j),
                }
            )

    status_str = "infeasible" if not is_feasible else ("optimal" if solver_ok else "feasible")
    assort_rows: list[dict[str, Any]] = []
    base_net_profit = 0.0
    opt_net_profit = 0.0
    total_post_units = 0.0
    total_lost_walk = 0.0
    total_space_used = 0.0

    for i_idx, ts_i in enumerate(ts_ids):
        kept = bool(z_sol[i_idx] >= 0.5)
        d_i = base_demand[ts_i]
        p_i = price_map[ts_i]
        c_i = cost_map[ts_i]
        m_i = p_i - c_i
        f_i = slot_map[ts_i]
        sp_i = space_map[ts_i]
        w_i = walk_map[ts_i]

        t_out = 0.0 if kept else float(min(d_i, trans_out_units[ts_i]))
        t_in = float(trans_in_units[ts_i]) if kept else 0.0
        lost_u = 0.0 if kept else float(max(0.0, d_i - t_out))
        post_u = float(d_i + t_in) if kept else 0.0

        base_prof_i = float(m_i * d_i - f_i)
        post_prof_i = float(m_i * post_u - f_i) if kept else 0.0
        base_net_profit += base_prof_i
        opt_net_profit += post_prof_i
        total_post_units += post_u
        total_lost_walk += lost_u
        if kept:
            total_space_used += sp_i

        assort_rows.append(
            {
                "ts_id": ts_i,
                "action": "KEEP" if kept else "DELIST",
                "is_retained": kept,
                "baseline_units": float(d_i),
                "walk_rate": float(w_i),
                "transferable_share": float(1.0 - w_i),
                "transferred_out_units": float(t_out),
                "transferred_in_units": float(t_in),
                "lost_walk_units": float(lost_u),
                "post_assortment_units": float(post_u),
                "unit_price": float(p_i),
                "unit_cost": float(c_i),
                "unit_margin": float(m_i),
                "fixed_slot_cost": float(f_i),
                "shelf_space": float(sp_i),
                "baseline_profit": float(base_prof_i),
                "post_assortment_profit": float(post_prof_i),
                "net_profit_contribution": float(post_prof_i - base_prof_i),
                "primary_substitute_ts_id": primary_sub_map[ts_i],
                "max_peer_similarity": float(max_sim_map[ts_i]),
                "status": status_str,
            }
        )

    assort_df = pd.DataFrame(assort_rows, columns=ASSORTMENT_OPTIMIZER_COLUMNS)
    trans_df = pd.DataFrame(trans_rows, columns=ASSORTMENT_TRANSFERENCE_COLUMNS)
    retained_cnt = int(sum(1 for r in assort_rows if r["is_retained"]))
    delisted_cnt = int(n_skus - retained_cnt)
    cat_ret_pct = float(total_post_units / total_base_units) if total_base_units > 1e-9 else 1.0
    rollup_df = _build_hierarchy_rollup_df(
        assort_df,
        source_df=ref_df,
        hierarchy_cols=hierarchy_cols,
        ts_id_col="ts_id",
    )

    return AssortmentOptimizationResult(
        assortment_df=assort_df,
        transference_df=trans_df,
        status=status_str,
        is_feasible=is_feasible,
        total_candidate_skus=n_skus,
        retained_skus=retained_cnt,
        delisted_skus=delisted_cnt,
        baseline_category_units=float(total_base_units),
        post_assortment_units=float(total_post_units),
        transferred_units=float(sum(trans_in_units.values())),
        lost_walk_units=float(total_lost_walk),
        category_retention_pct=float(np.clip(cat_ret_pct, 0.0, 1.0)),
        mean_walk_rate=float(np.mean(list(walk_map.values()))) if walk_map else 0.0,
        baseline_net_profit=float(base_net_profit),
        optimal_net_profit=float(opt_net_profit),
        net_profit_lift=float(opt_net_profit - base_net_profit),
        shelf_space_used=float(total_space_used),
        relaxation_hint=relaxation_hint,
        hierarchy_rollup_df=rollup_df,
    )

optimize_assortment_df

optimize_assortment_df(
    predictions_df, *, transference=False, **kwargs
)

Convenience wrapper around :func:optimize_assortment returning a tidy DataFrame.

Returns result.transference_df when transference=True and result.assortment_df otherwise, with the full :class:AssortmentOptimizationResult attached to df.attrs["assortment_result"].

Source code in src/scale_forecasting/clearance_optimizer.py
def optimize_assortment_df(
    predictions_df: pd.DataFrame,
    *,
    transference: bool = False,
    **kwargs: Any,
) -> pd.DataFrame:
    """Convenience wrapper around :func:`optimize_assortment` returning a tidy DataFrame.

    Returns ``result.transference_df`` when ``transference=True`` and ``result.assortment_df``
    otherwise, with the full :class:`AssortmentOptimizationResult` attached to
    ``df.attrs["assortment_result"]``.
    """
    res = optimize_assortment(predictions_df, **kwargs)
    out = res.transference_df.copy() if transference else res.assortment_df.copy()
    out.attrs["assortment_result"] = res
    out.attrs["status"] = res.status
    out.attrs["is_feasible"] = res.is_feasible
    out.attrs["relaxation_hint"] = res.relaxation_hint
    out.attrs["hierarchy_rollup_df"] = res.hierarchy_rollup_df
    return out

optimize_clearance

optimize_clearance(
    predictions_df,
    *,
    history_df=None,
    oof_df=None,
    initial_inventory=None,
    expiry_step=None,
    shelf_life_days=None,
    discount_ladder=DEFAULT_DISCOUNT_LADDER,
    monotone_markdown=True,
    allow_price_rebound=False,
    base_price=20.0,
    unit_cost=8.0,
    salvage_value=2.0,
    spoilage_cost=0.0,
    target_sell_through_pct=None,
    unit_volume=1.0,
    target_space_freed=None,
    reclaim_by_step=None,
    price_elasticity=None,
    price_col=None,
    covariate_cols=None,
    elasticity_df=None,
    use_digital_twin_elasticity=True,
    default_elasticity=-1.8,
    cannibalization_penalty=0.15,
    similarity_df=None,
    similarity_method="hybrid",
    model_type=None,
    reconciliation_method=None,
    prefer_reconciled=True,
    hierarchy_cols="auto",
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    horizon=14,
    freq="D",
    strict_feasibility=False,
)

Solve the multi-SKU lifecycle markdown, perishable expiry, and shelf-space reclamation MILP.

Formulates a Mixed-Integer Linear Program (scipy.optimize.milp / HiGHS) that selects a discount rung $d_{i,t} \in \text{discount_ladder}$ for each SKU $i$ and horizon step $t = 1 \dots H$, subject to:

  • Monotone markdown ladder: $d_{i,t} \le d_{i,t+1}$ when monotone_markdown=True and allow_price_rebound=False.
  • Finite initial inventory & expiry deadline: Cumulative sales up to expiry_step cannot exceed initial_inventory $I_{i,0}$, and demand after $T_{\text{expiry},i}$ is 0.
  • Minimum sell-through target: Optional per-SKU target_sell_through_pct $\in [0, 1]$.
  • Warehouse / shelf space reclamation: Optional portfolio capacity target $\sum_i v_i \sum_{t=1}^{T_{\text{reclaim}}} q_{i,t} \ge \text{target_space_freed}$.
Source code in src/scale_forecasting/clearance_optimizer.py
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
def optimize_clearance(
    predictions_df: pd.DataFrame,
    *,
    history_df: pd.DataFrame | None = None,
    oof_df: pd.DataFrame | None = None,
    initial_inventory: float | Mapping[str, float] | str | None = None,
    expiry_step: int | Mapping[str, int] | None = None,
    shelf_life_days: int | Mapping[str, int] | None = None,
    discount_ladder: Sequence[float] = DEFAULT_DISCOUNT_LADDER,
    monotone_markdown: bool = True,
    allow_price_rebound: bool = False,
    base_price: float | Mapping[str, float] | str = 20.0,
    unit_cost: float | Mapping[str, float] | str = 8.0,
    salvage_value: float | Mapping[str, float] | str = 2.0,
    spoilage_cost: float | Mapping[str, float] | str = 0.0,
    target_sell_through_pct: float | Mapping[str, float] | None = None,
    unit_volume: float | Mapping[str, float] | str = 1.0,
    target_space_freed: float | None = None,
    reclaim_by_step: int | None = None,
    price_elasticity: float | Mapping[str, float] | None = None,
    price_col: str | None = None,
    covariate_cols: Sequence[str] | None = None,
    elasticity_df: pd.DataFrame | None = None,
    use_digital_twin_elasticity: bool = True,
    default_elasticity: float = -1.8,
    cannibalization_penalty: float = 0.15,
    similarity_df: pd.DataFrame | None = None,
    similarity_method: str = "hybrid",
    model_type: str | None = None,
    reconciliation_method: str | None = None,
    prefer_reconciled: bool = True,
    hierarchy_cols: Sequence[str] | str | None = "auto",
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    horizon: int = 14,
    freq: str = "D",
    strict_feasibility: bool = False,
) -> ClearanceOptimizationResult:
    """Solve the multi-SKU lifecycle markdown, perishable expiry, and shelf-space reclamation MILP.

    Formulates a Mixed-Integer Linear Program (`scipy.optimize.milp` / `HiGHS`) that selects a
    discount rung $d_{i,t} \\in \\text{discount\\_ladder}$ for each SKU $i$ and horizon step
    $t = 1 \\dots H$, subject to:

    - **Monotone markdown ladder:** $d_{i,t} \\le d_{i,t+1}$ when ``monotone_markdown=True`` and
      ``allow_price_rebound=False``.
    - **Finite initial inventory & expiry deadline:** Cumulative sales up to ``expiry_step``
      cannot exceed ``initial_inventory`` $I_{i,0}$, and demand after $T_{\\text{expiry},i}$ is 0.
    - **Minimum sell-through target:** Optional per-SKU ``target_sell_through_pct`` $\\in [0, 1]$.
    - **Warehouse / shelf space reclamation:** Optional portfolio capacity target
      $\\sum_i v_i \\sum_{t=1}^{T_{\\text{reclaim}}} q_{i,t} \\ge \\text{target\\_space\\_freed}$.
    """
    fc_df, eff_hist = _prepare_forecast_frame(
        predictions_df,
        history_df=history_df,
        oof_df=oof_df,
        model_type=model_type,
        reconciliation_method=reconciliation_method,
        prefer_reconciled=prefer_reconciled,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        horizon=horizon,
        freq=freq,
    )
    if fc_df.empty:
        return ClearanceOptimizationResult(
            schedule_df=pd.DataFrame(columns=CLEARANCE_SCHEDULE_COLUMNS),
            summary_df=pd.DataFrame(columns=CLEARANCE_SUMMARY_COLUMNS),
            status="empty",
            is_feasible=True,
            total_baseline_profit=0.0,
            total_optimal_profit=0.0,
            total_profit_lift=0.0,
            total_space_freed=0.0,
            target_space_freed=target_space_freed,
            overall_sell_through_pct=0.0,
        )

    ladder = sorted({float(np.clip(d, 0.0, 0.95)) for d in discount_ladder})
    if not ladder or ladder[0] > 0.0:
        ladder = [0.0, *ladder]
    n_rungs = len(ladder)

    ts_ids = list(dict.fromkeys(fc_df["ts_id"].astype(str)))
    ref_df = eff_hist if (eff_hist is not None and not eff_hist.empty) else fc_df
    price_map = _resolve_sku_param(base_price, ts_ids, 20.0, df=ref_df, ts_id_col="ts_id")
    cost_map = _resolve_sku_param(unit_cost, ts_ids, 8.0, df=ref_df, ts_id_col="ts_id")
    salvage_map = _resolve_sku_param(salvage_value, ts_ids, 2.0, df=ref_df, ts_id_col="ts_id")
    spoil_map = _resolve_sku_param(spoilage_cost, ts_ids, 0.0, df=ref_df, ts_id_col="ts_id")
    vol_map = _resolve_sku_param(unit_volume, ts_ids, 1.0, df=ref_df, ts_id_col="ts_id")

    elast_map, source_map, peer_sim_map = _resolve_price_elasticities_and_similarity(
        ts_ids,
        history_df=eff_hist,
        price_elasticity=price_elasticity,
        price_col=price_col,
        covariate_cols=covariate_cols,
        elasticity_df=elasticity_df,
        use_digital_twin_elasticity=use_digital_twin_elasticity,
        default_elasticity=default_elasticity,
        similarity_df=similarity_df,
        similarity_method=similarity_method,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
    )

    # Group forecast horizon steps per SKU.
    sku_groups: dict[str, pd.DataFrame] = {}
    sku_horizon: dict[str, int] = {}
    default_inv_map: dict[str, float] = {}
    for ts in ts_ids:
        grp = fc_df[fc_df["ts_id"] == ts].sort_values("ds").reset_index(drop=True)
        sku_groups[ts] = grp
        sku_horizon[ts] = len(grp)
        base_sum = float(grp["yhat"].sum())
        default_inv_map[ts] = max(1.0, 0.85 * base_sum) if base_sum > 0 else 0.0

    inv_map = (
        {ts: default_inv_map[ts] for ts in ts_ids}
        if initial_inventory is None
        else _resolve_sku_param(initial_inventory, ts_ids, 100.0, df=ref_df, ts_id_col="ts_id")
    )
    for ts in ts_ids:
        inv_map[ts] = max(0.0, float(inv_map[ts]))

    raw_expiry = expiry_step if expiry_step is not None else shelf_life_days
    expiry_map: dict[str, int] = {}
    for ts in ts_ids:
        h_i = sku_horizon[ts]
        if raw_expiry is None:
            expiry_map[ts] = h_i
        elif isinstance(raw_expiry, Mapping):
            val = raw_expiry.get(ts, h_i)
            expiry_map[ts] = int(np.clip(int(val if val is not None else h_i), 1, h_i))
        else:
            expiry_map[ts] = int(np.clip(int(raw_expiry), 1, h_i))

    sell_through_map: dict[str, float] = {}
    if target_sell_through_pct is not None:
        raw_st = _resolve_sku_param(target_sell_through_pct, ts_ids, 0.0)
        for ts, st_val in raw_st.items():
            if st_val > 0.0:
                sell_through_map[ts] = float(np.clip(st_val, 0.0, 1.0))

    # Precompute demand table d_hat[ts][t, k] and check feasibility of sell-through & space targets.
    d_hat: dict[str, np.ndarray] = {}
    max_sellable_by_expiry: dict[str, float] = {}
    max_sellable_by_reclaim: dict[str, float] = {}

    for ts in ts_ids:
        grp = sku_groups[ts]
        h_i = sku_horizon[ts]
        exp_i = expiry_map[ts]
        rec_i = min(h_i, int(reclaim_by_step)) if reclaim_by_step is not None else h_i
        elast_i = elast_map[ts]
        mat = np.zeros((h_i, n_rungs), dtype=float)
        for t_idx in range(h_i):
            if t_idx + 1 <= exp_i:
                base_u = float(grp["yhat"].iloc[t_idx])
                for k_idx, disc in enumerate(ladder):
                    mat[t_idx, k_idx] = _demand_at_discount(base_u, disc, elast_i)
        d_hat[ts] = mat
        max_dem_exp = float(mat[:exp_i, -1].sum())
        max_dem_rec = float(mat[: min(exp_i, rec_i), -1].sum())
        max_sellable_by_expiry[ts] = min(inv_map[ts], max_dem_exp)
        max_sellable_by_reclaim[ts] = min(inv_map[ts], max_dem_rec)

    relaxation_notes: list[str] = []
    eff_sell_through_units: dict[str, float] = {}
    for ts, st_pct in sell_through_map.items():
        req_u = st_pct * inv_map[ts]
        max_u = max_sellable_by_expiry[ts]
        if req_u > max_u + 1e-6:
            max_pct = (max_u / inv_map[ts]) if inv_map[ts] > 0 else 0.0
            relaxation_notes.append(
                f"Infeasible target_sell_through_pct={st_pct:.1%} for '{ts}': maximum achievable "
                f"sell-through by expiry_step={expiry_map[ts]} at max discount "
                f"{ladder[-1]:.0%} is {max_pct:.1%} ({max_u:.2f} / {inv_map[ts]:.2f} units)."
            )
            eff_sell_through_units[ts] = max(0.0, 0.9999 * max_u)
        else:
            eff_sell_through_units[ts] = req_u

    max_possible_space = sum(max(0.0, vol_map[ts]) * max_sellable_by_reclaim[ts] for ts in ts_ids)
    eff_target_space: float | None = None
    if target_space_freed is not None and float(target_space_freed) > 0.0:
        req_space = float(target_space_freed)
        if req_space > max_possible_space + 1e-6:
            rec_label = reclaim_by_step if reclaim_by_step is not None else "horizon end"
            relaxation_notes.append(
                f"Infeasible target_space_freed={req_space:.2f}: maximum achievable space freed "
                f"by step {rec_label} at max discount {ladder[-1]:.0%} is "
                f"{max_possible_space:.2f} (capped by initial_inventory and demand elasticity). "
                f"Lower target_space_freed to <= {max_possible_space:.2f}, extend reclaim_by_step, "
                f"or add a deeper discount rung."
            )
            eff_target_space = max(0.0, 0.9999 * max_possible_space)
        else:
            eff_target_space = req_space

    if relaxation_notes and strict_feasibility:
        raise ValueError(" ".join(relaxation_notes))

    # Build MILP:
    # For each (ts, t, k), we have:
    # - binary rung choice z_{ts, t, k} in {0, 1}
    # - continuous realized sales s_{ts, t, k} in [0, d_hat[ts][t, k]]
    idx_z: dict[tuple[str, int, int], int] = {}
    idx_s: dict[tuple[str, int, int], int] = {}
    var_count = 0
    for ts in ts_ids:
        for t_idx in range(sku_horizon[ts]):
            for k_idx in range(n_rungs):
                idx_z[(ts, t_idx, k_idx)] = var_count
                var_count += 1
                idx_s[(ts, t_idx, k_idx)] = var_count
                var_count += 1

    c_obj = np.zeros(var_count, dtype=float)
    integrality = np.zeros(var_count, dtype=float)
    lb_vec = np.zeros(var_count, dtype=float)
    ub_vec = np.ones(var_count, dtype=float)

    enforce_monotone = bool(monotone_markdown) and not bool(allow_price_rebound)
    cannib_weight = max(0.0, float(cannibalization_penalty))

    for ts in ts_ids:
        p0 = price_map[ts]
        c_i = cost_map[ts]
        v_term = salvage_map[ts] - spoil_map[ts]
        base_unit_margin = max(0.0, p0 - c_i)
        sim_i = peer_sim_map[ts]
        exp_i = expiry_map[ts]
        h_i = sku_horizon[ts]
        for t_idx in range(h_i):
            fifo_bonus = 1e-4 * float(h_i - t_idx) / float(max(h_i, 1))
            for k_idx, disc in enumerate(ladder):
                z_col = idx_z[(ts, t_idx, k_idx)]
                s_col = idx_s[(ts, t_idx, k_idx)]
                integrality[z_col] = 1.0
                ub_vec[z_col] = 1.0
                dem_tk = float(d_hat[ts][t_idx, k_idx])
                ub_vec[s_col] = dem_tk

                if t_idx + 1 > exp_i:
                    # Expired steps have zero sales; lock discount to terminal rung or 0.
                    ub_vec[s_col] = 0.0
                    c_obj[z_col] = 1e-5 * disc
                    continue

                p_disc = p0 * (1.0 - disc)
                # Marginal profit of selling 1 unit at rung k vs. leaving it unsold at expiry:
                net_unit_gain = (p_disc - c_i) - v_term
                base_u = float(sku_groups[ts]["yhat"].iloc[t_idx])
                cannib_tk = cannib_weight * sim_i * disc * base_unit_margin * base_u
                # Small markdown signaling penalty prevents redundant markdowns after stockout.
                z_penalty = cannib_tk + 1e-3 * disc * max(p0, 1.0) * max(base_u, 1.0)
                # Negate for minimization in scipy.optimize.milp:
                c_obj[s_col] = -(net_unit_gain + fifo_bonus)
                c_obj[z_col] = z_penalty

    rows_a: list[np.ndarray] = []
    rows_lb: list[float] = []
    rows_ub: list[float] = []

    def _add_constraint(coeffs: dict[int, float], lower: float, upper: float) -> None:
        row = np.zeros(var_count, dtype=float)
        for col_i, val in coeffs.items():
            if val != 0.0:
                row[col_i] = val
        rows_a.append(row)
        rows_lb.append(lower)
        rows_ub.append(upper)

    for ts in ts_ids:
        h_i = sku_horizon[ts]
        exp_i = expiry_map[ts]
        # 1. Exactly one discount rung chosen per (ts, t), and s_{ts, t, k} <= d_hat * z_{ts, t, k}.
        for t_idx in range(h_i):
            _add_constraint(
                {idx_z[(ts, t_idx, k_idx)]: 1.0 for k_idx in range(n_rungs)},
                1.0,
                1.0,
            )
            for k_idx in range(n_rungs):
                dem_tk = float(d_hat[ts][t_idx, k_idx])
                if dem_tk > 0.0:
                    _add_constraint(
                        {
                            idx_s[(ts, t_idx, k_idx)]: 1.0,
                            idx_z[(ts, t_idx, k_idx)]: -dem_tk,
                        },
                        -np.inf,
                        0.0,
                    )

        # 2. Monotone non-decreasing markdown ladder across horizon steps:
        # sum_{m >= k} z_{t, m} - sum_{m >= k} z_{t+1, m} <= 0 for all k >= 1.
        if enforce_monotone and h_i >= 2:
            for t_idx in range(h_i - 1):
                for k_idx in range(1, n_rungs):
                    coeffs: dict[int, float] = {}
                    for m_idx in range(k_idx, n_rungs):
                        coeffs[idx_z[(ts, t_idx, m_idx)]] = 1.0
                        coeffs[idx_z[(ts, t_idx + 1, m_idx)]] = -1.0
                    _add_constraint(coeffs, -np.inf, 0.0)

        # 3. Finite initial inventory cap and optional minimum sell-through target:
        inv_coeffs = {
            idx_s[(ts, t_idx, k_idx)]: 1.0 for t_idx in range(exp_i) for k_idx in range(n_rungs)
        }
        min_st_u = eff_sell_through_units.get(ts, 0.0)
        _add_constraint(inv_coeffs, min_st_u, inv_map[ts])

    # 4. Portfolio warehouse / shelf space reclamation constraint by reclaim_by_step:
    if eff_target_space is not None and eff_target_space > 0.0:
        space_coeffs: dict[int, float] = {}
        for ts in ts_ids:
            v_i = max(0.0, vol_map[ts])
            if v_i <= 0.0:
                continue
            exp_i = expiry_map[ts]
            h_i = sku_horizon[ts]
            rec_i = min(exp_i, int(reclaim_by_step)) if reclaim_by_step is not None else exp_i
            rec_i = min(rec_i, h_i)
            for t_idx in range(rec_i):
                for k_idx in range(n_rungs):
                    space_coeffs[idx_s[(ts, t_idx, k_idx)]] = v_i
        if space_coeffs:
            _add_constraint(space_coeffs, eff_target_space, np.inf)

    a_mat = np.vstack(rows_a) if rows_a else np.zeros((0, var_count), dtype=float)
    constraints = (
        LinearConstraint(a_mat, np.array(rows_lb, dtype=float), np.array(rows_ub, dtype=float))
        if rows_a
        else None
    )
    bounds = Bounds(lb_vec, ub_vec)
    res = milp(
        c=c_obj,
        integrality=integrality,
        bounds=bounds,
        constraints=constraints,
    )

    sol_x = res.x if (res.success and res.x is not None) else np.zeros(var_count, dtype=float)
    solver_ok = bool(res.success and res.x is not None)

    # Extract chosen discount rungs and roll forward exact chronological inventory depletion.
    schedule_rows: list[dict[str, Any]] = []
    summary_rows: list[dict[str, Any]] = []
    total_base_profit = 0.0
    total_opt_profit = 0.0
    total_space_by_reclaim = 0.0
    total_initial_inv = 0.0
    total_opt_sold = 0.0

    for ts in ts_ids:
        grp = sku_groups[ts]
        h_i = sku_horizon[ts]
        exp_i = expiry_map[ts]
        rec_i = min(h_i, int(reclaim_by_step)) if reclaim_by_step is not None else h_i
        p0 = price_map[ts]
        c_i = cost_map[ts]
        salv_i = salvage_map[ts]
        spoil_i = spoil_map[ts]
        v_i = max(0.0, vol_map[ts])
        inv_0 = inv_map[ts]
        elast_i = elast_map[ts]
        src_i = source_map[ts]
        sim_i = peer_sim_map[ts]
        base_unit_margin = max(0.0, p0 - c_i)

        rem_base_inv = inv_0
        rem_opt_inv = inv_0
        cum_opt_units = 0.0
        cum_space_freed = 0.0
        space_freed_by_reclaim_i = 0.0
        base_sold_total = 0.0
        base_margin_total = 0.0
        opt_margin_total = 0.0
        cannib_total = 0.0
        chosen_discounts: list[float] = []
        first_md_step: int | None = None

        for t_idx in range(h_i):
            step_num = t_idx + 1
            ds_val = grp["ds"].iloc[t_idx]
            base_dem = float(grp["yhat"].iloc[t_idx])
            is_expired = step_num > exp_i

            if solver_ok:
                z_vals = [float(sol_x[idx_z[(ts, t_idx, k_idx)]]) for k_idx in range(n_rungs)]
                best_k = int(np.argmax(z_vals))
            else:
                best_k = 0
            if enforce_monotone and chosen_discounts:
                prev_d = chosen_discounts[-1]
                if ladder[best_k] < prev_d - 1e-9:
                    best_k = next(
                        (k_idx for k_idx, d in enumerate(ladder) if d >= prev_d - 1e-9),
                        n_rungs - 1,
                    )
            disc = float(ladder[best_k])
            chosen_discounts.append(disc)
            if disc > 0.0 and first_md_step is None and not is_expired:
                first_md_step = step_num

            opt_price = p0 * (1.0 - disc)
            if is_expired:
                base_u_step = 0.0
                opt_u_step = 0.0
                cannib_step = 0.0
            else:
                base_u_step = min(base_dem, rem_base_inv)
                rem_base_inv = max(0.0, rem_base_inv - base_u_step)
                dem_opt = float(d_hat[ts][t_idx, best_k])
                opt_u_step = min(dem_opt, rem_opt_inv)
                rem_opt_inv = max(0.0, rem_opt_inv - opt_u_step)
                cannib_step = (
                    cannib_weight * sim_i * disc * base_unit_margin * base_dem
                    if opt_u_step > 0.0
                    else 0.0
                )

            cum_opt_units += opt_u_step
            space_step = v_i * opt_u_step
            cum_space_freed += space_step
            if step_num <= rec_i:
                space_freed_by_reclaim_i += space_step

            base_rev = p0 * base_u_step
            opt_rev = opt_price * opt_u_step
            base_m = (p0 - c_i) * base_u_step
            opt_m = (opt_price - c_i) * opt_u_step
            net_contrib = opt_m - cannib_step

            base_sold_total += base_u_step
            base_margin_total += base_m
            opt_margin_total += opt_m
            cannib_total += cannib_step

            schedule_rows.append(
                {
                    "ts_id": ts,
                    "ds": ds_val,
                    "horizon_step": step_num,
                    "baseline_price": float(p0),
                    "optimal_discount_pct": float(disc),
                    "optimal_price": float(opt_price),
                    "baseline_units": float(base_u_step),
                    "expected_units": float(opt_u_step),
                    "incremental_units": float(opt_u_step - base_u_step),
                    "cumulative_units": float(cum_opt_units),
                    "remaining_inventory": float(rem_opt_inv),
                    "unit_cost": float(c_i),
                    "salvage_value": float(salv_i),
                    "unit_volume": float(v_i),
                    "space_freed_step": float(space_step),
                    "cumulative_space_freed": float(cum_space_freed),
                    "baseline_revenue": float(base_rev),
                    "optimal_revenue": float(opt_rev),
                    "baseline_margin": float(base_m),
                    "optimal_margin": float(opt_m),
                    "cannibalization_loss": float(cannib_step),
                    "net_profit_contribution": float(net_contrib),
                    "is_expired_step": bool(is_expired),
                    "price_elasticity": float(elast_i),
                    "elasticity_source": src_i,
                }
            )

        unsold_base = max(0.0, inv_0 - base_sold_total)
        unsold_opt = max(0.0, inv_0 - cum_opt_units)
        salv_rec_opt = unsold_opt * salv_i
        spoil_cost_opt = unsold_opt * spoil_i
        base_net_profit = base_margin_total + unsold_base * (salv_i - spoil_i)
        opt_net_profit = opt_margin_total - cannib_total + salv_rec_opt - spoil_cost_opt
        st_pct_achieved = (cum_opt_units / inv_0) if inv_0 > 0 else 1.0

        sku_status = "infeasible" if relaxation_notes else ("optimal" if solver_ok else "feasible")
        summary_rows.append(
            {
                "ts_id": ts,
                "initial_inventory": float(inv_0),
                "expiry_step": int(exp_i),
                "baseline_sell_through_units": float(base_sold_total),
                "optimal_sell_through_units": float(cum_opt_units),
                "sell_through_pct": float(st_pct_achieved),
                "unsold_terminal_units": float(unsold_opt),
                "salvage_recovery": float(salv_rec_opt),
                "spoilage_cost_incurred": float(spoil_cost_opt),
                "total_space_freed": float(space_freed_by_reclaim_i),
                "max_discount_pct": float(max(chosen_discounts) if chosen_discounts else 0.0),
                "first_markdown_step": int(first_md_step) if first_md_step is not None else 0,
                "baseline_gross_profit": float(base_net_profit),
                "optimal_gross_profit": float(opt_net_profit),
                "net_profit_lift": float(opt_net_profit - base_net_profit),
                "price_elasticity": float(elast_i),
                "elasticity_source": src_i,
                "status": sku_status,
            }
        )

        total_base_profit += base_net_profit
        total_opt_profit += opt_net_profit
        total_space_by_reclaim += space_freed_by_reclaim_i
        total_initial_inv += inv_0
        total_opt_sold += cum_opt_units

    is_feasible = len(relaxation_notes) == 0 and solver_ok
    overall_status = "infeasible" if not is_feasible else "optimal"
    overall_st = (total_opt_sold / total_initial_inv) if total_initial_inv > 0 else 1.0
    hint_str = " ".join(relaxation_notes) if relaxation_notes else None
    summary_df_out = pd.DataFrame(summary_rows, columns=CLEARANCE_SUMMARY_COLUMNS)
    rollup_df = _build_hierarchy_rollup_df(
        summary_df_out,
        source_df=ref_df,
        hierarchy_cols=hierarchy_cols,
        ts_id_col="ts_id",
    )

    return ClearanceOptimizationResult(
        schedule_df=pd.DataFrame(schedule_rows, columns=CLEARANCE_SCHEDULE_COLUMNS),
        summary_df=summary_df_out,
        status=overall_status,
        is_feasible=is_feasible,
        total_baseline_profit=float(total_base_profit),
        total_optimal_profit=float(total_opt_profit),
        total_profit_lift=float(total_opt_profit - total_base_profit),
        total_space_freed=float(total_space_by_reclaim),
        target_space_freed=float(target_space_freed) if target_space_freed is not None else None,
        overall_sell_through_pct=float(overall_st),
        relaxation_hint=hint_str,
        hierarchy_rollup_df=rollup_df,
    )

optimize_clearance_df

optimize_clearance_df(
    predictions_df, *, summary=False, **kwargs
)

Convenience wrapper around :func:optimize_clearance returning a tidy DataFrame.

Returns result.summary_df when summary=True and result.schedule_df otherwise, with solver metadata attached to df.attrs["clearance_result"].

Source code in src/scale_forecasting/clearance_optimizer.py
def optimize_clearance_df(
    predictions_df: pd.DataFrame,
    *,
    summary: bool = False,
    **kwargs: Any,
) -> pd.DataFrame:
    """Convenience wrapper around :func:`optimize_clearance` returning a tidy DataFrame.

    Returns ``result.summary_df`` when ``summary=True`` and ``result.schedule_df`` otherwise, with
    solver metadata attached to ``df.attrs["clearance_result"]``.
    """
    res = optimize_clearance(predictions_df, **kwargs)
    out = res.summary_df.copy() if summary else res.schedule_df.copy()
    out.attrs["clearance_result"] = res
    out.attrs["status"] = res.status
    out.attrs["is_feasible"] = res.is_feasible
    out.attrs["relaxation_hint"] = res.relaxation_hint
    out.attrs["hierarchy_rollup_df"] = res.hierarchy_rollup_df
    return out

optimize_contract_volume

optimize_contract_volume(
    predictions_df,
    *,
    history_df=None,
    oof_df=None,
    trajectories_df=None,
    contract_tiers=None,
    min_contract_volume=None,
    shortfall_penalty_per_unit=5.0,
    discount_ladder=(0.0, 0.05, 0.1, 0.15, 0.25),
    max_discount_pct=None,
    base_price=20.0,
    unit_cost=8.0,
    initial_inventory=None,
    price_elasticity=None,
    price_col=None,
    covariate_cols=None,
    elasticity_df=None,
    use_digital_twin_elasticity=True,
    default_elasticity=-1.8,
    risk_aversion_lambda=0.0,
    cvar_alpha=0.95,
    similarity_df=None,
    similarity_method="hybrid",
    model_type=None,
    reconciliation_method=None,
    prefer_reconciled=True,
    hierarchy_cols="auto",
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    horizon=14,
    freq="D",
)

Solve multi-SKU vendor contract volume, tiered rebate, and Take-or-Pay commitment MILP.

Allocates promotional discounts across a portfolio of SKUs (or energy Take-or-Pay / Cloud FinOps commitment lines) to maximize total gross profit plus unlocked all-units vendor rebates $R_m$ minus Take-or-Pay volume shortfall penalties and Copula $\text{CVaR}_{\alpha}$ tail shortfall risk.

Source code in src/scale_forecasting/clearance_optimizer.py
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
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
def optimize_contract_volume(
    predictions_df: pd.DataFrame,
    *,
    history_df: pd.DataFrame | None = None,
    oof_df: pd.DataFrame | None = None,
    trajectories_df: pd.DataFrame | None = None,
    contract_tiers: Sequence[tuple[float, float]] | Mapping[float, float] | None = None,
    min_contract_volume: float | None = None,
    shortfall_penalty_per_unit: float = 5.0,
    discount_ladder: Sequence[float] = (0.0, 0.05, 0.10, 0.15, 0.25),
    max_discount_pct: float | None = None,
    base_price: float | Mapping[str, float] | str = 20.0,
    unit_cost: float | Mapping[str, float] | str = 8.0,
    initial_inventory: float | Mapping[str, float] | None = None,
    price_elasticity: float | Mapping[str, float] | None = None,
    price_col: str | None = None,
    covariate_cols: Sequence[str] | None = None,
    elasticity_df: pd.DataFrame | None = None,
    use_digital_twin_elasticity: bool = True,
    default_elasticity: float = -1.8,
    risk_aversion_lambda: float = 0.0,
    cvar_alpha: float = 0.95,
    similarity_df: pd.DataFrame | None = None,
    similarity_method: str = "hybrid",
    model_type: str | None = None,
    reconciliation_method: str | None = None,
    prefer_reconciled: bool = True,
    hierarchy_cols: Sequence[str] | str | None = "auto",
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    horizon: int = 14,
    freq: str = "D",
) -> ContractVolumeOptimizationResult:
    """Solve multi-SKU vendor contract volume, tiered rebate, and Take-or-Pay commitment MILP.

    Allocates promotional discounts across a portfolio of SKUs (or energy Take-or-Pay / Cloud
    FinOps commitment lines) to maximize total gross profit plus unlocked all-units vendor rebates
    $R_m$ minus Take-or-Pay volume shortfall penalties and Copula $\\text{CVaR}_{\\alpha}$ tail
    shortfall risk.
    """
    fc_df, eff_hist = _prepare_forecast_frame(
        predictions_df,
        history_df=history_df,
        oof_df=oof_df,
        model_type=model_type,
        reconciliation_method=reconciliation_method,
        prefer_reconciled=prefer_reconciled,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        horizon=horizon,
        freq=freq,
    )
    if fc_df.empty:
        return ContractVolumeOptimizationResult(
            schedule_df=pd.DataFrame(columns=CONTRACT_VOLUME_COLUMNS),
            summary_df=pd.DataFrame(columns=CONTRACT_VOLUME_SUMMARY_COLUMNS),
            status="empty",
            is_feasible=True,
            baseline_portfolio_units=0.0,
            optimal_portfolio_units=0.0,
            target_contract_units=0.0,
            achieved_tier_units=0.0,
            rebate_earned=0.0,
            shortfall_units=0.0,
            shortfall_penalty=0.0,
            cvar_shortfall_units=0.0,
            baseline_net_value=0.0,
            optimal_net_value=0.0,
            net_value_lift=0.0,
        )

    ladder = sorted({float(np.clip(d, 0.0, 0.90)) for d in discount_ladder})
    if max_discount_pct is not None:
        ladder = [d for d in ladder if d <= float(max_discount_pct) + 1e-9]
    if not ladder or ladder[0] > 0.0:
        ladder = [0.0, *ladder]
    n_rungs = len(ladder)

    ts_ids = list(dict.fromkeys(fc_df["ts_id"].astype(str)))
    ref_df = eff_hist if (eff_hist is not None and not eff_hist.empty) else fc_df
    price_map = _resolve_sku_param(base_price, ts_ids, 20.0, df=ref_df, ts_id_col="ts_id")
    cost_map = _resolve_sku_param(unit_cost, ts_ids, 8.0, df=ref_df, ts_id_col="ts_id")
    inv_map = (
        None
        if initial_inventory is None
        else _resolve_sku_param(initial_inventory, ts_ids, 1e9, df=ref_df, ts_id_col="ts_id")
    )

    elast_map, source_map, _ = _resolve_price_elasticities_and_similarity(
        ts_ids,
        history_df=eff_hist,
        price_elasticity=price_elasticity,
        price_col=price_col,
        covariate_cols=covariate_cols,
        elasticity_df=elasticity_df,
        use_digital_twin_elasticity=use_digital_twin_elasticity,
        default_elasticity=default_elasticity,
        similarity_df=similarity_df,
        similarity_method=similarity_method,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
    )

    sku_groups: dict[str, pd.DataFrame] = {}
    d_hat: dict[str, np.ndarray] = {}
    base_portfolio_units = 0.0
    max_portfolio_units = 0.0

    for ts in ts_ids:
        grp = fc_df[fc_df["ts_id"] == ts].sort_values("ds").reset_index(drop=True)
        sku_groups[ts] = grp
        h_i = len(grp)
        mat = np.zeros((h_i, n_rungs), dtype=float)
        for t_idx in range(h_i):
            base_u = float(grp["yhat"].iloc[t_idx])
            for k_idx, disc in enumerate(ladder):
                mat[t_idx, k_idx] = _demand_at_discount(base_u, disc, elast_map[ts])
        if inv_map is not None and inv_map[ts] < float(mat[:, -1].sum()):
            scale = float(inv_map[ts]) / max(float(mat[:, -1].sum()), 1e-9)
            mat = mat * min(1.0, scale)
        d_hat[ts] = mat
        base_portfolio_units += float(mat[:, 0].sum())
        max_portfolio_units += float(mat[:, -1].sum())

    # Normalize contract_tiers into sorted list of (target_units, rebate_usd).
    tiers: list[tuple[float, float]] = []
    if contract_tiers is not None:
        raw_items = (
            list(contract_tiers.items())
            if isinstance(contract_tiers, Mapping)
            else list(contract_tiers)
        )
        for q_t, reb in raw_items:
            if float(q_t) > 0.0 and float(reb) >= 0.0:
                tiers.append((float(q_t), float(reb)))
        tiers.sort(key=lambda item: item[0])
    elif min_contract_volume is None:
        # Default 2-tier vendor rebate ladder at +10% and +20% above baseline volume.
        avg_margin = float(np.mean([max(1.0, price_map[ts] - cost_map[ts]) for ts in ts_ids]))
        tiers = [
            (
                round(1.10 * base_portfolio_units, 2),
                round(0.08 * base_portfolio_units * avg_margin, 2),
            ),
            (
                round(1.22 * base_portfolio_units, 2),
                round(0.18 * base_portfolio_units * avg_margin, 2),
            ),
        ]

    n_tiers = len(tiers)
    q_min = float(min_contract_volume) if min_contract_volume is not None else 0.0
    penalty_rate = max(0.0, float(shortfall_penalty_per_unit))

    # Estimate stochastic Copula / ACI / Conformal / OOF CVaR downside buffer.
    cvar_downside_frac = _estimate_cvar_downside_fraction(
        fc_df=fc_df,
        trajectories_df=trajectories_df,
        oof_df=oof_df,
        cvar_alpha=cvar_alpha,
        risk_aversion_lambda=risk_aversion_lambda,
    )

    risk_lam = max(0.0, float(risk_aversion_lambda))
    eff_q_min = q_min * (1.0 + risk_lam * cvar_downside_frac)

    relaxation_hint: str | None = None
    is_feasible = True
    if q_min > max_portfolio_units + 1e-6:
        is_feasible = False
        relaxation_hint = (
            f"min_contract_volume={q_min:.2f} exceeds maximum achievable portfolio demand "
            f"{max_portfolio_units:.2f} at max discount {ladder[-1]:.0%}; minimum unavoidable "
            f"shortfall is {q_min - max_portfolio_units:.2f} units."
        )

    # Build MILP variables:
    # - binary z_{ts, t, k} in {0, 1} for discount selection
    # - binary u_m in {0, 1} for contract tier m achievement
    # - continuous shortfall xi >= 0 for Take-or-Pay commitment
    idx_z: dict[tuple[str, int, int], int] = {}
    var_count = 0
    for ts in ts_ids:
        for t_idx in range(len(sku_groups[ts])):
            for k_idx in range(n_rungs):
                idx_z[(ts, t_idx, k_idx)] = var_count
                var_count += 1
    idx_u: list[int] = []
    for _ in range(n_tiers):
        idx_u.append(var_count)
        var_count += 1
    idx_xi = var_count
    var_count += 1

    c_obj = np.zeros(var_count, dtype=float)
    integrality = np.zeros(var_count, dtype=float)
    lb_vec = np.zeros(var_count, dtype=float)
    ub_vec = np.ones(var_count, dtype=float)

    for ts in ts_ids:
        p0 = price_map[ts]
        c_i = cost_map[ts]
        for t_idx in range(len(sku_groups[ts])):
            for k_idx, disc in enumerate(ladder):
                col = idx_z[(ts, t_idx, k_idx)]
                integrality[col] = 1.0
                dem_tk = float(d_hat[ts][t_idx, k_idx])
                margin_tk = (p0 * (1.0 - disc) - c_i) * dem_tk
                # Negate for minimization:
                c_obj[col] = -margin_tk + 1e-4 * disc

    for m_idx, (_, reb_val) in enumerate(tiers):
        u_col = idx_u[m_idx]
        integrality[u_col] = 1.0
        c_obj[u_col] = -float(reb_val)

    integrality[idx_xi] = 0.0
    ub_vec[idx_xi] = max(eff_q_min, max_portfolio_units, 1.0) * 2.0
    c_obj[idx_xi] = penalty_rate

    rows_a: list[np.ndarray] = []
    rows_lb: list[float] = []
    rows_ub: list[float] = []

    def _add_row(coeffs: dict[int, float], lower: float, upper: float) -> None:
        row = np.zeros(var_count, dtype=float)
        for c_i, val in coeffs.items():
            if val != 0.0:
                row[c_i] = val
        rows_a.append(row)
        rows_lb.append(lower)
        rows_ub.append(upper)

    # 1. One discount rung per (ts, t).
    for ts in ts_ids:
        for t_idx in range(len(sku_groups[ts])):
            _add_row(
                {idx_z[(ts, t_idx, k_idx)]: 1.0 for k_idx in range(n_rungs)},
                1.0,
                1.0,
            )

    # 2. At most one rebate tier selected, and portfolio units >= sum_m tau_m * u_m.
    if n_tiers > 0:
        _add_row(dict.fromkeys(idx_u, 1.0), -np.inf, 1.0)
        tier_link: dict[int, float] = {
            idx_z[(ts, t_idx, k_idx)]: float(d_hat[ts][t_idx, k_idx])
            for ts in ts_ids
            for t_idx in range(len(sku_groups[ts]))
            for k_idx in range(n_rungs)
        }
        for m_idx, (tau_m, _) in enumerate(tiers):
            tier_link[idx_u[m_idx]] = -float(tau_m)
        _add_row(tier_link, 0.0, np.inf)

    # 3. Take-or-Pay minimum volume constraint: portfolio_units + xi >= eff_q_min.
    if eff_q_min > 0.0:
        top_link: dict[int, float] = {
            idx_z[(ts, t_idx, k_idx)]: float(d_hat[ts][t_idx, k_idx])
            for ts in ts_ids
            for t_idx in range(len(sku_groups[ts]))
            for k_idx in range(n_rungs)
        }
        top_link[idx_xi] = 1.0
        _add_row(top_link, eff_q_min, np.inf)

    a_mat = np.vstack(rows_a) if rows_a else np.zeros((0, var_count), dtype=float)
    constraints = (
        LinearConstraint(a_mat, np.array(rows_lb, dtype=float), np.array(rows_ub, dtype=float))
        if rows_a
        else None
    )
    res = milp(
        c=c_obj,
        integrality=integrality,
        bounds=Bounds(lb_vec, ub_vec),
        constraints=constraints,
    )
    sol_x = res.x if (res.success and res.x is not None) else np.zeros(var_count, dtype=float)
    solver_ok = bool(res.success and res.x is not None)

    schedule_rows: list[dict[str, Any]] = []
    sku_stats: dict[str, dict[str, Any]] = {}
    opt_portfolio_units = 0.0
    base_margin_tot = 0.0
    opt_margin_tot = 0.0

    for ts in ts_ids:
        grp = sku_groups[ts]
        p0 = price_map[ts]
        c_i = cost_map[ts]
        base_u_i = 0.0
        opt_u_i = 0.0
        base_m_i = 0.0
        opt_m_i = 0.0
        discs_i: list[float] = []

        for t_idx in range(len(grp)):
            if solver_ok:
                z_vals = [float(sol_x[idx_z[(ts, t_idx, k_idx)]]) for k_idx in range(n_rungs)]
                best_k = int(np.argmax(z_vals))
            else:
                best_k = 0
            disc = float(ladder[best_k])
            discs_i.append(disc)
            opt_p = p0 * (1.0 - disc)
            b_u = float(d_hat[ts][t_idx, 0])
            o_u = float(d_hat[ts][t_idx, best_k])
            b_m = (p0 - c_i) * b_u
            o_m = (opt_p - c_i) * o_u

            base_u_i += b_u
            opt_u_i += o_u
            base_m_i += b_m
            opt_m_i += o_m
            opt_portfolio_units += o_u

            schedule_rows.append(
                {
                    "ts_id": ts,
                    "ds": grp["ds"].iloc[t_idx],
                    "horizon_step": t_idx + 1,
                    "baseline_price": float(p0),
                    "optimal_discount_pct": float(disc),
                    "optimal_price": float(opt_p),
                    "baseline_units": float(b_u),
                    "expected_units": float(o_u),
                    "incremental_units": float(o_u - b_u),
                    "cumulative_portfolio_units": float(opt_portfolio_units),
                    "unit_cost": float(c_i),
                    "baseline_margin": float(b_m),
                    "optimal_margin": float(o_m),
                }
            )

        base_margin_tot += base_m_i
        opt_margin_tot += opt_m_i
        sku_stats[ts] = {
            "baseline_units": base_u_i,
            "optimal_units": opt_u_i,
            "mean_discount_pct": float(np.mean(discs_i)) if discs_i else 0.0,
            "max_discount_pct": float(np.max(discs_i)) if discs_i else 0.0,
            "baseline_margin": base_m_i,
            "optimal_margin": opt_m_i,
        }

    # Evaluate earned rebate & shortfall on both baseline and optimal volume.
    base_rebate = 0.0
    achieved_tier_u = 0.0
    opt_rebate = 0.0
    for tau_m, reb_m in tiers:
        if base_portfolio_units + 1e-6 >= tau_m:
            base_rebate = max(base_rebate, reb_m)
        if opt_portfolio_units + 1e-6 >= tau_m and reb_m >= opt_rebate:
            opt_rebate = reb_m
            achieved_tier_u = tau_m

    base_shortfall = max(0.0, q_min - base_portfolio_units)
    opt_shortfall = max(0.0, q_min - opt_portfolio_units)
    base_penalty = base_shortfall * penalty_rate
    opt_penalty = opt_shortfall * penalty_rate
    cvar_shortfall = max(0.0, q_min - opt_portfolio_units * (1.0 - cvar_downside_frac))

    base_net_val = base_margin_tot + base_rebate - base_penalty
    opt_net_val = opt_margin_tot + opt_rebate - opt_penalty

    summary_rows: list[dict[str, Any]] = []
    for ts in ts_ids:
        st = sku_stats[ts]
        share = (
            st["optimal_units"] / opt_portfolio_units
            if opt_portfolio_units > 0
            else 1.0 / max(len(ts_ids), 1)
        )
        reb_alloc = opt_rebate * share
        pen_alloc = opt_penalty * share
        summary_rows.append(
            {
                "ts_id": ts,
                "baseline_units": float(st["baseline_units"]),
                "optimal_units": float(st["optimal_units"]),
                "incremental_units": float(st["optimal_units"] - st["baseline_units"]),
                "mean_discount_pct": float(st["mean_discount_pct"]),
                "max_discount_pct": float(st["max_discount_pct"]),
                "baseline_margin": float(st["baseline_margin"]),
                "optimal_margin": float(st["optimal_margin"]),
                "rebate_allocated": float(reb_alloc),
                "shortfall_penalty_allocated": float(pen_alloc),
                "net_contract_value": float(st["optimal_margin"] + reb_alloc - pen_alloc),
                "price_elasticity": float(elast_map[ts]),
                "elasticity_source": source_map[ts],
            }
        )

    target_u = max([q_min, *[t[0] for t in tiers]], default=0.0)
    status_str = "infeasible" if not is_feasible else ("optimal" if solver_ok else "feasible")
    summary_df_out = pd.DataFrame(summary_rows, columns=CONTRACT_VOLUME_SUMMARY_COLUMNS)
    rollup_df = _build_hierarchy_rollup_df(
        summary_df_out,
        source_df=ref_df,
        hierarchy_cols=hierarchy_cols,
        ts_id_col="ts_id",
    )

    return ContractVolumeOptimizationResult(
        schedule_df=pd.DataFrame(schedule_rows, columns=CONTRACT_VOLUME_COLUMNS),
        summary_df=summary_df_out,
        status=status_str,
        is_feasible=is_feasible,
        baseline_portfolio_units=float(base_portfolio_units),
        optimal_portfolio_units=float(opt_portfolio_units),
        target_contract_units=float(target_u),
        achieved_tier_units=float(achieved_tier_u),
        rebate_earned=float(opt_rebate),
        shortfall_units=float(opt_shortfall),
        shortfall_penalty=float(opt_penalty),
        cvar_shortfall_units=float(cvar_shortfall),
        baseline_net_value=float(base_net_val),
        optimal_net_value=float(opt_net_val),
        net_value_lift=float(opt_net_val - base_net_val),
        relaxation_hint=relaxation_hint,
        hierarchy_rollup_df=rollup_df,
    )

optimize_contract_volume_df

optimize_contract_volume_df(
    predictions_df, *, summary=False, **kwargs
)

Convenience wrapper around :func:optimize_contract_volume returning a tidy DataFrame.

Returns result.summary_df when summary=True and result.schedule_df otherwise, with the full :class:ContractVolumeOptimizationResult attached to df.attrs["contract_result"].

Source code in src/scale_forecasting/clearance_optimizer.py
def optimize_contract_volume_df(
    predictions_df: pd.DataFrame,
    *,
    summary: bool = False,
    **kwargs: Any,
) -> pd.DataFrame:
    """Convenience wrapper around :func:`optimize_contract_volume` returning a tidy DataFrame.

    Returns ``result.summary_df`` when ``summary=True`` and ``result.schedule_df`` otherwise, with
    the full :class:`ContractVolumeOptimizationResult` attached to ``df.attrs["contract_result"]``.
    """
    res = optimize_contract_volume(predictions_df, **kwargs)
    out = res.summary_df.copy() if summary else res.schedule_df.copy()
    out.attrs["contract_result"] = res
    out.attrs["status"] = res.status
    out.attrs["is_feasible"] = res.is_feasible
    out.attrs["relaxation_hint"] = res.relaxation_hint
    out.attrs["hierarchy_rollup_df"] = res.hierarchy_rollup_df
    return out

plot_clearance_schedule

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

Plot the optimal markdown discount ladder, inventory depletion trajectory, and profit/space summary for a clearance optimization run.

Source code in src/scale_forecasting/clearance_optimizer.py
def plot_clearance_schedule(
    result_or_df: ClearanceOptimizationResult | pd.DataFrame,
    *,
    ts_id: str | None = None,
    ax: Any = None,
    title: str | None = None,
) -> Any:
    """Plot the optimal markdown discount ladder, inventory depletion trajectory, and profit/space
    summary for a clearance optimization run.
    """
    import matplotlib.pyplot as plt

    if isinstance(result_or_df, ClearanceOptimizationResult):
        sched_df = result_or_df.schedule_df
        sum_df = result_or_df.summary_df
    elif isinstance(result_or_df, pd.DataFrame):
        stored = result_or_df.attrs.get("clearance_result")
        if isinstance(stored, ClearanceOptimizationResult):
            sched_df = stored.schedule_df
            sum_df = stored.summary_df
        elif "horizon_step" in result_or_df.columns:
            sched_df = result_or_df
            sum_df = pd.DataFrame()
        else:
            sched_df = pd.DataFrame()
            sum_df = result_or_df
    else:
        raise TypeError("result_or_df must be a ClearanceOptimizationResult or pandas DataFrame.")

    if ax is None:
        _, axes = plt.subplots(1, 2, figsize=(12, 4.4))
        ax_left, ax_right = axes[0], axes[1]
    elif isinstance(ax, Sequence) and len(ax) >= 2:
        ax_left, ax_right = ax[0], ax[1]
    else:
        ax_left = ax
        ax_right = None

    if not sched_df.empty:
        chosen_ts = (
            str(ts_id)
            if ts_id is not None and str(ts_id) in set(sched_df["ts_id"].astype(str))
            else str(sched_df["ts_id"].astype(str).iloc[0])
        )
        sub = sched_df[sched_df["ts_id"].astype(str) == chosen_ts].sort_values("horizon_step")
        steps = sub["horizon_step"].to_numpy(dtype=float)
        disc_pct = sub["optimal_discount_pct"].to_numpy(dtype=float) * 100.0
        rem_inv = sub["remaining_inventory"].to_numpy(dtype=float)

        ax_left.step(
            steps,
            disc_pct,
            where="post",
            color="#d93025",
            linewidth=2.2,
            label="Markdown Discount (%)",
        )
        ax_left.set_xlabel("Horizon Step")
        ax_left.set_ylabel("Markdown Discount (%)", color="#d93025")
        ax_left.set_ylim(bottom=-2.0, top=max(55.0, float(np.max(disc_pct)) + 8.0))
        ax_left.grid(True, linestyle="--", alpha=0.35)

        ax_inv = ax_left.twinx()
        ax_inv.plot(
            steps,
            rem_inv,
            color="#1a73e8",
            marker="o",
            markersize=4,
            linewidth=1.8,
            label="Remaining Inventory (units)",
        )
        ax_inv.set_ylabel("Remaining Inventory (units)", color="#1a73e8")
        if "is_expired_step" in sub.columns and sub["is_expired_step"].any():
            first_exp = int(sub.loc[sub["is_expired_step"], "horizon_step"].min())
            ax_left.axvline(
                first_exp - 0.5,
                color="#5f6368",
                linestyle=":",
                linewidth=1.5,
                label="Expiry Deadline",
            )
        ax_left.set_title(title or f"Clearance Ladder & Inventory Depletion ({chosen_ts})")

    if ax_right is not None and not sum_df.empty:
        skus = sum_df["ts_id"].astype(str).tolist()
        x = np.arange(len(skus))
        width = 0.36
        ax_right.bar(
            x - width / 2,
            sum_df["baseline_gross_profit"].to_numpy(dtype=float),
            width=width,
            color="#9aa0a6",
            label="Baseline Profit (0% Markdown)",
        )
        ax_right.bar(
            x + width / 2,
            sum_df["optimal_gross_profit"].to_numpy(dtype=float),
            width=width,
            color="#1e8e3e",
            label="Optimal Clearance Profit",
        )
        ax_right.set_xticks(x)
        ax_right.set_xticklabels(skus, rotation=20, ha="right")
        ax_right.set_ylabel("Net Profit ($)")
        ax_right.set_title("Baseline vs. Optimal Clearance Profit by SKU")
        ax_right.legend(loc="best", frameon=False)
        ax_right.grid(True, axis="y", linestyle="--", alpha=0.35)

    return ax_left