"""Exact finite Bernoulli qualification calculations; no sampled device data.""" from decimal import Decimal, localcontext from fractions import Fraction from math import comb from pathlib import Path import argparse import hashlib import json def probability(value, name): if not isinstance(value, Fraction) or not 0 < value < 1: raise ValueError(f"{name} must be a Fraction strictly between zero and one") def boundary(n, p0, alpha): """Largest k whose one-sided lower-tail probability is strictly below alpha.""" if type(n) is not int or n < 1: raise ValueError("n must be a positive integer") probability(p0, "p0") probability(alpha, "alpha") a, b = p0.numerator, p0.denominator denominator = b ** n total = 0 largest = -1 for k in range(n + 1): total += comb(n, k) * a ** k * (b - a) ** (n - k) if total * alpha.denominator < alpha.numerator * denominator: largest = k else: break return largest def evaluate(p, looks, boundaries): """Absorb first crossings; integers share denominator p.denominator**n.""" probability(p, "p") if (not looks or any(type(n) is not int or n < 1 for n in looks) or list(looks) != sorted(set(looks))): raise ValueError("looks must be strictly increasing positive integers") if len(looks) != len(boundaries): raise ValueError("one boundary is required per look") if any(type(k) is not int or not -1 <= k <= n for n, k in zip(looks, boundaries)): raise ValueError("boundaries must be integers in [-1, n]") by_n = dict(zip(looks, boundaries)) a, b = p.numerator, p.denominator live = [1] stopped = 0 denominator = 1 first = [] for n in range(1, looks[-1] + 1): following = [0] * (n + 1) for k, mass in enumerate(live): following[k] += mass * (b - a) following[k + 1] += mass * a live = following stopped *= b denominator *= b if n in by_n: kmax = by_n[n] new = sum(live[:kmax + 1]) live[:kmax + 1] = [0] * (kmax + 1) stopped += new first.append((n, Fraction(new, denominator))) if sum(live) + stopped != denominator: raise ArithmeticError("probability mass was not conserved") crossing = Fraction(stopped, denominator) expected = sum((n * mass for n, mass in first), Fraction()) expected += looks[-1] * (1 - crossing) return {"crossing": crossing, "first": first, "expected_n": expected} def encode(value): with localcontext() as ctx: ctx.prec = 40 decimal = Decimal(value.numerator) / Decimal(value.denominator) return {"numerator": str(value.numerator), "denominator": str(value.denominator), "decimal": str(decimal)} def calculate(): p0 = Fraction(1, 100) alpha = Fraction(1, 20) ten = list(range(100, 1001, 100)) plans = [ ("fixed_1000", [1000], [alpha], False), ("ten_nominal_looks", ten, [alpha] * 10, False), ("ten_budgeted_looks", ten, [alpha / 10] * 10, False), ("ten_zero_only_looks", ten, [alpha] * 10, True), ] rows = [] for name, looks, budgets, zero_only in plans: limits = [boundary(n, p0, budget) for n, budget in zip(looks, budgets)] if zero_only: limits = [min(k, 0) for k in limits] result = evaluate(p0, looks, limits) rows.append({ "id": name, "looks": looks, "per_look_alpha": [encode(x) for x in budgets], "largest_qualifying_failure_count": limits, "false_qualification_probability": encode(result["crossing"]), "expected_endpoint_outcomes_examined": encode(result["expected_n"]), "first_qualification": [ {"n": n, "probability": encode(mass)} for n, mass in result["first"] ], }) return { "schema_version": 1, "kind": "exact_synthetic_probability_calculation", "null_boundary_failure_probability": encode(p0), "family_error_budget": encode(alpha), "outcome": "First failure by the same prespecified device-age horizon.", "claim": "Common endpoint failure probability is below 0.01.", "assumptions": [ "Independent, identically distributed Bernoulli endpoint outcomes.", "One completed endpoint outcome per device; no missing or censored endpoints.", "Prespecified accrual order independent of outcomes; no resets or excluded failures.", "All look sizes and per-look budgets fixed before outcomes are observed.", "Stop and qualify only when BinomialCDF(k; n, p0) < per-look alpha.", "Otherwise finish at n=1000 without qualifying.", ], "scope": [ "Probabilities evaluated at p=p0, not measured fleet failure rates or AFR.", "No simulation, seed, Monte Carlo interval, device access or performance measurement.", "Expected sample count is not calendar duration or powered test design.", "Budget allocation is a simple finite union-bound control, not an implemented confidence sequence.", ], "rows": rows, } def packet(): return {"generator_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), **calculate()} def main(): parser = argparse.ArgumentParser() parser.add_argument("--write", type=Path) parser.add_argument("--verify", type=Path) args = parser.parse_args() result = packet() if args.verify: actual = json.loads(args.verify.read_text()) if actual != result: raise SystemExit("FAIL: results differ from exact regeneration") print("PASS: all packet fields match exact regeneration") elif args.write: args.write.write_text(json.dumps(result, indent=2) + "\n") for row in result["rows"]: print(row["id"], row["false_qualification_probability"]["decimal"], row["largest_qualifying_failure_count"]) else: print(json.dumps(result, indent=2)) if __name__ == "__main__": main()