# SPDX-License-Identifier: CC0-1.0 """Exact constructed class mixtures, not observed storage populations.""" import argparse from fractions import Fraction import json from pathlib import Path def metrics(tp, fp, fn, tn): counts = (tp, fp, fn, tn) if any(type(n) is not int or n < 0 for n in counts): raise ValueError("Counts must be nonnegative integers, not booleans.") total = sum(counts) if not total: raise ValueError("A population must be nonempty.") def ratio(n, d): return Fraction(n, d) if d else None return { "prevalence": ratio(tp + fn, total), "recall": ratio(tp, tp + fn), "false_positive_rate": ratio(fp, fp + tn), "precision": ratio(tp, tp + fp), } def mixture(positives, negatives, tpr, fpr): if any(type(n) is not int or n <= 0 for n in (positives, negatives)): raise ValueError("Both class counts must be positive integers.") if any(not isinstance(r, Fraction) or not 0 <= r <= 1 for r in (tpr, fpr)): raise ValueError("Rates must be exact Fractions in [0, 1].") tp, fp = positives * tpr, negatives * fpr if tp.denominator != 1 or fp.denominator != 1: raise ValueError("This finite population requires integral counts.") return (int(tp), int(fp), positives - int(tp), negatives - int(fp)) def precision_from_rates(prevalence, tpr, fpr): if any(not isinstance(r, Fraction) or not 0 <= r <= 1 for r in (prevalence, tpr, fpr)): raise ValueError("Inputs must be exact Fractions in [0, 1].") denominator = tpr * prevalence + fpr * (1 - prevalence) return tpr * prevalence / denominator if denominator else None def results(): scenarios = [ ("balanced", 5000, 5000, Fraction(4, 5), Fraction(1, 10)), ("rare_same_conditionals", 100, 9900, Fraction(4, 5), Fraction(1, 10)), ("rare_changed_healthy_conditional", 100, 9900, Fraction(4, 5), Fraction(1, 5)), ] rows = [] for name, positives, negatives, tpr, fpr in scenarios: counts = mixture(positives, negatives, tpr, fpr) rates = metrics(*counts) rows.append({ "scenario": name, "observation_count": sum(counts), "counts": dict(zip(("tp", "fp", "fn", "tn"), counts)), "rates": {key: str(value) if value is not None else None for key, value in rates.items()}, }) return { "schema_version": 1, "scope": "Exact constructed two-class, binary-feature populations; no measured disks or fitted model.", "rule": "Alert exactly when the binary feature is high; the rule is fixed in all scenarios.", "interpretation": "The third population changes P(X=high | Y=healthy), so it violates label shift relative to the first two.", "uncertainty": "No sampling is performed; fractions describe complete constructed populations, not estimates or confidence intervals.", "rows": rows, } if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check", action="store_true") args = parser.parse_args() payload = json.dumps(results(), indent=2) + "\n" destination = Path(__file__).with_name("results.json") if args.check: if destination.read_text() != payload: raise SystemExit("results.json differs from exact generated counts") print("label-shift results verified") else: destination.write_text(payload)