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 ... 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()