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