Research resources

operator_random_control_test.py

Historical scientific source text. The original date, test status, inputs and qualifications remain unchanged. Workspace locators and historical project labels are projected for this public source view. This source view does not execute the historical program.

Original SHA-256: 55f0ff0b5073b45d1d5c74942e21ec1457965cce4998ebaeeb5cd2e181ed8a83

#!/usr/bin/env python3
"""T4.1 — Random-stem control test for Test A. (Optimized.)

Tests whether HAGEVA-predicted operator term-stems return hit-counts
distinguishable from frequency-matched random word-stems starting with
the same operator letter, sampled from the same source OCR corpus.

Reads:
- HAGEVA mapping table (for operator letter list)
- 4 source OCRs
- Prior Test A summary (operator_cross_test_2026-04-29.json) for predicted-stem counts and observed totals

Writes:
- ~/hail/vms/analysis/operator_random_control_2026-04-29.json
"""
from __future__ import annotations

import json
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np

SOURCES = {
    "Montagnana_1476": "research-workspace/manuscripts/Untouched Manuscripts/Honeycutt Ai Labs-VMS-MS_Archive_Montagnana-Consilia_1476.txt",
    "Pal.lat.1268": "research-workspace/manuscripts/MSS_Pal.lat.1268/MSS_Pal.lat.1268_OCR.txt",
    "Pal.lat.1268_Heid": "research-workspace/manuscripts/MSS_Pal.lat.1268/MSS_Pal.lat.1268_Heidelberg_OCR.txt",
    "Pal.lat.1221": "research-workspace/manuscripts/MSS_Pal.lat.1221/MSS_Pal.lat.1221_OCR.txt",
}

PRIOR_TEST_PATH = Path("research-workspace/analysis/operator_cross_test_2026-04-29.json")
OUT_PATH = Path("research-workspace/analysis/operator_random_control_2026-04-29.json")
N_SAMPLES = 1000
RNG_SEED = 20260429
STEM_LEN_MIN = 3
STEM_LEN_MAX = 8
WORD_RE = re.compile(r"[a-zA-Zàèéìòùç]+")


def tokenize(text: str) -> list[str]:
    return [w.lower() for w in WORD_RE.findall(text)]


def precompute_index(tokens: list[str]):
    """Returns:
    - counter: word -> count
    - by_first: first_char -> list of (word, count)
    - by_first_len: (first_char, length) -> list of (word, count)  for stem-length matching
    """
    counter = Counter(tokens)
    by_first = defaultdict(list)
    by_first_len = defaultdict(list)
    for word, c in counter.items():
        if word and STEM_LEN_MIN <= len(word) <= STEM_LEN_MAX:
            by_first[word[0]].append((word, c))
            by_first_len[(word[0], len(word))].append((word, c))
        elif word:
            # Still index in by_first for prefix matching, but exclude short/long from stem-pool
            by_first[word[0]].append((word, c))
    return counter, by_first, by_first_len


def total_prefix_hits_for_stems(stems: list[str], by_first: dict) -> int:
    total = 0
    for stem in stems:
        if not stem:
            continue
        for word, c in by_first.get(stem[0], ()):
            if word.startswith(stem):
                total += c
    return total


def sample_random_stems_for_letter(
    letter: str,
    n_stems: int,
    by_first_len: dict,
    by_first: dict,
    rng: np.random.Generator,
) -> list[str]:
    # Pre-bucket stem candidates for this letter, length-stratified
    stems = []
    # Use length distribution proportional to candidate pool
    length_pool = []
    for L in range(STEM_LEN_MIN, STEM_LEN_MAX + 1):
        cands = by_first_len.get((letter, L), [])
        length_pool.extend([L] * len(cands))
    if not length_pool:
        # No candidates of right length — sample from any-length-letter words as fallback
        any_letter = [w for w, _ in by_first.get(letter, []) if STEM_LEN_MIN <= len(w) <= STEM_LEN_MAX]
        if not any_letter:
            return []
        idxs = rng.integers(0, len(any_letter), size=n_stems)
        return [any_letter[i] for i in idxs]

    # Pick lengths with empirical distribution, then sample words at that length
    chosen_lengths = rng.choice(length_pool, size=n_stems, replace=True)
    for L in chosen_lengths:
        bucket = by_first_len[(letter, int(L))]
        idx = rng.integers(0, len(bucket))
        stems.append(bucket[idx][0])
    return stems


def main():
    # Load OCR corpora
    indices = {}
    for src, path in SOURCES.items():
        try:
            text = Path(path).read_text(errors="ignore")
        except FileNotFoundError:
            print(f"WARN: missing source {path}, skipping {src}")
            continue
        tokens = tokenize(text)
        counter, by_first, by_first_len = precompute_index(tokens)
        indices[src] = {
            "n_tokens": len(tokens),
            "n_unique": len(counter),
            "counter": counter,
            "by_first": by_first,
            "by_first_len": by_first_len,
        }
        print(f"{src}: {len(tokens):,} tokens, {len(counter):,} unique", flush=True)

    # Load prior Test A
    prior = json.loads(PRIOR_TEST_PATH.read_text())
    operators = prior["results"]
    rng = np.random.default_rng(RNG_SEED)

    summary = {
        "test_id": "T4.1_operator_random_control",
        "date": "2026-04-29",
        "n_samples": N_SAMPLES,
        "rng_seed": RNG_SEED,
        "stem_length_range": [STEM_LEN_MIN, STEM_LEN_MAX],
        "sources": list(indices.keys()),
        "operators": {},
    }

    for op, info in operators.items():
        n_predictions = info["predictions"]
        observed_total_per_source = info["counts"]
        observed_total = info["total"]
        op_letter = op.lower()

        per_source = {}
        # Per-source: sample N stems, count prefix hits, repeat N_SAMPLES times
        for src, idx in indices.items():
            null_totals = np.zeros(N_SAMPLES, dtype=np.int64)
            for i in range(N_SAMPLES):
                stems = sample_random_stems_for_letter(
                    op_letter, n_predictions, idx["by_first_len"], idx["by_first"], rng
                )
                if not stems:
                    continue
                null_totals[i] = total_prefix_hits_for_stems(stems, idx["by_first"])
            obs = observed_total_per_source.get(src, 0)
            n_zero_pool = (null_totals == 0).sum() == N_SAMPLES
            if n_zero_pool:
                p_one = float("nan")
            else:
                p_one = float((null_totals >= obs).mean())
            per_source[src] = {
                "observed": obs,
                "null_mean": float(null_totals.mean()),
                "null_std": float(null_totals.std(ddof=1)),
                "null_p05": float(np.percentile(null_totals, 5)),
                "null_p50": float(np.percentile(null_totals, 50)),
                "null_p95": float(np.percentile(null_totals, 95)),
                "p_one_sided_obs_ge_null": p_one,
            }

        # Aggregate (sum across sources): for each iteration, sample once per source and sum
        agg_null = np.zeros(N_SAMPLES, dtype=np.int64)
        for i in range(N_SAMPLES):
            total = 0
            for src, idx in indices.items():
                stems = sample_random_stems_for_letter(
                    op_letter, n_predictions, idx["by_first_len"], idx["by_first"], rng
                )
                if stems:
                    total += total_prefix_hits_for_stems(stems, idx["by_first"])
            agg_null[i] = total

        agg_p = float((agg_null >= observed_total).mean())
        summary["operators"][op] = {
            "greek": info["greek"],
            "n_predictions": n_predictions,
            "observed_total_all_sources": observed_total,
            "per_source": per_source,
            "aggregate_null": {
                "mean": float(agg_null.mean()),
                "std": float(agg_null.std(ddof=1)),
                "min": int(agg_null.min()),
                "max": int(agg_null.max()),
                "p05": float(np.percentile(agg_null, 5)),
                "p50": float(np.percentile(agg_null, 50)),
                "p95": float(np.percentile(agg_null, 95)),
            },
            "p_one_sided_aggregate_obs_ge_null": agg_p,
            "verdict_at_alpha_0.05": (
                "ENRICHED OVER RANDOM" if agg_p < 0.05 else "NOT DISTINGUISHABLE FROM RANDOM"
            ),
        }
        print(
            f"  {op}: predictions={n_predictions}, obs_total={observed_total}, null_mean={agg_null.mean():.0f}, p={agg_p:.4f} -> {summary['operators'][op]['verdict_at_alpha_0.05']}",
            flush=True,
        )

    enriched = sum(1 for op in summary["operators"].values() if op["p_one_sided_aggregate_obs_ge_null"] < 0.05)
    not_dist = len(summary["operators"]) - enriched
    summary["overall"] = {
        "n_operators_tested": len(summary["operators"]),
        "n_enriched_at_alpha_0.05": enriched,
        "n_not_distinguishable_at_alpha_0.05": not_dist,
        "interpretation": (
            f"{enriched} of {len(summary['operators'])} operators show HAGEVA-predicted hits ENRICHED "
            f"over frequency-matched random control. {not_dist} of {len(summary['operators'])} are NOT "
            "distinguishable from base-rate Latin lexical density."
        ),
    }

    OUT_PATH.write_text(json.dumps(summary, indent=2))
    print(f"\nWrote {OUT_PATH}")
    print(summary["overall"]["interpretation"])


if __name__ == "__main__":
    main()