File size: 4,577 Bytes
3bbd5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""Aggregate Phase 2b per-cell outputs into results/phase2b_blockers.csv.

Blocker A's four cells are measured over one shared sentence subset, so the
cross-cell contrasts here are paired differences rather than differences of
independent means. The two contrasts that matter:

  model effect  = (sarvam - llama) computed within each script, twice
  script effect = (devanagari - romanized) computed within each model, twice

A model effect that holds its sign and magnitude across both scripts points
at model identity as the driver of the Phase 2 L1 anomaly; one that flips or
vanishes when the script changes points at a genuine script/fertility
interaction.
"""

import argparse
import csv
import json
import logging
from pathlib import Path

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("phase2b_agg")

import sys

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from src.measure.uncertainty import mean_estimate, paired_difference

A_CELLS = ("sarvam_dev", "sarvam_rom", "llama_dev", "llama_rom")
A_METRICS = ("fertility", "d_indep_k2", "d_indep_k3")


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--in-dir", required=True)
    p.add_argument("--out", default="results/phase2b_blockers.csv")
    p.add_argument("--resamples", type=int, default=2000)
    return p.parse_args()


def rows_for_blocker_a(in_dir: Path, resamples: int) -> list:
    cells = {}
    for cell in A_CELLS:
        path = in_dir / f"a_{cell}.json"
        if not path.exists():
            logger.warning("missing %s, skipping cell %s", path, cell)
            continue
        cells[cell] = json.loads(path.read_text())

    rows = []
    for cell, data in cells.items():
        for metric in A_METRICS:
            est = mean_estimate(data[metric], resamples=resamples)
            rows.append((cell, metric, est.mean, est.n))
            rows.append((cell, f"{metric}_stderr", est.stderr, est.n))
            rows.append((cell, f"{metric}_ci_low", est.ci_low, est.n))
            rows.append((cell, f"{metric}_ci_high", est.ci_high, est.n))

    contrasts = [
        ("model_effect_devanagari", "sarvam_dev", "llama_dev"),
        ("model_effect_romanized", "sarvam_rom", "llama_rom"),
        ("script_effect_sarvam", "sarvam_dev", "sarvam_rom"),
        ("script_effect_llama", "llama_dev", "llama_rom"),
    ]
    for name, a, b in contrasts:
        if a not in cells or b not in cells:
            continue
        for metric in A_METRICS:
            est = paired_difference(cells[a][metric], cells[b][metric], resamples=resamples)
            rows.append((name, f"{metric}_paired_diff", est.mean, est.n))
            rows.append((name, f"{metric}_paired_diff_stderr", est.stderr, est.n))
            rows.append((name, f"{metric}_paired_diff_ci_low", est.ci_low, est.n))
            rows.append((name, f"{metric}_paired_diff_ci_high", est.ci_high, est.n))
    return rows


B_OUTPUTS = (
    ("b_arch.json", "B_arch"),
    ("b_trough_L5.json", "B_trough_L5"),
    ("b_trough_L1.json", "B_trough_L1"),
    ("b_trough_L4.json", "B_trough_L4"),
)


def rows_for_blocker_b(in_dir: Path) -> list:
    rows = []
    for name, label in B_OUTPUTS:
        path = in_dir / name
        if not path.exists():
            logger.warning("missing %s", path)
            continue
        data = json.loads(path.read_text())
        for key, entry in data.items():
            cond = f"{label}__{key}"
            rows.append((cond, "entropy_trough_depth", entry["entropy_trough_depth"], entry["n_points"]))
            rows.append((cond, "n_h1_intraword", len(entry["h1_intraword_values"]), entry["n_points"]))
            rows.append((cond, "n_h1_boundary", len(entry["h1_boundary_values"]), entry["n_points"]))
            for metric, value in entry.get("by_horizon", {}).items():
                rows.append((cond, metric, value, entry["n_points"]))
    return rows


def main() -> None:
    args = parse_args()
    in_dir = Path(args.in_dir)
    rows = rows_for_blocker_a(in_dir, args.resamples) + rows_for_blocker_b(in_dir)

    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    with open(args.out, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["condition", "metric", "value", "n"])
        for cond, metric, value, n in rows:
            writer.writerow([cond, metric, value, n])
    logger.info("wrote %s (%d rows)", args.out, len(rows))


if __name__ == "__main__":
    main()