File size: 25,573 Bytes
3404d44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
#!/usr/bin/env python3
"""Extract metrics from JSON files and display as a table.

Columns:
  1. Peak consistency - horizontal
  2. Peak consistency - vertical
  3. Peak consistency - distance
  4. Entanglement Layer (fixed layer per model family)
  5. Layer Horiz SC (Sign-corrected consistency at fixed layer)
  6. Layer Vert SC (Sign-corrected consistency at fixed layer)
  7. Layer Dist SC (Sign-corrected consistency at fixed layer)
  8. VD-Entanglement (at fixed layer per model family)
  9. EmbSpatial Accuracy - consistent
  10. EmbSpatial Accuracy - counter
  11. CV-Bench-3D Accuracy - consistent
  12. CV-Bench-3D Accuracy - counter
"""

import argparse
import json
import re
from pathlib import Path

import numpy as np
import pandas as pd

# ---------------------------------------------------------------------------
# Display name and text-file model name mappings
# ---------------------------------------------------------------------------

DISPLAY_NAMES = {
    ("molmo", "vanilla"):          "Molmo vanilla",
    ("molmo", "80k"):              "Molmo 80k",
    ("molmo", "400k"):             "Molmo 400k",
    ("molmo", "800k"):             "Molmo 800k",
    ("molmo", "2m"):               "Molmo 2M",
    ("nvila", "vanilla"):          "NVILA vanilla",
    ("nvila", "80k"):              "NVILA 80k",
    ("nvila", "400k"):             "NVILA 400k",
    ("nvila", "800k"):             "NVILA 800k",
    ("nvila", "2m"):               "NVILA 2M",
    ("nvila", "roborefer"):        "RoboRefer",
    ("nvila_synthetic", "10pct"):  "NVILA 10pct",
    ("nvila_synthetic", "20pct"):  "NVILA 20pct",
    ("nvila_synthetic", "30pct"):  "NVILA 30pct",
    ("qwen", "vanilla"):           "Qwen vanilla",
    ("qwen", "80k"):               "Qwen 80k",
    ("qwen", "400k"):              "Qwen 400k",
    ("qwen", "800k"):              "Qwen 800k",
    ("qwen", "2m"):                "Qwen 2M",
    ("qwen_super", "qwen3_235b"):  "Qwen3-235B",
}

TEXT_FILE_MODEL_NAMES = {
    ("molmo", "vanilla"):   "molmo-7B-O-0924",
    ("molmo", "80k"):       "molmo-7B-O-0924-data_scale_exp_80k",
    ("molmo", "400k"):      "molmo-7B-O-0924-data_scale_exp_400k",
    ("molmo", "800k"):      "molmo-7B-O-0924-data_scale_exp_800k",
    ("molmo", "2m"):        "molmo-7B-O-0924-data_scale_exp_2m",
    ("nvila", "vanilla"):   "NVILA-Lite-2B",
    ("nvila", "80k"):       "NVILA-Lite-2B-data-scale-exp-80k",
    ("nvila", "400k"):      "NVILA-Lite-2B-data-scale-exp-400k",
    ("nvila", "800k"):      "NVILA-Lite-2B-data-scale-exp-800k",
    ("nvila", "2m"):        "NVILA-Lite-2B-data-scale-exp-2m",
    ("nvila", "roborefer"): "RoboRefer-2B-SFT",
    ("qwen", "vanilla"):    "Qwen2.5-VL-3B-Instruct",
    ("qwen", "80k"):        "Qwen2.5-VL-3B-Instruct-data_scale_exp_80k",
    ("qwen", "400k"):       "Qwen2.5-VL-3B-Instruct-data_scale_exp_400k",
    ("qwen", "800k"):       "Qwen2.5-VL-3B-Instruct-data_scale_exp_800k",
    ("qwen", "2m"):         "Qwen2.5-VL-3B-Instruct-data_scale_exp_2m",
    ("qwen_super", "qwen3_235b"): "Qwen3-VL-235B-A22B-Instruct",
}

FOLDER_ORDER = ["molmo", "nvila", "nvila_synthetic", "qwen", "qwen_super"]
SCALE_ORDER  = ["vanilla", "roborefer", "10pct", "20pct", "30pct", "80k", "400k", "800k", "2m",
                "qwen3_235b"]

# Fixed layer index used for entanglement per model family
FOLDER_TARGET_LAYER = {
    "molmo":           23,
    "nvila":           20,
    "nvila_synthetic": 20,   # same architecture as nvila
    "qwen":            27,
    "qwen_super":      87,   # Qwen3-VL-235B-A22B-Instruct
}

# Default extra model-family directories included in every run
_SWAP_ANALYSIS = Path("/data/shared/Qwen/experiments/swap_analysis")
DEFAULT_EXTRA_DIRS = [
    _SWAP_ANALYSIS / "results_0223" / "qwen_super",
]

# ---------------------------------------------------------------------------
# JSON helpers
# ---------------------------------------------------------------------------

def get_peak_consistency(json_file: Path) -> dict:
    """Return peak mean value per dimension (horizontal/vertical/distance)."""
    with open(json_file) as f:
        data = json.load(f)
    result = {}
    for dim in ("horizontal", "vertical", "distance"):
        vals = [v["mean"] for k, v in data.items() if k.startswith(f"{dim}_L")]
        result[dim] = max(vals) if vals else None
    return result


def get_layer_consistency(json_file: Path, layer: int) -> dict:
    """Sign-corrected consistency for horiz/vert/dist at a specific layer."""
    with open(json_file) as f:
        data = json.load(f)
    result = {}
    for dim in ("horizontal", "vertical", "distance"):
        key = f"{dim}_L{layer}"
        result[dim] = data[key]["mean"] if key in data else None
    return result


def _loc(df: pd.DataFrame, row: str, col: str) -> float:
    """Look up (row, col) with 'under' <-> 'below' aliasing."""
    aliases = {"below": "under", "under": "below"}
    r = row if row in df.index   else aliases.get(row, row)
    c = col if col in df.columns else aliases.get(col, col)
    if r not in df.index or c not in df.columns:
        return float("nan")
    return float(df.loc[r, c])


def get_vd_entanglement(csv_dir: Path, scale: str, layer: int) -> float | None:
    """Return VD-entanglement from delta_similarity_{scale}_L{layer}_all_pairs.csv.

    VD = (mean(above-far, below-close) - mean(above-close, below-far)) / 4
    """
    csv_file = csv_dir / f"delta_similarity_{scale}_L{layer}_all_pairs.csv"
    if not csv_file.exists():
        return None
    df = pd.read_csv(csv_file, index_col=0)
    vd = (
        _loc(df, "above", "far")   + _loc(df, "below", "close")
      - _loc(df, "above", "close") - _loc(df, "below", "far")
    ) / 4
    return float(vd) if np.isfinite(vd) else None


# ---------------------------------------------------------------------------
# Text file parser
# ---------------------------------------------------------------------------

def parse_accuracy_text(text_file: Path) -> dict:
    """Parse per-model TOTAL consistent/counter accuracies from a results text file.

    Returns:
        dict mapping model_name -> {"consistent": float, "counter": float}
    """
    content = text_file.read_text()
    # Split on section headers like  "Model: <name>"
    sections = re.split(r"={10,}\s*\nModel:\s*", content)
    result = {}
    for section in sections[1:]:
        lines = section.splitlines()
        model_name = lines[0].strip()
        consistent = counter = None
        for line in lines:
            m = re.match(r"\s*TOTAL\s+consistent\s+(\d+)\s+(\d+)\s+([\d.]+)%", line)
            if m:
                consistent = float(m.group(3))
            m = re.match(r"\s*TOTAL\s+counter\s+(\d+)\s+(\d+)\s+([\d.]+)%", line)
            if m:
                counter = float(m.group(3))
        if model_name:
            result[model_name] = {"consistent": consistent, "counter": counter}
    return result


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def fmt(val, fmt_str=".4f", suffix=""):
    return f"{val:{fmt_str}}{suffix}" if val is not None else "N/A"


def main():
    parser = argparse.ArgumentParser(description="Summarize metrics from JSON result files.")
    parser.add_argument(
        "folder",
        nargs="?",
        default="/data/shared/Qwen/experiments/swap_analysis/results_short_answer",
        help="Root folder whose subdirectories are each treated as a model family",
    )
    parser.add_argument(
        "--extra-dirs", "-e",
        nargs="+",
        metavar="DIR",
        default=[],
        help="Additional individual model-family directories to include "
             "(each dir's basename is used as the folder name)",
    )
    parser.add_argument(
        "--no-defaults",
        action="store_true",
        help="Do not automatically include the built-in extra directories (e.g. qwen_super)",
    )
    args = parser.parse_args()

    root    = Path(args.folder)
    exp_dir = Path("/data/shared/Qwen/experiments")

    # Collect model-family directories to scan:
    #   1. All subdirectories of the root folder
    #   2. Built-in defaults (e.g. qwen_super) unless --no-defaults
    #   3. Any explicitly provided --extra-dirs
    model_dirs: list[Path] = [d for d in sorted(root.iterdir()) if d.is_dir()]

    extra = [] if args.no_defaults else [d for d in DEFAULT_EXTRA_DIRS if d.is_dir()]
    extra += [Path(d) for d in args.extra_dirs]
    # Avoid duplicates (same resolved path)
    seen = {d.resolve() for d in model_dirs}
    for d in extra:
        if d.resolve() not in seen:
            model_dirs.append(d)
            seen.add(d.resolve())

    # Parse text-file accuracies
    embspatial = parse_accuracy_text(exp_dir / "counter_consistent_results_embspatial.txt")
    cvbench3d  = parse_accuracy_text(exp_dir / "counter_consistent_result_cvbench3d_depth.txt")

    rows = []
    for folder_dir in model_dirs:
        if not folder_dir.is_dir():
            continue
        folder_name = folder_dir.name

        # Find all sign_corrected_consistency_*_all_pairs.json under this folder
        for json_file in sorted(folder_dir.rglob("sign_corrected_consistency_*_all_pairs.json")):
            m = re.match(r"sign_corrected_consistency_(.+)_all_pairs\.json", json_file.name)
            if not m:
                continue
            scale = m.group(1)
            key   = (folder_name, scale)
            display = DISPLAY_NAMES.get(key, f"{folder_name} {scale}")

            # 1-3: Peak consistency
            consistency = get_peak_consistency(json_file)

            # 4: Layer values and VD-Entanglement at the fixed layer for this model family
            target_layer = FOLDER_TARGET_LAYER.get(folder_name)
            csv_dir = json_file.parent.parent / "csv"

            layer_sc = (
                get_layer_consistency(json_file, target_layer)
                if target_layer is not None
                else {"horizontal": None, "vertical": None, "distance": None}
            )

            vd_entanglement = (
                get_vd_entanglement(csv_dir, scale, target_layer)
                if (target_layer is not None and csv_dir.is_dir())
                else None
            )

            # 5-8: Text-file accuracies
            text_model = TEXT_FILE_MODEL_NAMES.get(key)
            emb_con = emb_ctr = cvb_con = cvb_ctr = None
            if text_model:
                if text_model in embspatial:
                    emb_con = embspatial[text_model]["consistent"]
                    emb_ctr = embspatial[text_model]["counter"]
                if text_model in cvbench3d:
                    cvb_con = cvbench3d[text_model]["consistent"]
                    cvb_ctr = cvbench3d[text_model]["counter"]

            rows.append(dict(
                folder=folder_name, scale=scale, display=display,
                peak_horiz=consistency.get("horizontal"),
                peak_vert=consistency.get("vertical"),
                peak_dist=consistency.get("distance"),
                layer_horiz=layer_sc["horizontal"],
                layer_vert=layer_sc["vertical"],
                layer_dist=layer_sc["distance"],
                vd_entanglement=vd_entanglement,
                emb_con=emb_con, emb_ctr=emb_ctr,
                cvb_con=cvb_con, cvb_ctr=cvb_ctr,
            ))

    # Sort by model family then scale
    def sort_key(r):
        fi = FOLDER_ORDER.index(r["folder"]) if r["folder"] in FOLDER_ORDER else 99
        si = SCALE_ORDER.index(r["scale"])   if r["scale"]  in SCALE_ORDER  else 99
        return (fi, si)

    rows.sort(key=sort_key)

    # Build table records
    records = []
    for r in rows:
        layer = FOLDER_TARGET_LAYER.get(r["folder"], "?")
        records.append({
            "Model":                r["display"],
            "Peak Horiz":           fmt(r["peak_horiz"]),
            "Peak Vert":            fmt(r["peak_vert"]),
            "Peak Dist":            fmt(r["peak_dist"]),
            "Entanglement Layer":   str(layer),
            "Layer Horiz SC":       fmt(r["layer_horiz"]),
            "Layer Vert SC":        fmt(r["layer_vert"]),
            "Layer Dist SC":        fmt(r["layer_dist"]),
            "Entanglement":         fmt(r["vd_entanglement"]),
            "EmbSpatial (con)":     fmt(r["emb_con"],  ".1f", "%"),
            "EmbSpatial (ctr)":     fmt(r["emb_ctr"],  ".1f", "%"),
            "CVBench3D (con)":      fmt(r["cvb_con"],  ".1f", "%"),
            "CVBench3D (ctr)":      fmt(r["cvb_ctr"],  ".1f", "%"),
        })

    if not records:
        print("No data found.")
        return

    df = pd.DataFrame(records)
    print(df.to_string(index=False))

    # Save to CSV: experiments/summarize_metrics/{parent_name}/{folder_name}.csv
    csv_rel = Path(root.parent.name) / (root.name + ".csv")
    csv_path = exp_dir / "summarize_metrics" / csv_rel
    csv_path.parent.mkdir(parents=True, exist_ok=True)
    df.to_csv(csv_path, index=False)
    print(f"\nSaved: {csv_path}")


if __name__ == "__main__":
    main()







































# #!/usr/bin/env python3
# """Extract metrics from JSON files and display as a table.

# Columns:
#   1. Peak consistency - horizontal
#   2. Peak consistency - vertical
#   3. Peak consistency - distance
#   4. VD-Entanglement  (at fixed layer per model family)
#   5. EmbSpatial Accuracy - consistent
#   6. EmbSpatial Accuracy - counter
#   7. CV-Bench-3D Accuracy - consistent
#   8. CV-Bench-3D Accuracy - counter
# """

# import argparse
# import json
# import re
# from pathlib import Path

# import numpy as np
# import pandas as pd

# # ---------------------------------------------------------------------------
# # Display name and text-file model name mappings
# # ---------------------------------------------------------------------------

# DISPLAY_NAMES = {
#     ("molmo", "vanilla"):          "Molmo vanilla",
#     ("molmo", "80k"):              "Molmo 80k",
#     ("molmo", "400k"):             "Molmo 400k",
#     ("molmo", "800k"):             "Molmo 800k",
#     ("molmo", "2m"):               "Molmo 2M",
#     ("nvila", "vanilla"):          "NVILA vanilla",
#     ("nvila", "80k"):              "NVILA 80k",
#     ("nvila", "400k"):             "NVILA 400k",
#     ("nvila", "800k"):             "NVILA 800k",
#     ("nvila", "2m"):               "NVILA 2M",
#     ("nvila", "roborefer"):        "RoboRefer",
#     ("nvila_synthetic", "10pct"):  "NVILA 10pct",
#     ("nvila_synthetic", "20pct"):  "NVILA 20pct",
#     ("nvila_synthetic", "30pct"):  "NVILA 30pct",
#     ("qwen", "vanilla"):           "Qwen vanilla",
#     ("qwen", "80k"):               "Qwen 80k",
#     ("qwen", "400k"):              "Qwen 400k",
#     ("qwen", "800k"):              "Qwen 800k",
#     ("qwen", "2m"):                "Qwen 2M",
#     ("qwen_super", "qwen3_235b"):  "Qwen3-235B",
# }

# TEXT_FILE_MODEL_NAMES = {
#     ("molmo", "vanilla"):   "molmo-7B-O-0924",
#     ("molmo", "80k"):       "molmo-7B-O-0924-data_scale_exp_80k",
#     ("molmo", "400k"):      "molmo-7B-O-0924-data_scale_exp_400k",
#     ("molmo", "800k"):      "molmo-7B-O-0924-data_scale_exp_800k",
#     ("molmo", "2m"):        "molmo-7B-O-0924-data_scale_exp_2m",
#     ("nvila", "vanilla"):   "NVILA-Lite-2B",
#     ("nvila", "80k"):       "NVILA-Lite-2B-data-scale-exp-80k",
#     ("nvila", "400k"):      "NVILA-Lite-2B-data-scale-exp-400k",
#     ("nvila", "800k"):      "NVILA-Lite-2B-data-scale-exp-800k",
#     ("nvila", "2m"):        "NVILA-Lite-2B-data-scale-exp-2m",
#     ("nvila", "roborefer"): "RoboRefer-2B-SFT",
#     ("qwen", "vanilla"):    "Qwen2.5-VL-3B-Instruct",
#     ("qwen", "80k"):        "Qwen2.5-VL-3B-Instruct-data_scale_exp_80k",
#     ("qwen", "400k"):       "Qwen2.5-VL-3B-Instruct-data_scale_exp_400k",
#     ("qwen", "800k"):       "Qwen2.5-VL-3B-Instruct-data_scale_exp_800k",
#     ("qwen", "2m"):         "Qwen2.5-VL-3B-Instruct-data_scale_exp_2m",
#     ("qwen_super", "qwen3_235b"): "Qwen3-VL-235B-A22B-Instruct",
# }

# FOLDER_ORDER = ["molmo", "nvila", "nvila_synthetic", "qwen", "qwen_super"]
# SCALE_ORDER  = ["vanilla", "roborefer", "10pct", "20pct", "30pct", "80k", "400k", "800k", "2m",
#                 "qwen3_235b"]

# # Fixed layer index used for entanglement per model family
# FOLDER_TARGET_LAYER = {
#     "molmo":           23,
#     "nvila":           20,
#     "nvila_synthetic": 20,   # same architecture as nvila
#     "qwen":            27,
#     "qwen_super":      87,   # Qwen3-VL-235B-A22B-Instruct
# }

# # Default extra model-family directories included in every run
# _SWAP_ANALYSIS = Path("/data/shared/Qwen/experiments/swap_analysis")
# DEFAULT_EXTRA_DIRS = [
#     _SWAP_ANALYSIS / "results_0223" / "qwen_super",
# ]

# # ---------------------------------------------------------------------------
# # JSON helpers
# # ---------------------------------------------------------------------------

# def get_peak_consistency(json_file: Path) -> dict:
#     """Return peak mean value per dimension (horizontal/vertical/distance)."""
#     with open(json_file) as f:
#         data = json.load(f)
#     result = {}
#     for dim in ("horizontal", "vertical", "distance"):
#         vals = [v["mean"] for k, v in data.items() if k.startswith(f"{dim}_L")]
#         result[dim] = max(vals) if vals else None
#     return result


# def _loc(df: pd.DataFrame, row: str, col: str) -> float:
#     """Look up (row, col) with 'under' <-> 'below' aliasing."""
#     aliases = {"below": "under", "under": "below"}
#     r = row if row in df.index   else aliases.get(row, row)
#     c = col if col in df.columns else aliases.get(col, col)
#     if r not in df.index or c not in df.columns:
#         return float("nan")
#     return float(df.loc[r, c])


# def get_vd_entanglement(csv_dir: Path, scale: str, layer: int) -> float | None:
#     """Return VD-entanglement from delta_similarity_{scale}_L{layer}_all_pairs.csv.

#     VD = (mean(above-far, below-close) - mean(above-close, below-far)) / 4
#     """
#     csv_file = csv_dir / f"delta_similarity_{scale}_L{layer}_all_pairs.csv"
#     if not csv_file.exists():
#         return None
#     df = pd.read_csv(csv_file, index_col=0)
#     vd = (
#         _loc(df, "above", "far")   + _loc(df, "below", "close")
#       - _loc(df, "above", "close") - _loc(df, "below", "far")
#     ) / 4
#     return float(vd) if np.isfinite(vd) else None


# # ---------------------------------------------------------------------------
# # Text file parser
# # ---------------------------------------------------------------------------

# def parse_accuracy_text(text_file: Path) -> dict:
#     """Parse per-model TOTAL consistent/counter accuracies from a results text file.

#     Returns:
#         dict mapping model_name -> {"consistent": float, "counter": float}
#     """
#     content = text_file.read_text()
#     # Split on section headers like  "Model: <name>"
#     sections = re.split(r"={10,}\s*\nModel:\s*", content)
#     result = {}
#     for section in sections[1:]:
#         lines = section.splitlines()
#         model_name = lines[0].strip()
#         consistent = counter = None
#         for line in lines:
#             m = re.match(r"\s*TOTAL\s+consistent\s+(\d+)\s+(\d+)\s+([\d.]+)%", line)
#             if m:
#                 consistent = float(m.group(3))
#             m = re.match(r"\s*TOTAL\s+counter\s+(\d+)\s+(\d+)\s+([\d.]+)%", line)
#             if m:
#                 counter = float(m.group(3))
#         if model_name:
#             result[model_name] = {"consistent": consistent, "counter": counter}
#     return result


# # ---------------------------------------------------------------------------
# # Main
# # ---------------------------------------------------------------------------

# def fmt(val, fmt_str=".4f", suffix=""):
#     return f"{val:{fmt_str}}{suffix}" if val is not None else "N/A"


# def main():
#     parser = argparse.ArgumentParser(description="Summarize metrics from JSON result files.")
#     parser.add_argument(
#         "folder",
#         nargs="?",
#         default="/data/shared/Qwen/experiments/swap_analysis/results_short_answer",
#         help="Root folder whose subdirectories are each treated as a model family",
#     )
#     parser.add_argument(
#         "--extra-dirs", "-e",
#         nargs="+",
#         metavar="DIR",
#         default=[],
#         help="Additional individual model-family directories to include "
#              "(each dir's basename is used as the folder name)",
#     )
#     parser.add_argument(
#         "--no-defaults",
#         action="store_true",
#         help="Do not automatically include the built-in extra directories (e.g. qwen_super)",
#     )
#     args = parser.parse_args()

#     root    = Path(args.folder)
#     exp_dir = Path("/data/shared/Qwen/experiments")

#     # Collect model-family directories to scan:
#     #   1. All subdirectories of the root folder
#     #   2. Built-in defaults (e.g. qwen_super) unless --no-defaults
#     #   3. Any explicitly provided --extra-dirs
#     model_dirs: list[Path] = [d for d in sorted(root.iterdir()) if d.is_dir()]

#     extra = [] if args.no_defaults else [d for d in DEFAULT_EXTRA_DIRS if d.is_dir()]
#     extra += [Path(d) for d in args.extra_dirs]
#     # Avoid duplicates (same resolved path)
#     seen = {d.resolve() for d in model_dirs}
#     for d in extra:
#         if d.resolve() not in seen:
#             model_dirs.append(d)
#             seen.add(d.resolve())

#     # Parse text-file accuracies
#     embspatial = parse_accuracy_text(exp_dir / "counter_consistent_results_embspatial.txt")
#     cvbench3d  = parse_accuracy_text(exp_dir / "counter_consistent_result_cvbench3d_depth.txt")

#     rows = []
#     for folder_dir in model_dirs:
#         if not folder_dir.is_dir():
#             continue
#         folder_name = folder_dir.name

#         # Find all sign_corrected_consistency_*_all_pairs.json under this folder
#         for json_file in sorted(folder_dir.rglob("sign_corrected_consistency_*_all_pairs.json")):
#             m = re.match(r"sign_corrected_consistency_(.+)_all_pairs\.json", json_file.name)
#             if not m:
#                 continue
#             scale = m.group(1)
#             key   = (folder_name, scale)
#             display = DISPLAY_NAMES.get(key, f"{folder_name} {scale}")

#             # 1-3: Peak consistency
#             consistency = get_peak_consistency(json_file)

#             # 4: VD-Entanglement at the fixed layer for this model family
#             target_layer = FOLDER_TARGET_LAYER.get(folder_name)
#             csv_dir = json_file.parent.parent / "csv"
#             vd_entanglement = (
#                 get_vd_entanglement(csv_dir, scale, target_layer)
#                 if (target_layer is not None and csv_dir.is_dir())
#                 else None
#             )

#             # 5-8: Text-file accuracies
#             text_model = TEXT_FILE_MODEL_NAMES.get(key)
#             emb_con = emb_ctr = cvb_con = cvb_ctr = None
#             if text_model:
#                 if text_model in embspatial:
#                     emb_con = embspatial[text_model]["consistent"]
#                     emb_ctr = embspatial[text_model]["counter"]
#                 if text_model in cvbench3d:
#                     cvb_con = cvbench3d[text_model]["consistent"]
#                     cvb_ctr = cvbench3d[text_model]["counter"]

#             rows.append(dict(
#                 folder=folder_name, scale=scale, display=display,
#                 peak_horiz=consistency.get("horizontal"),
#                 peak_vert=consistency.get("vertical"),
#                 peak_dist=consistency.get("distance"),
#                 vd_entanglement=vd_entanglement,
#                 emb_con=emb_con, emb_ctr=emb_ctr,
#                 cvb_con=cvb_con, cvb_ctr=cvb_ctr,
#             ))

#     # Sort by model family then scale
#     def sort_key(r):
#         fi = FOLDER_ORDER.index(r["folder"]) if r["folder"] in FOLDER_ORDER else 99
#         si = SCALE_ORDER.index(r["scale"])   if r["scale"]  in SCALE_ORDER  else 99
#         return (fi, si)

#     rows.sort(key=sort_key)

#     # Build table records
#     records = []
#     for r in rows:
#         layer = FOLDER_TARGET_LAYER.get(r["folder"], "?")
#         records.append({
#             "Model":                r["display"],
#             "Peak Horiz":           fmt(r["peak_horiz"]),
#             "Peak Vert":            fmt(r["peak_vert"]),
#             "Peak Dist":            fmt(r["peak_dist"]),
#             "Entanglement Layer":   str(layer),
#             "Entanglement":         fmt(r["vd_entanglement"]),
#             "EmbSpatial (con)":     fmt(r["emb_con"],  ".1f", "%"),
#             "EmbSpatial (ctr)":     fmt(r["emb_ctr"],  ".1f", "%"),
#             "CVBench3D (con)":      fmt(r["cvb_con"],  ".1f", "%"),
#             "CVBench3D (ctr)":      fmt(r["cvb_ctr"],  ".1f", "%"),
#         })

#     if not records:
#         print("No data found.")
#         return

#     df = pd.DataFrame(records)
#     print(df.to_string(index=False))

#     # Save to CSV: experiments/summarize_metrics/{parent_name}/{folder_name}.csv
#     csv_rel = Path(root.parent.name) / (root.name + ".csv")
#     csv_path = exp_dir / "summarize_metrics" / csv_rel
#     csv_path.parent.mkdir(parents=True, exist_ok=True)
#     df.to_csv(csv_path, index=False)
#     print(f"\nSaved: {csv_path}")


# if __name__ == "__main__":
#     main()