| """Tangled Closed-Loop Counting. |
| |
| Each string is a smooth **closed curve** living entirely in the interior |
| of the canvas. Loops are generated by sampling interior waypoints on a |
| jittered ring around a random centre and fitting a periodic cubic |
| B-spline through them — the resulting curve has no endpoints at all, |
| which plugs the "skeletonize → count degree-1 pixels → divide by 2" |
| shortcut that beat the previous perimeter-anchored design. |
| |
| All loops render in the same dark colour. Loops may cross other loops |
| or themselves, but long parallel runs are rejected so every loop stays |
| individually traceable. |
| |
| The model is asked to count the total number of distinct closed loops. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import math |
| import os |
| import random |
| import sys |
| from collections import defaultdict |
| from pathlib import Path |
| from typing import Dict, List, Tuple |
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import numpy as np |
| from scipy.interpolate import splev, splprep |
| from tqdm import tqdm |
|
|
|
|
| LINE_COLOR = "#2f2f2f" |
|
|
|
|
| |
|
|
| def build_closed_loop( |
| rng: random.Random, |
| width: int, |
| height: int, |
| interior_margin: int = 55, |
| num_waypoints_range: Tuple[int, int] = (6, 10), |
| radius_range: Tuple[float, float] = (130.0, 215.0), |
| radius_jitter: float = 0.30, |
| angle_jitter: float = 0.42, |
| num_samples: int = 520, |
| existing_centers: List[Tuple[float, float]] | None = None, |
| min_center_gap: float = 190.0, |
| center_placement_attempts: int = 80, |
| ) -> Tuple[np.ndarray, Tuple[float, float]] | None: |
| """Build one smooth closed curve through jittered ring waypoints. |
| |
| Returns ``(polyline, (cx, cy))`` where the polyline's last point |
| equals its first, or ``None`` if no valid placement was found. |
| """ |
| num_wp = rng.randint(*num_waypoints_range) |
| r_mean = rng.uniform(*radius_range) |
| max_r = r_mean * (1 + radius_jitter) |
|
|
| low_x = interior_margin + max_r |
| high_x = width - interior_margin - max_r |
| low_y = interior_margin + max_r |
| high_y = height - interior_margin - max_r |
| if low_x >= high_x or low_y >= high_y: |
| return None |
|
|
| cx = cy = None |
| centers = existing_centers or [] |
| for _ in range(center_placement_attempts): |
| cand_x = rng.uniform(low_x, high_x) |
| cand_y = rng.uniform(low_y, high_y) |
| ok = True |
| for ex_x, ex_y in centers: |
| if (cand_x - ex_x) ** 2 + (cand_y - ex_y) ** 2 < min_center_gap ** 2: |
| ok = False |
| break |
| if ok: |
| cx, cy = cand_x, cand_y |
| break |
| if cx is None: |
| return None |
|
|
| base_angles = np.linspace(0.0, 2 * math.pi, num_wp, endpoint=False) |
| phase = rng.uniform(0.0, 2 * math.pi) |
|
|
| xs: List[float] = [] |
| ys: List[float] = [] |
| for base in base_angles: |
| ang = base + phase + rng.uniform(-angle_jitter, angle_jitter) |
| r = r_mean * (1.0 + rng.uniform(-radius_jitter, radius_jitter)) |
| xs.append(cx + r * math.cos(ang)) |
| ys.append(cy + r * math.sin(ang)) |
|
|
| |
| xs.append(xs[0]) |
| ys.append(ys[0]) |
|
|
| try: |
| tck, _ = splprep([xs, ys], s=0.0, per=True, k=3) |
| except (TypeError, ValueError): |
| return None |
|
|
| u_dense = np.linspace(0.0, 1.0, num_samples) |
| x_dense, y_dense = splev(u_dense, tck) |
| poly = np.column_stack([np.asarray(x_dense), np.asarray(y_dense)]) |
|
|
| if (poly[:, 0].min() < interior_margin - 5 |
| or poly[:, 0].max() > width - interior_margin + 5 |
| or poly[:, 1].min() < interior_margin - 5 |
| or poly[:, 1].max() > height - interior_margin + 5): |
| return None |
|
|
| poly[-1] = poly[0] |
| return poly, (cx, cy) |
|
|
|
|
| |
|
|
| def _segments_cross(p0, p1, q0, q1) -> bool: |
| eps = 1e-8 |
| o1 = (p1[0]-p0[0])*(q0[1]-p0[1]) - (p1[1]-p0[1])*(q0[0]-p0[0]) |
| o2 = (p1[0]-p0[0])*(q1[1]-p0[1]) - (p1[1]-p0[1])*(q1[0]-p0[0]) |
| o3 = (q1[0]-q0[0])*(p0[1]-q0[1]) - (q1[1]-q0[1])*(p0[0]-q0[0]) |
| o4 = (q1[0]-q0[0])*(p1[1]-q0[1]) - (q1[1]-q0[1])*(p1[0]-q0[0]) |
| return ((o1 > eps and o2 < -eps) or (o1 < -eps and o2 > eps)) and \ |
| ((o3 > eps and o4 < -eps) or (o3 < -eps and o4 > eps)) |
|
|
|
|
| def _circular_seg_gap(i: int, j: int, n: int) -> int: |
| d = abs(i - j) |
| return min(d, n - d) |
|
|
|
|
| def _find_crossings( |
| poly_a: np.ndarray, |
| poly_b: np.ndarray, |
| same_curve: bool = False, |
| min_seg_gap: int = 10, |
| ) -> List[Dict]: |
| na = len(poly_a) - 1 |
| nb = len(poly_b) - 1 |
|
|
| a_min_x = np.minimum(poly_a[:-1, 0], poly_a[1:, 0]) |
| a_max_x = np.maximum(poly_a[:-1, 0], poly_a[1:, 0]) |
| a_min_y = np.minimum(poly_a[:-1, 1], poly_a[1:, 1]) |
| a_max_y = np.maximum(poly_a[:-1, 1], poly_a[1:, 1]) |
|
|
| b_min_x = np.minimum(poly_b[:-1, 0], poly_b[1:, 0]) |
| b_max_x = np.maximum(poly_b[:-1, 0], poly_b[1:, 0]) |
| b_min_y = np.minimum(poly_b[:-1, 1], poly_b[1:, 1]) |
| b_max_y = np.maximum(poly_b[:-1, 1], poly_b[1:, 1]) |
|
|
| cell_size = max(np.median(np.concatenate([a_max_x - a_min_x, |
| b_max_x - b_min_x])), 1.0) * 3 |
|
|
| grid_b = defaultdict(list) |
| for j in range(nb): |
| cx0 = int(b_min_x[j] / cell_size); cx1 = int(b_max_x[j] / cell_size) |
| cy0 = int(b_min_y[j] / cell_size); cy1 = int(b_max_y[j] / cell_size) |
| for gx in range(cx0, cx1 + 1): |
| for gy in range(cy0, cy1 + 1): |
| grid_b[(gx, gy)].append(j) |
|
|
| checked = set() |
| details: List[Dict] = [] |
| for i in range(na): |
| cx0 = int(a_min_x[i] / cell_size); cx1 = int(a_max_x[i] / cell_size) |
| cy0 = int(a_min_y[i] / cell_size); cy1 = int(a_max_y[i] / cell_size) |
| for gx in range(cx0, cx1 + 1): |
| for gy in range(cy0, cy1 + 1): |
| if (gx, gy) not in grid_b: |
| continue |
| for j in grid_b[(gx, gy)]: |
| if same_curve: |
| ii, jj = min(i, j), max(i, j) |
| |
| if _circular_seg_gap(ii, jj, na) < min_seg_gap: |
| continue |
| key = (ii, jj) |
| else: |
| key = (i, j) |
| if key in checked: |
| continue |
| checked.add(key) |
| if same_curve: |
| si, sj = key |
| else: |
| si, sj = i, j |
| p0, p1 = poly_a[si], poly_a[si + 1] |
| q0, q1 = poly_b[sj], poly_b[sj + 1] |
| if not _segments_cross(p0, p1, q0, q1): |
| continue |
| d1 = p1 - p0 |
| d2 = q1 - q0 |
| denom = d1[0] * d2[1] - d1[1] * d2[0] |
| if abs(denom) < 1e-12: |
| continue |
| ti = ((q0[0] - p0[0]) * d2[1] - (q0[1] - p0[1]) * d2[0]) / denom |
| px = float(p0[0] + ti * d1[0]) |
| py = float(p0[1] + ti * d1[1]) |
| details.append({"px": px, "py": py}) |
| return details |
|
|
|
|
| def _details_to_points(details: List[Dict]) -> np.ndarray: |
| if not details: |
| return np.zeros((0, 2)) |
| return np.array([[d["px"], d["py"]] for d in details]) |
|
|
|
|
| def _curves_too_close( |
| poly_a: np.ndarray, |
| poly_b: np.ndarray, |
| same_curve: bool = False, |
| min_dist: float = 7.0, |
| sample_step: int = 3, |
| self_index_gap: int = 30, |
| known_crossings: np.ndarray | None = None, |
| crossing_exclude_radius: float = 55.0, |
| ) -> bool: |
| nb = len(poly_b) - 1 |
| b_pts = poly_b[:-1] |
| b_vecs = poly_b[1:] - poly_b[:-1] |
| b_lens_sq = np.maximum((b_vecs ** 2).sum(axis=1), 1e-12) |
|
|
| has_crossings = known_crossings is not None and len(known_crossings) > 0 |
|
|
| for idx in range(0, len(poly_a), sample_step): |
| px, py = poly_a[idx] |
| p = np.array([px, py]) |
| dp = p - b_pts |
| t = (dp * b_vecs).sum(axis=1) / b_lens_sq |
| t = np.clip(t, 0.0, 1.0) |
| proj = b_pts + t[:, None] * b_vecs |
| dists = np.sqrt(((p - proj) ** 2).sum(axis=1)) |
| if same_curve: |
| |
| seg_idx = np.arange(nb) |
| lin = np.abs(seg_idx - idx) |
| circ = np.minimum(lin, nb - lin) |
| mask = circ < self_index_gap |
| dists[mask] = 9999.0 |
| if dists.min() < min_dist: |
| if has_crossings: |
| cross_dists = np.sqrt(((p - known_crossings) ** 2).sum(axis=1)) |
| if cross_dists.min() < crossing_exclude_radius: |
| continue |
| return True |
| return False |
|
|
|
|
| |
|
|
| QUESTION = ( |
| "How many distinct closed loops are tangled together in this image? " |
| "Each loop is a single continuous curve that closes back on itself — " |
| "there are no loose endpoints anywhere. All loops are drawn in the " |
| "same colour and may cross other loops or themselves freely. Count " |
| "the total number of distinct closed loops and report the count as " |
| "a positive integer. " |
| "Provide your final answer enclosed in <answer>...</answer> tags." |
| ) |
|
|
|
|
| def _min_crossing_angle_deg(poly_a: np.ndarray, poly_b: np.ndarray, |
| details: List[Dict], same_curve: bool = False) -> float: |
| """Return the smallest crossing angle (deg) across all crossings, or |
| 180.0 if there are no crossings.""" |
| if not details: |
| return 180.0 |
| |
| na = len(poly_a) - 1 |
| nb = len(poly_b) - 1 |
| min_angle = 180.0 |
| for i in range(na): |
| p0, p1 = poly_a[i], poly_a[i + 1] |
| for j in range(nb): |
| if same_curve: |
| ii, jj = min(i, j), max(i, j) |
| if _circular_seg_gap(ii, jj, na) < 10: |
| continue |
| q0, q1 = poly_b[j], poly_b[j + 1] |
| if not _segments_cross(p0, p1, q0, q1): |
| continue |
| d1 = p1 - p0 |
| d2 = q1 - q0 |
| n1 = math.hypot(d1[0], d1[1]) |
| n2 = math.hypot(d2[0], d2[1]) |
| if n1 < 1e-9 or n2 < 1e-9: |
| continue |
| cos_a = (d1[0] * d2[0] + d1[1] * d2[1]) / (n1 * n2) |
| cos_a = max(-1.0, min(1.0, cos_a)) |
| ang = math.degrees(math.acos(abs(cos_a))) |
| if ang < min_angle: |
| min_angle = ang |
| return min_angle |
|
|
|
|
| def sample_instance( |
| rng: random.Random, |
| width: int, |
| height: int, |
| num_loops: int, |
| interior_margin: int = 55, |
| max_attempts: int = 600, |
| min_inter_crossings: int = 0, |
| max_self_crossings_per_loop: int = 0, |
| min_crossing_angle_deg: float = 30.0, |
| ) -> Dict | None: |
| for _ in range(max_attempts): |
| polylines: List[np.ndarray] = [] |
| centers: List[Tuple[float, float]] = [] |
| build_failed = False |
| for _ in range(num_loops): |
| result = None |
| for _ in range(40): |
| result = build_closed_loop( |
| rng, width, height, |
| interior_margin=interior_margin, |
| existing_centers=centers, |
| ) |
| if result is not None: |
| break |
| if result is None: |
| build_failed = True |
| break |
| poly, centre = result |
| polylines.append(poly) |
| centers.append(centre) |
| if build_failed: |
| continue |
|
|
| self_details: List[List[Dict]] = [] |
| pair_details: Dict[Tuple[int, int], List[Dict]] = {} |
| for a in range(num_loops): |
| self_details.append(_find_crossings(polylines[a], polylines[a], |
| same_curve=True)) |
| for b in range(a + 1, num_loops): |
| pair_details[(a, b)] = _find_crossings(polylines[a], polylines[b]) |
|
|
| |
| if any(len(sd) > max_self_crossings_per_loop for sd in self_details): |
| continue |
|
|
| |
| total_inter = sum(len(v) for v in pair_details.values()) |
| if total_inter < min_inter_crossings: |
| continue |
|
|
| |
| bad_angle = False |
| for a in range(num_loops): |
| if _min_crossing_angle_deg(polylines[a], polylines[a], |
| self_details[a], same_curve=True) < min_crossing_angle_deg: |
| bad_angle = True |
| break |
| for b in range(a + 1, num_loops): |
| if _min_crossing_angle_deg(polylines[a], polylines[b], |
| pair_details[(a, b)]) < min_crossing_angle_deg: |
| bad_angle = True |
| break |
| if bad_angle: |
| break |
| if bad_angle: |
| continue |
|
|
| too_close = False |
| for a in range(num_loops): |
| if _curves_too_close(polylines[a], polylines[a], same_curve=True, |
| known_crossings=_details_to_points(self_details[a])): |
| too_close = True |
| break |
| for b in range(a + 1, num_loops): |
| if _curves_too_close(polylines[a], polylines[b], |
| known_crossings=_details_to_points(pair_details[(a, b)])): |
| too_close = True |
| break |
| if too_close: |
| break |
| if too_close: |
| continue |
|
|
| return { |
| "width": width, |
| "height": height, |
| "num_loops": num_loops, |
| "polylines": polylines, |
| "inter_loop_crossings": int(total_inter), |
| "question": QUESTION, |
| "answer": num_loops, |
| } |
| return None |
|
|
|
|
| |
|
|
| def render_instance(out_path: Path, record: Dict, noise_seed: int, |
| thickness: float) -> None: |
| width = int(record["width"]) |
| height = int(record["height"]) |
| polylines = record["polylines"] |
|
|
| 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") |
|
|
| 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") |
|
|
| for poly in polylines: |
| ax.plot(poly[:, 0], poly[:, 1], |
| color=LINE_COLOR, linewidth=thickness, alpha=0.92, |
| solid_capstyle="round", solid_joinstyle="round", |
| zorder=2.0) |
|
|
| fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0) |
| plt.close(fig) |
|
|
|
|
| |
|
|
| 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("--min-loops", type=int, default=3) |
| parser.add_argument("--max-loops", type=int, default=5) |
| parser.add_argument("--thickness", type=float, default=2.0, |
| help="Absolute pixel thickness; never scaled.") |
| parser.add_argument("--difficulty", type=int, default=5, |
| help="Integer difficulty >=0; scales loop count.") |
| parser.add_argument("--workers", type=int, default=8, |
| help="Parallel worker processes for sampling. 1 = serial.") |
| args = parser.parse_args() |
|
|
| d = max(0, int(args.difficulty)) |
|
|
| |
| N_d = 5 + d |
| N_0 = 5 |
| s = math.sqrt(max(1.0, N_d / N_0)) |
| args.width = int(round(args.width * s)) |
| args.height = int(round(args.height * s)) |
|
|
| |
| args.min_loops = 10 |
| args.max_loops = 10 + 2 * d |
|
|
| |
| max_self_crossings_per_loop = 0 |
| min_inter_crossings = 10 + 2 * d |
| min_crossing_angle_deg = 30.0 |
| loop_thickness_px = 4.0 |
|
|
| out_root: Path = args.output_root |
| img_dir = out_root / "images" |
| img_dir.mkdir(parents=True, exist_ok=True) |
|
|
| sys.path.insert(0, str(Path(__file__).resolve().parents[3])) |
| from _sample_pool import parallel_sample_records |
|
|
| |
| if args.count > 1: |
| forced_targets = [ |
| int(round(args.min_loops + i * (args.max_loops - args.min_loops) / (args.count - 1))) |
| for i in range(args.count) |
| ] |
| else: |
| forced_targets = [args.min_loops] |
| print(f"forced loop counts: {forced_targets}") |
|
|
| records_raw = [] |
| for ti, tgt in enumerate(forced_targets): |
| def _attempt(rng, _tgt=tgt): |
| rec = sample_instance( |
| rng, args.width, args.height, num_loops=_tgt, |
| min_inter_crossings=min_inter_crossings, |
| max_self_crossings_per_loop=max_self_crossings_per_loop, |
| min_crossing_angle_deg=min_crossing_angle_deg, |
| max_attempts=50, |
| ) |
| return rec |
| sub = parallel_sample_records( |
| _attempt, count=1, workers=args.workers, |
| seed_base=args.seed + ti * 977, |
| ) |
| records_raw.extend(sub) |
| rng_render = random.Random(args.seed ^ 0xA5A5) |
| records = [] |
| for idx, record in enumerate(records_raw): |
| name = f"tangled_loops_{idx:05d}.png" |
| ns = rng_render.randint(0, 10**9) |
| render_instance(img_dir / name, record, noise_seed=ns, |
| thickness=loop_thickness_px) |
| record.pop("polylines") |
| record["image"] = f"images/{name}" |
| records.append(record) |
| print(f" {len(records)}/{args.count} valid samples (workers={args.workers})") |
|
|
| with (out_root / "annotations.jsonl").open("w") as fh: |
| for r in records: |
| fh.write(json.dumps(r) + "\n") |
|
|
| data_json = { |
| "task": "tangled_loops", |
| "category": "distributed_scanning", |
| "count": len(records), |
| "items": [ |
| {"image": r["image"], "question": r["question"], "answer": r["answer"]} |
| for r in records |
| ], |
| } |
| (out_root / "data.json").write_text(json.dumps(data_json, indent=2)) |
| print(f"Saved {len(records)} items to {out_root}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|