File size: 19,548 Bytes
f69e256 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | """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"
# ── Closed-loop construction ───────────────────────────────────────
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))
# splprep with per=True expects the input to already be closed.
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)
# ── Crossing detection (used for the close-approach validation) ────
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)
# Closed curve: neighbours wrap around.
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:
# Closed curve: mask neighbours with wraparound distance.
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
# ── Instance sampling ──────────────────────────────────────────────
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
# Re-detect with segment indices for angle computation.
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])
# Enforce: no self-crossings beyond allowed limit.
if any(len(sd) > max_self_crossings_per_loop for sd in self_details):
continue
# Enforce: total inter-loop crossings >= min_inter_crossings.
total_inter = sum(len(v) for v in pair_details.values())
if total_inter < min_inter_crossings:
continue
# Enforce: every crossing has angle >= min_crossing_angle_deg.
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
# ── Rendering ──────────────────────────────────────────────────────
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)
# ── 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=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))
# Canvas scaling: N_d = 5 + d, N_0 = 5.
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))
# num_loops ∈ [3, 5 + d]
args.min_loops = 10
args.max_loops = 10 + 2 * d
# Fixed constraints.
max_self_crossings_per_loop = 0
min_inter_crossings = 10 + 2 * d
min_crossing_angle_deg = 30.0
loop_thickness_px = 4.0 # absolute; do not scale
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 # noqa: E402
# Force evenly-spaced answer counts across [min_loops, max_loops].
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()
|