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.size = [1] * 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 set_size(self, x: int) -> int: return self.size[self.find(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 self.size[ra] += self.size[rb] 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]]: """ Build a set of edges that: 1. Are shorter than max_edge_len 2. Don't pass within dot_radius of any other dot 3. Don't cross each other (planar) Returns list of (i, j, dist) sorted by dist, with the planar filter applied. """ n = len(dots) # Step 1: candidate edges sorted by length, filtered by dot clearance 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 # Check this edge doesn't pass near any other dot 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() # Step 2: greedily add edges, skip if they cross an already-added edge accepted: List[Tuple[int, int, float]] = [] # For fast crossing checks, store segment coords 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: # Skip if shared endpoint 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 def build_spanning_forest( rng: random.Random, n: int, planar_edges: List[Tuple[int, int, float]], num_components: int, ) -> Tuple[List[Tuple[int, int]], List[List[int]]]: """ From the planar edge set, build a spanning forest with exactly num_components trees using Union-Find. Strategy: shuffle edges, greedily merge until we reach the target number of components. Then collect extra intra-component edges. """ uf = UnionFind(n) # We need to reduce n sets down to num_components, so we need n - num_components merges. target_merges = n - num_components # Cap: no single component should exceed ~2x the ideal even share. max_component_size = max(4, (n // num_components) * 2) # Shuffle edges but bias toward shorter ones: split into short/long halves, # shuffle each, concatenate. mid = len(planar_edges) // 2 short = list(planar_edges[:mid]) long = list(planar_edges[mid:]) rng.shuffle(short) rng.shuffle(long) shuffled = short + long tree_edges: List[Tuple[int, int]] = [] deferred: List[Tuple[int, int, float]] = [] extra_edges: List[Tuple[int, int]] = [] for i, j, d in shuffled: if uf.find(i) != uf.find(j): if len(tree_edges) < target_merges: merged_size = uf.set_size(i) + uf.set_size(j) if merged_size <= max_component_size: uf.union(i, j) tree_edges.append((i, j)) else: deferred.append((i, j, d)) else: extra_edges.append((i, j)) else: extra_edges.append((i, j)) # Second pass: use deferred edges if we still need merges for i, j, _d in deferred: if len(tree_edges) >= target_merges: break if uf.find(i) != uf.find(j): uf.union(i, j) tree_edges.append((i, j)) # Add some extra intra-component edges for visual richness # Only pick edges where both endpoints are already in the same component intra_edges = [(i, j) for i, j in extra_edges if uf.find(i) == uf.find(j)] rng.shuffle(intra_edges) bonus = min(len(intra_edges), max(n // 6, 3)) tree_edges.extend(intra_edges[:bonus]) # Build component membership comp_map: Dict[int, List[int]] = {} for node in range(n): root = uf.find(node) comp_map.setdefault(root, []).append(node) components = list(comp_map.values()) return tree_edges, components # --------------------------------------------------------------------------- # Instance sampling # --------------------------------------------------------------------------- def sample_instance( rng: random.Random, width: int, height: int, grid_rows: int, grid_cols: int, min_components: int, max_components: int, num_dots_min: int, num_dots_max: int, min_gap: float, dot_radius: float, max_edge_len: float, close_strand_tolerance: float = 0.0, ) -> Dict[str, object] | None: num_components = rng.randint(min_components, max_components) num_dots = rng.randint(max(num_dots_min, num_components * 2), num_dots_max) dots = place_dots(rng, grid_rows, grid_cols, num_dots, min_gap) if len(dots) < num_components * 2: return None planar_edges = build_planar_edge_set(dots, dot_radius, max_edge_len) # Check we have enough edges to connect dots into num_components trees # (need at least len(dots) - num_components edges in a spanning forest) if len(planar_edges) < len(dots) - num_components: return None edges, components = build_spanning_forest(rng, len(dots), planar_edges, num_components) # Reject if any component has fewer than 2 dots if any(len(c) < 2 for c in components): return None actual_components = len(components) if actual_components < min_components: return None # Enforce close_strand_tolerance: dots from different components must be # at least this many grid units apart (visual separation). if close_strand_tolerance > 0: node_to_comp = {} for ci, comp in enumerate(components): for node in comp: node_to_comp[node] = ci for a in range(len(dots)): ra, ca = dots[a] for b in range(a + 1, len(dots)): if node_to_comp[a] == node_to_comp[b]: continue rb, cb = dots[b] if math.hypot(ra - rb, ca - cb) < close_strand_tolerance: 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_components": actual_components, "num_dots": len(dots), "question": ( "How many connected components are there in the image? " "A connected component is a maximal group of dots such that any two dots " "in the group are linked by a path of one or more drawn line segments " "(directly or through other dots in the same group). " "Every component contains at least two dots. " "Two dots that are not linked by any chain of line segments " "belong to different components, even if they appear visually close. " "Count every connected component and report the total. " "Provide your final answer enclosed in ... tags." ), "answer": actual_components, "dots": [[r, c] for r, c in dots], "components": components, "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 border_lw = 2.0 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=border_lw, 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 ensure_output_dir(root: Path) -> Tuple[Path, Path]: root.mkdir(parents=True, exist_ok=True) images_dir = root / "images" images_dir.mkdir(exist_ok=True) return root, images_dir def generate_dataset( rng: random.Random, count: int, output_dir: Path, images_dir: Path, width: int, height: int, grid_rows: int, grid_cols: int, min_components: int, max_components: int, num_dots_min: int, num_dots_max: int, min_gap: float, dot_radius: float, max_edge_len: float, close_strand_tolerance: float = 0.0, ) -> None: records: List[Dict[str, object]] = [] data_records: List[Dict[str, object]] = [] # Force evenly-spaced answers across [min_components, max_components]. if count > 1: forced_targets = [ int(round(min_components + i * (max_components - min_components) / (count - 1))) for i in range(count) ] else: forced_targets = [min_components] print(f"forced component counts: {forced_targets}") for idx in range(count): sub_seed = rng.randint(0, 2**31 - 1) tgt = forced_targets[idx] for _ in range(2000): record = sample_instance( rng=rng, width=width, height=height, grid_rows=grid_rows, grid_cols=grid_cols, min_components=tgt, max_components=tgt, num_dots_min=num_dots_min, num_dots_max=num_dots_max, min_gap=min_gap, dot_radius=dot_radius, max_edge_len=max_edge_len, close_strand_tolerance=close_strand_tolerance, ) if record is not None and record.get("answer") == tgt: break else: print(f"Warning: could not generate sample {idx}, skipping") continue image_name = f"counting_connected_components_{idx:05d}.png" render_instance(images_dir / image_name, record, noise_seed=sub_seed) record["image"] = f"images/{image_name}" records.append(record) data_records.append({ "image": record["image"], "question": record["question"], "answer": record["answer"], }) print(f" [{idx+1}/{count}] components={record['answer']} dots={record['num_dots']}") with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh: for record in records: fh.write(json.dumps(record) + "\n") data_json = { "task": "counting_connected_components", "category": "distributed_scanning", "count": len(data_records), "items": data_records, } with (output_dir / "data.json").open("w", encoding="utf-8") as fh: json.dump(data_json, fh, indent=2) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Generate a counting-connected-components dataset.") parser.add_argument("--output-root", type=Path, required=True, help="Dataset root directory.") parser.add_argument("--count", type=int, default=30) 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-components", type=int, default=4) parser.add_argument("--max-components", type=int, default=12) 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("--seed", type=int, default=42) parser.add_argument("--difficulty", type=int, default=5, help="Integer difficulty >=0; scales components and dot count.") return parser.parse_args() def main() -> None: args = parse_args() rng = random.Random(args.seed) output_dir, images_dir = ensure_output_dir(args.output_root) d = max(0, int(args.difficulty)) # Difficulty scaling per spec min_components = 10 max_components = 10 + 2 * d num_dots_min = 40 num_dots_max = 40 + 20 * d close_strand_tolerance = float(max(3, 8 - 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)) generate_dataset( rng=rng, count=args.count, output_dir=output_dir, images_dir=images_dir, width=args.width, height=args.height, grid_rows=args.grid_rows, grid_cols=args.grid_cols, min_components=min_components, max_components=max_components, num_dots_min=num_dots_min, num_dots_max=num_dots_max, min_gap=args.min_gap, dot_radius=args.dot_radius, max_edge_len=args.max_edge_len, close_strand_tolerance=close_strand_tolerance, ) print(f"Saved dataset to {args.output_root}") if __name__ == "__main__": main()