File size: 8,077 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
"""R6 @30k vs @5k — aggregate the 30k eval with the EXACT registered
definitions of df_eval_agg.py (arm_stats copied verbatim), compare
against the official ladder numbers in df_eval_summary.json and
df_corr_eval.json, check Gate Object Grounding for R6@30k, and write
results/df_r6_30k_compare.json (+ dashboard state)."""
import json
import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from v2_dash import merge_item                   # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
RES = EXP / "trace_validation" / "results"
CONDS = ["P0", "P1", "P2", "P3", "P4", "P5", "P6"]
CF = ["P4", "P5", "P6"]          # counterfactual selection suite
MAIN = ["P0", "P1", "P2", "P3", "P4", "P5"]


# --- arm_stats copied verbatim from df_eval_agg.py (registered) ---
def rate(vals):
    vals = [v for v in vals if v is not None]
    return round(float(sum(vals)) / len(vals), 4) if vals else None


def arm_stats(recs):
    feas = [r for r in recs if not r.get("infeasible")]
    out = {"n": len(feas),
           "n_infeasible": len(recs) - len(feas), "by_cond": {}}
    for c in CONDS:
        sub = [r for r in feas if r["cond"] == c]
        if not sub:
            continue
        out["by_cond"][c] = {
            "n": len(sub),
            "selection_rate": rate([r["selection_correct"]
                                    for r in sub]),
            "approach_rate": rate([r["approached"] for r in sub]),
            "grasp_correct_rate": rate([r["grasped_correct"]
                                        for r in sub]),
            "grasp_wrong_rate": rate([bool(r["grasped_wrong"])
                                      for r in sub]),
            "placement_rate": rate([r["placement_end"]
                                    for r in sub]),
            "success_rate": rate([r["success"] for r in sub]),
            "min_dist_target_mean": rate([r["min_dist_target"]
                                          for r in sub]),
            "min_dist_old_mean": rate([r["min_dist_old"]
                                       for r in sub]),
        }
    cf = [r for r in feas if r["cond"] in CF]
    main = [r for r in feas if r["cond"] in MAIN]
    out["counterfactual"] = {
        "n": len(cf),
        "selection_rate": rate([r["selection_correct"] for r in cf]),
        "grasp_wrong_rate": rate([bool(r["grasped_wrong"])
                                  for r in cf]),
        "success_rate": rate([r["success"] for r in cf])}
    out["main"] = {
        "n": len(main),
        "grasp_correct_rate": rate([r["grasped_correct"]
                                    for r in main]),
        "success_rate": rate([r["success"] for r in main]),
        "selection_rate": rate([r["selection_correct"]
                                for r in main])}
    return out
# --- end verbatim copy ---


def se_binom(p, n):
    """Binomial standard error of a rate (percentage points)."""
    if p is None or not n:
        return None
    return round(100.0 * math.sqrt(p * (1 - p) / n), 2)


def delta_row(name, v5, v30, n_eff):
    d = None
    if v5 is not None and v30 is not None:
        d = round(100.0 * (v30 - v5), 2)
    se = se_binom(v30, n_eff)
    within = None
    if d is not None and se:
        within = abs(d) <= 2 * se
    return {"metric": name,
            "r6_5k_pct": None if v5 is None else round(100 * v5, 2),
            "r6_30k_pct": None if v30 is None else round(100 * v30, 2),
            "delta_pts": d, "se_30k_pts": se,
            "within_noise_2se": within}


def main():
    recs = [json.loads(x) for x in
            (RES / "df_eval_r6_30k.jsonl").read_text().splitlines()
            if x.strip()]
    s30 = arm_stats(recs)
    summ = json.loads((RES / "df_eval_summary.json").read_text())
    s5 = summ["arms"]["r6"]
    s2 = summ["arms"]["r2"]
    corr5 = json.loads((RES / "df_corr_eval.json").read_text())["r6"]
    corr30 = json.loads(
        (RES / "df_corr_eval_r6_30k.json").read_text())["r6"]

    # effective denominators: selection rates exclude None rows
    def n_sel(recs_, conds):
        return sum(1 for r in recs_
                   if not r.get("infeasible") and r["cond"] in conds
                   and r.get("selection_correct") is not None)

    rows = [
        delta_row("Success — suite chính (P0–P5)",
                  s5["main"]["success_rate"],
                  s30["main"]["success_rate"], s30["main"]["n"]),
        delta_row("Grasp đúng — suite chính",
                  s5["main"]["grasp_correct_rate"],
                  s30["main"]["grasp_correct_rate"], s30["main"]["n"]),
        delta_row("Chọn đúng vật — suite chính",
                  s5["main"]["selection_rate"],
                  s30["main"]["selection_rate"],
                  n_sel(recs, MAIN)),
        delta_row("Chọn đúng vật — phản thực (P4+P5+P6)",
                  s5["counterfactual"]["selection_rate"],
                  s30["counterfactual"]["selection_rate"],
                  n_sel(recs, CF)),
        delta_row("Grasp sai — phản thực",
                  s5["counterfactual"]["grasp_wrong_rate"],
                  s30["counterfactual"]["grasp_wrong_rate"],
                  s30["counterfactual"]["n"]),
        delta_row("Success — phản thực",
                  s5["counterfactual"]["success_rate"],
                  s30["counterfactual"]["success_rate"],
                  s30["counterfactual"]["n"]),
        delta_row("Recall@1 correspondence — can thiệp (480 scene)",
                  corr5["recall@1_intervention"],
                  corr30["recall@1_intervention"], 320),
        delta_row("Recall@1 correspondence — mọi scene",
                  corr5["recall@1_all"], corr30["recall@1_all"], 480),
    ]
    for c in CONDS:
        if c in s30["by_cond"] and c in s5["by_cond"]:
            rows.append(delta_row(
                f"Success — {c}", s5["by_cond"][c]["success_rate"],
                s30["by_cond"][c]["success_rate"],
                s30["by_cond"][c]["n"]))

    grasp_gain_vs_r2 = round(
        s30["main"]["grasp_correct_rate"]
        - s2["main"]["grasp_correct_rate"], 4)
    grasp_gain_vs_5k = round(
        s30["main"]["grasp_correct_rate"]
        - s5["main"]["grasp_correct_rate"], 4)
    gate = {
        "recall@1_intervention>=0.80": bool(
            corr30["recall@1_intervention"] is not None
            and corr30["recall@1_intervention"] >= 0.80),
        "recall@1_intervention": corr30["recall@1_intervention"],
        "selection_counterfactual>=0.80": bool(
            s30["counterfactual"]["selection_rate"] is not None
            and s30["counterfactual"]["selection_rate"] >= 0.80),
        "selection_counterfactual":
            s30["counterfactual"]["selection_rate"],
        "wrong_grasp_counterfactual<0.10": bool(
            s30["counterfactual"]["grasp_wrong_rate"] is not None
            and s30["counterfactual"]["grasp_wrong_rate"] < 0.10),
        "wrong_grasp_counterfactual":
            s30["counterfactual"]["grasp_wrong_rate"],
        "grasp_gain_vs_R2>=+0.15": bool(grasp_gain_vs_r2 >= 0.15),
        "grasp_gain_vs_R2": grasp_gain_vs_r2,
        "grasp_gain_vs_R6_5k": grasp_gain_vs_5k,
    }
    gate_pass = all(v for k, v in gate.items()
                    if k.endswith("0.80") or k.endswith("0.10")
                    or k.endswith("+0.15"))
    out = {"arm": "r6", "n_30k": s30["n"],
           "n_infeasible_30k": s30["n_infeasible"],
           "stats_30k": s30, "corr_30k": corr30,
           "rows": rows, "gate_r6_30k": gate,
           "gate_object_grounding_pass": gate_pass}
    (RES / "df_r6_30k_compare.json").write_text(
        json.dumps(out, indent=1, ensure_ascii=False))
    merge_item("data_factory.r6_30k_compare", {
        "status": "done", "rows": rows, "gate": gate,
        "gate_pass": gate_pass})
    print(json.dumps({"rows": rows, "gate": gate,
                      "gate_pass": gate_pass}, indent=1,
                     ensure_ascii=False))


if __name__ == "__main__":
    main()