File size: 8,929 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
"""
Visualize fingerprint images at representative score milestones.
Shows one sample per score bucket (e.g. every 10 points) with quality
score and all 6 concept signals.

Usage:
    python sifq/visualize_score_milestones.py \
        --scores sifq/eval_results/sifq_scores_v13.jsonl \
        --output sifq/eval_results/v13/milestone_samples.png \
        [--n_buckets 8] [--sensor R_1000_slap] [--seed 42]
"""

from __future__ import annotations

import argparse
import json
import random
from pathlib import Path

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

CONCEPT_NAMES = [
    "orientation_coherence",
    "ridge_valley_clarity",
    "continuity",
    "noise_level",
    "contrast_uniformity",
    "minutiae_reliability",
]
CONCEPT_COLORS = [
    "#4c72b0", "#dd8452", "#55a868", "#c44e52", "#8172b3", "#937860"
]


def load_scores(path: str) -> list[dict]:
    records = []
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line:
                records.append(json.loads(line))
    return records


def pick_milestone_samples(
    records: list[dict],
    n_buckets: int,
    sensor: str | None,
    seed: int,
    excluded_sensors: set[str] | None = None,
) -> list[dict]:
    rng = random.Random(seed)

    if excluded_sensors:
        records = [r for r in records if r["sensor_id"] not in excluded_sensors]

    if sensor:
        pool = [r for r in records if r["sensor_id"] == sensor]
        if not pool:
            raise ValueError(
                f"No records for sensor '{sensor}'. "
                f"Available: {sorted(set(r['sensor_id'] for r in records))}"
            )
    else:
        pool = records

    scores = [r["q_score"] for r in pool]
    q_min, q_max = min(scores), max(scores)
    edges = np.linspace(q_min, q_max, n_buckets + 1)

    samples = []
    for i in range(n_buckets):
        lo, hi = edges[i], edges[i + 1]
        bucket = [r for r in pool if lo <= r["q_score"] < hi]
        if i == n_buckets - 1:  # include right edge on last bucket
            bucket = [r for r in pool if lo <= r["q_score"] <= hi]
        if not bucket:
            continue
        # Pick sample closest to bucket midpoint
        mid = (lo + hi) / 2
        bucket.sort(key=lambda r: abs(r["q_score"] - mid))
        samples.append(bucket[0])

    return samples


def draw_concept_bar(ax, concepts: list[float]):
    """Draw a horizontal bar chart of concept values."""
    y = np.arange(len(CONCEPT_NAMES))
    bars = ax.barh(
        y,
        concepts,
        color=CONCEPT_COLORS,
        height=0.6,
        edgecolor="none",
    )
    ax.set_xlim(0, 1)
    ax.set_yticks(y)
    ax.set_yticklabels(
        [n.replace("_", "\n") for n in CONCEPT_NAMES],
        fontsize=6,
    )
    ax.set_xticks([0, 0.5, 1.0])
    ax.tick_params(axis="x", labelsize=6)
    ax.spines[["top", "right"]].set_visible(False)
    ax.set_xlabel("activation", fontsize=6)
    # Annotate values
    for bar, v in zip(bars, concepts):
        ax.text(
            min(v + 0.03, 0.97),
            bar.get_y() + bar.get_height() / 2,
            f"{v:.2f}",
            va="center",
            fontsize=5.5,
            color="#333333",
        )


def make_score_colormap(q_min: float, q_max: float):
    cmap = plt.cm.RdYlGn
    norm = plt.Normalize(vmin=q_min, vmax=q_max)
    return cmap, norm


def visualize(
    scores_path: str,
    output_path: str,
    n_buckets: int = 8,
    sensor: str | None = None,
    excluded_sensors: set[str] | None = None,
    seed: int = 42,
    version: str = "",
):
    records = load_scores(scores_path)
    samples = pick_milestone_samples(records, n_buckets, sensor, seed, excluded_sensors)

    n = len(samples)
    all_scores = [r["q_score"] for r in records]
    q_min, q_max = min(all_scores), max(all_scores)
    cmap, norm = make_score_colormap(q_min, q_max)

    # Layout: each sample = 1 column with [image | concept bar]
    # Top row: images, bottom row: concept bars
    fig = plt.figure(figsize=(n * 2.8, 7))
    fig.patch.set_facecolor("#1a1a2e")

    title_sensor = sensor if sensor else "all sensors"
    ver_tag = f"SIFQ {version} — " if version else "SIFQ — "
    fig.suptitle(
        f"{ver_tag}Score Milestones  ({title_sensor})\n"
        f"Score range: {q_min:.1f}{q_max:.1f}  |  "
        f"n_buckets={n_buckets}  |  total={len(records):,} samples",
        color="white",
        fontsize=11,
        y=0.99,
    )

    outer = gridspec.GridSpec(
        2, n,
        figure=fig,
        hspace=0.08,
        wspace=0.35,
        top=0.92,
        bottom=0.04,
        left=0.04,
        right=0.97,
        height_ratios=[3, 2],
    )

    for col, rec in enumerate(samples):
        q = rec["q_score"]
        color = cmap(norm(q))

        # ---- Image ----
        ax_img = fig.add_subplot(outer[0, col])
        img_path = rec["image_path"]
        try:
            img = Image.open(img_path).convert("L")
            ax_img.imshow(img, cmap="gray", aspect="auto")
        except Exception:
            ax_img.set_facecolor("#333")
            ax_img.text(
                0.5, 0.5, "N/A",
                ha="center", va="center",
                color="white", fontsize=8,
                transform=ax_img.transAxes,
            )

        # Score badge
        ax_img.set_title(
            f"Q = {q:.1f}",
            color="white",
            fontsize=9,
            fontweight="bold",
            pad=3,
        )
        # Colored border around image matching score
        for spine in ax_img.spines.values():
            spine.set_edgecolor(color)
            spine.set_linewidth(3)
        ax_img.set_xticks([])
        ax_img.set_yticks([])
        ax_img.set_facecolor("#111")

        # Sensor + identity label below image
        sensor_lbl = rec.get("sensor_id", "")
        identity_lbl = rec.get("identity_id", "")[:8]
        ax_img.set_xlabel(
            f"{sensor_lbl}\n{identity_lbl}",
            color="#aaaaaa",
            fontsize=6,
            labelpad=2,
        )

        # ---- Concept bar ----
        ax_bar = fig.add_subplot(outer[1, col])
        ax_bar.set_facecolor("#0d0d1a")
        for spine in ax_bar.spines.values():
            spine.set_edgecolor("#444")
        ax_bar.tick_params(colors="white")
        ax_bar.yaxis.label.set_color("white")
        ax_bar.xaxis.label.set_color("#aaaaaa")
        ax_bar.set_xlabel("activation", fontsize=6, color="#aaaaaa")

        concepts = rec.get("concepts", [0.0] * 6)
        draw_concept_bar(ax_bar, concepts)

        # Style ticks for dark bg
        for lbl in ax_bar.get_yticklabels():
            lbl.set_color("white")
        for lbl in ax_bar.get_xticklabels():
            lbl.set_color("#aaaaaa")
        ax_bar.tick_params(axis="both", colors="#aaaaaa")

    # Colorbar legend
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    sm.set_array([])
    cbar_ax = fig.add_axes([0.15, 0.005, 0.70, 0.012])
    cb = fig.colorbar(sm, cax=cbar_ax, orientation="horizontal")
    cb.set_label("Quality Score", color="white", fontsize=8)
    cb.ax.xaxis.set_tick_params(color="white")
    plt.setp(cb.ax.xaxis.get_ticklabels(), color="white", fontsize=7)

    out = Path(output_path)
    out.parent.mkdir(parents=True, exist_ok=True)
    plt.savefig(out, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
    plt.close()
    print(f"Saved → {out}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--scores",
        default="sifq/eval_results/sifq_scores_v13.jsonl",
        help="Path to sifq_scores_*.jsonl",
    )
    parser.add_argument(
        "--output",
        default="sifq/eval_results/v13/milestone_samples.png",
        help="Output PNG path",
    )
    parser.add_argument(
        "--n_buckets",
        type=int,
        default=8,
        help="Number of score buckets / columns",
    )
    parser.add_argument(
        "--sensor",
        default=None,
        help="Filter to a specific sensor_id (e.g. R_1000_slap)",
    )
    parser.add_argument(
        "--exclude-sensor",
        default="",
        help="Comma-separated sensor_ids to exclude. "
             "E.g. 'R_1000_slap,R_500_slap,S_500_slap'",
    )
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--version", type=str, default="", help="Version tag shown in plot title (e.g. v17)")
    args = parser.parse_args()

    excluded: set[str] = set()
    if args.exclude_sensor:
        excluded = {s.strip() for s in args.exclude_sensor.split(",") if s.strip()}

    visualize(
        scores_path=args.scores,
        output_path=args.output,
        n_buckets=args.n_buckets,
        sensor=args.sensor,
        excluded_sensors=excluded,
        seed=args.seed,
        version=args.version,
    )


if __name__ == "__main__":
    main()