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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
from __future__ import annotations

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

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


# ---------------------------------------------------------------------------
# Random irregular shape generation
# ---------------------------------------------------------------------------

def generate_blob_vertices(rng: random.Random,
                           fourier_perturbation_amplitude: float = 0.20,
                           num_samples: int = 80) -> List[Tuple[float, float]]:
    """Generate a random irregular closed shape as unit-radius vertices.

    ``fourier_perturbation_amplitude`` scales the harmonic amplitude budget.
    At the default of 0.20 we match the original shape character; smaller
    values produce blobs that are closer to a smooth near-circular profile,
    making silhouettes harder to distinguish visually.
    """
    # Vary structure dramatically across shapes
    num_lobes = rng.randint(3, 12)
    base_radius = rng.uniform(0.5, 0.8)

    # Random harmonics with wide amplitude range. Scale amplitudes by the
    # perturbation factor so that smaller perturbation => gentler bumps.
    amp_scale = max(fourier_perturbation_amplitude, 1e-6) / 0.20
    harmonics = []
    for k in range(2, num_lobes + 1):
        amp = rng.uniform(0.08, 0.45) / (k ** rng.uniform(0.3, 0.7))
        harmonics.append((k, amp * amp_scale, rng.uniform(0, 2 * math.pi)))

    # Optionally add one dominant low-frequency lobe for variety
    if rng.random() < 0.5:  # unrelated coin (kept as-is)
        dom_freq = rng.randint(2, 4)
        dom_amp = rng.uniform(0.15, 0.35) * amp_scale
        dom_phase = rng.uniform(0, 2 * math.pi)
        harmonics.append((dom_freq, dom_amp, dom_phase))

    # Build polar radius function
    angles = [2 * math.pi * i / num_samples for i in range(num_samples)]
    radii = []
    for a in angles:
        r = base_radius
        for freq, amp, phase in harmonics:
            r += amp * math.sin(freq * a + phase)
        radii.append(max(r, 0.12))

    # Convert to cartesian
    pts = [(r * math.cos(a), r * math.sin(a)) for r, a in zip(radii, angles)]

    # Random aspect stretch + rotation for more variety
    stretch_x = rng.uniform(0.6, 1.0)
    stretch_y = rng.uniform(0.6, 1.0)
    rot = rng.uniform(0, 2 * math.pi)
    cos_r, sin_r = math.cos(rot), math.sin(rot)
    stretched = []
    for x, y in pts:
        sx, sy = x * stretch_x, y * stretch_y
        rx = sx * cos_r - sy * sin_r
        ry = sx * sin_r + sy * cos_r
        stretched.append((rx, ry))
    pts = stretched

    # Normalise so max extent = 1.0
    max_ext = max(max(abs(x), abs(y)) for x, y in pts)
    if max_ext > 0:
        pts = [(x / max_ext, y / max_ext) for x, y in pts]

    return pts


def _silhouette_distance(a: List[Tuple[float, float]],
                         b: List[Tuple[float, float]],
                         num_samples: int = 64) -> float:
    """Rotation/reflection-invariant silhouette distance between two unit blobs.

    We compare the two shapes via their polar radius signatures sampled on
    a common angular grid. We minimise over cyclic rotations and a reflection
    to account for the shapes' arbitrary orientation.
    """
    def radial_signature(pts: List[Tuple[float, float]]) -> np.ndarray:
        xs = np.asarray([p[0] for p in pts])
        ys = np.asarray([p[1] for p in pts])
        # Centre at centroid
        xs = xs - xs.mean()
        ys = ys - ys.mean()
        angs = np.arctan2(ys, xs) % (2 * np.pi)
        rads = np.hypot(xs, ys)
        grid = np.linspace(0, 2 * np.pi, num_samples, endpoint=False)
        order = np.argsort(angs)
        angs_sorted = angs[order]
        rads_sorted = rads[order]
        # Extend for wrap-around interpolation
        ang_ext = np.concatenate([angs_sorted - 2 * np.pi, angs_sorted,
                                   angs_sorted + 2 * np.pi])
        rad_ext = np.concatenate([rads_sorted, rads_sorted, rads_sorted])
        sig = np.interp(grid, ang_ext, rad_ext)
        # Normalise
        m = sig.max()
        if m > 0:
            sig = sig / m
        return sig

    sa = radial_signature(a)
    sb = radial_signature(b)
    sb_rev = sb[::-1]

    best = float("inf")
    for sig_b in (sb, sb_rev):
        for shift in range(num_samples):
            rolled = np.roll(sig_b, shift)
            d = float(np.mean(np.abs(sa - rolled)))
            if d < best:
                best = d
    return best


def generate_distinct_shapes(rng: random.Random, n: int,
                             fourier_perturbation_amplitude: float,
                             min_pairwise_silhouette_distance: float,
                             max_attempts_per_shape: int = 60,
                             ) -> List[List[Tuple[float, float]]]:
    """Generate ``n`` blob shapes whose pairwise silhouette distances all exceed
    ``min_pairwise_silhouette_distance``.

    Falls back to the best-available shape after ``max_attempts_per_shape``
    retries to avoid pathological infinite loops at tight thresholds.
    """
    shapes: List[List[Tuple[float, float]]] = []
    for _ in range(n):
        best_candidate = None
        best_min_dist = -1.0
        for _attempt in range(max_attempts_per_shape):
            verts = generate_blob_vertices(rng, fourier_perturbation_amplitude)
            if not shapes:
                shapes.append(verts)
                break
            min_d = min(_silhouette_distance(verts, s) for s in shapes)
            if min_d >= min_pairwise_silhouette_distance:
                shapes.append(verts)
                break
            if min_d > best_min_dist:
                best_min_dist = min_d
                best_candidate = verts
        else:
            # Couldn't satisfy threshold; use best candidate we found.
            shapes.append(best_candidate if best_candidate is not None
                          else generate_blob_vertices(rng, fourier_perturbation_amplitude))
    return shapes


# ---------------------------------------------------------------------------
# Position sampling
# ---------------------------------------------------------------------------

def sample_positions(rng: random.Random, n: int, width: int, height: int,
                     margin: int, min_dist: float, max_attempts: int = 8000) -> List[Tuple[float, float]]:
    pts: List[Tuple[float, float]] = []
    for _ in range(max_attempts):
        if len(pts) == n:
            break
        x = rng.uniform(margin, width - margin)
        y = rng.uniform(margin, height - margin)
        if all(math.hypot(x - px, y - py) >= min_dist for px, py in pts):
            pts.append((x, y))
    return pts


# ---------------------------------------------------------------------------
# Replica sampling
# ---------------------------------------------------------------------------

def _sample_replicas(rng: random.Random, d_val: int) -> int:
    """Replica count from a flatter geometric: continue with prob 0.8 each
    step, capped at max(2, d). P(k=1)=0.2, P(k=2)=0.16, P(k=3)=0.128, …,
    with the residual mass piling at k=cap. Distribution is much more
    spread-out than p=0.5 → meaningful chance of seeing replica counts
    near the cap, while small counts are still common.
    """
    cap = max(2, d_val)
    k = 1
    while k < cap and rng.random() < 0.8:
        k += 1
    return k


# ---------------------------------------------------------------------------
# Sample generation
# ---------------------------------------------------------------------------

ELEMENT_COLOR = "#303030"


def sample_instance(rng: random.Random, width: int, height: int,
                    answer_lo: int, answer_hi: int,
                    d_val: int,
                    fourier_perturbation_amplitude: float,
                    min_pairwise_silhouette_distance: float,
                    radius: int) -> Dict[str, object] | None:
    num_groups = rng.randint(answer_lo, answer_hi)

    blob_shapes = generate_distinct_shapes(
        rng,
        num_groups,
        fourier_perturbation_amplitude=fourier_perturbation_amplitude,
        min_pairwise_silhouette_distance=min_pairwise_silhouette_distance,
    )

    elements: List[Dict[str, object]] = []
    group_records: List[Dict[str, object]] = []
    for gid, blob in enumerate(blob_shapes):
        size = _sample_replicas(rng, d_val)
        for _ in range(size):
            elements.append({
                "shape_id": gid,
                "group": gid,
            })
        group_records.append({
            "id": gid,
            "shape_id": gid,
            "size": size,
            "shape_vertices": [[round(x, 4), round(y, 4)] for x, y in blob],
        })

    n = len(elements)
    min_dist = radius * 2.4
    positions = sample_positions(rng, n, width, height, margin=radius + 6, min_dist=min_dist)
    if len(positions) < n:
        return None

    rng.shuffle(positions)
    for el, (x, y) in zip(elements, positions):
        el["x"] = round(x, 2)
        el["y"] = round(y, 2)

    return {
        "width": width,
        "height": height,
        "num_groups": num_groups,
        "num_elements": n,
        "answer": num_groups,
        "elements": elements,
        "groups": group_records,
        "radius": radius,
        "fourier_perturbation_amplitude": round(fourier_perturbation_amplitude, 5),
        "min_pairwise_silhouette_distance": round(min_pairwise_silhouette_distance, 5),
        "blob_shapes": [[[round(x, 4), round(y, 4)] for x, y in b] for b in blob_shapes],
    }


def render_instance(out_path: Path, record: Dict[str, object]) -> None:
    width = int(record["width"])
    height = int(record["height"])
    radius = float(record["radius"])
    blob_shapes = record["blob_shapes"]

    fig = plt.figure(figsize=(width / 100, height / 100), dpi=100)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)
    ax.axis("off")
    ax.set_facecolor("#faf6ed")

    for el in record["elements"]:
        cx = float(el["x"])
        cy = float(el["y"])
        blob = blob_shapes[el["shape_id"]]

        # Scale blob vertices to canvas coordinates
        verts = [(cx + vx * radius, cy + vy * radius) for vx, vy in blob]
        verts.append(verts[0])

        codes = [MplPath.MOVETO] + [MplPath.LINETO] * (len(verts) - 2) + [MplPath.CLOSEPOLY]
        path = MplPath(verts, codes)
        patch = mpatches.PathPatch(
            path,
            facecolor=ELEMENT_COLOR,
            edgecolor=ELEMENT_COLOR,
            linewidth=1.8,
            alpha=0.92,
            joinstyle="round",
            capstyle="round",
            zorder=2,
        )
        ax.add_patch(patch)

    fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0)
    plt.close(fig)


QUESTION = (
    "How many distinct shapes are in the image? "
    "The image contains many small irregular shapes (blobs) scattered across the canvas. "
    "All shapes are the same color. Two shapes belong to the same type if and only if "
    "they have exactly the same silhouette. The shapes are irregular and cannot be described "
    "by simple geometric names — you must visually compare them. "
    "Some shapes may appear only once while others appear multiple times. "
    "Count the total number of distinct shape types and report the count as a positive integer. "
    "Provide your final answer enclosed in <answer>...</answer> tags."
)


def generate_dataset(rng: random.Random, count: int, output_dir: Path,
                     width: int, height: int,
                     answer_lo: int, answer_hi: int,
                     d_val: int,
                     fourier_perturbation_amplitude: float,
                     min_pairwise_silhouette_distance: float,
                     radius: int) -> None:
    images_dir = output_dir / "images"
    images_dir.mkdir(parents=True, exist_ok=True)

    # Force evenly-spaced answers across [answer_lo, answer_hi].
    if count > 1:
        forced_targets = [
            int(round(answer_lo + i * (answer_hi - answer_lo) / (count - 1)))
            for i in range(count)
        ]
    else:
        forced_targets = [answer_lo]
    print(f"forced group counts: {forced_targets}")

    records: List[Dict[str, object]] = []
    data_records: List[Dict[str, object]] = []
    for idx in range(count):
        target = forced_targets[idx]
        for _ in range(2000):
            rec = sample_instance(
                rng, width, height,
                answer_lo=target, answer_hi=target,
                d_val=d_val,
                fourier_perturbation_amplitude=fourier_perturbation_amplitude,
                min_pairwise_silhouette_distance=min_pairwise_silhouette_distance,
                radius=radius,
            )
            if rec is not None and rec.get("answer") == target:
                break
        else:
            print(f"Skip {idx} (could not hit target={target})")
            continue
        name = f"attribute_group_counting_{idx:05d}.png"
        render_instance(images_dir / name, rec)
        rec["image"] = f"images/{name}"
        rec["question"] = QUESTION
        records.append(rec)
        data_records.append({"image": rec["image"], "question": QUESTION, "gt": rec["answer"]})
        print(f"  [{idx+1}/{count}] groups={rec['answer']} elements={rec['num_elements']}")

    (output_dir / "annotations.jsonl").write_text(
        "\n".join(json.dumps(r) for r in records) + "\n"
    )
    (output_dir / "data.json").write_text(json.dumps(data_records, indent=4))


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser()
    p.add_argument("--output-root", type=Path, required=True)
    p.add_argument("--count", type=int, default=30)
    p.add_argument("--width", type=int, default=900)
    p.add_argument("--height", type=int, default=900)
    p.add_argument("--radius", type=int, default=36)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--difficulty", type=int, default=5,
                   help="Integer difficulty >=0; scales distinct-shape count, "
                        "replica geometric cap, blob perturbation, silhouette "
                        "separation, and canvas area.")
    return p.parse_args()


def main() -> None:
    args = parse_args()
    rng = random.Random(args.seed)

    d = max(0, int(args.difficulty))

    # Difficulty formulas.
    answer_lo = 3
    answer_hi = 5 + d
    fourier_perturbation_amplitude = 0.20 / (1 + 0.2 * d)
    min_pairwise_silhouette_distance = 0.22 / (1 + 0.2 * d)

    # Canvas scaling: area ~ total shape instances (answer_hi * E[replicas=2]).
    N_d = (5 + d) * 2
    N_0 = 5 * 2
    s = math.sqrt(max(1.0, N_d / N_0))
    args.width = int(round(args.width * s))
    args.height = int(round(args.height * s))

    print(f"difficulty={d} answer_range=[{answer_lo},{answer_hi}] "
          f"fourier_amp={fourier_perturbation_amplitude:.4f} "
          f"silhouette_min={min_pairwise_silhouette_distance:.4f} "
          f"canvas={args.width}x{args.height}")

    generate_dataset(
        rng=rng, count=args.count, output_dir=args.output_root,
        width=args.width, height=args.height,
        answer_lo=answer_lo, answer_hi=answer_hi,
        d_val=d,
        fourier_perturbation_amplitude=fourier_perturbation_amplitude,
        min_pairwise_silhouette_distance=min_pairwise_silhouette_distance,
        radius=args.radius,
    )
    print(f"Saved to {args.output_root}")


if __name__ == "__main__":
    main()