"""Exact covariance arithmetic for a pooled mean, not a fleet estimator.""" from fractions import Fraction import json from math import sqrt from pathlib import Path import sys def calculate(sizes, rho): sizes = tuple(sizes) if not sizes or any(type(m) is not int or m <= 0 for m in sizes): raise ValueError("Group sizes must be nonempty positive integers") if type(rho) not in (int, Fraction): raise ValueError("Use an integer or exact Fraction for correlation") rho = Fraction(rho) if not 0 <= rho <= 1: raise ValueError("This worksheet supports correlation from zero to one") n = sum(sizes) squares = sum(m * m for m in sizes) design = 1 + rho * (Fraction(squares, n) - 1) effective = n / design return { "sizes": list(sizes), "groups": len(sizes), "observations": n, "rho": str(rho), "sum_squared_sizes": squares, "ordered_within_group_pairs": squares - n, "design_effect_exact": str(design), "variance_over_marginal_variance_exact": str(design / n), "effective_n_exact": str(effective), "design_effect": float(design), "standard_error_multiplier": sqrt(float(design)), "effective_n": float(effective), } def results(): plans = [ ("Independent reference", [100] * 10, Fraction(0)), ("Ten groups of 100", [100] * 10, Fraction(1, 100)), ("Nine groups of 20, one of 820", [20] * 9 + [820], Fraction(1, 100)), ] return { "schema_version": 1, "kind": "synthetic-exact-covariance-calculation", "estimator": "equally weighted mean of all device endpoint outcomes", "reference": "N independent observations with the same marginal variance", "assumptions": [ "Fixed positive group sizes, independent groups, equal marginal variances.", "Common within-group pair correlation rho, specified rather than estimated.", "Complete fixed-horizon binary outcomes with common marginal probability 0