File size: 6,111 Bytes
dedf737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""Summarise the ontology / global-representation experiments.

Reads every result CSV that contains the schema blocks and the reference
PhysChem-Tree run, normalises them to ``(config, task, study, spearman)`` and
emits:

* ``results/schema_summary.csv``  -- per-config, per-study means
* ``results/schema_paired.csv``   -- paired Wilcoxon of each config against the
  identity-free reference on the 20 shared external tasks
* ``results/schema_results.md``   -- the markdown tables used in the report

The reference is the plain chemistry block (``base``), which is the strongest
published single model (PhysChem-Tree, 0.376), so every delta below is a delta
against the current state of the art under the strict protocol.

Usage::

    python scripts/schema_report.py
"""

from __future__ import annotations

from pathlib import Path
from typing import List

import numpy as np
import pandas as pd
from scipy.stats import spearmanr, wilcoxon

RESULTS = Path("results")
STUDIES = ["LM_2019", "BL_2023", "SL_2020", "ZC_2023"]
PRETTY = {
    "base": "PhysChem-Tree (reference)",
    "base+onto": "+ontology / schema",
    "base+cb": "+global codebook",
    "base+onto+cb": "+ontology +codebook",
    "base+spec": "+spectral embedding",
    "onto": "ontology only",
    "cb": "codebook only",
}


def _load(paths: List[Path]) -> pd.DataFrame:
    frames = []
    for p in paths:
        if not p.exists():
            continue
        df = pd.read_csv(p)
        if "config" in df.columns and "spearman" in df.columns:
            keep = df[["config", "task", "study", "spearman"]].copy()
        elif "k_shot" in df.columns:
            keep = df[df.k_shot == 0][["task", "study", "spearman"]].copy()
            keep["config"] = "base"
        elif "model" in df.columns and "spearman" in df.columns:
            keep = df[df.seed == 0][["task", "study", "spearman"]].copy() if "seed" in df else df[["task", "study", "spearman"]].copy()
            keep["config"] = df["model"].iloc[0]
        else:
            continue
        frames.append(keep)
    if not frames:
        return pd.DataFrame(columns=["config", "task", "study", "spearman"])
    out = pd.concat(frames, ignore_index=True)
    out = out.drop_duplicates(["config", "task"], keep="last")
    return out


def main() -> None:
    df = _load([
        RESULTS / "fewshot.csv",          # k=0 rows -> base
        RESULTS / "schema_bench2.csv",    # base+onto / base+cb / base+onto+cb
        RESULTS / "schema_bench1.csv",    # optional extra configs
        RESULTS / "schema_bench_spec.csv",
    ])
    if df.empty:
        print("no results found")
        return

    order = [c for c in PRETTY if c in df.config.unique()]
    order += [c for c in df.config.unique() if c not in order]
    df["config"] = pd.Categorical(df.config, order, ordered=True)
    df = df.sort_values(["config", "study", "task"])

    # ---- per-study means ---------------------------------------------------
    piv = df.pivot_table(index="config", columns="study", values="spearman", aggfunc="mean")
    mean = df.groupby("config").spearman.agg(["size", "mean", "std"]).rename(columns={"size": "n_tasks"})
    summary = mean.join(piv[STUDIES]).reset_index()
    summary.to_csv(RESULTS / "schema_summary.csv", index=False)

    # ---- paired tests against the reference --------------------------------
    ref = df[df.config == "base"].set_index("task").spearman
    rows = []
    for cfg in order:
        cur = df[df.config == cfg].set_index("task").spearman
        common = ref.index.intersection(cur.index)
        if cfg == "base" or len(common) < 5:
            continue
        a, b = cur[common].to_numpy(), ref[common].to_numpy()
        try:
            p = wilcoxon(a, b).pvalue
        except ValueError:
            p = float("nan")
        rows.append({
            "config": cfg, "n": len(common),
            "mean": float(a.mean()), "ref_mean": float(b.mean()),
            "delta": float(a.mean() - b.mean()),
            "relative": float((a.mean() - b.mean()) / abs(b.mean())) if b.mean() else float("nan"),
            "wilcoxon_p": float(p),
            "n_tasks_improved": int((a > b).sum()),
        })
    paired = pd.DataFrame(rows).sort_values("delta", ascending=False)
    paired.to_csv(RESULTS / "schema_paired.csv", index=False)

    # ---- markdown ----------------------------------------------------------
    lines = ["# Ontology / schema and global-representation experiments", ""]
    lines.append("All numbers are full runs: 4 fully held-out studies x 5 published folds "
                 "= 20 external tasks, seed 0, identical estimator (random forest, "
                 "400 trees, `min_samples_leaf=2`), identical splits. Only the feature "
                 "block changes.")
    lines.append("")
    lines.append("## Per-study Spearman")
    lines.append("")
    lines.append("| config | " + " | ".join(STUDIES) + " | mean | n |")
    lines.append("|---|" + "---|" * (len(STUDIES) + 2))
    for _, r in summary.iterrows():
        label = PRETTY.get(str(r["config"]), str(r["config"]))
        cells = [f"{r[s]:.3f}" if pd.notna(r.get(s)) else "–" for s in STUDIES]
        lines.append(f"| {label} | " + " | ".join(cells) + f" | **{r['mean']:.3f}** | {int(r['n_tasks'])} |")
    lines.append("")
    if len(paired):
        lines.append("## Paired Wilcoxon against the reference (20 tasks)")
        lines.append("")
        lines.append("| config | mean | reference | delta | relative | tasks improved | p |")
        lines.append("|---|---|---|---|---|---|---|")
        for _, r in paired.iterrows():
            label = PRETTY.get(str(r["config"]), str(r["config"]))
            lines.append(
                f"| {label} | {r['mean']:.3f} | {r['ref_mean']:.3f} | {r['delta']:+.3f} | "
                f"{100*r['relative']:+.1f}% | {r['n_tasks_improved']}/{int(r['n'])} | {r['wilcoxon_p']:.4f} |"
            )
        lines.append("")
    out = RESULTS / "schema_results.md"
    out.write_text("\n".join(lines))
    print("\n".join(lines))
    print("wrote", out)


if __name__ == "__main__":
    main()