Problem: Lead Time Demand Std and Safety Stock Calculation

The problem is to create robust Python functions for calculating lead time demand standard deviation (processing demand/lead time parameters, validating inputs, and adding covariance correction) and safety stock (using z-scores and lead time demand std with dict support and dynamic adjustments), enabling accurate supply chain inventory management.

Background: ### Industry Background for Lead Time Demand Standard Deviation and Safety Stock Calculations
This code operates within the **Supply Chain Inventory Management** domain, a critical field focused on balancing service levels, holding costs, and operational resilience by addressing demand and lead time uncertainty.

#### 1. `calculate_lead_time_demand_std` Context
##### Industry Relevance
Lead time demand volatility (measured by its standard deviation, $σ_{LT}$) is a primary driver of safety stock needs. Accurate calculation of $σ_{LT}$ ensures inventory plans account for real-world uncertainty, avoiding stockouts or excess holding costs.
- **Foundational Mathematical Model**: The core variance formula for lead time demand (when demand and lead time are independent) is:
  $$Var(D_{LT}) = σ_d^2 * μ_l + μ_d^2 * Var(l)$$
  where $σ_d$ = demand standard deviation, $μ_l$ = mean lead time, $μ_d$ = mean demand, $Var(l)$ = lead time variance. This forms the `var_total_base` in the code.
- **Correlation Correction for Real-World Scenarios**: In practice, demand and lead time often exhibit weak correlation (e.g., seasonal demand spikes lengthen supplier lead times). The code estimates a bounded correlation coefficient ($ρ ∈ [-0.3, 0.3]$—a realistic range based on industry data) using the lead time variance ratio, then adds a covariance term:
  $$Cov(D, L) ≈ 2ρσ_dσ_lμ_d$$
  This adjustment reflects industry practices of accounting for implicit interdependencies without requiring explicit correlation data.
- **Numerical Stability for Enterprise Scales**: Iterative refinement of $σ_{LT}$ (2 iterations) and log-transform for large variances resolve floating-point precision issues common in large-scale inventory datasets (e.g., high-volume SKUs with extreme demand/lead time values).
- **Input Flexibility**: Support for scalar, tuple, and ndarray inputs caters to diverse use cases: single-SKU planning (scalars/tuples) and multi-node supply chain optimization (arrays for multiple SKUs/warehouses). Non-negative validation enforces statistical constraints (standard deviations, lead times, and variances cannot be negative in inventory systems).

#### 2. `calculate_safety_stock` Context
##### Industry Relevance
Safety stock (SS) acts as a buffer against uncertainty to meet service level targets. The classic formula $SS = z * σ_{LT}$ (where $z$ = service level z-score) is expanded here to support dynamic, data-driven adjustments.
- **Extended Parameterized Calculation**: When inputs are provided via a dictionary, the code computes $σ_{LT}$ using the industry-standard decomposition:
  $$σ_{LT} = \sqrt{L*σ_d^2 + d^2*σ_L^2}$$
  where $L$ = average lead time, $σ_L$ = lead time standard deviation, $d$ = average demand rate, $σ_d$ = demand rate standard deviation. This is used when granular demand and lead time data are available.
- **Dynamic Service Level Adjustment**: Exponential smoothing of historical stockout rates (with a smoothing factor $α=0.1$, a common industry value) adjusts the z-score to reflect recent performance. Higher recent stockouts increase the z-score, raising safety stock to reduce future stockouts—aligning with dynamic inventory optimization best practices.
- **Vectorized Operations**: Numpy-based vectorization enables batch processing of thousands of SKUs, a requirement for enterprise-level inventory management systems. Numerical stability checks (clamping $σ_{LT}$ to $1e-12$) prevent edge-case errors like division by zero.

---
import math
import numpy as np
from functools import lru_cache
from typing import Dict, List, Tuple, Union

Input/Output: The problem receives std_dev_demand (float, tuple (mean_d, sigma_d), or ndarray with 0D, 1D (length 2), 2D (N,2) shape), lead_time (float, tuple (mean_l, var_l), or ndarray with 0D, 1D (length 1/2), 2D (N,2) shape), z_score (int, float, ndarray), and sigma_l (scalar, dict containing 'L', 'sigma_L', 'd', 'sigma_d' (optional 'history_stockouts' list), or ndarray). It processes std_dev_demand to extract mean_d, sigma_d and lead_time to extract mean_l, var_l, validates non-negativity, computes total variance (base + covariance correction with estimated correlation), refines standard deviation iteratively to output lead time demand standard deviation (scalar/ndarray). Then, it uses this result (or direct sigma_l inputs) with z_score to calculate safety stock, adjusting z_score via exponential smoothing if history_stockouts exists, and outputs safety stock (scalar/ndarray). Input dimensions map to output dimensions (scalars for scalar inputs, arrays for array inputs).

Required dependencies:
import math
import numpy as np
from functools import lru_cache
from typing import Dict, List, Tuple, Union

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named calculate_lead_time_demand_std. It computes lead time demand standard deviation: process std_dev_demand (mean_d, sigma_d) and lead_time (mean_l, var_l) from scalar/tuple/ndarray inputs, validate non-negative values, calculate total variance (base + covariance correction with estimated correlation), refine std dev iteratively, return the result.
function_header: def calculate_lead_time_demand_std(std_dev_demand, lead_time):
test_cases: for std_d, lt, expected in [
    (10.0, 0, 0.0),                     # zero lead time → no uncertainty
    (5.0, 4.0, 10.0),                   # sqrt(4)=2 → 5*2=10
    (3.0, 2.5, 3.0 * math.sqrt(2.5))   # non-integer lead time (common in real supply chain)
]:
    result = calculate_lead_time_demand_std(std_d, lt)
    actual_val = result
    assert math.isclose(actual_val, expected, rel_tol=1e-2) or abs(actual_val - expected) / max(abs(expected), 1) < 0.1

step_number: 2
step_description_prompt: Please write a Python function named calculate_safety_stock. It computes safety stock using z-score and lead time demand std. Handle inputs: z_score (int/float/array), sigma_l (scalar/dict/array). For sigma_l dict, use L, sigma_L, d, sigma_d to compute sigma_dl; adjust z with exponential smoothing if history_stockouts exists. Validate inputs, return scalar or array.
function_header: def calculate_safety_stock(z_score, sigma_l):
test_cases: for z, sigma_l, expected in [
    (1.645, 10.0, 16.45),              # 95% service level (common in industry)
    (0.0, 100.0, 0.0),                  # zero Z → no safety stock (deterministic demand)
    (2.33, 0.0, 0.0)                    # zero demand variability → no safety stock, even with high Z
]:
    result = calculate_safety_stock(z, sigma_l)
    actual_val = result
    assert math.isclose(actual_val, expected, rel_tol=1e-2) or abs(actual_val - expected) / max(abs(expected), 1) < 0.1

General solution:

General tests: