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 numpy as np Cell = Tuple[int, int] # --------------------------------------------------------------------------- # Geometry helpers # --------------------------------------------------------------------------- def _cross(ox: float, oy: float, px: float, py: float, qx: float, qy: float) -> float: return (px - ox) * (qy - oy) - (py - oy) * (qx - ox) def segments_intersect_properly( ax: float, ay: float, bx: float, by: float, cx: float, cy: float, dx: float, dy: float, ) -> bool: """True if segment AB *properly* crosses segment CD (shared endpoints don't count).""" d1 = _cross(cx, cy, dx, dy, ax, ay) d2 = _cross(cx, cy, dx, dy, bx, by) d3 = _cross(ax, ay, bx, by, cx, cy) d4 = _cross(ax, ay, bx, by, dx, dy) if ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and \ ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)): return True return False def point_seg_dist(px: float, py: float, ax: float, ay: float, bx: float, by: float) -> float: dx = bx - ax dy = by - ay len_sq = dx * dx + dy * dy if len_sq < 1e-12: return math.hypot(px - ax, py - ay) t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / len_sq)) return math.hypot(px - (ax + t * dx), py - (ay + t * dy)) # --------------------------------------------------------------------------- # Union-Find # --------------------------------------------------------------------------- class UnionFind: def __init__(self, n: int) -> None: self.parent = list(range(n)) self.rank = [0] * n self.num_sets = n def find(self, x: int) -> int: while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x def union(self, a: int, b: int) -> bool: ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra self.parent[rb] = ra if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 self.num_sets -= 1 return True # --------------------------------------------------------------------------- # Graph construction — planar, no-dot-crossing edge set # --------------------------------------------------------------------------- def place_dots( rng: random.Random, grid_rows: int, grid_cols: int, num_dots: int, min_gap: float, border_margin: int = 5, max_attempts: int = 8000, ) -> List[Cell]: cells: List[Cell] = [] lo_r, hi_r = border_margin, grid_rows - border_margin lo_c, hi_c = border_margin, grid_cols - border_margin for _ in range(max_attempts): if len(cells) == num_dots: break r = rng.randint(lo_r, hi_r - 1) c = rng.randint(lo_c, hi_c - 1) if all(math.hypot(r - er, c - ec) >= min_gap for er, ec in cells): cells.append((r, c)) return cells def build_planar_edge_set( dots: List[Cell], dot_radius: float, max_edge_len: float, ) -> List[Tuple[int, int, float]]: n = len(dots) candidates: List[Tuple[float, int, int]] = [] for i in range(n): ri, ci = dots[i] for j in range(i + 1, n): rj, cj = dots[j] d = math.hypot(ri - rj, ci - cj) if d > max_edge_len: continue clear = True for k in range(n): if k == i or k == j: continue if point_seg_dist(dots[k][0], dots[k][1], ri, ci, rj, cj) < dot_radius + 0.8: clear = False break if clear: candidates.append((d, i, j)) candidates.sort() accepted: List[Tuple[int, int, float]] = [] seg_coords: List[Tuple[float, float, float, float]] = [] for dist, i, j in candidates: ri, ci = dots[i] rj, cj = dots[j] crosses = False for ax, ay, bx, by in seg_coords: if (ri == ax and ci == ay) or (ri == bx and ci == by) or \ (rj == ax and cj == ay) or (rj == bx and cj == by): continue if segments_intersect_properly(ri, ci, rj, cj, ax, ay, bx, by): crosses = True break if not crosses: accepted.append((i, j, dist)) seg_coords.append((float(ri), float(ci), float(rj), float(cj))) return accepted # --------------------------------------------------------------------------- # Graph construction for bounded faces # --------------------------------------------------------------------------- def build_graph_with_faces( rng: random.Random, n: int, planar_edges: List[Tuple[int, int, float]], target_faces: int, ) -> Tuple[List[Tuple[int, int]], int, int] | None: """Build a planar graph targeting a specific number of bounded faces. Strategy: 1. Build a spanning forest from shuffled edges (connecting as many dots as possible into one component). 2. Each additional intra-component edge beyond the spanning forest creates exactly one new bounded face (Euler: F_bounded = E - V + C). 3. Add extra edges until we reach the target face count. Returns (edges, bounded_faces, num_components) or None if infeasible. """ uf = UnionFind(n) # Shuffle edges, biased toward shorter ones mid = len(planar_edges) // 2 short = list(planar_edges[:mid]) long = list(planar_edges[mid:]) rng.shuffle(short) rng.shuffle(long) shuffled = short + long # Phase 1: build spanning forest (connect everything into one component ideally) tree_edges: List[Tuple[int, int]] = [] extra_edges: List[Tuple[int, int]] = [] for i, j, d in shuffled: if uf.find(i) != uf.find(j): uf.union(i, j) tree_edges.append((i, j)) else: extra_edges.append((i, j)) num_components = uf.num_sets # Phase 2: add extra edges to create faces # bounded_faces = E - V + C = (tree + extra) - V + C # spanning forest has V - C edges, so faces = num_extra_added rng.shuffle(extra_edges) if len(extra_edges) < target_faces: return None selected_edges = tree_edges + extra_edges[:target_faces] bounded_faces = target_faces return selected_edges, bounded_faces, num_components # --------------------------------------------------------------------------- # Instance sampling # --------------------------------------------------------------------------- QUESTION = ( "How many distinct enclosed regions (bounded faces) are visible in this image? " "An enclosed region is a maximal area that is fully surrounded by the drawn " "line segments on every side, with no opening to the outside background. The " "unbounded outside area does not count as an enclosed region. Each enclosed " "region should be counted exactly once, regardless of its shape. Count every " "enclosed region in the entire image and report the total as a positive integer. " "Provide your final answer enclosed in ... tags." ) def sample_instance( rng: random.Random, width: int, height: int, grid_rows: int, grid_cols: int, min_faces: int, max_faces: int, num_dots_min: int, num_dots_max: int, min_gap: float, dot_radius: float, max_edge_len: float, ) -> Dict[str, object] | None: target_faces = rng.randint(min_faces, max_faces) num_dots = rng.randint(num_dots_min, num_dots_max) dots = place_dots(rng, grid_rows, grid_cols, num_dots, min_gap) if len(dots) < 10: return None planar_edges = build_planar_edge_set(dots, dot_radius, max_edge_len) result = build_graph_with_faces(rng, len(dots), planar_edges, target_faces) if result is None: return None edges, bounded_faces, num_components = result if bounded_faces < min_faces: return None margin = int(min(width, height) * 0.10) square_size = min(width, height) - 2 * margin square_left = (width - square_size) / 2.0 square_top = (height - square_size) / 2.0 return { "width": width, "height": height, "grid_rows": grid_rows, "grid_cols": grid_cols, "square_left": round(square_left, 2), "square_top": round(square_top, 2), "square_size": round(square_size, 2), "num_dots": len(dots), "num_edges": len(edges), "num_components": num_components, "question": QUESTION, "answer": bounded_faces, "dots": [[r, c] for r, c in dots], "edges": [[i, j] for i, j in edges], "dot_radius": dot_radius, } # --------------------------------------------------------------------------- # Rendering (matplotlib — smooth anti-aliased output) # --------------------------------------------------------------------------- LINE_COLOR = "#2f2f2f" DOT_COLOR = "#1d1916" def render_instance(out_path: Path, record: Dict[str, object], noise_seed: int = 0) -> None: width = int(record["width"]) height = int(record["height"]) grid_rows = int(record["grid_rows"]) grid_cols = int(record["grid_cols"]) square_left = float(record["square_left"]) square_top = float(record["square_top"]) square_size = float(record["square_size"]) dots: List[List[int]] = record["dots"] # type: ignore[assignment] edges: List[List[int]] = record["edges"] # type: ignore[assignment] dot_radius_grid = float(record["dot_radius"]) cell_w = square_size / grid_cols cell_h = square_size / grid_rows def to_pixel(r: float, c: float) -> Tuple[float, float]: px = square_left + (c + 0.5) * cell_w py = square_top + (r + 0.5) * cell_h return px, py pixel_dot_radius = dot_radius_grid * min(cell_w, cell_h) * 0.5 edge_thickness = max(1.5, pixel_dot_radius * 0.3) 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("#f8f6f0") # Subtle noise background nrng = np.random.default_rng(noise_seed) noise = nrng.normal(0.0, 1.0, size=(height, width)) noise = (noise - noise.min()) / max(noise.max() - noise.min(), 1e-6) ax.imshow(noise, cmap="Greys", alpha=0.05, extent=(0, width, height, 0), interpolation="bilinear") # White square background ax.fill_between( [square_left, square_left + square_size], [square_top, square_top], [square_top + square_size, square_top + square_size], color="#fffdf8", zorder=0.5, ) # Border bx = [square_left, square_left + square_size, square_left + square_size, square_left, square_left] by = [square_top, square_top, square_top + square_size, square_top + square_size, square_top] ax.plot(bx, by, color="#2d2720", linewidth=2.0, solid_capstyle="round", zorder=1.0) # Plain (v4_plain): solid edges. No dashed-line anti-shortcut. for i, j in edges: px1, py1 = to_pixel(dots[i][0], dots[i][1]) px2, py2 = to_pixel(dots[j][0], dots[j][1]) ax.plot([px1, px2], [py1, py2], color=LINE_COLOR, linewidth=edge_thickness, solid_capstyle="round", alpha=0.92, zorder=2.0) # Dots on top for r, c in dots: px, py = to_pixel(r, c) circle = plt.Circle((px, py), pixel_dot_radius, color=DOT_COLOR, zorder=3.0) ax.add_patch(circle) fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0) plt.close(fig) # --------------------------------------------------------------------------- # Dataset generation # --------------------------------------------------------------------------- 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=42) parser.add_argument("--width", type=int, default=1024) parser.add_argument("--height", type=int, default=1024) parser.add_argument("--grid-rows", type=int, default=100) parser.add_argument("--grid-cols", type=int, default=100) parser.add_argument("--min-faces", type=int, default=4) parser.add_argument("--max-faces", type=int, default=15) parser.add_argument("--num-dots-min", type=int, default=60) parser.add_argument("--num-dots-max", type=int, default=120) parser.add_argument("--min-gap", type=float, default=5.0) parser.add_argument("--dot-radius", type=float, default=1.5) parser.add_argument("--max-edge-len", type=float, default=25.0) parser.add_argument("--difficulty", type=int, default=5, help="Integer difficulty >=0; scales faces and dot count.") args = parser.parse_args() d = max(0, int(args.difficulty)) # Difficulty scaling per spec args.min_faces = 5 args.max_faces = 5 + 2 * d args.num_dots_min = 10 * d args.num_dots_max = 20 + 10 * d base_max_edge_len = args.max_edge_len args.max_edge_len = base_max_edge_len / (1.0 + 0.08 * d) # Canvas scaling based on num_dots_max growth N_d = 20 + 10 * d N_0 = 20 s = math.sqrt(max(1.0, N_d / N_0)) args.width = int(round(args.width * s)) args.height = int(round(args.height * s)) 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" rng = random.Random(args.seed) records = [] # Force evenly-spaced answers across [min_faces, max_faces]. if args.count > 1: forced_targets = [ int(round(args.min_faces + i * (args.max_faces - args.min_faces) / (args.count - 1))) for i in range(args.count) ] else: forced_targets = [args.min_faces] print(f"forced face counts: {forced_targets}") with ann_path.open("w") as f: for i in range(args.count): sub_seed = rng.randint(0, 2**31 - 1) tgt = forced_targets[i] for _ in range(2000): record = sample_instance( rng=rng, width=args.width, height=args.height, grid_rows=args.grid_rows, grid_cols=args.grid_cols, min_faces=tgt, max_faces=tgt, num_dots_min=args.num_dots_min, num_dots_max=args.num_dots_max, min_gap=args.min_gap, dot_radius=args.dot_radius, max_edge_len=args.max_edge_len, ) if record is not None and record.get("answer") == tgt: break else: print(f" [{i+1}/{args.count}] SKIP (failed to generate)") continue name = f"bounded_faces_counting_{i:05d}.png" render_instance(img_dir / name, record, noise_seed=sub_seed) print(f" [{i+1}/{args.count}] faces={record['answer']} dots={record['num_dots']} edges={record['num_edges']}") rec = { "image": f"images/{name}", "question": QUESTION, "answer": record["answer"], "metadata": { "bounded_faces": record["answer"], "num_dots": record["num_dots"], "num_edges": record["num_edges"], "num_components": record["num_components"], "seed": sub_seed, }, } f.write(json.dumps(rec) + "\n") records.append(rec) data_json = { "task": "bounded_faces_counting", "category": "distributed_scanning", "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()