File size: 8,867 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
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env python3
"""Data Factory — aggregate the matched eval (Phase C) and verdicts.

Reads results/df_eval_<arm>.jsonl for r0..r4 plus
results/df_corr_eval.json (standalone correspondence). Computes,
per arm and per condition, the spec 15.2 metrics kept separate;
the Gate Object Grounding checks of spec XV.3; and the mandatory
separation of gains: data gain (R1-R0, R2-R1) vs architecture
gain (R3-R2, R4-R2). Writes results/df_eval_summary.json and the
dashboard verdict cards.
"""
import json
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"
ARMS = ["r0", "r1", "r2", "r3", "r5", "r6"]
CONDS = ["P0", "P1", "P2", "P3", "P4", "P5", "P6"]
CF = ["P4", "P5", "P6"]          # counterfactual selection suite
MAIN = ["P0", "P1", "P2", "P3", "P4", "P5"]


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


def main():
    stats = {}
    for arm in ARMS:
        f = RES / f"df_eval_{arm}.jsonl"
        if not f.exists():
            continue
        recs = [json.loads(x) for x in f.read_text().splitlines()
                if x.strip()]
        stats[arm] = arm_stats(recs)
    corr = {}
    cf_path = RES / "df_corr_eval.json"
    if cf_path.exists():
        corr = json.loads(cf_path.read_text())

    def diff(a, b, section, key):
        if a in stats and b in stats:
            va, vb = stats[a][section][key], stats[b][section][key]
            if va is not None and vb is not None:
                return round(va - vb, 4)
        return None

    gains = {
        "data_R1_minus_R0": {
            "success_main": diff("r1", "r0", "main", "success_rate"),
            "grasp_correct_main": diff("r1", "r0", "main",
                                       "grasp_correct_rate")},
        "data_R2_minus_R1": {
            "success_main": diff("r2", "r1", "main", "success_rate"),
            "grasp_correct_main": diff("r2", "r1", "main",
                                       "grasp_correct_rate")},
        "arch_R3_minus_R2": {
            "success_main": diff("r3", "r2", "main", "success_rate"),
            "grasp_correct_main": diff("r3", "r2", "main",
                                       "grasp_correct_rate")},
        "spec_R5_minus_R3": {
            "success_main": diff("r5", "r3", "main", "success_rate"),
            "grasp_correct_main": diff("r5", "r3", "main",
                                       "grasp_correct_rate")},
        "optional_R6_minus_R5": {
            "success_main": diff("r6", "r5", "main", "success_rate"),
            "grasp_correct_main": diff("r6", "r5", "main",
                                       "grasp_correct_rate")},
    }
    gate = {}
    gain_key = {"r3": "arch_R3_minus_R2", "r5": "spec_R5_minus_R3",
                "r6": "optional_R6_minus_R5"}
    gain_ref = {"r3": "R2", "r5": "R3", "r6": "R5"}
    for arm in ("r3", "r5", "r6"):
        g = {}
        if arm in corr:
            g["recall@1_intervention>=0.80"] = bool(
                corr[arm]["recall@1_intervention"] is not None
                and corr[arm]["recall@1_intervention"] >= 0.80)
            g["recall@1_intervention"] = corr[arm][
                "recall@1_intervention"]
        if arm in stats:
            sel = stats[arm]["counterfactual"]["selection_rate"]
            wr = stats[arm]["counterfactual"]["grasp_wrong_rate"]
            g["selection_counterfactual>=0.80"] = bool(
                sel is not None and sel >= 0.80)
            g["selection_counterfactual"] = sel
            g["wrong_grasp_counterfactual<0.10"] = bool(
                wr is not None and wr < 0.10)
            g["wrong_grasp_counterfactual"] = wr
            gg = gains[gain_key[arm]]["grasp_correct_main"]
            g[f"grasp_gain_vs_{gain_ref[arm]}>=+0.15"] = bool(
                gg is not None and gg >= 0.15)
            g[f"grasp_gain_vs_{gain_ref[arm]}"] = gg
        gate[arm] = g
    summary = {"arms": stats, "correspondence": corr,
               "gains": gains, "gate_object_grounding": gate}
    (RES / "df_eval_summary.json").write_text(
        json.dumps(summary, indent=1))

    def pct(x):
        return "—" if x is None else f"{100 * x:.1f}%"
    lines = []
    for arm in ARMS:
        if arm not in stats:
            continue
        m, c = stats[arm]["main"], stats[arm]["counterfactual"]
        lines.append(
            f"{arm.upper()}: success {pct(m['success_rate'])}, "
            f"grasp đúng {pct(m['grasp_correct_rate'])}, "
            f"chọn đúng (CF) {pct(c['selection_rate'])}, "
            f"grasp sai (CF) {pct(c['grasp_wrong_rate'])}")
    merge_item("data_factory.eval_summary", {
        "status": "done",
        "verdict": " · ".join(lines),
        "metrics": {
            "Gain dữ liệu R1-R0 (success)": str(
                gains["data_R1_minus_R0"]["success_main"]),
            "Gain dữ liệu R2-R1 (success)": str(
                gains["data_R2_minus_R1"]["success_main"]),
            "Gain kiến trúc R3-R2 (success)": str(
                gains["arch_R3_minus_R2"]["success_main"]),
            "Gain trung thực spec R5-R3 (success)": str(
                gains["spec_R5_minus_R3"]["success_main"]),
            "Gain module tuỳ chọn R6-R5 (success)": str(
                gains["optional_R6_minus_R5"]["success_main"])}})
    g3 = gate.get("r3", {})
    complete = len(stats) == len(ARMS) and bool(corr)
    if complete:
        merge_item("data_factory.final", {
            "status": "done",
            "verdict": (
                f"Gate Object Grounding R3: Recall@1 "
                f"{g3.get('recall@1_intervention')} (≥0,80: "
                f"{g3.get('recall@1_intervention>=0.80')}); chọn đúng CF "
                f"{g3.get('selection_counterfactual')} (≥0,80: "
                f"{g3.get('selection_counterfactual>=0.80')}); grasp sai "
                f"CF {g3.get('wrong_grasp_counterfactual')} (<0,10: "
                f"{g3.get('wrong_grasp_counterfactual<0.10')}); gain grasp "
                f"vs R2 {g3.get('grasp_gain_vs_R2')} (≥+0,15: "
                f"{g3.get('grasp_gain_vs_R2>=+0.15')}) · Gain spec R5-R3 "
                f"(success) {gains['spec_R5_minus_R3']['success_main']} · "
                f"Gain tuỳ chọn R6-R5 (success) "
                f"{gains['optional_R6_minus_R5']['success_main']}")})
    else:
        merge_item("data_factory.final", {
            "status": "running",
            "verdict": (
                "Gate Object Grounding: đang chờ đủ eval — đã xong "
                + (", ".join(sorted(stats)) or "chưa arm nào")
                + ("; đã có correspondence." if corr else
                   "; chưa có correspondence."))})
    print(json.dumps(summary, indent=1))


if __name__ == "__main__":
    main()