Files
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

299 lines
16 KiB
Python

#!/usr/bin/env python3
"""Component classifier for COMPONENT-level evidence (STRA-313, S0.10b): AC10 reading (i)-(vi) and the AC5(b) alternative verdict.
Implements the evaluation rule of STRA-245 (AC10 reading, AC5(b); BA comments 3eeb53e1, dabfd08e; ARCHITECT comment 395f0394). The statistics
are NOT implemented here: the Student-t quantile, the lag-1 / n_eff correction and the CI are the functions of series_eval.py (STRA-290,
one evaluator); the class thresholds are its strict rule (classify). This file only maps the CI to the AC10 vocabulary and holds the A/A,
SUSPECTED/CONFIRMED and Pocock-look logic. Its output class never reaches AC1-AC3 (AC9).
Stdlib only, Python >= 3.9. Offline, no GPU, no network. Writes nothing.
INTERFACE v1
component_class.py cell <cell.json> [--confirm <confirm_cell.json>]
component_class.py ac5 <alt.json>
cell.json {"cell_id": str, "kind": "time"|"rate", "pairs": [{"v": vanilla value, "o": ours value}, ...],
"aa": {"ours": [l, ...], "vanilla": [l, ...]}, "prior": null | {"suspected": bool, "aa_failed_once": bool}}
l_j = ln(v / o) for kind time (lower is better), ln(o / v) for kind rate (higher is better); positive = ours better
(log_ratio_convention positive_means_ours_better of schema_component.json, STRA-287). aa entries are natural logs of the
per-round ratios of the A/A runs (ours vs ours, vanilla vs vanilla), already converted by the caller.
stdout {"cell_id","kind","n","mean_l","ci_lo","ci_hi","half_width","ci_level","class","aa_valid","aa","action","suspected","owner_list",
"screening", ...}
class: FASTER | SLOWER | EQUAL | INCONCLUSIVE, and with --confirm CONFIRMED-SLOWER | NOT-CONFIRMED
action: OK | RERUN_ONCE | OWNER
alt.json {"cell_id": str, "N": 30, "pairs": [{"d": ours-default value, "a": ours-alternative value}, ...]} l = ln(d / a)
stdout {"cell_id","n","N","mean_l","ci_lo","ci_hi","ci_level","verdict","look","looks"}
verdict: SLOWER | FASTER | TIE | INCONCLUSIVE | SCREENING
exit 0 result produced; 3 malformed input (also a usage error and a --confirm cell with fewer than 30 pairs).
RULES
class (95 percent two-sided t-CI of the mean l, n_eff rule of E3): FASTER lo > 0; SLOWER hi < 0 (however small); EQUAL CI contains 0
and lies inside [ln 0.99, ln 1.01]; everything else INCONCLUSIVE (never EQUAL, an open finding). Bounds within series_eval.EPS
of a threshold count as ON it.
n < 30 screening (E6, RULE_SMALL_N_CLASS of schema_component.json): class INCONCLUSIVE, screening true, screening_class = what the CI
says; a screening cell never closes or opens a finding.
A/A both A/A CIs (95 percent, same function) must contain 0. Otherwise aa_valid false, class INCONCLUSIVE (RULE_AA_INVALID_CLASS),
action RERUN_ONCE, or OWNER when prior.aa_failed_once (second consecutive failure: the cell stays invalid and goes to the owner).
owner_list true for an EQUAL cell whose mean l is below 0 (EQUAL can hide a loss below 1 percent).
suspected true iff class is SLOWER (a first SLOWER; it does not block). --confirm <cell with >= 30 fresh pairs on a new schedule>: the
confirm cell is classified by the same rule; SLOWER again gives CONFIRMED-SLOWER, otherwise NOT-CONFIRMED (no finding). The
confirm is ignored (confirm_ignored) when the first class is not SLOWER. Without --confirm no CONFIRMED-SLOWER is ever reported.
prior.suspected is echoed as prior_suspected and changes nothing.
ac5 looks after each block of 6 pairs (6, 12, 18, 24, 30 up to N, N = 30 by default) on l = ln(d / a): upper CI bound below 0 at
the two-sided Pocock level 0.0158 -> SLOWER at that look (n and mean_l are those of the pairs seen up to it, ci at that level).
At N pairs without an exit: FASTER (95 percent lower bound > 0), TIE (CI contains 0, inside [ln 0.99, ln 1.01]), else
INCONCLUSIVE (also when the 95 percent upper bound is below 0 but the Pocock bound is not). Fewer than N pairs and no exit:
SCREENING (n, mean_l and the 95 percent CI are reported).
"""
import argparse
import json
import math
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
sys.path.insert(0, HERE)
import series_eval as S # noqa: E402 (STRA-290: one evaluator; t quantile, n_eff rule, CI and class thresholds are imported, not copied)
SCHEMA = "component-class-v1"
MIN_CLASSIFIED_N = 30 # schema_component.json constants.min_classified_n; AC10 (v), (vi), E6
ALPHA_AA = S.ALPHA_FINAL # the A/A CI is the same 95 percent CI
ALPHA_AC5_LOOK = 0.0158 # Pocock, five looks (AC5(b))
AC5_BLOCK = 6
AC5_DEFAULT_N = 30
STRICT = "wall_norm" # the strict rule of series_eval: PASS lo > 0, SLOWER hi < 0, TIE inside [ln 0.99, ln 1.01]
CLASS_OF_RULE = {"PASS": "FASTER", "SLOWER": "SLOWER", "TIE": "EQUAL", "INCONCLUSIVE": "INCONCLUSIVE"}
VERDICT_OF_RULE = {"PASS": "FASTER", "SLOWER": "SLOWER", "TIE": "TIE", "INCONCLUSIVE": "INCONCLUSIVE"}
Malformed = S.Malformed
# --------------------------------------------------------------------------------------------------------------------------------
# input
# --------------------------------------------------------------------------------------------------------------------------------
def _load(path):
try:
with open(path, "r", encoding="utf-8") as handle:
return json.load(handle)
except (OSError, ValueError) as exc:
raise Malformed("%s: %s" % (path, exc))
def _positive(x):
return S._is_number(x) and x > 0
def _check_log_list(values, where):
if not isinstance(values, list) or len(values) < 2 or not all(S._is_number(x) for x in values):
raise Malformed("%s must be a list of at least 2 finite numbers" % where)
def _check_prior(prior):
if prior is None:
return {}
if not isinstance(prior, dict):
raise Malformed("prior must be null or an object")
for key in ("suspected", "aa_failed_once"):
if key in prior and not isinstance(prior[key], bool):
raise Malformed("prior.%s must be a boolean" % key)
return prior
def parse_cell(doc, where="cell"):
if not isinstance(doc, dict):
raise Malformed("%s must be a JSON object" % where)
if not isinstance(doc.get("cell_id"), str) or not doc["cell_id"]:
raise Malformed("%s.cell_id must be a non-empty string" % where)
if doc.get("kind") not in ("time", "rate"):
raise Malformed("%s.kind must be \"time\" or \"rate\"" % where)
pairs = doc.get("pairs")
if not isinstance(pairs, list) or len(pairs) < 2:
raise Malformed("%s.pairs must be a list of at least 2 {\"v\",\"o\"} objects" % where)
for index, pair in enumerate(pairs):
if not isinstance(pair, dict) or not _positive(pair.get("v")) or not _positive(pair.get("o")):
raise Malformed("%s.pairs[%d] needs positive finite \"v\" and \"o\"" % (where, index))
aa = doc.get("aa")
if not isinstance(aa, dict):
raise Malformed("%s.aa must be an object with the lists \"ours\" and \"vanilla\" (an A/A control is required)" % where)
for key in ("ours", "vanilla"):
_check_log_list(aa.get(key), "%s.aa.%s" % (where, key))
return doc, _check_prior(doc.get("prior"))
def cell_logs(cell):
"""l_j per pair: ln(v / o) for time-like, ln(o / v) for rate-like values (series_eval.log_ratio: positive = ours better)."""
metric = "wall_norm" if cell["kind"] == "time" else "decode_tps"
return [S.log_ratio(metric, p["o"], p["v"]) for p in cell["pairs"]]
# --------------------------------------------------------------------------------------------------------------------------------
# classification
# --------------------------------------------------------------------------------------------------------------------------------
def ci_class(lo, hi):
return CLASS_OF_RULE[S.classify(STRICT, lo, hi)]
def _block(st):
return {"n": st["n"], "mean_l": st["mean_l"], "ci_lo": st["ci_lo"], "ci_hi": st["ci_hi"]}
def aa_result(cell):
out = {}
valid = True
for key in ("ours", "vanilla"):
st = S.summarize([float(x) for x in cell["aa"][key]], ALPHA_AA)
contains = st["ci_lo"] <= S.EPS and st["ci_hi"] >= -S.EPS
block = _block(st)
block["contains_zero"] = contains
out[key] = block
valid = valid and contains
return valid, out
def classify_cell(cell, prior):
"""One cell without confirmation: statistics, class, A/A validity and action."""
st = S.summarize(cell_logs(cell), S.ALPHA_FINAL)
raw = ci_class(st["ci_lo"], st["ci_hi"])
aa_valid, aa = aa_result(cell)
screening = st["n"] < MIN_CLASSIFIED_N
cls = raw
if screening or not aa_valid:
cls = "INCONCLUSIVE"
if aa_valid:
action = "OK"
else:
action = "OWNER" if prior.get("aa_failed_once") else "RERUN_ONCE"
out = {"schema": SCHEMA, "cell_id": cell["cell_id"], "kind": cell["kind"], "n": st["n"], "mean_l": st["mean_l"],
"ci_lo": st["ci_lo"], "ci_hi": st["ci_hi"], "half_width": st["half_width"], "ci_level": 1.0 - S.ALPHA_FINAL,
"r1": st["r1"], "n_eff": st["n_eff"], "class": cls, "aa_valid": aa_valid, "aa": aa, "action": action,
"suspected": cls == "SLOWER", "owner_list": cls == "EQUAL" and st["mean_l"] < 0.0,
"screening": screening, "min_n": MIN_CLASSIFIED_N}
if screening or not aa_valid:
out["screening_class"] = raw
if prior.get("suspected"):
out["prior_suspected"] = True
return out
def classify_with_confirm(cell, prior, confirm_cell, confirm_prior):
out = classify_cell(cell, prior)
if out["class"] != "SLOWER":
out["confirm_ignored"] = "the first class is %s, not SLOWER" % out["class"]
return out
if confirm_cell["kind"] != cell["kind"]:
raise Malformed("the confirm cell has kind %s, the cell %s" % (confirm_cell["kind"], cell["kind"]))
if len(confirm_cell["pairs"]) < MIN_CLASSIFIED_N:
raise Malformed("the confirm cell needs at least %d fresh pairs, got %d" % (MIN_CLASSIFIED_N, len(confirm_cell["pairs"])))
second = classify_cell(confirm_cell, confirm_prior)
out["confirmation"] = {"cell_id": second["cell_id"], "n": second["n"], "mean_l": second["mean_l"], "ci_lo": second["ci_lo"],
"ci_hi": second["ci_hi"], "class": second["class"], "aa_valid": second["aa_valid"], "aa": second["aa"]}
if not second["aa_valid"]:
# an invalid confirm run confirms nothing and refutes nothing: the first SLOWER stays suspected, the confirm run is repeated
out["action"] = second["action"]
out["confirm_invalid"] = True
return out
out["class"] = "CONFIRMED-SLOWER" if second["class"] == "SLOWER" else "NOT-CONFIRMED"
out["suspected"] = False
return out
# --------------------------------------------------------------------------------------------------------------------------------
# AC5(b)
# --------------------------------------------------------------------------------------------------------------------------------
def parse_alt(doc):
if not isinstance(doc, dict):
raise Malformed("alt must be a JSON object")
if not isinstance(doc.get("cell_id"), str) or not doc["cell_id"]:
raise Malformed("alt.cell_id must be a non-empty string")
n_reg = doc.get("N", AC5_DEFAULT_N)
if isinstance(n_reg, bool) or not isinstance(n_reg, int) or n_reg < AC5_BLOCK or n_reg % AC5_BLOCK:
raise Malformed("alt.N must be a positive multiple of %d" % AC5_BLOCK)
pairs = doc.get("pairs")
if not isinstance(pairs, list) or not pairs:
raise Malformed("alt.pairs must be a non-empty list of {\"d\",\"a\"} objects")
for index, pair in enumerate(pairs):
if not isinstance(pair, dict) or not _positive(pair.get("d")) or not _positive(pair.get("a")):
raise Malformed("alt.pairs[%d] needs positive finite \"d\" and \"a\"" % index)
return n_reg, pairs
def ac5_verdict(doc):
n_reg, pairs = parse_alt(doc)
ls = [math.log(p["d"] / p["a"]) for p in pairs[:n_reg]] # the first N pairs form the series (later pairs are outside the schedule)
ignored = len(pairs) - len(ls)
looks = []
for k in range(1, len(ls) // AC5_BLOCK + 1):
size = AC5_BLOCK * k
st = S.summarize(ls[:size], ALPHA_AC5_LOOK)
slower = st["ci_hi"] < -S.EPS
looks.append({"look": k, "n": size, "ci_hi": st["ci_hi"], "slower": slower})
if slower:
return {"schema": SCHEMA, "cell_id": doc["cell_id"], "n": size, "N": n_reg, "mean_l": st["mean_l"], "ci_lo": st["ci_lo"],
"ci_hi": st["ci_hi"], "ci_level": 1.0 - ALPHA_AC5_LOOK, "verdict": "SLOWER", "look": k, "looks": looks,
"ignored_pairs": ignored}
n = len(ls)
out = {"schema": SCHEMA, "cell_id": doc["cell_id"], "n": n, "N": n_reg, "ci_level": 1.0 - S.ALPHA_FINAL, "looks": looks,
"look": len(looks), "ignored_pairs": ignored}
if n >= 2:
st = S.summarize(ls, S.ALPHA_FINAL)
out.update({"mean_l": st["mean_l"], "ci_lo": st["ci_lo"], "ci_hi": st["ci_hi"], "half_width": st["half_width"]})
else:
out.update({"mean_l": ls[0], "ci_lo": None, "ci_hi": None, "half_width": None})
if n < n_reg:
out["verdict"] = "SCREENING"
return out
rule = S.classify(STRICT, out["ci_lo"], out["ci_hi"])
if rule == "SLOWER":
# the 95 percent bound is below 0 but the Pocock bound is not: no SLOWER exit was earned at the family-wise level
out["verdict"] = "INCONCLUSIVE"
out["slower_at_95_only"] = True
else:
out["verdict"] = VERDICT_OF_RULE[rule]
return out
# --------------------------------------------------------------------------------------------------------------------------------
# command line
# --------------------------------------------------------------------------------------------------------------------------------
class _Parser(argparse.ArgumentParser):
def error(self, message): # argparse exits 2 by default; the interface knows 0 and 3 only
sys.stderr.write("%s: error: %s\n" % (self.prog, message))
raise SystemExit(3)
def _emit(result):
sys.stdout.write(json.dumps(result, indent=2, allow_nan=False) + "\n")
def main(argv=None):
parser = _Parser(prog="component_class.py", description="Component classifier (STRA-313)")
sub = parser.add_subparsers(dest="command")
cell_p = sub.add_parser("cell", help="classify one component cell (AC10)")
cell_p.add_argument("cell", help="cell.json")
cell_p.add_argument("--confirm", help="confirm cell.json (30 fresh pairs on a new pre-registered schedule)")
ac5_p = sub.add_parser("ac5", help="AC5(b) verdict of one alternative")
ac5_p.add_argument("alt", help="alt.json")
args = parser.parse_args(argv)
if args.command is None:
parser.error("a subcommand (cell or ac5) is required")
try:
if args.command == "cell":
cell, prior = parse_cell(_load(args.cell))
if args.confirm:
confirm_cell, confirm_prior = parse_cell(_load(args.confirm), "confirm cell")
result = classify_with_confirm(cell, prior, confirm_cell, confirm_prior)
else:
result = classify_cell(cell, prior)
else:
result = ac5_verdict(_load(args.alt))
_emit(result)
return 0
except Malformed as exc:
sys.stderr.write("MALFORMED INPUT: %s\n" % exc)
return 3
if __name__ == "__main__":
sys.exit(main())