#!/usr/bin/env python3
# Source: q6-experimentation.html
import numpy as np

def cuped(y: np.ndarray, x: np.ndarray) -> np.ndarray:
    """Pooled fitted CUPED demo. Exact finite-sample unbiasedness is not promised."""
    y, x = np.asarray(y, dtype=float), np.asarray(x, dtype=float)
    if y.ndim != 1 or y.shape != x.shape or len(y) < 2:
        raise ValueError("Use matching one-dimensional arrays with at least two units")
    if not np.isfinite(y).all() or not np.isfinite(x).all():
        raise ValueError("CUPED inputs must be finite")
    if np.var(x) == 0:
        return y.copy()  # A constant covariate cannot reduce variance.
    theta = np.cov(y, x, ddof=1)[0, 1] / np.var(x, ddof=1)
    return y - theta * (x - x.mean())

rng = np.random.default_rng(0)
n = 20_000
x = rng.gamma(2.0, 5.0, size=2 * n)                 # pre-period spend
y = 0.8 * x + rng.normal(0, 6, size=2 * n)          # in-test spend
arm = np.repeat([0, 1], n)
y = y + 0.3 * arm                                   # true effect = 0.3

y_adj = cuped(y, x)
for name, v in [("raw", y), ("cuped", y_adj)]:
    diff = v[arm == 1].mean() - v[arm == 0].mean()
    se = np.sqrt(v[arm == 1].var() / n + v[arm == 0].var() / n)
    print(f"{name:6s} diff={diff:.3f} se={se:.3f}")
# raw    diff about 0.3, se about 0.082
# cuped  diff about 0.3, se about 0.060  (rho about 0.69, so var about halves)
