File size: 30,400 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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
"""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",
]


# ── Perimeter anchors ──────────────────────────────────────────────

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:     # top edge, left -> right
        x = margin + (width - 2 * margin) * t
        y = margin
        inward = np.array([0.0, 1.0])
    elif side == 1:   # right edge, top -> bottom
        x = width - margin
        y = margin + (height - 2 * margin) * t
        inward = np.array([-1.0, 0.0])
    elif side == 2:   # bottom edge, right -> left
        x = width - margin - (width - 2 * margin) * t
        y = height - margin
        inward = np.array([0.0, -1.0])
    else:             # left edge, bottom -> top
        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:
        # 50% of perfectly even spacing
        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)
                # small angular jitter of the inward direction
                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


# ── Turtle body with anchored start/end ────────────────────────────

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])

    # Waypoints in interior, ordered by progress from start→end.
    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 waypoint deep on the exit axis pulls the turtle onto the axis
    # before the exit leader. Virtual lookahead past the exit then keeps
    # heading aligned with -end_inward as we approach end_pos.
    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 to end_inward (for lateral-offset measurement along perimeter edge).
    perp = np.array([-end_inward[1], end_inward[0]])

    for step_count in range(max_steps):
        # Signed perpendicular distance from turtle to end_pos perimeter plane.
        # end_inward points from perimeter INTO canvas, so on interior side
        # dot(pos - end_pos, end_inward) > 0; crossing the plane → <= 0.
        sd = ((x - end_pos[0]) * end_inward[0]
              + (y - end_pos[1]) * end_inward[1])
        # Lateral offset along the perimeter edge from end_pos.
        lat = abs((x - end_pos[0]) * perp[0] + (y - end_pos[1]) * perp[1])

        # Termination: turtle has reached/crossed the perimeter.
        if sd <= 0.0:
            break

        if step_count < entry_steps:
            # Entry leader: no turn (straight).
            turn = 0.0
        elif sd < leader_length and lat < 40.0:
            # Exit leader: pure head-alignment, no positional steering.
            head_err = _angle_diff(theta, exit_theta)
            turn = max(-max_turn, min(max_turn, head_err))
        else:
            # Body: waypoint steering.
            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)
                # reach must exceed turning diameter (2 * step / max_turn)
                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)


# ── Intersection detection ─────────────────────────────────────────

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  # enforce i < j for self-crossings
                    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  # close approach explained by a real crossing
            return True
    return False


# ── Instance sampling ──────────────────────────────────────────────

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

        # Pair anchor i with anchor i+num_lines: opposite-side pairing to
        # force curves through the interior.
        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

        # 1% of the canvas's short side keeps curves visibly separated
        # at any resolution while still letting the sampler converge at
        # higher difficulties.
        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

        # Reject if any two crossing points are too close to each other —
        # that would let multiple intersections be mistaken for one.
        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

        # Pick label positions: one of the two endpoints per curve.
        # "label_at_start" picks the first endpoint (index 0) when True.
        label_starts = [rng.random() < 0.5 for _ in range(num_lines)]

        # Per-curve sequence length: each self-crossing is hit twice during
        # the trace (entering + leaving), each pair-crossing once.
        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)

        # Prefer a query line whose sequence length is near ~10.
        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]

        # Build the ordered crossing sequence along the query curve.
        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]] = []
        # Self-crossings contribute two entries (both passes), labeled Q.
        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))
        # Pair-crossings contribute one entry, labeled with the other curve.
        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:
                    # query curve is poly_b in this pair → use j, tj
                    pos = qcum[d["j"]] + d["tj"] * qseg_lens[d["j"]]
                    entries.append((pos, labels[other]))

        # Orientation: labeled endpoint at poly[0] → forward arc order;
        # labeled endpoint at poly[-1] → reverse arc order.
        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


# ── Rendering ──────────────────────────────────────────────────────

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,
        )
        # Dashed connector from endpoint to offset label
        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)
        # Dot at the actual endpoint
        ax.scatter([labeled_pt[0]], [labeled_pt[1]], s=110,
                   facecolors=lc, edgecolors="white", linewidths=1.8, zorder=4.0)
        # Label at offset position
        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)


# ── Main ───────────────────────────────────────────────────────────

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))
    # num_lines grows as 3 + d//3 (no cap). num_crossings ∈ [3, 5 + 2d].
    # Fixed 45° minimum crossing angle (handled inside sample_instance).
    args.min_lines = 3 + d // 3
    args.max_lines = 3 + d // 3
    args.min_crossings = 10
    args.max_crossings = 10 + 2 * d

    # Canvas scaling: area ∝ N_d / N_0 with N_d = 5 + 2d.
    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  # noqa: E402

    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()