# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy"]
# ///
# Copyright (c) 2026 Aayush Sharma · SPDX-License-Identifier: MIT
# https://thedataengineering.com/lab-code/LICENSE.txt
"""The multiplexing dividend, and its collapse.

16 tenants whose demand is 10 + 5·(√ρ·z + √(1−ρ)·eᵢ), with z a shared random
factor and eᵢ independent noise. The 99th percentile of the summed demand
against the sum of the 99th percentiles, for ρ from 0 to 1.
"""
import argparse, json
import numpy as np

p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--tenants", type=int, default=16, help="Tenants.")
p.add_argument("--samples", type=int, default=200_000, help="Time samples.")
p.add_argument("--rhos", default="0,0.3,0.6,1.0", help="Correlations.")
p.add_argument("--seed", type=int, default=0, help="Random seed.")
p.add_argument("--json", help="Also write the results to this JSON file.")
args = p.parse_args()

rng = np.random.default_rng(args.seed); rows = []
for rho in map(float, args.rhos.split(",")):
    z = rng.standard_normal((args.samples, 1)); e = rng.standard_normal((args.samples, args.tenants))
    d = 10 + 5 * (np.sqrt(rho) * z + np.sqrt(1 - rho) * e)
    shared = float(np.percentile(d.sum(axis=1), 99)); separate = float(sum(np.percentile(d[:, i], 99) for i in range(args.tenants)))
    rows.append({"rho": rho, "shared": shared, "separate": separate, "ratio": shared / separate})
for r in rows: print(f"rho={r['rho']:.1f}  shared={r['shared']:6.1f}  separate={r['separate']:6.1f}  ratio={r['ratio']:.2f}")

if args.json:
    with open(args.json, "w") as f:
        json.dump({"tables": {"rhos": rows}}, f)
