File size: 21,876 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
"""Generate constellation_match_count samples.

Each sample produces a SINGLE side-by-side image: Template on the left,
Field on the right, separated by a thin divider.

The Template panel shows the reference constellation, and the Field shows
30-60 white "star" dots (with planted copies of the template among
distractor stars).

The task: count how many translated copies of the template pattern occur
in the Field (same relative offsets within a tolerance, no rotation/reflection).

The generator performs rejection sampling in TWO directions:
  * it places the desired number of planted template instances, and
  * it scatters additional non-template "distractor" stars while rejecting
    any configuration that would accidentally form another template match.
After all dots are placed the final match-count is verified; a mismatch
against the intended count causes the sample to be regenerated.
"""

from __future__ import annotations

import argparse
import io
import json
import math
import random
from pathlib import Path
from typing import List, Tuple

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from tqdm import tqdm


QUESTION = (
    "This image has two panels separated by a thin vertical divider. "
    "The left panel shows the Template: a small constellation of white dots. "
    "The right panel shows the Field: a larger scene with many white stars. "
    "The two panels are drawn at the SAME pixel scale and the dots are the "
    "SAME pixel size. Count how many copies of the Template pattern appear "
    "in the Field. A copy may be rotated by a small angle (up to about 20 "
    "degrees in either direction) and individual dot positions may be jittered "
    "slightly, but the overall pattern of relative dot positions must be "
    "preserved. The patterns may be rotated by a small angle. No mirroring "
    "or scaling. Report the count as a non-negative integer. "
    "Provide your final answer enclosed in <answer>...</answer> tags."
)

# Per-copy rotation angle drawn from [-MAX_ANGLE_DEG, +MAX_ANGLE_DEG].
# Chosen large enough to break translation-only Hausdorff matching (which
# succeeded at 100% on the unrotated version) but small enough that human
# viewers readily identify each copy as the same pattern.
MAX_ANGLE_DEG = 20.0
# Candidate angles sampled in the matching verifier.
ANGLE_SEARCH_STEP = 2.0


# Shared dot size (matplotlib scatter ``s`` is marker area in points^2).
# Same value used for both the Template panel and the Field so the model has
# a direct pixel-to-pixel correspondence.
DOT_SIZE = 130


# ---------------------------------------------------------------------------
# Template generation
# ---------------------------------------------------------------------------


def random_template(rng: random.Random) -> np.ndarray:
    """Build a template of exactly 5 dots with distinct relative offsets.

    Returned as an (n, 2) ndarray of offsets relative to the first dot,
    so the first row is always (0, 0).
    """
    n = 5
    # Draw points on a coarse integer grid so that offsets are well separated,
    # then jitter slightly to keep the pattern visually non-lattice.
    scale = rng.uniform(36.0, 54.0)  # pixel scale of the template
    while True:
        grid_pts = set()
        grid_pts.add((0, 0))
        while len(grid_pts) < n:
            gx = rng.randint(-3, 3)
            gy = rng.randint(-3, 3)
            grid_pts.add((gx, gy))
        pts_grid = list(grid_pts)
        pts = []
        for gx, gy in pts_grid:
            jitter_x = rng.uniform(-4.0, 4.0)
            jitter_y = rng.uniform(-4.0, 4.0)
            pts.append((gx * scale + jitter_x, gy * scale + jitter_y))
        arr = np.asarray(pts, dtype=np.float64)
        # Normalise so first point is origin
        arr = arr - arr[0]
        # Reject degenerate patterns: ensure min pairwise distance is comfortable,
        # and that the pattern occupies a reasonable bounding box.
        diffs = arr[:, None, :] - arr[None, :, :]
        dists = np.linalg.norm(diffs, axis=-1)
        np.fill_diagonal(dists, np.inf)
        if dists.min() < 28.0:
            continue
        bbox = arr.max(axis=0) - arr.min(axis=0)
        if bbox[0] < 40.0 or bbox[1] < 40.0:
            continue
        if bbox[0] > 260.0 or bbox[1] > 260.0:
            continue
        return arr


# ---------------------------------------------------------------------------
# Template matching
# ---------------------------------------------------------------------------


def _rot_matrix(theta_deg: float) -> np.ndarray:
    t = np.deg2rad(theta_deg)
    c, s = np.cos(t), np.sin(t)
    return np.array([[c, -s], [s, c]])


def count_template_matches(stars: np.ndarray, template: np.ndarray,
                           tol: float,
                           max_angle_deg: float = MAX_ANGLE_DEG,
                           angle_step_deg: float = ANGLE_SEARCH_STEP) -> int:
    """Count distinct (translation, rotation) placements such that every
    (R(theta) @ template[i] + T) has a star within `tol` pixels, where T is
    a candidate translation and theta is a rotation angle in
    [-max_angle_deg, +max_angle_deg]. We deduplicate by translation only:
    two matches are the same if their anchor translations differ by less
    than `tol`.

    stars: (S, 2) array, template: (n, 2) with template[0] = (0,0).
    """
    if len(stars) == 0:
        return 0
    n = template.shape[0]
    tol_sq = tol * tol
    angles = np.arange(-max_angle_deg, max_angle_deg + 1e-6, angle_step_deg)

    found_translations: List[np.ndarray] = []
    for anchor in stars:
        anchor_matched = False
        for theta in angles:
            R = _rot_matrix(float(theta))
            rotated = template @ R.T  # (n, 2), first row still (0, 0)
            ok = True
            for k in range(1, n):
                target = anchor + rotated[k]
                d2 = np.sum((stars - target) ** 2, axis=1)
                if d2.min() > tol_sq:
                    ok = False
                    break
            if ok:
                anchor_matched = True
                break
        if not anchor_matched:
            continue
        # Deduplicate by anchor translation
        is_new = True
        for t in found_translations:
            if np.sum((t - anchor) ** 2) < tol_sq:
                is_new = False
                break
        if is_new:
            found_translations.append(anchor.copy())
    return len(found_translations)


# ---------------------------------------------------------------------------
# Sample building
# ---------------------------------------------------------------------------


def build_sample(rng: random.Random, width: int, height: int,
                 target_matches: int, total_stars: int,
                 tol: float) -> Tuple[np.ndarray, np.ndarray, int]:
    """Return (stars, template, realised_matches). Raises RuntimeError if
    it could not construct the intended configuration after many tries."""

    for attempt in range(30):
        template = random_template(rng)
        n_tmpl = template.shape[0]

        # Margins for anchor placement so full template stays inside
        tmin = template.min(axis=0)
        tmax = template.max(axis=0)
        pad = 60.0
        anchor_xmin = pad - tmin[0]
        anchor_xmax = width - pad - tmax[0]
        anchor_ymin = pad - tmin[1]
        anchor_ymax = height - pad - tmax[1]
        if anchor_xmax - anchor_xmin < 100 or anchor_ymax - anchor_ymin < 100:
            continue

        placed_stars: List[np.ndarray] = []
        # Separation so planted instances don't overlap each other excessively,
        # and so the template anchors are themselves far enough apart to be
        # counted as distinct translations.
        min_anchor_sep = float(np.linalg.norm(tmax - tmin)) + 40.0

        # 1. Plant template instances. Each planted copy carries a per-copy
        # rotation in [-MAX_ANGLE_DEG, +MAX_ANGLE_DEG]. This breaks
        # translation-only matching (Hausdorff + centroid-anchored offsets).
        anchors: List[np.ndarray] = []
        planted_angles: List[float] = []
        for _ in range(target_matches):
            ok = False
            for _try in range(400):
                ax = rng.uniform(anchor_xmin, anchor_xmax)
                ay = rng.uniform(anchor_ymin, anchor_ymax)
                theta = rng.uniform(-MAX_ANGLE_DEG, MAX_ANGLE_DEG)
                candidate = np.array([ax, ay])
                too_close = False
                for a in anchors:
                    if np.linalg.norm(candidate - a) < min_anchor_sep:
                        too_close = True
                        break
                if too_close:
                    continue
                R = _rot_matrix(theta)
                rotated_template = template @ R.T
                # Check rotated bounding box still inside the panel padding.
                rtmin = rotated_template.min(axis=0)
                rtmax = rotated_template.max(axis=0)
                if (candidate[0] + rtmin[0] < pad or
                        candidate[0] + rtmax[0] > width - pad or
                        candidate[1] + rtmin[1] < pad or
                        candidate[1] + rtmax[1] > height - pad):
                    continue
                # Try adding this instance's dots while ensuring each new dot
                # is at least `tol * 2.5` from all existing dots.
                new_dots = [candidate + rotated_template[k] for k in range(n_tmpl)]
                clash = False
                for nd in new_dots:
                    for ex in placed_stars:
                        if np.linalg.norm(nd - ex) < tol * 2.5:
                            clash = True
                            break
                    if clash:
                        break
                if clash:
                    continue
                anchors.append(candidate)
                planted_angles.append(float(theta))
                placed_stars.extend(new_dots)
                ok = True
                break
            if not ok:
                break
        if len(anchors) != target_matches:
            continue

        # 2. Scatter distractor stars, rejection-sample to avoid new matches
        distractors_needed = total_stars - len(placed_stars)
        if distractors_needed < 0:
            continue
        fail = False
        for _d in range(distractors_needed):
            added = False
            for _try in range(500):
                dx = rng.uniform(pad, width - pad)
                dy = rng.uniform(pad, height - pad)
                cand = np.array([dx, dy])
                # Keep distractors from overlapping existing dots
                too_close = False
                for ex in placed_stars:
                    if np.linalg.norm(cand - ex) < 22.0:
                        too_close = True
                        break
                if too_close:
                    continue
                # Tentatively add and verify match count is unchanged
                trial = np.asarray(placed_stars + [cand])
                count = count_template_matches(trial, template, tol)
                if count != target_matches:
                    continue
                placed_stars.append(cand)
                added = True
                break
            if not added:
                fail = True
                break
        if fail:
            continue

        final_stars = np.asarray(placed_stars)
        realised = count_template_matches(final_stars, template, tol)
        if realised == target_matches:
            return final_stars, template, realised

    raise RuntimeError("Failed to build sample after many attempts")


# ---------------------------------------------------------------------------
# Rendering - two separate images per sample
# ---------------------------------------------------------------------------


def _add_dust(ax, rng: random.Random, width: int, height: int,
              n_dust: int = 800) -> None:
    dust_rng = np.random.default_rng(rng.randint(0, 2**31 - 1))
    dx = dust_rng.uniform(0, width, size=n_dust)
    dy = dust_rng.uniform(0, height, size=n_dust)
    ds = dust_rng.uniform(0.3, 2.5, size=n_dust)
    ax.scatter(dx, dy, s=ds, c="#1a2238", alpha=0.45, linewidths=0, zorder=1)


def render_field(width: int, height: int,
                 stars: np.ndarray, rng: random.Random) -> Image.Image:
    """Render the field image: dark sky with scattered white stars, no
    template overlay.  Returns a PIL Image."""
    fig = plt.figure(figsize=(width / 100, height / 100), dpi=100,
                     facecolor="#0a1020")
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)
    ax.axis("off")
    ax.set_facecolor("#0a1020")

    _add_dust(ax, rng, width, height)

    # All stars at a single, larger pixel size so the model can compare
    # dot-to-dot spacings directly between Template and Field.
    ax.scatter(stars[:, 0], stars[:, 1], s=DOT_SIZE, c="white", alpha=1.0,
               linewidths=0, zorder=3)

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=100, bbox_inches="tight", pad_inches=0,
                facecolor=fig.get_facecolor())
    plt.close(fig)
    buf.seek(0)
    return Image.open(buf).convert("RGB")


def render_template(template: np.ndarray,
                    rng: random.Random) -> Image.Image:
    """Render the template panel at the SAME pixel scale as the field.

    The canvas is a tight bounding box around the template dots plus a
    small margin, so pixel-distances between template dots equal pixel-
    distances between the corresponding dots in the field (1:1 scale).
    A short header strip labels the panel as TEMPLATE.
    Returns a PIL Image.
    """
    from matplotlib.patches import Rectangle

    tpl_min = template.min(axis=0)
    tpl_max = template.max(axis=0)
    span_x = float(tpl_max[0] - tpl_min[0])
    span_y = float(tpl_max[1] - tpl_min[1])

    margin = 50.0          # empty space around the dots
    header_h = 34.0        # top strip for the TEMPLATE label
    min_width = 240.0      # keep the header legible for narrow patterns

    content_w = span_x + 2 * margin
    content_h = span_y + 2 * margin
    canvas_w = max(content_w, min_width)
    canvas_h = header_h + content_h

    # Offset that places tpl_min at (margin_x, header_h + margin) with the
    # dots horizontally centred inside the canvas.
    margin_x = (canvas_w - span_x) / 2.0
    ox = margin_x - tpl_min[0]
    oy = (header_h + margin) - tpl_min[1]
    disp = template + np.array([ox, oy])

    fig = plt.figure(figsize=(canvas_w / 100, canvas_h / 100), dpi=100,
                     facecolor="#070b14")
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, canvas_w)
    ax.set_ylim(canvas_h, 0)
    ax.axis("off")
    ax.set_facecolor("#070b14")

    _add_dust(ax, rng, int(canvas_w), int(canvas_h),
              n_dust=max(40, int(canvas_w * canvas_h / 1800)))

    # Header strip
    ax.add_patch(Rectangle((0, 0), canvas_w, header_h,
                           facecolor="#11182a", edgecolor="none", zorder=4))
    ax.plot([0, canvas_w], [header_h, header_h],
            color="#2d3a5a", linewidth=1.0, zorder=5)
    ax.text(canvas_w / 2, header_h / 2, "TEMPLATE",
            color="#cfe0ff", fontsize=14, fontweight="bold",
            ha="center", va="center", zorder=6,
            family="DejaVu Sans")

    # Subtle border around the whole canvas
    ax.add_patch(Rectangle((1.5, 1.5), canvas_w - 3, canvas_h - 3,
                           facecolor="none", edgecolor="#7aa6ff",
                           linewidth=2.0, zorder=6))

    ax.scatter(disp[:, 0], disp[:, 1], s=DOT_SIZE, c="white",
               linewidths=0, zorder=7)

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=100, bbox_inches=None, pad_inches=0,
                facecolor=fig.get_facecolor())
    plt.close(fig)
    buf.seek(0)
    return Image.open(buf).convert("RGB")


BG_COLOR = "#0a1020"
DIVIDER_WIDTH = 3
DIVIDER_COLOR = (51, 51, 85)  # #333355


def render_combined(out_path: Path, template_img: Image.Image,
                    field_img: Image.Image) -> None:
    """Concatenate template (left) and field (right) with a thin divider."""
    bg = tuple(int(BG_COLOR.lstrip("#")[i:i+2], 16) for i in (0, 2, 4))
    tw, th = template_img.size
    fw, fh = field_img.size
    combined_h = max(th, fh)
    combined_w = tw + DIVIDER_WIDTH + fw
    combined = Image.new("RGB", (combined_w, combined_h), bg)
    # Vertically centre template
    t_y = (combined_h - th) // 2
    combined.paste(template_img, (0, t_y))
    # Divider
    for x in range(tw, tw + DIVIDER_WIDTH):
        for y in range(combined_h):
            combined.putpixel((x, y), DIVIDER_COLOR)
    # Field
    f_y = (combined_h - fh) // 2
    combined.paste(field_img, (tw + DIVIDER_WIDTH, f_y))
    combined.save(out_path)


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


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--count", type=int, default=30)
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--width", type=int, default=900)
    parser.add_argument("--height", type=int, default=900)
    parser.add_argument("--tolerance", type=float, default=10.0,
                        help="Position tolerance (pixels) for a template match")
    parser.add_argument("--difficulty", type=int, default=5,
                        help="Integer difficulty >=0; scales copies, angle, field stars.")
    args = parser.parse_args()

    d = max(0, int(args.difficulty))
    # Canvas scaling: N_d = 50 + 5*d, N_0 = 50
    N_d = 50 + 5 * d
    N_0 = 50
    s = math.sqrt(max(1.0, N_d / N_0))
    args.width = int(round(args.width * s))
    args.height = int(round(args.height * s))

    if d > 0:
        _min_copies = 5
        _max_copies = 5 + d
        # Override module-level MAX_ANGLE_DEG so both the builder and the
        # verifier see the same scaled max angle.
        global MAX_ANGLE_DEG
        MAX_ANGLE_DEG = float(min(10, d))
        _field_stars_target = 50 + 5 * d
    else:
        _min_copies = 5
        _max_copies = 5
        _field_stars_target = 50

    out_root: Path = args.output_root
    img_dir = out_root / "images"
    img_dir.mkdir(parents=True, exist_ok=True)

    ann_path = out_root / "annotations.jsonl"
    master_rng = random.Random(args.seed)

    # Force evenly-spaced answers across [_min_copies, _max_copies].
    if args.count > 1:
        plan = [
            int(round(_min_copies + i * (_max_copies - _min_copies) / (args.count - 1)))
            for i in range(args.count)
        ]
    else:
        plan = [_min_copies]
    print(f"forced constellation match counts: {plan}")

    records = []
    with ann_path.open("w") as f:
        for i in tqdm(range(args.count), desc="constellation_match_count"):
            target = plan[i]
            # Total star count: default 30-60, scaled a bit with target so high-match
            # images stay legible. With difficulty override, use _field_stars_target.
            if _field_stars_target is not None:
                base_total = master_rng.randint(_field_stars_target,
                                                _field_stars_target + 15)
                total_stars = max(base_total, target * 5 + master_rng.randint(8, 18))
            else:
                base_total = master_rng.randint(30, 55)
                total_stars = max(base_total, target * 5 + master_rng.randint(8, 18))
                total_stars = min(total_stars, 60)

            # Retry loop in case build_sample can't meet constraints
            built = False
            for retry in range(12):
                sub_seed = master_rng.randint(0, 2**31 - 1)
                sub_rng = random.Random(sub_seed)
                try:
                    stars, template, realised = build_sample(
                        sub_rng, args.width, args.height,
                        target_matches=target,
                        total_stars=total_stars,
                        tol=args.tolerance,
                    )
                except RuntimeError:
                    continue
                built = True
                break
            if not built:
                raise RuntimeError(f"sample {i} could not be generated")

            img_name = f"constellation_match_count_{i:05d}.png"
            tpl_img = render_template(template, random.Random(sub_seed + 2))
            fld_img = render_field(args.width, args.height,
                                   stars, random.Random(sub_seed + 1))
            render_combined(img_dir / img_name, tpl_img, fld_img)

            rec = {
                "image": f"images/{img_name}",
                "question": QUESTION,
                "answer": realised,
                "num_template_dots": int(template.shape[0]),
                "total_stars": int(stars.shape[0]),
                "num_matches": realised,
                "metadata": {
                    "seed": sub_seed,
                    "tolerance": args.tolerance,
                    "template_offsets": template.tolist(),
                },
            }
            f.write(json.dumps(rec) + "\n")
            f.flush()
            records.append(rec)

    data_json = {
        "task": "constellation_match_count",
        "category": "visual_attribute_transfer",
        "count": len(records),
        "items": records,
    }
    (out_root / "data.json").write_text(json.dumps(data_json, indent=2))
    print(f"Saved to {out_root}")


if __name__ == "__main__":
    main()