| """Line Intersections (turtle-based, anchored endpoints). |
| |
| Each curve has two preset endpoints placed on the perimeter of the canvas. |
| A straight "leader" segment connects each endpoint to an interior point |
| (~150px inward), keeping the perimeter band free of crossings. The middle |
| body of the curve is a turtle-style walk through waypoints distributed |
| across a generous interior zone — tangled, but not concentrated at the |
| very center. |
| |
| Only one of the two endpoints of each curve is labeled (A, B, C, ...). |
| The model starts tracing from the labeled endpoint and follows the |
| queried curve through the interior tangle. At every crossing it passes |
| through, it records the label of the OTHER curve involved (for a |
| self-crossing, that label is the queried curve's own letter). The |
| answer is the ordered sequence of labels. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import math |
| import os |
| import random |
| import string |
| 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 tqdm import tqdm |
|
|
| LINE_COLOR = "#2f2f2f" |
| LABEL_COLORS = [ |
| "#c23030", |
| "#1a6dba", |
| "#2d8e2d", |
| "#c47a18", |
| "#7a35a0", |
| ] |
|
|
|
|
| |
|
|
| def _perimeter_point(s: float, width: int, height: int, margin: int |
| ) -> Tuple[np.ndarray, np.ndarray]: |
| """Map s ∈ [0, 4) to (position, inward_unit_vector) on rect perimeter.""" |
| side = int(s) % 4 |
| t = s - int(s) |
| if side == 0: |
| x = margin + (width - 2 * margin) * t |
| y = margin |
| inward = np.array([0.0, 1.0]) |
| elif side == 1: |
| x = width - margin |
| y = margin + (height - 2 * margin) * t |
| inward = np.array([-1.0, 0.0]) |
| elif side == 2: |
| x = width - margin - (width - 2 * margin) * t |
| y = height - margin |
| inward = np.array([0.0, -1.0]) |
| else: |
| x = margin |
| y = height - margin - (height - 2 * margin) * t |
| inward = np.array([1.0, 0.0]) |
| return np.array([x, y]), inward |
|
|
|
|
| def sample_perimeter_anchors( |
| rng: random.Random, |
| num_anchors: int, |
| width: int, |
| height: int, |
| margin: int, |
| min_gap: float | None = None, |
| jitter_deg: float = 10.0, |
| max_attempts: int = 300, |
| ) -> List[Tuple[np.ndarray, np.ndarray]]: |
| """Sample `num_anchors` positions around the canvas perimeter, enforcing |
| a minimum gap (in perimeter units, 1 unit = one side).""" |
| if min_gap is None: |
| |
| min_gap = (4.0 / num_anchors) * 0.5 |
| for _ in range(max_attempts): |
| positions = sorted(rng.uniform(0.0, 4.0) for _ in range(num_anchors)) |
| ok = True |
| for i in range(num_anchors): |
| gap = (positions[(i + 1) % num_anchors] - positions[i]) % 4.0 |
| if gap < min_gap: |
| ok = False |
| break |
| if ok: |
| anchors = [] |
| for s in positions: |
| pt, inward = _perimeter_point(s, width, height, margin) |
| |
| ang = math.atan2(inward[1], inward[0]) |
| ang += math.radians(rng.uniform(-jitter_deg, jitter_deg)) |
| inward = np.array([math.cos(ang), math.sin(ang)]) |
| anchors.append((pt, inward)) |
| return anchors |
| return None |
|
|
|
|
| |
|
|
| def _angle_diff(current: float, target: float) -> float: |
| d = target - current |
| return (d + math.pi) % (2 * math.pi) - math.pi |
|
|
|
|
| def build_anchored_curve( |
| rng: random.Random, |
| width: int, |
| height: int, |
| start_pos: np.ndarray, |
| start_inward: np.ndarray, |
| end_pos: np.ndarray, |
| end_inward: np.ndarray, |
| leader_length: float = 150.0, |
| step_size: float = 3.3, |
| max_turn: float = 0.028, |
| drift_rate: float = 0.007, |
| num_waypoints: int = 2, |
| interior_margin: int = 260, |
| max_steps: int = 1800, |
| ) -> np.ndarray: |
| """Single-turtle curve from start_pos to a point near end_pos. |
| |
| Phase-dependent turning: |
| - Entry leader (first `leader_length` of path): max_turn = 0 (straight). |
| - Body (interior): waypoint steering within max_turn clamp. |
| - Exit leader (within `leader_length` of end_pos perimeter plane): |
| head-alignment only (no waypoint steering), rotating toward |
| -end_inward at up to max_turn/step. Then drives straight. |
| |
| Because the entire curve is a single turtle walk, there are no splice |
| discontinuities. The curve terminates when it crosses the perimeter plane |
| at end_pos; the final point is wherever it actually crosses (close to |
| end_pos when head-alignment locks in time). |
| """ |
| pts: List[np.ndarray] = [start_pos.copy()] |
| x, y = float(start_pos[0]), float(start_pos[1]) |
| theta = math.atan2(start_inward[1], start_inward[0]) |
|
|
| |
| raw_wps: List[np.ndarray] = [] |
| for _ in range(num_waypoints): |
| wx = rng.uniform(interior_margin, width - interior_margin) |
| wy = rng.uniform(interior_margin, height - interior_margin) |
| raw_wps.append(np.array([wx, wy])) |
| direction = end_pos - start_pos |
| dir_norm = direction / (np.linalg.norm(direction) + 1e-9) |
| raw_wps.sort(key=lambda p: float(np.dot(p - start_pos, dir_norm))) |
|
|
| |
| |
| |
| funnel = end_pos + end_inward * 400.0 |
| lookahead = end_pos + (-end_inward) * 240.0 |
| waypoints: List[np.ndarray] = raw_wps + [funnel, lookahead] |
|
|
| exit_theta = math.atan2(-end_inward[1], -end_inward[0]) |
| entry_steps = max(2, int(leader_length / step_size)) |
|
|
| wp_idx = 0 |
| drift = 0.0 |
|
|
| |
| perp = np.array([-end_inward[1], end_inward[0]]) |
|
|
| for step_count in range(max_steps): |
| |
| |
| |
| sd = ((x - end_pos[0]) * end_inward[0] |
| + (y - end_pos[1]) * end_inward[1]) |
| |
| lat = abs((x - end_pos[0]) * perp[0] + (y - end_pos[1]) * perp[1]) |
|
|
| |
| if sd <= 0.0: |
| break |
|
|
| if step_count < entry_steps: |
| |
| turn = 0.0 |
| elif sd < leader_length and lat < 40.0: |
| |
| head_err = _angle_diff(theta, exit_theta) |
| turn = max(-max_turn, min(max_turn, head_err)) |
| else: |
| |
| is_final = (wp_idx == len(waypoints) - 1) |
| if is_final: |
| wx, wy = waypoints[-1] |
| pull = 0.18 |
| else: |
| wx, wy = waypoints[wp_idx] |
| steer_dist = math.hypot(wx - x, wy - y) |
| |
| if steer_dist < 140.0: |
| wp_idx += 1 |
| continue |
| pull = 0.09 |
|
|
| drift += rng.gauss(0, drift_rate) |
| drift = max(-max_turn * 0.7, min(max_turn * 0.7, drift)) |
| turn = drift + rng.gauss(0, max_turn * 0.12) |
| target_ang = math.atan2(wy - y, wx - x) |
| steer = _angle_diff(theta, target_ang) |
| turn += steer * pull |
| turn = max(-max_turn, min(max_turn, turn)) |
|
|
| theta += turn |
| x += step_size * math.cos(theta) |
| y += step_size * math.sin(theta) |
| pts.append(np.array([x, y])) |
|
|
| return np.array(pts) |
|
|
|
|
| |
|
|
| 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 _crossing_angle(p0, p1, q0, q1) -> float: |
| d1 = p1 - p0 |
| d2 = q1 - q0 |
| cos_a = np.dot(d1, d2) / (np.linalg.norm(d1) * np.linalg.norm(d2) + 1e-12) |
| return math.degrees(math.acos(min(1.0, abs(cos_a)))) |
|
|
|
|
| def _find_crossings( |
| poly_a: np.ndarray, |
| poly_b: np.ndarray, |
| same_curve: bool = False, |
| min_seg_gap: int = 10, |
| ): |
| """Returns (count, worst_angle, details). |
| |
| `details` is a list of dicts, one per crossing, with keys: |
| i, j — segment indices on poly_a and poly_b |
| ti, tj — crossing parameters ∈ (0, 1) along each segment |
| px, py — exact crossing point |
| angle — crossing angle in degrees |
| For same_curve=True, i < j is enforced so each crossing appears once. |
| """ |
| 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]) |
|
|
| all_min_x = np.concatenate([a_min_x, b_min_x]) |
| all_max_x = np.concatenate([a_max_x, b_max_x]) |
| cell_size = max(np.median(all_max_x - all_min_x), 1.0) * 3 |
|
|
| grid_a = defaultdict(list) |
| 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): |
| grid_a[(gx, gy)].append(i) |
|
|
| 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() |
| worst_angle = 180.0 |
| details: List[Dict] = [] |
| for cell_key in grid_a: |
| if cell_key not in grid_b: |
| continue |
| for i in grid_a[cell_key]: |
| for j in grid_b[cell_key]: |
| if same_curve: |
| ii, jj = min(i, j), max(i, j) |
| if jj - ii < min_seg_gap: |
| continue |
| key = (ii, jj) |
| else: |
| key = (i, j) |
| if key in checked: |
| continue |
| checked.add(key) |
|
|
| if a_max_x[i] < b_min_x[j] or b_max_x[j] < a_min_x[i] or \ |
| a_max_y[i] < b_min_y[j] or b_max_y[j] < a_min_y[i]: |
| continue |
|
|
| if same_curve: |
| si, sj = key |
| p0, p1 = poly_a[si], poly_a[si + 1] |
| q0, q1 = poly_b[sj], poly_b[sj + 1] |
| 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 |
| tj = ((q0[0] - p0[0]) * d1[1] - (q0[1] - p0[1]) * d1[0]) / denom |
| px = float(p0[0] + ti * d1[0]) |
| py = float(p0[1] + ti * d1[1]) |
| angle = _crossing_angle(p0, p1, q0, q1) |
| worst_angle = min(worst_angle, angle) |
| details.append({ |
| "i": int(si), "j": int(sj), |
| "ti": float(ti), "tj": float(tj), |
| "px": px, "py": py, "angle": float(angle), |
| }) |
| return len(details), worst_angle, 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 = 50, |
| known_crossings: np.ndarray | None = None, |
| crossing_exclude_radius: float = 30.0, |
| ) -> bool: |
| """Flag if ANY sample point on A comes within `min_dist` of B without |
| being attributable to a real crossing. Samples within |
| `crossing_exclude_radius` of any point in `known_crossings` are ignored |
| (that's the crossing region itself, where near-zero distance is expected). |
| """ |
| nb = len(poly_b) - 1 |
| if nb <= 0 or len(poly_a) == 0: |
| return False |
| 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: |
| mask = np.abs(np.arange(nb) - idx) < 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 |
|
|
|
|
| |
|
|
| def sample_instance( |
| rng: random.Random, |
| width: int, |
| height: int, |
| min_lines: int = 4, |
| max_lines: int = 4, |
| min_total_crossings: int = 12, |
| max_total_crossings: int = 60, |
| perimeter_margin: int = 70, |
| leader_length: float = 150.0, |
| interior_margin: int = 260, |
| max_attempts: int = 2500, |
| ) -> Dict | None: |
| labels = list(string.ascii_uppercase) |
|
|
| for _ in range(max_attempts): |
| num_lines = rng.randint(min_lines, max_lines) |
|
|
| anchors = sample_perimeter_anchors( |
| rng, num_lines * 2, width, height, |
| margin=perimeter_margin, |
| ) |
| if anchors is None: |
| continue |
|
|
| |
| |
| pairs = [(anchors[i], anchors[i + num_lines]) for i in range(num_lines)] |
| rng.shuffle(pairs) |
|
|
| polylines = [] |
| for (sp, sd), (ep, ed) in pairs: |
| poly = build_anchored_curve( |
| rng, width, height, |
| start_pos=sp, start_inward=sd, |
| end_pos=ep, end_inward=ed, |
| leader_length=leader_length, |
| step_size=rng.uniform(3.0, 3.8), |
| max_turn=rng.uniform(0.034, 0.044), |
| drift_rate=rng.uniform(0.010, 0.016), |
| num_waypoints=rng.randint(4, 6), |
| interior_margin=interior_margin, |
| ) |
| polylines.append(poly) |
|
|
| total = 0 |
| global_min_angle = 180.0 |
| self_details: Dict[int, List[Dict]] = {} |
| pair_details: Dict[Tuple[int, int], List[Dict]] = {} |
|
|
| for a in range(num_lines): |
| sc, ang, det = _find_crossings(polylines[a], polylines[a], |
| same_curve=True) |
| self_details[a] = det |
| total += sc |
| global_min_angle = min(global_min_angle, ang) |
| for b in range(a + 1, num_lines): |
| cc, ang, det = _find_crossings(polylines[a], polylines[b]) |
| pair_details[(a, b)] = det |
| total += cc |
| global_min_angle = min(global_min_angle, ang) |
|
|
| if total < min_total_crossings or total > max_total_crossings: |
| continue |
| if global_min_angle < 45.0: |
| continue |
|
|
| |
| |
| |
| min_dist_px = 0.01 * float(min(width, height)) |
| too_close = False |
| for a in range(num_lines): |
| if _curves_too_close(polylines[a], polylines[a], same_curve=True, |
| min_dist=min_dist_px, |
| known_crossings=_details_to_points(self_details[a])): |
| too_close = True; break |
| for b in range(a + 1, num_lines): |
| if _curves_too_close(polylines[a], polylines[b], |
| min_dist=min_dist_px, |
| known_crossings=_details_to_points(pair_details[(a, b)])): |
| too_close = True; break |
| if too_close: |
| break |
| if too_close: |
| continue |
|
|
| |
| |
| all_cross_pts = [] |
| for a in range(num_lines): |
| pts = _details_to_points(self_details[a]) |
| if len(pts) > 0: |
| all_cross_pts.append(pts) |
| for b in range(a + 1, num_lines): |
| pts = _details_to_points(pair_details[(a, b)]) |
| if len(pts) > 0: |
| all_cross_pts.append(pts) |
| if all_cross_pts: |
| stacked = np.concatenate(all_cross_pts, axis=0) |
| if len(stacked) >= 2: |
| diffs = stacked[:, None, :] - stacked[None, :, :] |
| dmat = np.sqrt((diffs ** 2).sum(axis=-1)) |
| np.fill_diagonal(dmat, np.inf) |
| if dmat.min() < 20.0: |
| continue |
|
|
| |
| |
| label_starts = [rng.random() < 0.5 for _ in range(num_lines)] |
|
|
| |
| |
| seq_lens = [] |
| for q in range(num_lines): |
| sl = 2 * len(self_details[q]) |
| for b in range(num_lines): |
| if b == q: |
| continue |
| key = (min(q, b), max(q, b)) |
| sl += len(pair_details[key]) |
| seq_lens.append(sl) |
|
|
| |
| TARGET = 10 |
| candidates = sorted( |
| range(num_lines), key=lambda i: abs(seq_lens[i] - TARGET) |
| ) |
| query_line = candidates[0] |
| seq_len = seq_lens[query_line] |
| if seq_len < 8 or seq_len > 13: |
| continue |
|
|
| query_label = labels[query_line] |
| line_labels = labels[:num_lines] |
|
|
| |
| query_poly = polylines[query_line] |
| qdiffs = np.diff(query_poly, axis=0) |
| qseg_lens = np.sqrt((qdiffs ** 2).sum(axis=1)) |
| qcum = np.concatenate([[0.0], np.cumsum(qseg_lens)]) |
|
|
| entries: List[Tuple[float, str]] = [] |
| |
| for d in self_details[query_line]: |
| pos_a = qcum[d["i"]] + d["ti"] * qseg_lens[d["i"]] |
| pos_b = qcum[d["j"]] + d["tj"] * qseg_lens[d["j"]] |
| entries.append((pos_a, query_label)) |
| entries.append((pos_b, query_label)) |
| |
| for other in range(num_lines): |
| if other == query_line: |
| continue |
| if query_line < other: |
| dets = pair_details[(query_line, other)] |
| for d in dets: |
| pos = qcum[d["i"]] + d["ti"] * qseg_lens[d["i"]] |
| entries.append((pos, labels[other])) |
| else: |
| dets = pair_details[(other, query_line)] |
| for d in dets: |
| |
| pos = qcum[d["j"]] + d["tj"] * qseg_lens[d["j"]] |
| entries.append((pos, labels[other])) |
|
|
| |
| |
| trace_forward = label_starts[query_line] |
| entries.sort(key=lambda e: e[0] if trace_forward else -e[0]) |
| answer_sequence = [label for _, label in entries] |
| answer = ", ".join(answer_sequence) |
|
|
| question = ( |
| f"The image shows {num_lines} curves. Each curve has one labeled " |
| f"endpoint on the perimeter (labels: {', '.join(line_labels)}). " |
| f"Starting from the labeled endpoint of curve {query_label}, follow " |
| f"curve {query_label} through the interior tangle. At every " |
| f"crossing you pass through, record the label of the OTHER curve " |
| f"involved — when curve {query_label} crosses itself, record " |
| f"{query_label}. Report the ordered sequence of labels, separated " |
| f"by commas (for example: A, C, B, C, A). " |
| f"Provide your final answer enclosed in <answer>...</answer> tags." |
| ) |
|
|
| return { |
| "width": width, |
| "height": height, |
| "num_lines": num_lines, |
| "query_line": query_line, |
| "query_label": query_label, |
| "line_labels": line_labels, |
| "total_crossings": total, |
| "sequence_length": seq_len, |
| "polylines": polylines, |
| "label_starts": label_starts, |
| "question": question, |
| "answer": answer, |
| } |
| return None |
|
|
|
|
| |
|
|
| def label_anchor_for_endpoint( |
| polyline: np.ndarray, |
| at_start: bool, |
| width: int, |
| height: int, |
| offset: float = 46.0, |
| tangent_span: int = 10, |
| ) -> Tuple[float, float]: |
| """Offset a label perpendicular to the leader direction at a labeled |
| curve endpoint. Prefer the side that keeps the label inside the canvas |
| and farther from the polyline.""" |
| if at_start: |
| pt = polyline[0] |
| tan = polyline[min(tangent_span, len(polyline) - 1)] - polyline[0] |
| else: |
| pt = polyline[-1] |
| tan = polyline[-1] - polyline[max(-tangent_span - 1, -len(polyline))] |
| tnorm = math.hypot(float(tan[0]), float(tan[1])) |
| if tnorm < 1e-8: |
| ux, uy = 0.0, -1.0 |
| else: |
| ux = float(tan[0]) / tnorm |
| uy = float(tan[1]) / tnorm |
| perps = [(-uy, ux), (uy, -ux)] |
| best = None |
| best_score = -1e9 |
| for px, py in perps: |
| cx = float(pt[0]) + px * offset |
| cy = float(pt[1]) + py * offset |
| score = 0.0 |
| if 30 < cx < width - 30 and 30 < cy < height - 30: |
| score += 200.0 |
| diffs = polyline - np.array([cx, cy]) |
| dists = np.sqrt((diffs ** 2).sum(axis=1)) |
| score += float(dists.min()) |
| if score > best_score: |
| best_score = score |
| best = (cx, cy) |
| cx, cy = best |
| return ( |
| float(np.clip(cx, 28, width - 28)), |
| float(np.clip(cy, 28, height - 28)), |
| ) |
|
|
|
|
| def render_instance(out_path: Path, record: Dict, noise_seed: int) -> None: |
| width = int(record["width"]) |
| height = int(record["height"]) |
| polylines = record["polylines"] |
| num_lines = record["num_lines"] |
| line_labels = record["line_labels"] |
| label_starts = record["label_starts"] |
|
|
| 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("#f3efe8") |
|
|
| 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.06, extent=(0, width, height, 0), |
| interpolation="bilinear") |
|
|
| for i in range(num_lines): |
| poly = polylines[i] |
| ax.plot( |
| poly[:, 0], poly[:, 1], |
| color=LINE_COLOR, linewidth=2.8, |
| solid_capstyle="round", solid_joinstyle="round", |
| zorder=2.0 + i * 0.05, |
| ) |
|
|
| for i in range(num_lines): |
| poly = polylines[i] |
| labeled_pt = poly[0] if label_starts[i] else poly[-1] |
| lc = LABEL_COLORS[i % len(LABEL_COLORS)] |
| lx, ly = label_anchor_for_endpoint( |
| poly, at_start=label_starts[i], width=width, height=height, |
| ) |
| |
| ax.plot([labeled_pt[0], lx], [labeled_pt[1], ly], |
| color="#9b7b56", linewidth=1.0, alpha=0.7, |
| linestyle=(0, (2.0, 3.2)), zorder=3.8) |
| |
| ax.scatter([labeled_pt[0]], [labeled_pt[1]], s=110, |
| facecolors=lc, edgecolors="white", linewidths=1.8, zorder=4.0) |
| |
| ax.text(lx, ly, line_labels[i], |
| fontsize=17, fontweight="bold", color=lc, |
| ha="center", va="center", zorder=5.0, |
| bbox=dict(boxstyle="round,pad=0.2", facecolor="#f3efe8", |
| edgecolor=lc, alpha=0.95, linewidth=1.2)) |
|
|
| fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0) |
| plt.close(fig) |
|
|
|
|
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--output-root", type=Path, required=True) |
| parser.add_argument("--count", type=int, default=20) |
| 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-lines", type=int, default=3) |
| parser.add_argument("--max-lines", type=int, default=5) |
| parser.add_argument("--min-crossings", type=int, default=3) |
| parser.add_argument("--max-crossings", type=int, default=25) |
| parser.add_argument("--difficulty", type=int, default=5, |
| help="Integer difficulty >=0; scales line and crossing counts.") |
| parser.add_argument("--workers", type=int, default=8) |
| args = parser.parse_args() |
|
|
| d = max(0, int(args.difficulty)) |
| |
| |
| args.min_lines = 3 + d // 3 |
| args.max_lines = 3 + d // 3 |
| args.min_crossings = 10 |
| args.max_crossings = 10 + 2 * d |
|
|
| |
| N_d = 5 + 2 * 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)) |
|
|
| out_root = 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 |
|
|
| def _attempt(rng): |
| return sample_instance( |
| rng, args.width, args.height, |
| min_lines=args.min_lines, max_lines=args.max_lines, |
| min_total_crossings=args.min_crossings, |
| max_total_crossings=args.max_crossings, |
| max_attempts=50, |
| ) |
|
|
| records_raw = parallel_sample_records( |
| _attempt, count=args.count, workers=args.workers, |
| seed_base=args.seed, |
| ) |
| rng_render = random.Random(args.seed ^ 0xA5A5) |
| records = [] |
| for idx, record in enumerate(records_raw): |
| name = f"line_intersections_{idx:05d}.png" |
| ns = rng_render.randint(0, 10**9) |
| render_instance(img_dir / name, record, noise_seed=ns) |
| 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": "line_intersections", |
| "category": "sequential_traversal", |
| "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() |
|
|