File size: 22,223 Bytes
f69e256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate 'Spot the Field Diff' visual benchmark dataset.

Two 2D color fields are shown side by side. Each sample uses a randomly-
chosen colour mode: a scalar 2D multi-scale noise field rendered through
one of several colormaps (viridis / plasma / inferno / magma / cividis /
coolwarm), OR a full-RGB variant where three independent scalar fields are
stacked directly as red, green and blue channels.

Each panel is divided into a 3×3 grid of 9 cells. Independently for each
cell, the right panel may or may not have a radially-faded perturbation
applied at the cell's centre. At the perturbation's rim the right panel
matches the left exactly (seamless), and at the centre its content is
blended toward a freshly-drawn, DC-matched field so only the texture
differs — there is no visible "dot" of uniform offset.

Task: count how many of the 9 cells are identical between the two panels
(i.e. how many cells have NO perturbation). Answer is an integer 0..9.
"""
from __future__ import annotations

import argparse
import json
import random
from pathlib import Path
from typing import Any, Dict, List, Tuple

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
from tqdm import tqdm


# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

GRID_N = 3                          # 3×3 grid → 9 cells (difficulty-tunable)
CELL_W = 200                        # pixels per cell (fixed; panel auto-scales)
CELL_H = 200
PANEL_W = CELL_W * GRID_N           # pixels per panel (square field)
PANEL_H = CELL_H * GRID_N

# Radius of the (optional) circular perturbation centred inside each cell.
# Must stay within the cell so perturbations don't cross cell boundaries.
CIRCLE_RADIUS = 70
assert CIRCLE_RADIUS < min(CELL_W, CELL_H) // 2

# Visibility thresholds for the blended-fresh texture inside a perturbed
# cell. Peak and mean |fresh − orig| (after DC-matching) must exceed these
# multiples of the field std; otherwise the fresh field is resampled.
MIN_BLEND_DIFF_MULT = 2.6
MIN_BLEND_MEAN_DIFF_MULT = 1.0

# Frequency scale multiplier on generate_field sigmas (difficulty-tunable).
# Smaller value → finer-grained texture, harder task.
FIELD_FREQUENCY_SCALE = 1.0

# Rendering modes — one is picked at random per sample.
COLOR_MODES: List[str] = [
    "viridis", "plasma", "inferno", "magma", "cividis", "coolwarm", "rgb",
]
JITTER_AMPLITUDE = 0.012

BG_COLOR = "#ffffff"
BORDER_COLOR = "#888888"
BORDER_WIDTH = 1.5
GRID_LINE_COLOR = "#ffffff"
GRID_LINE_WIDTH = 1.6
GRID_LINE_ALPHA = 0.85
LABEL_COLOR = "#333333"
HIGHLIGHT_COLOR = "#dc1e1e"

MARGIN_PX = 70
GAP_PX = 90
LABEL_HEIGHT = 44

def _build_question() -> str:
    n = GRID_N
    total = n * n
    return (
        f"Three panels are shown side by side. The leftmost panel is an INDEX "
        f"key: a {n}×{n} grid whose cells are numbered 1 through {total} in "
        f"row-major order (top-left = 1, increasing left-to-right then "
        f"top-to-bottom). The middle and right panels are 2D color fields, "
        f"each divided into the same {n}×{n} grid by thin white gridlines. "
        f"Compare the middle (Field A) and right (Field B) panels cell by "
        f"cell. List the numbers of all cells that DIFFER between Field A "
        f"and Field B, in ascending order, separated by commas (for example: "
        f"\"1, 4, {total}\"). If no cells differ, write \"none\". "
        f"Provide your final answer enclosed in <answer>...</answer> tags."
    )


QUESTION = (
    "Two panels are shown side by side. Each panel is a 2D color field, and "
    "each panel is divided into a 3×3 grid of 9 cells by thin white "
    "gridlines. Compare the left and right panels cell by cell. Count how "
    "many of the 9 cells are DIFFERENT between the two panels. Report the "
    "count as an integer between 0 and 9. "
    "Provide your final answer enclosed in <answer>...</answer> tags."
)


# ---------------------------------------------------------------------------
# 2D field generator (multi-scale smoothed Gaussian noise)
# ---------------------------------------------------------------------------


def _separable_gaussian_blur(arr: np.ndarray, sigma: float) -> np.ndarray:
    """Apply a separable 2D Gaussian blur via two 1D convolutions."""
    max_radius = max(1, min(arr.shape) // 2 - 1)
    radius = max(1, min(int(sigma * 4), max_radius))
    k = np.arange(-radius, radius + 1, dtype=np.float64)
    w = np.exp(-(k * k) / (2.0 * sigma * sigma))
    kernel = w / w.sum()
    out = np.apply_along_axis(
        lambda row: np.convolve(row, kernel, mode="same"), axis=1, arr=arr
    )
    out = np.apply_along_axis(
        lambda col: np.convolve(col, kernel, mode="same"), axis=0, arr=out
    )
    return out


def _smoothed_noise_2d(
    np_rng: np.random.Generator,
    shape: Tuple[int, int],
    sigma: float,
) -> np.ndarray:
    raw = np_rng.standard_normal(size=shape)
    return _separable_gaussian_blur(raw, sigma)


def generate_field(
    np_rng: np.random.Generator,
    shape: Tuple[int, int],
) -> np.ndarray:
    """Arbitrary non-periodic 2D random field built from multi-scale smoothed
    Gaussian noise."""
    fs = max(0.1, float(FIELD_FREQUENCY_SCALE))
    coarse = _smoothed_noise_2d(np_rng, shape, sigma=np_rng.uniform(28.0, 44.0) * fs)
    medium = _smoothed_noise_2d(np_rng, shape, sigma=np_rng.uniform(9.0, 16.0) * fs)
    fine = _smoothed_noise_2d(np_rng, shape, sigma=np_rng.uniform(2.5, 4.5) * fs)
    micro = _smoothed_noise_2d(np_rng, shape, sigma=np_rng.uniform(0.9, 1.4) * fs)

    def _norm(a: np.ndarray) -> np.ndarray:
        s = float(np.std(a)) or 1.0
        return a / s

    f = (
        1.8 * _norm(coarse)
        + 0.75 * _norm(medium)
        + 0.40 * _norm(fine)
        + 0.20 * _norm(micro)
    )
    f = f + np_rng.normal(0.0, 0.04, size=shape)
    return f


# ---------------------------------------------------------------------------
# Cell geometry and perturbation selection
# ---------------------------------------------------------------------------


def _cell_center(row: int, col: int) -> Tuple[int, int]:
    cx = col * CELL_W + CELL_W // 2
    cy = row * CELL_H + CELL_H // 2
    return cx, cy


MIN_PERTURBED = 0
MAX_PERTURBED = GRID_N * GRID_N


def _sample_perturbed_cells(rng: random.Random) -> List[Tuple[int, int]]:
    """Return list of (row, col) cells to perturb. Draws ``num_perturbed``
    uniformly from [MIN_PERTURBED..MAX_PERTURBED] then picks that many cells."""
    num_perturbed = rng.randint(MIN_PERTURBED, MAX_PERTURBED)
    all_cells = [(r, c) for r in range(GRID_N) for c in range(GRID_N)]
    rng.shuffle(all_cells)
    return sorted(all_cells[:num_perturbed])


# ---------------------------------------------------------------------------
# Radial-fade perturbation (circle-shaped, magnitude fades to zero at rim)
# ---------------------------------------------------------------------------


def _build_disk_mask(radius: int) -> np.ndarray:
    """Smootherstep radial fade mask, exactly 0 at the rim and C²-smooth."""
    n = 2 * radius + 1
    yy, xx = np.mgrid[0:n, 0:n].astype(np.float64)
    c = float(radius)
    dist = np.sqrt((xx - c) ** 2 + (yy - c) ** 2)
    t = np.clip(dist / float(radius), 0.0, 1.0)
    mask = 1.0 - (6.0 * t ** 5 - 15.0 * t ** 4 + 10.0 * t ** 3)
    return mask


def _apply_radial_perturbation(
    np_rng: np.random.Generator,
    left: np.ndarray,
    right: np.ndarray,
    cx: int,
    cy: int,
    radius: int,
    field_std: float,
    max_tries: int = 40,
) -> None:
    r = radius
    n = 2 * r + 1
    y_lo, y_hi = cy - r, cy + r + 1
    x_lo, x_hi = cx - r, cx + r + 1
    orig = left[y_lo:y_hi, x_lo:x_hi]

    mask = _build_disk_mask(r)
    min_peak = MIN_BLEND_DIFF_MULT * field_std
    min_mean = MIN_BLEND_MEAN_DIFF_MULT * field_std
    inner = mask > 0.5

    pad_canvas = n + 60
    pad_off = (pad_canvas - n) // 2

    for _ in range(max_tries):
        fresh_full = generate_field(np_rng, shape=(pad_canvas, pad_canvas))
        fresh = fresh_full[pad_off:pad_off + n, pad_off:pad_off + n].copy()

        # DC-match: remove bulk brightness offset so only texture differs.
        fresh = fresh - (float(np.mean(fresh[inner])) - float(np.mean(orig[inner])))

        abs_diff = np.abs(fresh[inner] - orig[inner])
        if float(np.max(abs_diff)) < min_peak:
            continue
        if float(np.mean(abs_diff)) < min_mean:
            continue

        right[y_lo:y_hi, x_lo:x_hi] = (1.0 - mask) * orig + mask * fresh
        return

    raise RuntimeError("Could not find a sufficiently different fresh field for this cell.")


def build_sample(
    rng: random.Random,
    np_rng: np.random.Generator,
    mode: str,
) -> Tuple[np.ndarray, np.ndarray, List[Dict[str, Any]]]:
    """Return ``(left, right, cell_records)``. One record per cell with
    ``row``, ``col``, ``perturbed`` (bool), ``cx``, ``cy``, ``radius``."""
    n_channels = 3 if mode == "rgb" else 1

    channels_left = [
        generate_field(np_rng, shape=(PANEL_H, PANEL_W)) for _ in range(n_channels)
    ]
    channels_right = [c.copy() for c in channels_left]

    perturbed = set(_sample_perturbed_cells(rng))

    cell_records: List[Dict[str, Any]] = []
    for row in range(GRID_N):
        for col in range(GRID_N):
            cx, cy = _cell_center(row, col)
            is_perturbed = (row, col) in perturbed
            if is_perturbed:
                for ch_left, ch_right in zip(channels_left, channels_right):
                    ch_std = float(np.std(ch_left)) or 1.0
                    _apply_radial_perturbation(
                        np_rng, ch_left, ch_right, cx, cy, CIRCLE_RADIUS, ch_std,
                    )
            cell_records.append({
                "row": row,
                "col": col,
                "perturbed": is_perturbed,
                "cx": int(cx),
                "cy": int(cy),
                "radius": int(CIRCLE_RADIUS),
            })

    if mode == "rgb":
        left = np.stack(channels_left, axis=-1)
        right = np.stack(channels_right, axis=-1)
    else:
        left = channels_left[0]
        right = channels_right[0]
    return left, right, cell_records


# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------


LEGEND_SCALE = 0.4   # legend is 40% the dimensions of a field panel


def _legend_dims() -> Tuple[int, int]:
    return int(round(PANEL_W * LEGEND_SCALE)), int(round(PANEL_H * LEGEND_SCALE))


def _panel_origins() -> Tuple[Tuple[float, float],
                              Tuple[float, float],
                              Tuple[float, float]]:
    """(ox, oy) for legend (small, vertically centered), left field, right
    field. Layout: [legend] [GAP] [Field A] [GAP] [Field B]."""
    oy_field = MARGIN_PX + LABEL_HEIGHT
    leg_w, leg_h = _legend_dims()
    ox_legend = MARGIN_PX
    oy_legend = oy_field + (PANEL_H - leg_h) / 2
    ox_left = ox_legend + leg_w + GAP_PX
    ox_right = ox_left + PANEL_W + GAP_PX
    return (ox_legend, oy_legend), (ox_left, oy_field), (ox_right, oy_field)


def _canvas_size() -> Tuple[int, int]:
    leg_w, _ = _legend_dims()
    w = MARGIN_PX + leg_w + GAP_PX + PANEL_W + GAP_PX + PANEL_W + MARGIN_PX
    h = MARGIN_PX + LABEL_HEIGHT + PANEL_H + MARGIN_PX
    return int(w), int(h)


def _draw_legend(ax: plt.Axes, ox: float, oy: float) -> None:
    """Small index-key panel: light grey background, N×N gridlines, each
    cell labeled with its 1-based row-major number in bold font."""
    leg_w, leg_h = _legend_dims()
    cell_w = leg_w / GRID_N
    cell_h = leg_h / GRID_N
    legend_bg = mpatches.Rectangle(
        (ox, oy), leg_w, leg_h,
        facecolor="#e8e6e0", edgecolor=BORDER_COLOR,
        linewidth=BORDER_WIDTH, zorder=2,
    )
    ax.add_patch(legend_bg)
    for i in range(1, GRID_N):
        gx = ox + i * cell_w
        ax.plot([gx, gx], [oy, oy + leg_h],
                color="#888", linewidth=GRID_LINE_WIDTH, zorder=3)
        gy = oy + i * cell_h
        ax.plot([ox, ox + leg_w], [gy, gy],
                color="#888", linewidth=GRID_LINE_WIDTH, zorder=3)
    fontsize = max(10, int(min(cell_w, cell_h) * 0.36))
    for r in range(GRID_N):
        for c in range(GRID_N):
            n = r * GRID_N + c + 1
            cx = ox + c * cell_w + cell_w / 2
            cy = oy + r * cell_h + cell_h / 2
            ax.text(cx, cy, str(n),
                    ha="center", va="center",
                    fontsize=fontsize, fontweight="bold",
                    color="#222", zorder=4)


def _normalise(field: np.ndarray, v_lo: float, v_hi: float) -> np.ndarray:
    if v_hi <= v_lo:
        return np.zeros_like(field, dtype=np.float64)
    return (field - v_lo) / (v_hi - v_lo)


def _field_to_rgba(
    field: np.ndarray,
    mode: str,
    v_lo: Any,
    v_hi: Any,
    np_rng: np.random.Generator,
) -> np.ndarray:
    if mode == "rgb":
        norm = np.stack(
            [_normalise(field[..., c], v_lo[c], v_hi[c]) for c in range(3)],
            axis=-1,
        )
        norm = norm + np_rng.uniform(-JITTER_AMPLITUDE, JITTER_AMPLITUDE, size=norm.shape)
        norm = np.clip(norm, 0.0, 1.0)
        alpha = np.ones(norm.shape[:2] + (1,), dtype=norm.dtype)
        rgba = np.concatenate([norm, alpha], axis=-1)
    else:
        norm = _normalise(field, v_lo, v_hi)
        norm = norm + np_rng.uniform(-JITTER_AMPLITUDE, JITTER_AMPLITUDE, size=norm.shape)
        norm = np.clip(norm, 0.0, 1.0)
        rgba = plt.get_cmap(mode)(norm)

    return (rgba * 255.0 + 0.5).astype(np.uint8)


def _draw_grid(ax: plt.Axes, ox: float, oy: float) -> None:
    """Draw the 3×3 white gridlines on a panel (2 vertical + 2 horizontal)."""
    for i in range(1, GRID_N):
        gx = ox + i * CELL_W
        ax.plot(
            [gx, gx], [oy, oy + PANEL_H],
            color=GRID_LINE_COLOR, linewidth=GRID_LINE_WIDTH,
            alpha=GRID_LINE_ALPHA, zorder=4,
        )
        gy = oy + i * CELL_H
        ax.plot(
            [ox, ox + PANEL_W], [gy, gy],
            color=GRID_LINE_COLOR, linewidth=GRID_LINE_WIDTH,
            alpha=GRID_LINE_ALPHA, zorder=4,
        )


def _render(
    out_path: Path,
    left: np.ndarray,
    right: np.ndarray,
    mode: str,
    np_rng: np.random.Generator,
    cell_records: List[Dict[str, Any]] | None = None,
) -> None:
    w, h = _canvas_size()
    dpi = 100
    fig, ax = plt.subplots(1, 1, figsize=(w / dpi, h / dpi), dpi=dpi)
    ax.set_xlim(0, w)
    ax.set_ylim(h, 0)
    ax.set_aspect("auto")
    ax.axis("off")
    fig.patch.set_facecolor(BG_COLOR)
    ax.set_facecolor(BG_COLOR)

    (ox_legend, oy_legend), (ox_left, oy), (ox_right, _) = _panel_origins()
    _draw_legend(ax, ox_legend, oy_legend)
    leg_w, _ = _legend_dims()
    ax.text(
        ox_legend + leg_w / 2, oy_legend - 12,
        "Index", ha="center", va="bottom",
        fontsize=13, fontweight="bold", color=LABEL_COLOR,
    )

    if mode == "rgb":
        v_lo, v_hi = [], []
        for c in range(3):
            both = np.concatenate([left[..., c].ravel(), right[..., c].ravel()])
            v_lo.append(float(np.quantile(both, 0.01)))
            v_hi.append(float(np.quantile(both, 0.99)))
    else:
        both = np.concatenate([left.ravel(), right.ravel()])
        v_lo = float(np.quantile(both, 0.01))
        v_hi = float(np.quantile(both, 0.99))

    left_rgba = _field_to_rgba(left, mode, v_lo, v_hi, np_rng)
    right_rgba = _field_to_rgba(right, mode, v_lo, v_hi, np_rng)

    ax.imshow(
        left_rgba,
        extent=(ox_left, ox_left + PANEL_W, oy + PANEL_H, oy),
        interpolation="nearest",
        zorder=2,
    )
    ax.imshow(
        right_rgba,
        extent=(ox_right, ox_right + PANEL_W, oy + PANEL_H, oy),
        interpolation="nearest",
        zorder=2,
    )

    for ox in (ox_left, ox_right):
        border = mpatches.Rectangle(
            (ox, oy), PANEL_W, PANEL_H,
            facecolor="none", edgecolor=BORDER_COLOR,
            linewidth=BORDER_WIDTH, zorder=3,
        )
        ax.add_patch(border)
        _draw_grid(ax, ox, oy)

    ax.text(
        ox_left + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5,
        "Field A", ha="center", va="center",
        fontsize=15, fontweight="bold", color=LABEL_COLOR,
    )
    ax.text(
        ox_right + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5,
        "Field B", ha="center", va="center",
        fontsize=15, fontweight="bold", color=LABEL_COLOR,
    )

    if cell_records:
        for rec in cell_records:
            if not rec["perturbed"]:
                continue
            cx, cy, rr = rec["cx"], rec["cy"], rec["radius"]
            for ox in (ox_left, ox_right):
                ax.add_patch(mpatches.Circle(
                    (ox + cx, oy + cy), rr,
                    facecolor="none", edgecolor=HIGHLIGHT_COLOR,
                    linewidth=2.2, zorder=5,
                ))

    fig.savefig(out_path, facecolor=BG_COLOR)
    plt.close(fig)


def render_pair(
    out_path: Path,
    left: np.ndarray,
    right: np.ndarray,
    mode: str,
    np_rng: np.random.Generator,
) -> None:
    _render(out_path, left, right, mode, np_rng)


def render_answer(
    out_path: Path,
    left: np.ndarray,
    right: np.ndarray,
    cell_records: List[Dict[str, Any]],
    mode: str,
    np_rng: np.random.Generator,
) -> None:
    _render(out_path, left, right, mode, np_rng, cell_records)


# ---------------------------------------------------------------------------
# Annotation
# ---------------------------------------------------------------------------


def build_annotation(
    image_name: str,
    cell_records: List[Dict[str, Any]],
    mode: str,
) -> Dict[str, Any]:
    num_identical = sum(1 for r in cell_records if not r["perturbed"])
    num_different = GRID_N * GRID_N - num_identical
    diff_indices = sorted(
        r["row"] * GRID_N + r["col"] + 1
        for r in cell_records if r["perturbed"]
    )
    answer = ", ".join(str(i) for i in diff_indices) if diff_indices else "none"
    return {
        "image": image_name,
        "color_mode": mode,
        "grid": GRID_N,
        "num_cells": GRID_N * GRID_N,
        "num_identical": num_identical,
        "num_different": num_different,
        "diff_indices": diff_indices,
        "cells": cell_records,
        "question": _build_question(),
        "answer": answer,
    }


# ---------------------------------------------------------------------------
# Dataset generation
# ---------------------------------------------------------------------------


def generate_dataset(
    rng: random.Random,
    np_rng: np.random.Generator,
    count: int,
    output_dir: Path,
) -> None:
    images_dir = output_dir / "images"
    answers_dir = output_dir / "answers"
    images_dir.mkdir(parents=True, exist_ok=True)
    answers_dir.mkdir(parents=True, exist_ok=True)

    annotations: List[Dict[str, Any]] = []
    data_items: List[Dict[str, Any]] = []

    for idx in tqdm(range(count), desc="Generating field diff pairs"):
        mode = rng.choice(COLOR_MODES)
        for _ in range(20):
            try:
                left, right, cell_records = build_sample(rng, np_rng, mode)
                break
            except RuntimeError:
                continue
        else:
            raise RuntimeError(f"Failed to build sample {idx}")

        image_name = f"field_diff_{idx:05d}.png"
        img_path = images_dir / image_name
        ans_path = answers_dir / image_name

        render_pair(img_path, left, right, mode, np_rng)
        render_answer(ans_path, left, right, cell_records, mode, np_rng)

        rel_image = f"images/{image_name}"
        diff_indices = sorted(
            r["row"] * GRID_N + r["col"] + 1
            for r in cell_records if r["perturbed"]
        )
        answer = ", ".join(str(i) for i in diff_indices) if diff_indices else "none"
        annotations.append(build_annotation(rel_image, cell_records, mode))
        data_items.append({
            "image": rel_image,
            "question": _build_question(),
            "answer": answer,
        })

    with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh:
        for rec in annotations:
            fh.write(json.dumps(rec) + "\n")

    data_json = {
        "task": "spot_the_field_diff",
        "category": "visual_attribute_transfer",
        "count": len(data_items),
        "items": data_items,
    }
    with (output_dir / "data.json").open("w", encoding="utf-8") as fh:
        json.dump(data_json, fh, indent=2)
        fh.write("\n")


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(
        description="Generate 'Spot the Field Diff' visual benchmark dataset."
    )
    p.add_argument("--output-root", type=Path, default=".")
    p.add_argument("--count", type=int, default=20)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--difficulty", type=int, default=5,
                   help="Integer difficulty >=0; scales perturbed cells and blend subtlety.")
    return p.parse_args()


def main() -> None:
    args = parse_args()
    rng = random.Random(args.seed)
    np_rng = np.random.default_rng(args.seed)
    d = max(0, int(args.difficulty))

    global GRID_N, PANEL_W, PANEL_H, MIN_PERTURBED, MAX_PERTURBED
    global MIN_BLEND_DIFF_MULT, MIN_BLEND_MEAN_DIFF_MULT, FIELD_FREQUENCY_SCALE

    GRID_N = 3 + d // 3
    PANEL_W = CELL_W * GRID_N
    PANEL_H = CELL_H * GRID_N
    MIN_PERTURBED = 1
    MAX_PERTURBED = GRID_N * GRID_N
    MIN_BLEND_DIFF_MULT = 3.0 - 0.1 * d
    MIN_BLEND_MEAN_DIFF_MULT = max(0.5, 1.0 - 0.05 * d)
    FIELD_FREQUENCY_SCALE = max(0.4, 1.0 - 0.08 * d)

    generate_dataset(rng, np_rng, args.count, args.output_root)
    print(f"Saved {args.count} field diff pairs to {args.output_root}")


if __name__ == "__main__":
    main()