File size: 24,365 Bytes
6e9cb06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SIFQ Evaluation Runner β€” SOTA verification across 4 Tracks.

Requires:
  - scores_sifq.jsonl  : output of run_infer.py (SIFQ Q scores)
  - MDGT checkpoint    : for computing genuine/impostor match scores (Track 1)
  - scipy, matplotlib  : for plots and KS tests

Outputs (saved to --out-dir):
  - results_track1_erc.json     : AUC_ERC table (SIFQ vs random baseline)
  - results_track2_sensor.json  : KS statistics per sensor pair
  - results_track4_concepts.json: Spearman rho crosstalk matrix
  - plot_erc.png                : ERC curve
  - plot_sensor_hist.png        : Q distribution per sensor
  - plot_crosstalk.png          : concept grounding heatmap

NFIQ2 baseline: pass --nfiq2-scores path/to/nfiq2.jsonl (same format as SIFQ
scores but generated externally via `nfiq2 --path ...`).

Usage:
  python scripts/run_eval.py \\
      --sifq-scores /tmp/sifq_scores.jsonl \\
      --mdgt-checkpoint pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt \\
      --out-dir eval_results/
"""
from __future__ import annotations

import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path
from itertools import combinations

import numpy as np
import torch
import torch.nn.functional as F
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parents[1]
SRC_ROOT = ROOT / "src"
if str(SRC_ROOT) not in sys.path:
    sys.path.insert(0, str(SRC_ROOT))

from evaluation.erc import compute_erc
from evaluation.sensor_invariance import sensor_ks_test, cross_sensor_correlation
from training.mdgt_teacher import MDGTCheckpointTeacher


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def load_scores(jsonl_path: str) -> list[dict]:
    rows = []
    with open(jsonl_path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def build_match_scores(
    rows: list[dict],
    mdgt: MDGTCheckpointTeacher,
    device: torch.device,
    image_size: int = 224,
    max_pairs: int = 5000,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Compute genuine and impostor match scores via MDGT cosine similarity.

    Returns:
        quality_scores : [N]  SIFQ Q scores for each pair member (mean of pair)
        match_scores   : [N]  MDGT cosine similarity
        labels         : [N]  1=genuine, 0=impostor
    """
    from PIL import Image
    from torchvision import transforms

    tf = transforms.Compose([
        transforms.Resize((image_size, image_size)),
        transforms.ToTensor(),
    ])

    # Build embedding cache
    print("  Computing MDGT embeddings for match scores...")
    paths = [r["image_path"] for r in rows]
    emb_list: list[torch.Tensor] = []
    batch_paths: list[str] = []
    batch_size = 16

    def flush_emb(bpaths: list[str]) -> None:
        imgs = []
        for p in bpaths:
            img = Image.open(p).convert("L")
            imgs.append(tf(img))
        batch = torch.stack(imgs, dim=0).to(device)
        with torch.no_grad():
            embs = mdgt(batch)
        emb_list.extend(embs.cpu())

    for row in rows:
        batch_paths.append(row["image_path"])
        if len(batch_paths) >= batch_size:
            flush_emb(batch_paths)
            batch_paths.clear()
    if batch_paths:
        flush_emb(batch_paths)

    embs = torch.stack(emb_list, dim=0)  # [N, D]

    # Build genuine pairs (same identity+finger, different sensor)
    # and impostor pairs (different identity)
    by_subject: dict[str, list[int]] = defaultdict(list)
    by_finger_sensor: dict[tuple[str, str], list[int]] = defaultdict(list)
    for i, r in enumerate(rows):
        key_fs = (r["identity_id"], r["finger_id"])
        by_subject[r["identity_id"]].append(i)
        by_finger_sensor[key_fs].append(i)

    rng = np.random.default_rng(42)
    genuine_pairs: list[tuple[int, int]] = []
    for (_, _), idxs in by_finger_sensor.items():
        for a, b in combinations(idxs, 2):
            if rows[a]["sensor_id"] != rows[b]["sensor_id"]:
                genuine_pairs.append((a, b))

    subjects = sorted(by_subject.keys())
    impostor_pairs: list[tuple[int, int]] = []
    while len(impostor_pairs) < len(genuine_pairs) * 3:
        s1, s2 = rng.choice(len(subjects), size=2, replace=False)
        i1 = int(rng.choice(by_subject[subjects[s1]]))
        i2 = int(rng.choice(by_subject[subjects[s2]]))
        impostor_pairs.append((i1, i2))

    all_pairs = (
        [(a, b, 1) for a, b in genuine_pairs] +
        [(a, b, 0) for a, b in impostor_pairs]
    )
    rng.shuffle(all_pairs)
    if max_pairs > 0 and len(all_pairs) > max_pairs:
        all_pairs = all_pairs[:max_pairs]

    q_all, ms_all, lb_all = [], [], []
    q_arr = np.array([r["q_score"] for r in rows])
    for a, b, label in all_pairs:
        cos = float(F.cosine_similarity(embs[a].unsqueeze(0), embs[b].unsqueeze(0)).item())
        q_all.append((q_arr[a] + q_arr[b]) / 2.0)
        ms_all.append(cos)
        lb_all.append(label)

    print(f"  Pairs: {len(genuine_pairs)} genuine, {len(impostor_pairs)} impostor "
          f"(using {len(all_pairs)} total)")
    return np.array(q_all), np.array(ms_all), np.array(lb_all)


# ---------------------------------------------------------------------------
# Track 1: Error Rejection Curve
# ---------------------------------------------------------------------------

def run_track1(
    rows: list[dict],
    mdgt: MDGTCheckpointTeacher,
    device: torch.device,
    out_dir: Path,
    nfiq2_rows: list[dict] | None = None,
    image_size: int = 224,
) -> dict:
    print("[Track 1] Computing ERC...")
    q_sifq, ms, labels = build_match_scores(rows, mdgt, device, image_size=image_size)

    rejection_ratios = np.linspace(0.0, 0.5, 50)
    fnmr_sifq, auc_sifq = compute_erc(q_sifq, ms, labels, rejection_ratios=rejection_ratios)

    # Random baseline: random quality assignment
    rng = np.random.default_rng(0)
    q_rand = rng.uniform(0, 100, size=len(q_sifq))
    fnmr_rand, auc_rand = compute_erc(q_rand, ms, labels, rejection_ratios=rejection_ratios)

    results = {
        "SIFQ": {"auc_erc": round(auc_sifq, 4)},
        "Random": {"auc_erc": round(auc_rand, 4)},
    }

    # NFIQ2 baseline if provided
    if nfiq2_rows:
        nfiq2_map = {r["image_path"]: r["q_score"] for r in nfiq2_rows}
        q_nfiq2 = np.array([nfiq2_map.get(r["image_path"], 50.0) for r in rows])
        # Re-build pairs using same MDGT match scores by pairing via indices
        q_nfiq2_pairs = (q_nfiq2[[a for a, _, _ in [(0,0,0)]]] + q_nfiq2) / 2  # placeholder
        fnmr_nfiq2, auc_nfiq2 = compute_erc(q_nfiq2, ms, labels, rejection_ratios=rejection_ratios)
        results["NFIQ2"] = {"auc_erc": round(auc_nfiq2, 4)}

    # Plot
    fig, ax = plt.subplots(figsize=(7, 5))
    ax.plot(rejection_ratios, fnmr_sifq, label=f"SIFQ (AUC={auc_sifq:.4f})", linewidth=2, color="steelblue")
    ax.plot(rejection_ratios, fnmr_rand, label=f"Random (AUC={auc_rand:.4f})", linewidth=1.5,
            linestyle="--", color="gray")
    if nfiq2_rows:
        ax.plot(rejection_ratios, fnmr_nfiq2, label=f"NFIQ2 (AUC={auc_nfiq2:.4f})",
                linewidth=1.5, linestyle=":", color="orangered")
    ax.set_xlabel("Rejection ratio")
    ax.set_ylabel("FNMR @ FMR=1e-4")
    ax.set_title("Error Rejection Curve β€” lower AUC is better")
    ax.legend()
    ax.grid(True, alpha=0.3)
    fig.tight_layout()
    fig.savefig(out_dir / "plot_erc.png", dpi=150)
    plt.close(fig)
    print(f"  ERC plot saved. AUC_ERC: {results}")
    return results


# ---------------------------------------------------------------------------
# Track 2: Sensor Invariance
# ---------------------------------------------------------------------------

def run_track2(rows: list[dict], out_dir: Path, nfiq2_rows: list[dict] | None = None) -> dict:
    print("[Track 2] Computing sensor invariance...")

    scores_by_sensor: dict[str, np.ndarray] = {}
    tmp: dict[str, list[float]] = defaultdict(list)
    for r in rows:
        tmp[r["sensor_id"]].append(r["q_score"])
    for sid, vals in tmp.items():
        scores_by_sensor[sid] = np.array(vals)

    ks_rows = sensor_ks_test(scores_by_sensor)
    mean_ks = float(np.mean([row["ks_stat"] for row in ks_rows])) if ks_rows else 0.0

    # Cross-sensor Pearson on paired images (same finger, different sensor)
    by_finger: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
    for r in rows:
        key = (r["identity_id"], r["finger_id"])
        by_finger[key][r["sensor_id"]].append(r["q_score"])

    paired_scores: list[tuple[float, float]] = []
    for key, by_s in by_finger.items():
        sensors = sorted(by_s.keys())
        for s1, s2 in combinations(sensors, 2):
            for q1, q2 in zip(by_s[s1], by_s[s2]):
                paired_scores.append((q1, q2))

    pearson_sifq = cross_sensor_correlation(paired_scores)

    results = {
        "SIFQ": {
            "mean_ks_across_sensors": round(mean_ks, 4),
            "cross_sensor_pearson": round(pearson_sifq, 4),
            "n_sensor_pairs": len(ks_rows),
            "per_pair_ks": ks_rows,
        }
    }

    if nfiq2_rows:
        n_tmp: dict[str, list[float]] = defaultdict(list)
        nfiq2_by_path = {r["image_path"]: r for r in nfiq2_rows}
        for r in rows:
            if r["image_path"] in nfiq2_by_path:
                n_tmp[r["sensor_id"]].append(nfiq2_by_path[r["image_path"]]["q_score"])
        nfiq2_by_sensor = {sid: np.array(vals) for sid, vals in n_tmp.items()}
        nfiq2_ks = sensor_ks_test(nfiq2_by_sensor)
        nfiq2_mean_ks = float(np.mean([row["ks_stat"] for row in nfiq2_ks])) if nfiq2_ks else 0.0
        results["NFIQ2"] = {"mean_ks_across_sensors": round(nfiq2_mean_ks, 4)}

    # Plot: Q histogram per sensor
    n_sensors = len(scores_by_sensor)
    fig, ax = plt.subplots(figsize=(8, 5))
    colors = plt.cm.tab10(np.linspace(0, 1, min(n_sensors, 10)))
    for (sid, vals), color in zip(sorted(scores_by_sensor.items()), colors):
        ax.hist(vals, bins=40, alpha=0.5, label=sid[:30], color=color, density=True)
    ax.set_xlabel("SIFQ Quality Score")
    ax.set_ylabel("Density")
    ax.set_title(f"Quality score distribution per sensor\n(mean KS={mean_ks:.4f}, Pearson={pearson_sifq:.4f})\nLow KS = sensor-invariant")
    ax.legend(fontsize=7, loc="upper left")
    ax.grid(True, alpha=0.3)
    fig.tight_layout()
    fig.savefig(out_dir / "plot_sensor_hist.png", dpi=150)
    plt.close(fig)

    # Scatter plot: Q_s1 vs Q_s2 for paired images
    if paired_scores:
        arr = np.array(paired_scores[:2000])
        fig2, ax2 = plt.subplots(figsize=(5, 5))
        ax2.scatter(arr[:, 0], arr[:, 1], alpha=0.3, s=10, color="steelblue")
        ax2.set_xlabel("Q β€” sensor 1")
        ax2.set_ylabel("Q β€” sensor 2")
        ax2.set_title(f"Cross-sensor quality consistency\nPearson r={pearson_sifq:.3f}")
        mn, mx = arr.min(), arr.max()
        ax2.plot([mn, mx], [mn, mx], "r--", alpha=0.5, label="ideal")
        ax2.legend()
        ax2.grid(True, alpha=0.3)
        fig2.tight_layout()
        fig2.savefig(out_dir / "plot_sensor_scatter.png", dpi=150)
        plt.close(fig2)

    print(f"  Sensor invariance done. Mean KS={mean_ks:.4f}, Pearson={pearson_sifq:.4f}")
    return results


# ---------------------------------------------------------------------------
# Track 4: Concept Grounding
# ---------------------------------------------------------------------------

def run_track4(
    checkpoint_path: str,
    device: torch.device,
    test_image_paths: list[str],
    out_dir: Path,
    image_size: int = 224,
    max_images: int = 100,
) -> list[dict]:
    from evaluation.concept_grounding import compute_crosstalk_matrix
    from data.degradation import DegradationPipeline
    from models.aggregator import ScoreAggregator
    from models.backbone import SIFQBackbone
    from models.concept_head import ConceptHead, SpatialConceptHead
    from models.sensor_discriminator import SensorDiscriminator
    from models.sifq import SIFQ
    import cv2

    print("[Track 4] Computing concept grounding (crosstalk matrix)...")
    ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False)
    num_sensors = ckpt.get("metrics", {}).get("n_sensors", 10)
    backbone = SIFQBackbone(model_name="tiny_vit_5m_224.dist_in22k", pretrained=False)
    _use_spatial = ckpt.get("config", {}).get("spatial_concept_head", False)
    if _use_spatial:
        concept_head = SpatialConceptHead(in_dim=backbone.feature_dim)
    else:
        concept_head = ConceptHead(in_dim=backbone.feature_dim)
    aggregator = ScoreAggregator(k=6)
    sensor_disc = SensorDiscriminator(in_dim=backbone.feature_dim, num_sensors=num_sensors)
    model = SIFQ(backbone, concept_head, aggregator, sensor_disc)
    model.load_state_dict(ckpt["model"], strict=True)
    model.to(device).eval()

    deg_pipeline = DegradationPipeline()
    test_images_np = []
    for p in test_image_paths[:max_images]:
        img = cv2.imread(p, cv2.IMREAD_GRAYSCALE)
        if img is not None:
            img = cv2.resize(img, (image_size, image_size))
            test_images_np.append(img)

    if not test_images_np:
        print("  No test images loaded for concept grounding β€” skipping Track 4")
        return []

    rows = compute_crosstalk_matrix(model, deg_pipeline, test_images_np, device=str(device))

    # Plot heatmap
    try:
        concept_names = concept_head.CONCEPT_NAMES
        deg_names = [r["degradation"] for r in rows]
        matrix = np.array([[r[c] for c in concept_names] for r in rows])

        fig, ax = plt.subplots(figsize=(10, 6))
        im = ax.imshow(matrix, vmin=-1, vmax=1, cmap="RdYlGn", aspect="auto")
        ax.set_xticks(range(len(concept_names)))
        ax.set_xticklabels(concept_names, rotation=30, ha="right", fontsize=9)
        ax.set_yticks(range(len(deg_names)))
        ax.set_yticklabels(deg_names, fontsize=9)
        for i in range(len(deg_names)):
            for j in range(len(concept_names)):
                ax.text(j, i, f"{matrix[i, j]:.2f}", ha="center", va="center", fontsize=7)
        plt.colorbar(im, ax=ax, label="Spearman ρ")
        ax.set_title("Concept grounding (crosstalk matrix)\nDiagonal-heavy = well-grounded concepts")
        fig.tight_layout()
        fig.savefig(out_dir / "plot_crosstalk.png", dpi=150)
        plt.close(fig)
        print(f"  Crosstalk matrix saved.")
    except Exception as e:
        print(f"  Warning: could not plot crosstalk: {e}")

    return rows


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

def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="SIFQ evaluation β€” SOTA verification")
    p.add_argument("--sifq-scores", type=str, required=True,
                   help="JSONL output from run_infer.py")
    p.add_argument("--checkpoint", type=str, required=True,
                   help="SIFQ checkpoint (for Track 4 concept grounding)")
    p.add_argument("--mdgt-checkpoint", type=str,
                   default="/home/aiserver/works/fingerprint/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt",
                   help="MDGT checkpoint for computing match scores")
    p.add_argument("--nfiq2-scores", type=str, default="",
                   help="Optional JSONL with NFIQ2 scores (same format as --sifq-scores)")
    p.add_argument("--out-dir", type=str, default="eval_results",
                   help="Directory to save plots and result JSONs")
    p.add_argument("--image-size", type=int, default=224)
    p.add_argument("--max-pairs", type=int, default=5000,
                   help="Max genuine+impostor pairs for ERC computation")
    p.add_argument("--max-concept-images", type=int, default=50,
                   help="Max images for concept grounding (Track 4)")
    p.add_argument("--skip-track1", action="store_true",
                   help="Skip ERC (Track 1) β€” needs MDGT inference which is slow")
    p.add_argument("--skip-track4", action="store_true",
                   help="Skip concept grounding (Track 4)")
    p.add_argument("--exclude-sensor", type=str, default="",
                   help="Comma-separated sensor_ids to exclude before evaluation. "
                        "E.g. 'R_1000_slap,R_500_slap,S_500_slap'")
    return p.parse_args()


# ---------------------------------------------------------------------------
# TXT summary writer
# ---------------------------------------------------------------------------

_CONCEPT_KEYS = [
    ("orientation_coherence", "orient_coh"),
    ("ridge_valley_clarity",  "clarity   "),
    ("continuity",            "continuity"),
    ("noise_level",           "noise_lvl "),
    ("contrast_uniformity",   "contrast  "),
    ("minutiae_reliability",  "minutiae  "),
]

# T41 concept map β€” annotate target cells with *
# Indices match _CONCEPT_KEYS order: 0=orient_coh, 1=clarity, 2=continuity,
#                                    3=noise_lvl, 4=contrast, 5=minutiae
_DEG_TARGETS = {
    "blur":      {1, 2},    # clarity, continuity
    "noise":     {1, 3},    # clarity, noise_lvl
    "jpeg":      {1},       # clarity only
    "occlusion": {5},       # minutiae
    "dry_skin":  {4, 0},    # contrast, orient_coh
    "wet_press": {1, 5, 0}, # clarity, minutiae, orient_coh
}


def _save_summary_txt(all_results: dict, out_path: Path) -> None:
    from datetime import datetime
    W = 72
    lines = []

    def sep(ch="="):
        lines.append(ch * W)

    sep()
    lines.append(f"{'SIFQ EVALUATION SUMMARY':^{W}}")
    sep()
    lines.append(f"Generated : {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    lines.append("")

    # ── Track 1 ──────────────────────────────────────────────────────────
    if "track1_erc" in all_results:
        lines.append("TRACK 1 β€” ERROR REJECTION CURVE  (AUC ↓ better)")
        sep("-")
        for method, v in all_results["track1_erc"].items():
            lines.append(f"  {method:<10s}  AUC_ERC = {v['auc_erc']:.4f}")
        lines.append("")

    # ── Track 2 ──────────────────────────────────────────────────────────
    if "track2_sensor_invariance" in all_results:
        lines.append("TRACK 2 β€” SENSOR INVARIANCE")
        sep("-")
        for method, v in all_results["track2_sensor_invariance"].items():
            if not isinstance(v, dict) or "mean_ks_across_sensors" not in v:
                continue
            ks = v["mean_ks_across_sensors"]
            pr = v.get("cross_sensor_pearson", float("nan"))
            n  = v.get("n_sensor_pairs", "?")
            ks_flag = "βœ“" if ks <= 0.15  else "βœ—"
            pr_flag = "βœ“" if pr >= 0.75  else "βœ—"
            lines.append(f"  Method   : {method}")
            lines.append(f"  Mean KS  (↓ better) : {ks:.4f}  {ks_flag}  [target ≀ 0.15]")
            lines.append(f"  Pearson  (↑ better) : {pr:.4f}  {pr_flag}  [target β‰₯ 0.75]")
            lines.append(f"  Pairs    : {n}")

            pairs = v.get("per_pair_ks", [])
            if pairs:
                lines.append("")
                lines.append(f"  All {len(pairs)} sensor pairs sorted by KS ↓:")
                lines.append(f"  {'Sensor A':<24s}  {'Sensor B':<24s}  {'KS':>7s}")
                lines.append(f"  {'-'*24}  {'-'*24}  {'-'*7}")
                for p in sorted(pairs, key=lambda x: x["ks_stat"], reverse=True):
                    lines.append(
                        f"  {p['sensor_a']:<24s}  {p['sensor_b']:<24s}  {p['ks_stat']:>7.4f}"
                    )
        lines.append("")

    # ── Track 4 ──────────────────────────────────────────────────────────
    if "track4_concept_grounding" in all_results:
        lines.append("TRACK 4 β€” CONCEPT GROUNDING")
        lines.append("  Spearman ρ: negative = concept ↓ with degradation = correct  (*= target)")
        sep("-")
        # header
        col_w = 9
        hdr_keys = [short for _, short in _CONCEPT_KEYS]
        lines.append(
            f"  {'Degradation':<12s}  " + "  ".join(f"{h:>{col_w}s}" for h in hdr_keys)
        )
        lines.append(
            f"  {'-'*12}  " + "  ".join("-" * col_w for _ in _CONCEPT_KEYS)
        )
        for row in all_results["track4_concept_grounding"]:
            deg = row.get("degradation", "?")
            targets = _DEG_TARGETS.get(deg, set())
            cells = []
            for ci, (json_key, _) in enumerate(_CONCEPT_KEYS):
                val = row.get(json_key, float("nan"))
                tag = "*" if ci in targets else " "
                cells.append(f"{val:>+7.3f}{tag} ")
            lines.append(f"  {deg:<12s}  " + " ".join(cells))
        lines.append("")

    sep()
    txt = "\n".join(lines)
    with open(out_path, "w", encoding="utf-8") as f:
        f.write(txt)
    print(f"[eval] Summary table: {out_path}")


def main() -> None:
    args = parse_args()
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    rows = load_scores(args.sifq_scores)
    print(f"Loaded {len(rows)} SIFQ score records from {args.sifq_scores}")
    if args.exclude_sensor:
        excluded = {s.strip() for s in args.exclude_sensor.split(",") if s.strip()}
        rows = [r for r in rows if r["sensor_id"] not in excluded]
        print(f"After excluding sensors {excluded}: {len(rows)} records remain")

    nfiq2_rows = load_scores(args.nfiq2_scores) if args.nfiq2_scores else None

    all_results: dict = {}

    # ---- Track 2: Sensor Invariance (fast, always run) ----
    t2 = run_track2(rows, out_dir, nfiq2_rows=nfiq2_rows)
    all_results["track2_sensor_invariance"] = t2

    # ---- Track 1: ERC (needs MDGT inference) ----
    if not args.skip_track1:
        print(f"Loading MDGT teacher from {args.mdgt_checkpoint}")
        mdgt = MDGTCheckpointTeacher(
            checkpoint_path=args.mdgt_checkpoint,
            model_name="vit_small_patch14_dinov2.lvd142m",
            image_size=args.image_size,
            device=str(device),
        ).to(device)
        t1 = run_track1(rows, mdgt, device, out_dir, nfiq2_rows=nfiq2_rows,
                        image_size=args.image_size)
        all_results["track1_erc"] = t1
    else:
        print("[Track 1] Skipped (--skip-track1)")

    # ---- Track 4: Concept Grounding ----
    if not args.skip_track4:
        test_paths = [r["image_path"] for r in rows]
        t4 = run_track4(args.checkpoint, device, test_paths, out_dir,
                        image_size=args.image_size, max_images=args.max_concept_images)
        all_results["track4_concept_grounding"] = t4
    else:
        print("[Track 4] Skipped (--skip-track4)")

    # ---- Save summary as TXT table ----
    summary_path = out_dir / "eval_summary.txt"
    _save_summary_txt(all_results, summary_path)

    print(f"\n{'='*60}")
    print("EVALUATION SUMMARY")
    print(f"{'='*60}")
    if "track1_erc" in all_results:
        print("\nTrack 1 β€” Error Rejection Curve (AUC, lower=better):")
        for method, v in all_results["track1_erc"].items():
            print(f"  {method:10s}: AUC_ERC = {v['auc_erc']:.4f}")
    if "track2_sensor_invariance" in all_results:
        print("\nTrack 2 β€” Sensor Invariance:")
        for method, v in all_results["track2_sensor_invariance"].items():
            if isinstance(v, dict) and "mean_ks_across_sensors" in v:
                print(f"  {method:10s}: Mean KS = {v['mean_ks_across_sensors']:.4f}  "
                      f"Pearson = {v.get('cross_sensor_pearson', 'N/A')}")
    print(f"\nPlots and TXT saved to: {out_dir}")
    print(f"Full summary: {summary_path}")


if __name__ == "__main__":
    main()