Files
leleka/scripts/e2e/evidence/test_component_class.py
Pavlo RatushnyiandClaude Sonnet 5.5 8d33052ab2 STRA-313: component classifier (AC10 classes, A/A validity, SUSPECTED/CONFIRMED, AC5 alternative verdict)
component_class.py classifies COMPONENT cells with the statistics imported from series_eval.py
(one evaluator) and gives the AC5(b) Pocock-look verdict; test_component_class.py adds 43 tests.
The 27 ComponentClassGolden vectors of STRA-310 pass unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 21:37:12 +01:00

407 lines
20 KiB
Python

"""Tests of component_class.py (STRA-313, S0.10b): the acceptance commands AC2-AC6 of the leaf, the sign convention, screening (n < 30),
the A/A and confirmation paths, the AC5(b) looks and malformed input. The golden cases (test_series_eval_golden.ComponentClassGolden,
STRA-310) are NOT edited here and not repeated.
Run: python -m unittest scripts.e2e.evidence.test_series_eval_golden scripts.e2e.evidence.test_component_class -v (from the repository root)
Stdlib only, Python >= 3.9. Expected values are published t values (t(0.975,29) = 2.04523), closed forms of the alternating test series and
hand arithmetic; none comes from component_class.py or series_eval.py.
Test series: l_i = m + (-1)^i d over n = 30 values has the mean m exactly, a negative lag-1 autocorrelation (so n_eff = n and the degrees of
freedom are n - 1 = 29), sd = d sqrt(30/29), standard error d / sqrt(29) and so the 95 percent CI m +- 2.04523 d / sqrt(29).
"""
import json
import math
import os
import re
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
COMPONENT_CLASS = os.path.join(HERE, "component_class.py")
T29 = 2.04523 # t(0.975, 29), published table
T29_POCOCK = 2.56 # t(0.9921, 29) to about 1 percent (interpolation of the published 0.99 / 0.995 rows); used with a 10 percent margin only
LN099 = math.log(0.99)
LN101 = math.log(1.01)
def alternating(m, d, n=30):
return [m + (d if i % 2 == 0 else -d) for i in range(n)]
def half_width(d, n=30):
return T29 * d / math.sqrt(n - 1)
def d_for_half_width(h, n=30):
return h * math.sqrt(n - 1) / T29
def ci_series(lo, hi, n=30):
"""l values whose 95 percent CI is [lo, hi]."""
return alternating((lo + hi) / 2.0, d_for_half_width((hi - lo) / 2.0, n), n)
def make_cell(ls, kind="time", cell_id="t", aa_ours=None, aa_vanilla=None, prior=None):
if kind == "time":
pairs = [{"v": 100.0 * math.exp(l), "o": 100.0} for l in ls] # l = ln(v / o)
else:
pairs = [{"v": 100.0, "o": 100.0 * math.exp(l)} for l in ls] # l = ln(o / v)
return {"cell_id": cell_id, "kind": kind, "pairs": pairs,
"aa": {"ours": aa_ours if aa_ours is not None else alternating(0.0, 0.01),
"vanilla": aa_vanilla if aa_vanilla is not None else alternating(0.0, 0.01)},
"prior": prior}
AA_BAD = alternating(0.02, 0.005) # mean +2 percent, CI about [1.9, 2.1] percent: excludes 0
class Tool(unittest.TestCase):
def run_tool(self, args):
return subprocess.run([sys.executable, COMPONENT_CLASS] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True, cwd=REPO, timeout=120)
def write(self, tmp, name, doc):
path = os.path.join(tmp, name)
with open(path, "w", encoding="utf-8") as handle:
if isinstance(doc, str):
handle.write(doc)
else:
json.dump(doc, handle)
return path
def cell(self, cell, confirm=None, expect_exit=0):
with tempfile.TemporaryDirectory() as tmp:
args = ["cell", self.write(tmp, "cell.json", cell)]
if confirm is not None:
args += ["--confirm", self.write(tmp, "confirm.json", confirm)]
proc = self.run_tool(args)
self.assertEqual(proc.returncode, expect_exit, "stdout %r stderr %r" % (proc.stdout[:300], proc.stderr[:300]))
return json.loads(proc.stdout) if expect_exit == 0 else proc
def ac5(self, alt, expect_exit=0):
with tempfile.TemporaryDirectory() as tmp:
proc = self.run_tool(["ac5", self.write(tmp, "alt.json", alt)])
self.assertEqual(proc.returncode, expect_exit, "stdout %r stderr %r" % (proc.stdout[:300], proc.stderr[:300]))
return json.loads(proc.stdout) if expect_exit == 0 else proc
def alt_of(ls, n_reg=30, cell_id="a"):
return {"cell_id": cell_id, "N": n_reg, "pairs": [{"d": 70.0 * math.exp(l), "a": 70.0} for l in ls]} # l = ln(d / a)
class ClassBoundaries(Tool):
def test_ci_minus_2_percent_to_zero_is_inconclusive_not_equal(self):
# AC2: CI [-2%, 0] -> INCONCLUSIVE with owner_list false. An upper bound of exactly 0 cannot be built from data with a 5-digit t
# table value (the error of 1e-9 exceeds the evaluator's EPS), so the bound is put just above 0; the exact-0 case is golden cell_exact_zero_equal
for hi in (1e-6, 1e-4):
out = self.cell(make_cell(ci_series(math.log(0.98), hi)))
self.assertEqual(out["class"], "INCONCLUSIVE", hi)
self.assertFalse(out["owner_list"])
self.assertFalse(out["suspected"])
self.assertAlmostEqual(out["ci_lo"], math.log(0.98), places=7)
self.assertAlmostEqual(out["ci_hi"], hi, places=7)
def test_ci_minus_half_to_plus_eight_tenths_is_equal(self):
out = self.cell(make_cell(ci_series(math.log(0.995), math.log(1.008))))
self.assertEqual(out["class"], "EQUAL")
self.assertFalse(out["owner_list"]) # mean > 0
self.assertEqual(out["n"], 30)
self.assertAlmostEqual(out["ci_level"], 0.95)
def test_ci_minus_3_to_minus_1_tenths_is_slower(self):
out = self.cell(make_cell(ci_series(math.log(0.997), math.log(0.999))))
self.assertEqual(out["class"], "SLOWER")
self.assertTrue(out["suspected"])
self.assertEqual(out["action"], "OK")
def test_bounds_inside_and_outside_the_equivalence_interval(self):
inside = self.cell(make_cell(ci_series(LN099 + 1e-6, LN101 - 1e-6)))
self.assertEqual(inside["class"], "EQUAL")
low_out = self.cell(make_cell(ci_series(LN099 - 1e-4, LN101 - 1e-3)))
self.assertEqual(low_out["class"], "INCONCLUSIVE")
high_out = self.cell(make_cell(ci_series(LN099 + 1e-3, LN101 + 1e-4)))
self.assertEqual(high_out["class"], "INCONCLUSIVE")
def test_faster_when_the_lower_bound_is_positive(self):
out = self.cell(make_cell(ci_series(0.001, 0.021)))
self.assertEqual(out["class"], "FASTER")
self.assertFalse(out["suspected"])
self.assertAlmostEqual(out["half_width"], 0.01, places=6)
def test_ci_matches_the_closed_form(self):
out = self.cell(make_cell(alternating(-0.02, 0.01)))
h = half_width(0.01)
self.assertAlmostEqual(out["mean_l"], -0.02, places=12)
self.assertAlmostEqual(out["ci_lo"], -0.02 - h, places=5)
self.assertAlmostEqual(out["ci_hi"], -0.02 + h, places=5)
self.assertAlmostEqual(out["n_eff"], 30.0, places=9)
def test_equal_with_negative_mean_is_listed_for_the_owner(self):
out = self.cell(make_cell(ci_series(math.log(0.993), math.log(1.003))))
self.assertEqual(out["class"], "EQUAL")
self.assertTrue(out["owner_list"])
def test_exact_zero_cell_is_equal_and_not_listed(self):
out = self.cell(make_cell([0.0] * 30))
self.assertEqual((out["class"], out["owner_list"], out["suspected"]), ("EQUAL", False, False))
def test_positive_autocorrelation_widens_the_interval(self):
# a slowly drifting series has r1 > 0: n_eff < n and the CI is wider than for the same mean and sd without the correction
ls = [0.002 * (i - 14.5) / 14.5 + 0.001 for i in range(30)]
out = self.cell(make_cell(ls))
self.assertGreater(out["r1"], 0.5)
self.assertLess(out["n_eff"], 30.0)
mean = sum(ls) / 30
sd = math.sqrt(sum((x - mean) ** 2 for x in ls) / 29)
self.assertGreater(out["half_width"], T29 * sd / math.sqrt(30))
class SignConvention(Tool):
def test_time_cell_ours_lower_is_faster(self):
ls = alternating(0.02, 0.01)
self.assertEqual(self.cell(make_cell(ls, "time"))["class"], "FASTER")
self.assertAlmostEqual(self.cell(make_cell(ls, "time"))["mean_l"], 0.02, places=12)
def test_rate_cell_ours_higher_is_faster(self):
out = self.cell(make_cell(alternating(0.02, 0.01), "rate"))
self.assertEqual(out["class"], "FASTER")
self.assertAlmostEqual(out["mean_l"], 0.02, places=12)
def test_rate_cell_ours_lower_is_slower(self):
out = self.cell(make_cell(alternating(-0.02, 0.005), "rate"))
self.assertEqual(out["class"], "SLOWER")
def test_pair_values_are_mapped_by_kind(self):
# one pair set read as time and as rate gives opposite signs
pairs = [{"v": 110.0 + (i % 2), "o": 100.0} for i in range(30)]
base = make_cell([0.0] * 30)
time_cell = dict(base, kind="time", pairs=pairs)
rate_cell = dict(base, kind="rate", pairs=pairs)
self.assertGreater(self.cell(time_cell)["mean_l"], 0.0)
self.assertLess(self.cell(rate_cell)["mean_l"], 0.0)
self.assertAlmostEqual(self.cell(time_cell)["mean_l"], -self.cell(rate_cell)["mean_l"], places=12)
class Screening(Tool):
def test_fewer_than_30_pairs_never_gets_a_class(self):
faster = self.cell(make_cell(alternating(0.05, 0.005, 12)))
self.assertEqual(faster["class"], "INCONCLUSIVE")
self.assertTrue(faster["screening"])
self.assertEqual(faster["screening_class"], "FASTER")
self.assertEqual(faster["n"], 12)
slower = self.cell(make_cell(alternating(-0.05, 0.005, 12)))
self.assertEqual(slower["class"], "INCONCLUSIVE")
self.assertFalse(slower["suspected"])
self.assertEqual(slower["screening_class"], "SLOWER")
equal = self.cell(make_cell(alternating(0.0, 0.001, 29)))
self.assertEqual((equal["class"], equal["screening_class"], equal["owner_list"]), ("INCONCLUSIVE", "EQUAL", False))
def test_30_pairs_are_classified(self):
self.assertFalse(self.cell(make_cell(alternating(0.05, 0.005, 30)))["screening"])
class AAControl(Tool):
def test_invalid_ours_aa_is_rerun_once(self):
out = self.cell(make_cell(alternating(0.02, 0.01), aa_ours=AA_BAD))
self.assertFalse(out["aa_valid"])
self.assertEqual(out["action"], "RERUN_ONCE")
self.assertEqual(out["class"], "INCONCLUSIVE") # RULE_AA_INVALID_CLASS of schema_component.json
self.assertEqual(out["screening_class"], "FASTER")
self.assertFalse(out["suspected"])
self.assertFalse(out["aa"]["ours"]["contains_zero"])
self.assertTrue(out["aa"]["vanilla"]["contains_zero"])
def test_invalid_vanilla_aa_is_rerun_once(self):
out = self.cell(make_cell(alternating(0.02, 0.01), aa_vanilla=alternating(-0.02, 0.005)))
self.assertEqual((out["aa_valid"], out["action"]), (False, "RERUN_ONCE"))
def test_second_consecutive_failure_goes_to_the_owner(self):
out = self.cell(make_cell(alternating(0.02, 0.01), aa_ours=AA_BAD, prior={"aa_failed_once": True}))
self.assertEqual((out["aa_valid"], out["action"], out["class"]), (False, "OWNER", "INCONCLUSIVE"))
def test_valid_rerun_is_ok_and_classified(self):
out = self.cell(make_cell(alternating(0.02, 0.01), prior={"aa_failed_once": True}))
self.assertEqual((out["aa_valid"], out["action"], out["class"]), (True, "OK", "FASTER"))
def test_invalid_aa_cell_is_not_equal_and_not_listed(self):
out = self.cell(make_cell(ci_series(math.log(0.993), math.log(1.003)), aa_vanilla=AA_BAD))
self.assertEqual((out["class"], out["owner_list"]), ("INCONCLUSIVE", False))
def test_aa_with_a_single_value_is_malformed(self):
cell = make_cell(alternating(0.0, 0.01))
cell["aa"]["ours"] = [0.0]
self.assertEqual(self.cell(cell, expect_exit=3).stdout, "")
class Confirmation(Tool):
SLOWER = alternating(-0.01, 0.004)
def test_first_slower_without_confirm_is_only_suspected(self):
out = self.cell(make_cell(self.SLOWER))
self.assertEqual((out["class"], out["suspected"], out["action"]), ("SLOWER", True, "OK"))
self.assertNotIn("confirmation", out)
def test_confirm_slower_again_is_confirmed(self):
out = self.cell(make_cell(self.SLOWER), make_cell(alternating(-0.009, 0.004), cell_id="c"))
self.assertEqual(out["class"], "CONFIRMED-SLOWER")
self.assertFalse(out["suspected"])
self.assertEqual(out["confirmation"]["class"], "SLOWER")
self.assertEqual(out["confirmation"]["n"], 30)
def test_confirm_not_slower_is_not_confirmed(self):
out = self.cell(make_cell(self.SLOWER), make_cell(alternating(0.0, 0.004), cell_id="c"))
self.assertEqual(out["class"], "NOT-CONFIRMED")
self.assertEqual(out["confirmation"]["class"], "EQUAL")
self.assertEqual(out["action"], "OK")
def test_confirm_with_fewer_than_30_pairs_is_malformed(self):
proc = self.cell(make_cell(self.SLOWER), make_cell(alternating(-0.009, 0.004, 29), cell_id="c"), expect_exit=3)
self.assertIn("30", proc.stderr)
def test_confirm_kind_must_match(self):
self.cell(make_cell(self.SLOWER), make_cell(alternating(-0.009, 0.004), kind="rate", cell_id="c"), expect_exit=3)
def test_confirm_is_ignored_when_the_first_class_is_not_slower(self):
out = self.cell(make_cell(alternating(0.02, 0.01)), make_cell(alternating(-0.02, 0.004), cell_id="c"))
self.assertEqual(out["class"], "FASTER")
self.assertIn("confirm_ignored", out)
self.assertNotIn("confirmation", out)
def test_invalid_confirm_aa_confirms_nothing(self):
out = self.cell(make_cell(self.SLOWER), make_cell(alternating(-0.009, 0.004), cell_id="c", aa_ours=AA_BAD))
self.assertEqual((out["class"], out["suspected"], out["action"]), ("SLOWER", True, "RERUN_ONCE"))
self.assertTrue(out["confirm_invalid"])
again = self.cell(make_cell(self.SLOWER),
make_cell(alternating(-0.009, 0.004), cell_id="c", aa_ours=AA_BAD, prior={"aa_failed_once": True}))
self.assertEqual(again["action"], "OWNER")
def test_prior_suspected_is_echoed_and_changes_nothing(self):
out = self.cell(make_cell(self.SLOWER, prior={"suspected": True}))
self.assertEqual((out["class"], out["suspected"], out["prior_suspected"]), ("SLOWER", True, True))
eq = self.cell(make_cell([0.0] * 30, prior={"suspected": True}))
self.assertEqual((eq["class"], eq["suspected"]), ("EQUAL", False))
class AC5(Tool):
def test_slower_exit_at_look_2(self):
# block 1: m +- 0.03 (6 pairs, the Pocock bound stays above 0), block 2: m +- 0.001: at 12 pairs the bound is about -0.012
ls = alternating(-0.03, 0.03, 6) + alternating(-0.03, 0.001, 6)
out = self.ac5(alt_of(ls))
self.assertEqual((out["verdict"], out["look"], out["n"]), ("SLOWER", 2, 12))
self.assertAlmostEqual(out["mean_l"], -0.03, places=9)
self.assertLess(out["ci_hi"], 0.0)
self.assertAlmostEqual(out["ci_level"], 1.0 - 0.0158, places=9)
def test_exit_reports_the_pairs_seen_up_to_the_first_flagged_look(self):
out = self.ac5(alt_of(alternating(-0.05, 0.01, 18)))
self.assertEqual((out["verdict"], out["look"], out["n"]), ("SLOWER", 1, 6))
def test_29_pairs_without_exit_is_screening(self):
out = self.ac5(alt_of(alternating(0.001, 0.01, 29)))
self.assertEqual((out["verdict"], out["n"]), ("SCREENING", 29))
self.assertAlmostEqual(out["ci_level"], 0.95)
self.assertNotIn("PASS", json.dumps(out))
def test_below_pocock_level_is_not_an_exit(self):
# 12 pairs with mean/se between t(0.975,11) = 2.201 and t(0.9921,11) (about 2.85): the 95 percent bound is below 0, the Pocock bound is not
d = 0.03
se = d * math.sqrt(12 / 11.0) / math.sqrt(12)
m = -2.5 * se
out = self.ac5(alt_of(alternating(m, d, 12)))
self.assertEqual((out["verdict"], out["n"]), ("SCREENING", 12))
self.assertLess(out["ci_hi"], 0.0)
def test_final_verdicts_at_30(self):
faster = self.ac5(alt_of(alternating(0.02, 0.02)))
self.assertEqual((faster["verdict"], faster["n"]), ("FASTER", 30))
tie = self.ac5(alt_of(alternating(0.001, 0.01)))
self.assertEqual(tie["verdict"], "TIE")
inconclusive = self.ac5(alt_of(alternating(0.01, 0.04)))
self.assertEqual(inconclusive["verdict"], "INCONCLUSIVE")
for out in (faster, tie, inconclusive):
self.assertAlmostEqual(out["ci_level"], 0.95)
self.assertIsNotNone(out["ci_lo"])
def test_slower_at_95_only_is_inconclusive(self):
# n = 30: the 95 percent upper bound m + 2.045 c is below 0 but the Pocock bound m + 2.56 c is not; no earlier look exits either
c = 0.01 / math.sqrt(29)
m = -2.3 * c
out = self.ac5(alt_of(alternating(m, 0.01)))
self.assertEqual(out["verdict"], "INCONCLUSIVE")
self.assertTrue(out["slower_at_95_only"])
self.assertLess(out["ci_hi"], 0.0)
def test_pairs_beyond_n_are_outside_the_schedule(self):
out = self.ac5(alt_of(alternating(0.02, 0.02, 30) + [-5.0] * 6))
self.assertEqual((out["verdict"], out["n"], out["ignored_pairs"]), ("FASTER", 30, 6))
def test_alternative_slower_means_positive_l_is_faster(self):
# l = ln(D / A): the default's value above the alternative's is a faster alternative
faster = self.ac5(alt_of(alternating(0.02, 0.02)))
self.assertGreater(faster["mean_l"], 0.0)
class Malformed(Tool):
def test_bad_inputs_exit_3(self):
good = make_cell(alternating(0.0, 0.01))
for label, mutate in (("no pairs", lambda c: c.update(pairs=[])),
("one pair", lambda c: c.update(pairs=c["pairs"][:1])),
("bad kind", lambda c: c.update(kind="speed")),
("zero value", lambda c: c["pairs"][0].update(v=0.0)),
("negative value", lambda c: c["pairs"][0].update(o=-1.0)),
("text value", lambda c: c["pairs"][0].update(v="1")),
("no cell_id", lambda c: c.pop("cell_id")),
("no aa", lambda c: c.pop("aa")),
("aa not finite", lambda c: c["aa"].update(ours=[0.0, "x"])),
("bad prior", lambda c: c.update(prior={"aa_failed_once": "yes"}))):
cell = json.loads(json.dumps(good))
mutate(cell)
proc = self.cell(cell, expect_exit=3)
self.assertIn("MALFORMED", proc.stderr, label)
self.assertEqual(proc.stdout, "", label)
def test_not_json_and_missing_file(self):
with tempfile.TemporaryDirectory() as tmp:
bad = self.write(tmp, "bad.json", "{not json")
self.assertEqual(self.run_tool(["cell", bad]).returncode, 3)
self.assertEqual(self.run_tool(["ac5", bad]).returncode, 3)
self.assertEqual(self.run_tool(["cell", os.path.join(tmp, "missing.json")]).returncode, 3)
def test_usage_errors_exit_3(self):
self.assertEqual(self.run_tool([]).returncode, 3)
self.assertEqual(self.run_tool(["frobnicate"]).returncode, 3)
def test_ac5_bad_inputs(self):
for alt in ({"cell_id": "a", "N": 30, "pairs": []},
{"cell_id": "a", "N": 7, "pairs": [{"d": 1.0, "a": 1.0}]},
{"cell_id": "a", "N": 30, "pairs": [{"d": 1.0, "a": 0.0}]},
{"N": 30, "pairs": [{"d": 1.0, "a": 1.0}]}):
self.ac5(alt, expect_exit=3)
class OneEvaluator(unittest.TestCase):
def test_no_statistics_are_defined_in_component_class(self):
with open(COMPONENT_CLASS, "r", encoding="utf-8") as handle:
text = handle.read()
self.assertIsNone(re.search(r"def t_quantile|def student", text))
self.assertIsNone(re.search(r"def (t_crit|summarize|lag1_autocorr|classify)\b", text))
self.assertRegex(text, r"(?m)^import series_eval as S")
def test_the_statistics_come_from_series_eval(self):
sys.path.insert(0, HERE)
try:
import series_eval
import component_class
finally:
sys.path.remove(HERE)
self.assertIs(component_class.S, series_eval)
self.assertAlmostEqual(series_eval.t_quantile(0.975, 29), T29, places=4)
if __name__ == "__main__":
unittest.main()