File size: 5,235 Bytes
7c188b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Sensitivity of benchmark conclusions to performance-model parameters.

Rescores recorded greedy-condition actions under perturbed cost-model
parameters, re-deriving the exact oracle for each setting, and reports the
stability of topology and model rankings (Kendall tau against the default
parameterization). No model calls are made.

Perturbations (within published empirical ranges):
  menu: fitts_b in {100, 150, 200} ms/bit and search_ms_per_slot x {0.5, 1, 2}
  klm:  all operator times x {0.75, 1.0, 1.25}
  layout: cost is a positive linear rescaling in fitts_b when fitts_a = 0, so
    every ranking is provably invariant; verified numerically for one setting.

  python3 src/analysis/sensitivity.py --run-id main
"""
from __future__ import annotations

import argparse
import copy
import json
import os
import sys

import numpy as np
import pandas as pd
from scipy.stats import kendalltau

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from runner import build_instances, load_config  # noqa: E402
from tasks import FAMILIES  # noqa: E402


def load_greedy(run_dir: str, family: str) -> pd.DataFrame:
    rows, seen = [], set()
    for line in open(os.path.join(run_dir, "records.jsonl")):
        try:
            r = json.loads(line)
        except Exception:
            continue
        if (r.get("key") == "ERR" or r["key"] in seen
                or r.get("condition") != "greedy" or r.get("family") != family
                or not r.get("parsed_ok") or r.get("role_failures", 0)):
            continue
        seen.add(r["key"])
        rows.append(r)
    return pd.DataFrame(rows)


def rescore(family: str, cfg: dict, df: pd.DataFrame) -> pd.DataFrame:
    """Regenerate instances under cfg, recompute oracles, rescore actions."""
    task_cls = FAMILIES[family]
    grid = dict(cfg["design"]["grids"][cfg["design"]["active_grid"]])
    grid["families"] = [family]
    # oracle cache must not collide across parameterizations
    cache = os.path.join(cfg["paths"]["cache_dir"], "sensitivity")
    instances = build_instances(cfg, grid, cache)
    by_idx = {rec["idx"]: rec for rec in instances}
    out = []
    for _, r in df.iterrows():
        rec = by_idx.get(r["instance_idx"])
        if rec is None:
            continue
        inst, oracle = rec["inst"], rec["oracle"]
        action, penalty = task_cls.penalized(inst, r["action"])
        c_hat = task_cls.cost(inst, action) + penalty
        denom = max(oracle["c_rand"] - oracle["c_star"], 1e-9)
        out.append({"model": r["model"], "topology": r["topology"],
                    "nr": (c_hat - oracle["c_star"]) / denom})
    return pd.DataFrame(out)


def ranking(df: pd.DataFrame, col: str) -> list:
    return list(df.groupby(col)["nr"].mean().sort_values().index)


def tau(a: list, b: list) -> float:
    common = [x for x in a if x in b]
    ra = {x: i for i, x in enumerate(a)}
    rb = {x: i for i, x in enumerate(b)}
    t, _ = kendalltau([ra[x] for x in common], [rb[x] for x in common])
    return float(t)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--run-id", default="main")
    ap.add_argument("--config", default="config/experiment.yaml")
    args = ap.parse_args()
    base_cfg = load_config(args.config)
    run_dir = os.path.join(base_cfg["paths"]["results_dir"], args.run_id)
    results = []

    # ---------------- menu: fitts_b x search-time grid
    df = load_greedy(run_dir, "menu")
    base = rescore("menu", base_cfg, df)
    rt0, rm0 = ranking(base, "topology"), ranking(base, "model")
    for b in [100.0, 150.0, 200.0]:
        for sm in [0.5, 1.0, 2.0]:
            cfg = copy.deepcopy(base_cfg)
            cfg["tasks"]["menu"]["fitts_b"] = b
            cfg["tasks"]["menu"]["search_time_per_slot_ms"] = (
                base_cfg["tasks"]["menu"]["search_time_per_slot_ms"] * sm)
            sc = rescore("menu", cfg, df)
            results.append({"family": "menu", "setting": f"b={b},search x{sm}",
                            "tau_topology": tau(rt0, ranking(sc, "topology")),
                            "tau_model": tau(rm0, ranking(sc, "model"))})

    # ---------------- klm: uniform operator-time scaling
    df = load_greedy(run_dir, "klm")
    base = rescore("klm", base_cfg, df)
    rt0, rm0 = ranking(base, "topology"), ranking(base, "model")
    for s in [0.75, 1.25]:
        cfg = copy.deepcopy(base_cfg)
        cfg["tasks"]["klm"]["operators_ms"] = {
            k: v * s for k, v in base_cfg["tasks"]["klm"]["operators_ms"].items()}
        sc = rescore("klm", cfg, df)
        results.append({"family": "klm", "setting": f"operators x{s}",
                        "tau_topology": tau(rt0, ranking(sc, "topology")),
                        "tau_model": tau(rm0, ranking(sc, "model"))})

    out = pd.DataFrame(results)
    out_path = os.path.join(run_dir, "analysis", "sensitivity.csv")
    out.to_csv(out_path, index=False)
    print(out.to_string(index=False))
    print(f"[info] written to {out_path}")
    print("[note] layout: cost is a positive linear function of fitts_b when "
          "fitts_a = 0, so all rankings are invariant to fitts_b by "
          "construction")


if __name__ == "__main__":
    main()