-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibcompose.py
More file actions
2214 lines (1841 loc) · 82.6 KB
/
libcompose.py
File metadata and controls
2214 lines (1841 loc) · 82.6 KB
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
High-level composition API for Truchet tiling.
Provides compose_* functions that place groups of tiles onto an existing Plane,
and make_* convenience wrappers that create a fresh Plane. Each returns a
Composition with the plane and tile outlines (for rendering).
"""
from __future__ import annotations
import os
import random as _random_module
from dataclasses import dataclass, field
from enum import Enum
from math import sqrt, hypot
from time import perf_counter
from z3 import Int, If, Solver, Optimize, sat, Or, And, Sum
from libgeom import (Point, rect, hexagon_in_rect,
oct_square_corners, corner_tri_vertices,
octagon_in_square)
from libtile import (TileType, edge_point_world, edge_points_with_normals,
oct_tile_type,
corner_tri_tile_type, enriched_square_tile_type,
hex_tile_type, tri30_tile_type,
equilateral_tri_tile_type)
from libtopo import Plane, ConstraintKind, Tile
class UnsatisfiableMatchingError(Exception):
"""Raised when solve_matching_assignment cannot find a valid matching assignment.
This can occur when:
1. No compatible matchings exist for a shared edge between tiles
2. The Z3 solver determines the constraints are unsatisfiable
Attributes:
message: Human-readable error description
tile_i: Index of first tile (for edge incompatibility)
tile_j: Index of second tile (for edge incompatibility)
edge_i: Edge index on tile_i (for edge incompatibility)
edge_j: Edge index on tile_j (for edge incompatibility)
positions: Full list of tile positions (for unsat case)
"""
def __init__(self, message: str, *,
tile_i: int | None = None,
tile_j: int | None = None,
edge_i: int | None = None,
edge_j: int | None = None,
positions: list[TilePosition] | None = None):
super().__init__(message)
self.message = message
self.tile_i = tile_i
self.tile_j = tile_j
self.edge_i = edge_i
self.edge_j = edge_j
self.positions = positions
@dataclass
class Composition:
plane: Plane
tile_outlines: list[list[Point]] = field(default_factory=list[list[Point]])
# ---------------------------------------------------------------------------
# compose_* functions — place tiles onto an existing Plane
# ---------------------------------------------------------------------------
def compose_square(plane: Plane, x: float, y: float, s: float,
tile_type: TileType | None = None) -> Composition:
"""Place a single square tile at (x, y) with side s."""
if tile_type is None:
tile_type = TileType.uniform("sq", 4, [0.5])
verts = list(rect(x, y, s, s))
plane.place_tile(tile_type, verts)
return Composition(plane=plane, tile_outlines=[verts])
def compose_square_grid(plane: Plane, x: float, y: float, s: float,
rows: int, cols: int,
tile_type: TileType | None = None) -> Composition:
"""Place a rows x cols grid of square tiles."""
if tile_type is None:
tile_type = TileType.uniform("sq", 4, [0.5])
outlines: list[list[Point]] = []
for r in range(rows):
for c in range(cols):
verts = list(rect(x + c * s, y + r * s, s, s))
plane.place_tile(tile_type, verts)
outlines.append(verts)
return Composition(plane=plane, tile_outlines=outlines)
def compose_488(plane: Plane, x: float, y: float, s: float) -> Composition:
"""Place a full 4.8.8 cell: octagon + 4 corner triangles + 4 enriched squares."""
sq_corners, oct_v = oct_square_corners(x, y, s)
tri_verts = corner_tri_vertices(sq_corners, oct_v)
plane.place_tile(oct_tile_type(), oct_v)
for tv in tri_verts:
plane.place_tile(corner_tri_tile_type(), tv)
sq_rects = [
list(rect(x, y - s, s, s)),
list(rect(x + s, y, s, s)),
list(rect(x, y + s, s, s)),
list(rect(x - s, y, s, s)),
]
for sq_edge, sq_v in zip([2, 3, 0, 1], sq_rects):
plane.place_tile(enriched_square_tile_type(sq_edge), sq_v)
outlines: list[list[Point]] = [list(oct_v)] + [list(tv) for tv in tri_verts] + sq_rects
return Composition(plane=plane, tile_outlines=outlines)
def compose_hex_corners(plane: Plane, x: float, y: float, L: float) -> Composition:
"""Place a hexagon + 4 corner 30-60-90 triangles in a 2L x L*sqrt(3) rect."""
w = 2 * L
h = L * sqrt(3)
hex_v = hexagon_in_rect(x, y, L)
r_tl: Point = (x, y)
r_tr: Point = (x + w, y)
r_br: Point = (x + w, y + h)
r_bl: Point = (x, y + h)
plane.place_tile(hex_tile_type(), hex_v)
tri_verts_list = [
[r_tl, hex_v[0], hex_v[5]],
[r_tr, hex_v[2], hex_v[1]],
[r_br, hex_v[3], hex_v[2]],
[r_bl, hex_v[5], hex_v[4]],
]
for tv in tri_verts_list:
plane.place_tile(tri30_tile_type(), tv)
outlines: list[list[Point]] = [list(hex_v)] + tri_verts_list
return Composition(plane=plane, tile_outlines=outlines)
def compose_hex_stacked(plane: Plane, x: float, y: float, L: float,
n: int = 2) -> Composition:
"""Place n vertically stacked hexagons."""
h = L * sqrt(3)
outlines: list[list[Point]] = []
for i in range(n):
hex_v = hexagon_in_rect(x, y + i * h, L)
plane.place_tile(hex_tile_type(), hex_v)
outlines.append(list(hex_v))
return Composition(plane=plane, tile_outlines=outlines)
def compose_equilateral_cell(plane: Plane, x: float, y: float,
L: float) -> Composition:
"""Place an equilateral triangle cell: 4 equilateral tris + 4 corner tris."""
w = 2 * L
h = L * sqrt(3)
sl = L / 2
ll = L * sqrt(3) / 2
rc = list(rect(x, y, w, h))
tl, tr, br, bl = rc
t1 = [(x + sl, y), (x, y + ll), (x + L, y + ll)]
t2 = [(x + sl, y), (x + L, y + ll), (x + w - sl, y)]
t3 = [(x + sl, y + h), (x, y + ll), (x + L, y + ll)]
t4 = [(x + w - sl, y + h), (x + sl, y + h), (x + L, y + ll)]
teq = equilateral_tri_tile_type()
t30 = tri30_tile_type()
outlines: list[list[Point]] = []
for tv in [t1, t2, t3, t4]:
plane.place_tile(teq, tv)
outlines.append(tv)
corner_tris = [
[tl, (x + sl, y), (x, y + ll)],
[tr, (x + w, y + ll), (x + w - sl, y)],
[br, (x + w - sl, y + h), (x + w, y + ll)],
[bl, (x, y + ll), (x + sl, y + h)],
]
for tv in corner_tris:
plane.place_tile(t30, tv)
outlines.append(tv)
return Composition(plane=plane, tile_outlines=outlines)
def compose_hex_eq_grid(plane: Plane, x: float, y: float, L: float,
rows: int, cols: int,
hex_cols: int = 2) -> Composition:
"""Place a grid mixing hex cells and equilateral triangle cells.
First hex_cols columns use hex+corners, remaining columns use equilateral cells.
"""
w = 2 * L
h = L * sqrt(3)
all_outlines: list[list[Point]] = []
for row in range(rows):
for col in range(cols):
gx = x + col * w
gy = y + row * h
if col < hex_cols:
comp = compose_hex_corners(plane, gx, gy, L)
else:
comp = compose_equilateral_cell(plane, gx, gy, L)
all_outlines.extend(comp.tile_outlines)
return Composition(plane=plane, tile_outlines=all_outlines)
# ---------------------------------------------------------------------------
# Non-crossing perfect matchings
# ---------------------------------------------------------------------------
def noncrossing_matchings(n: int) -> list[list[tuple[int, int]]]:
"""All non-crossing perfect matchings of n points on a circle (0..n-1).
n must be even. Returns list of matchings, each a sorted list of pairs.
Counted by Catalan number C(n/2).
"""
if n % 2 != 0:
raise ValueError(f"n must be even, got {n}")
if n == 0:
return [[]]
def _enum(pts: list[int]) -> list[list[tuple[int, int]]]:
if len(pts) == 0:
return [[]]
if len(pts) == 2:
return [[(pts[0], pts[1])]]
result: list[list[tuple[int, int]]] = []
first = pts[0]
# first matches with pts[k] for odd k (1, 3, 5, ...)
for k in range(1, len(pts), 2):
partner = pts[k]
left = pts[1:k] # between first and partner
right = pts[k + 1:] # after partner
for m_left in _enum(left):
for m_right in _enum(right):
result.append(sorted([(first, partner)] + m_left + m_right))
return result
return _enum(list(range(n)))
def _catalan_table(n: int) -> list[int]:
"""Precompute Catalan numbers C(0)..C(n)."""
c = [0] * (n + 1)
c[0] = 1
for i in range(1, n + 1):
c[i] = c[i - 1] * 2 * (2 * i - 1) // (i + 1)
return c
def sample_random_ncpm(n: int, rng: _random_module.Random,
min_span: int = 0) -> list[tuple[int, int]]:
"""Sample one random NCPM of n points (0..n-1) uniformly at random. O(n).
Uses Catalan-weighted recursive decomposition: pick a partner for the
first point in each sub-region with probability proportional to the
product of Catalan numbers for the resulting sub-problems.
min_span: if > 0, reject candidates whose circular distance to the
first point is less than min_span (eliminates pips when min_span=2).
"""
if n % 2 != 0:
raise ValueError(f"n must be even, got {n}")
if n == 0:
return []
cat = _catalan_table(n // 2)
result: list[tuple[int, int]] = []
def _sample(pts: list[int]):
if len(pts) == 0:
return
if len(pts) == 2:
result.append((pts[0], pts[1]))
return
first = pts[0]
m = len(pts)
# Candidates: pts[k] for odd k (1, 3, 5, ...)
weights: list[int] = []
candidates: list[int] = []
for k in range(1, m, 2):
left_size = k - 1 # points between first and partner
right_size = m - k - 1 # points after partner
w = cat[left_size // 2] * cat[right_size // 2]
# Skip too-close candidates (circular distance on original ring)
if min_span > 0 and w > 0:
dist = pts[k] - first
circ_dist = min(dist, n - dist)
if circ_dist < min_span:
w = 0
weights.append(w)
candidates.append(k)
# Weighted random choice
total = sum(weights)
if total == 0:
raise UnsatisfiableMatchingError(
f"No valid partner for point {first} with min_span={min_span}")
r = rng.randrange(total)
cumulative = 0
chosen_k = candidates[-1]
for k_idx, w in zip(candidates, weights):
if w == 0:
continue
cumulative += w
if r < cumulative:
chosen_k = k_idx
break
partner = pts[chosen_k]
result.append((first, partner))
_sample(pts[1:chosen_k])
_sample(pts[chosen_k + 1:])
_sample(list(range(n)))
return sorted(result)
def sample_constrained_ncpm(
n: int,
forced_pairs: list[tuple[int, int]],
rng: _random_module.Random,
min_span: int = 0,
) -> list[tuple[int, int]]:
"""Sample one random NCPM of n points with some pairs forced. O(n).
forced_pairs: pairs that must appear in the matching (from neighbor
edge constraints). These must be non-crossing among themselves.
min_span: if > 0, skip free candidates whose circular distance to
the first point is less than min_span.
Raises UnsatisfiableMatchingError if the constraints can't be satisfied.
"""
if n % 2 != 0:
raise ValueError(f"n must be even, got {n}")
if n == 0:
return []
if not forced_pairs:
return sample_random_ncpm(n, rng, min_span=min_span)
cat = _catalan_table(n // 2)
# Build forced partner lookup
forced_partner: dict[int, int] = {}
for a, b in forced_pairs:
forced_partner[a] = b
forced_partner[b] = a
result: list[tuple[int, int]] = []
def _sample(pts: list[int]):
if len(pts) == 0:
return
if len(pts) == 2:
result.append((min(pts[0], pts[1]), max(pts[0], pts[1])))
return
if len(pts) % 2 != 0:
raise UnsatisfiableMatchingError(
f"Odd number of points ({len(pts)}) in sub-region")
first = pts[0]
m = len(pts)
# If first has a forced partner, pair them directly
if first in forced_partner:
partner = forced_partner[first]
k = pts.index(partner)
if k % 2 == 0:
raise UnsatisfiableMatchingError(
f"Forced pair ({first}, {partner}) encloses odd points")
result.append((min(first, partner), max(first, partner)))
_sample(pts[1:k])
_sample(pts[k + 1:])
return
# First is free — pick a random partner from valid odd-indexed candidates
weights: list[int] = []
candidates: list[int] = []
for k in range(1, m, 2):
candidate = pts[k]
# If candidate is forced to someone other than first, skip —
# candidate is reserved for its forced partner
if candidate in forced_partner:
weights.append(0)
candidates.append(k)
continue
left = pts[1:k]
right = pts[k + 1:]
left_set = set(left)
right_set = set(right)
# Check no forced pair is split across left/right
valid = True
for p in left:
if p in forced_partner and forced_partner[p] not in left_set:
valid = False
break
if valid:
for p in right:
if p in forced_partner and forced_partner[p] not in right_set:
valid = False
break
if not valid:
weights.append(0)
candidates.append(k)
continue
# Count free points in each sub-region
left_free = sum(1 for p in left if p not in forced_partner)
right_free = sum(1 for p in right if p not in forced_partner)
if left_free % 2 != 0 or right_free % 2 != 0:
weights.append(0)
candidates.append(k)
continue
w = cat[left_free // 2] * cat[right_free // 2]
# Skip too-close free candidates (circular distance on original ring)
if min_span > 0 and w > 0:
dist = candidate - first
circ_dist = min(dist, n - dist)
if circ_dist < min_span:
w = 0
weights.append(w)
candidates.append(k)
total = sum(weights)
if total == 0:
raise UnsatisfiableMatchingError(
f"No valid partner for point {first} in sub-region of {m} points")
r = rng.randrange(total)
cumulative = 0
chosen_k = candidates[-1]
for k_idx, w in zip(candidates, weights):
if w == 0:
continue
cumulative += w
if r < cumulative:
chosen_k = k_idx
break
partner = pts[chosen_k]
result.append((min(first, partner), max(first, partner)))
_sample(pts[1:chosen_k])
_sample(pts[chosen_k + 1:])
_sample(list(range(n)))
return sorted(result)
def tile_edge_points(tile_type: TileType, vertices: list[Point]
) -> list[Point]:
"""Compute world-coordinate positions of all edge points for a tile."""
pts: list[Point] = []
for edge_idx, tvals in enumerate(tile_type.edge_points):
for t in tvals:
pts.append(edge_point_world(vertices, edge_idx, t))
return pts
def tile_matchings(tile_type: TileType, vertices: list[Point]
) -> list[list[tuple[Point, Point]]]:
"""For a tile, return all NCPMs as lists of world-coordinate endpoint pairs."""
n = sum(len(ep) for ep in tile_type.edge_points)
matchings = noncrossing_matchings(n)
world_pts = tile_edge_points(tile_type, vertices)
result: list[list[tuple[Point, Point]]] = []
for matching in matchings:
pairs = [(world_pts[a], world_pts[b]) for a, b in matching]
result.append(pairs)
return result
# ---------------------------------------------------------------------------
# make_* convenience functions — create a fresh Plane
# ---------------------------------------------------------------------------
def make_square(x: float = 0, y: float = 0, s: float = 1,
tile_type: TileType | None = None) -> Composition:
return compose_square(Plane(), x, y, s, tile_type)
def make_square_grid(x: float = 0, y: float = 0, s: float = 1,
rows: int = 2, cols: int = 2,
tile_type: TileType | None = None) -> Composition:
return compose_square_grid(Plane(), x, y, s, rows, cols, tile_type)
def make_488(x: float = 0, y: float = 0, s: float = 1) -> Composition:
return compose_488(Plane(), x, y, s)
def make_hex_corners(x: float = 0, y: float = 0,
L: float = 1) -> Composition:
return compose_hex_corners(Plane(), x, y, L)
def make_hex_eq_grid(x: float = 0, y: float = 0, L: float = 1,
rows: int = 2, cols: int = 3,
hex_cols: int = 2) -> Composition:
return compose_hex_eq_grid(Plane(), x, y, L, rows, cols, hex_cols)
# ---------------------------------------------------------------------------
# Edge signature functions for SAT-based matching assignment
# ---------------------------------------------------------------------------
def edge_local_pairing(matching: list[tuple[int, int]], tile_type: TileType
) -> tuple[frozenset[tuple[int, int]], ...]:
"""Per-edge local pairing for a matching.
Returns N frozensets, one per edge. Each frozenset contains
(local_i, local_j) pairs of edge points paired within that edge.
Points not in any local pair connect to other edges.
"""
offsets: list[int] = []
offset = 0
for ep in tile_type.edge_points:
offsets.append(offset)
offset += len(ep)
result: list[frozenset[tuple[int, int]]] = []
for e in range(tile_type.n_edges):
k = len(tile_type.edge_points[e])
start = offsets[e]
edge_indices = set(range(start, start + k))
pairs: set[tuple[int, int]] = set()
for a, b in matching:
if a in edge_indices and b in edge_indices:
la, lb = a - start, b - start
pairs.add((min(la, lb), max(la, lb)))
result.append(frozenset(pairs))
return tuple(result)
def reversed_edge_pairing(pairing: frozenset[tuple[int, int]], k: int
) -> frozenset[tuple[int, int]]:
"""Reverse a local pairing for edge traversal in opposite direction.
k is the number of edge points on this edge."""
reversed_pairs: set[tuple[int, int]] = set()
for a, b in pairing:
ra = k - 1 - a
rb = k - 1 - b
reversed_pairs.add((min(ra, rb), max(ra, rb)))
return frozenset(reversed_pairs)
def matching_edge_pairings(tile_type: TileType
) -> list[tuple[frozenset[tuple[int, int]], ...]]:
"""Precompute edge pairings for all NCPMs of a tile type."""
n = sum(len(ep) for ep in tile_type.edge_points)
matchings = noncrossing_matchings(n)
return [edge_local_pairing(m, tile_type) for m in matchings]
EdgeSig = frozenset[tuple[int, int]]
@dataclass
class SignatureData:
"""Precomputed per-edge signature groupings for a tile type."""
n_matchings: int
# edge_groups[edge_idx] maps each unique signature -> list of matching indices with that signature
edge_groups: list[dict[EdgeSig, list[int]]]
# full_sig_groups maps (sig_e0, sig_e1, ...) -> list of matching indices
full_sig_groups: dict[tuple[EdgeSig, ...], list[int]]
def compute_signature_data(tile_type: TileType) -> SignatureData:
"""Group matchings by their per-edge signature."""
n = sum(len(ep) for ep in tile_type.edge_points)
matchings = noncrossing_matchings(n)
all_pairings = [edge_local_pairing(m, tile_type) for m in matchings]
edge_groups: list[dict[EdgeSig, list[int]]] = []
for edge_idx in range(tile_type.n_edges):
groups: dict[EdgeSig, list[int]] = {}
for m_idx, pairings in enumerate(all_pairings):
sig = pairings[edge_idx]
groups.setdefault(sig, []).append(m_idx)
edge_groups.append(groups)
full_sig_groups: dict[tuple[EdgeSig, ...], list[int]] = {}
for m_idx, pairings in enumerate(all_pairings):
full_sig_groups.setdefault(pairings, []).append(m_idx)
return SignatureData(len(matchings), edge_groups, full_sig_groups)
class SolveStrategy(Enum):
BASELINE = "baseline" # Current: enumerate all matching pairs
GROUPED = "grouped" # Group by signature, no new Z3 vars
TWOPHASE = "twophase" # Phase 1: Z3 picks edge sigs. Phase 2: random matching
@dataclass
class TilePosition:
tile_type: TileType
vertices: list[Point]
neighbors: list[tuple[int, int, int]] = field(default_factory=list[tuple[int, int, int]])
# neighbors: list of (neighbor_idx, my_edge, their_edge)
def find_adjacency(positions: list[TilePosition], tol: float = 1e-6) -> None:
"""Find shared edges between tile positions by vertex matching.
Populates each position's neighbors list in-place.
"""
def quantize(p: Point) -> tuple[int, int]:
return (round(p[0] / tol), round(p[1] / tol))
# Map directed edge (va, vb) to (tile_idx, edge_idx)
edge_map: dict[tuple[tuple[int, int], tuple[int, int]],
tuple[int, int]] = {}
for i, pos in enumerate(positions):
n = len(pos.vertices)
for e in range(n):
va = quantize(pos.vertices[e])
vb = quantize(pos.vertices[(e + 1) % n])
forward = (va, vb)
reverse = (vb, va)
if reverse in edge_map:
j, ej = edge_map[reverse]
pos.neighbors.append((j, e, ej))
positions[j].neighbors.append((i, ej, e))
del edge_map[reverse]
else:
edge_map[forward] = (i, e)
def validate_matching_assignment(positions: list[TilePosition],
assignment: list[int]) -> None:
"""Verify all shared edges have compatible pairings.
Raises AssertionError if any shared edge has incompatible pairings.
"""
type_cache: dict[int, list[tuple[frozenset[tuple[int, int]], ...]]] = {}
for pos in positions:
key = id(pos.tile_type)
if key not in type_cache:
type_cache[key] = matching_edge_pairings(pos.tile_type)
for i, pos in enumerate(positions):
for j, my_edge, their_edge in pos.neighbors:
if j <= i:
continue
pairings_i = type_cache[id(pos.tile_type)]
pairings_j = type_cache[id(positions[j].tile_type)]
k = len(pos.tile_type.edge_points[my_edge])
sig_i = pairings_i[assignment[i]][my_edge]
sig_j = pairings_j[assignment[j]][their_edge]
assert sig_i == reversed_edge_pairing(sig_j, k), (
f"Edge incompatibility: tile {i} edge {my_edge} "
f"vs tile {j} edge {their_edge}")
def _add_baseline_constraints(
s: Solver, variables: list[Int], positions: list[TilePosition],
type_cache: dict[int, list[tuple[frozenset[tuple[int, int]], ...]]],
) -> None:
"""BASELINE strategy: enumerate all matching pairs per shared edge."""
processed: set[frozenset[tuple[int, int, int]]] = set()
for i, pos in enumerate(positions):
for neighbor_idx, my_edge, their_edge in pos.neighbors:
edge_key = frozenset({(i, my_edge), (neighbor_idx, their_edge)})
if edge_key in processed:
continue
processed.add(edge_key)
j = neighbor_idx
pairings_i = type_cache[id(pos.tile_type)]
pairings_j = type_cache[id(positions[j].tile_type)]
k = len(pos.tile_type.edge_points[my_edge])
k_j = len(positions[j].tile_type.edge_points[their_edge])
if k != k_j:
raise UnsatisfiableMatchingError(
f"Incompatible edge point counts: tile {i} edge {my_edge} has {k} points, "
f"but tile {j} edge {their_edge} has {k_j} points. "
f"Tile {i} type: {pos.tile_type.name}, "
f"Tile {j} type: {positions[j].tile_type.name}. "
f"Shared edges must have the same number of edge points.",
tile_i=i, tile_j=j, edge_i=my_edge, edge_j=their_edge)
compatible: list = []
for mi, pi in enumerate(pairings_i):
for mj, pj in enumerate(pairings_j):
sig_i = pi[my_edge]
sig_j = pj[their_edge]
if sig_i == reversed_edge_pairing(sig_j, k):
compatible.append(And(variables[i] == mi,
variables[j] == mj))
if not compatible:
raise UnsatisfiableMatchingError(
f"No compatible matchings found between tile {i} edge {my_edge} "
f"and tile {j} edge {their_edge}. "
f"Tile {i} type: {pos.tile_type.name}, "
f"Tile {j} type: {positions[j].tile_type.name}. "
f"Edge has {k} edge points but none of the {len(pairings_i)} x {len(pairings_j)} "
f"matching combinations produce compatible edge pairings.",
tile_i=i, tile_j=j, edge_i=my_edge, edge_j=their_edge)
s.add(Or(*compatible))
def _add_grouped_constraints(
s: Solver, variables: list[Int], positions: list[TilePosition],
sig_cache: dict[int, SignatureData],
) -> None:
"""GROUPED strategy: group matchings by signature, O(1) lookup per signature."""
processed: set[frozenset[tuple[int, int, int]]] = set()
for i, pos in enumerate(positions):
for neighbor_idx, my_edge, their_edge in pos.neighbors:
edge_key = frozenset({(i, my_edge), (neighbor_idx, their_edge)})
if edge_key in processed:
continue
processed.add(edge_key)
j = neighbor_idx
k = len(pos.tile_type.edge_points[my_edge])
k_j = len(positions[j].tile_type.edge_points[their_edge])
if k != k_j:
raise UnsatisfiableMatchingError(
f"Incompatible edge point counts: tile {i} edge {my_edge} has {k} points, "
f"but tile {j} edge {their_edge} has {k_j} points. "
f"Tile {i} type: {pos.tile_type.name}, "
f"Tile {j} type: {positions[j].tile_type.name}. "
f"Shared edges must have the same number of edge points.",
tile_i=i, tile_j=j, edge_i=my_edge, edge_j=their_edge)
groups_i = sig_cache[id(pos.tile_type)].edge_groups[my_edge]
groups_j = sig_cache[id(positions[j].tile_type)].edge_groups[their_edge]
clauses = []
for sig_i, members_i in groups_i.items():
sig_j_needed = reversed_edge_pairing(sig_i, k)
if sig_j_needed in groups_j:
members_j = groups_j[sig_j_needed]
clause_i = Or([variables[i] == m for m in members_i])
clause_j = Or([variables[j] == m for m in members_j])
clauses.append(And(clause_i, clause_j))
if not clauses:
raise UnsatisfiableMatchingError(
f"No compatible matchings found between tile {i} edge {my_edge} "
f"and tile {j} edge {their_edge}. "
f"Tile {i} type: {pos.tile_type.name}, "
f"Tile {j} type: {positions[j].tile_type.name}. "
f"Edge has {k} edge points but no compatible signature groups.",
tile_i=i, tile_j=j, edge_i=my_edge, edge_j=their_edge)
s.add(Or(*clauses))
def _solve_twophase(
positions: list[TilePosition],
sig_cache: dict[int, SignatureData],
diverse: bool = True,
) -> list[int]:
"""Two-phase solver: Z3 picks edge signatures, Python picks matchings.
Phase 1: One Z3 variable per shared edge choosing a compatible
signature pair (domain ~6-20). Per-tile constraint ensures the
combination of chosen edge sigs is jointly realizable.
Phase 2: For each tile, randomly pick a matching consistent with
the chosen signatures on all shared edges.
"""
import random
# Enumerate shared edges and their compatible signature pairs
shared_edges: list[tuple[int, int, int, int]] = [] # (i, my_edge, j, their_edge)
processed: set[frozenset[tuple[int, int]]] = set()
for i, pos in enumerate(positions):
for j, my_edge, their_edge in pos.neighbors:
edge_key = frozenset({(i, my_edge), (j, their_edge)})
if edge_key in processed:
continue
processed.add(edge_key)
shared_edges.append((i, my_edge, j, their_edge))
# For each shared edge, find compatible (sig_i, sig_j) pairs
# and number the sigs for each (tile_type, edge) combination
type_edge_sig_list: dict[tuple[int, int], list[EdgeSig]] = {}
def get_sig_idx(tile_type_id: int, edge: int, sig: EdgeSig) -> int:
key = (tile_type_id, edge)
if key not in type_edge_sig_list:
sd = sig_cache[tile_type_id]
type_edge_sig_list[key] = list(sd.edge_groups[edge].keys())
return type_edge_sig_list[key].index(sig)
edge_compat: list[list[tuple[int, int]]] = [] # per shared edge: list of (sig_idx_i, sig_idx_j)
for i, my_edge, j, their_edge in shared_edges:
ti_id = id(positions[i].tile_type)
tj_id = id(positions[j].tile_type)
groups_i = sig_cache[ti_id].edge_groups[my_edge]
groups_j = sig_cache[tj_id].edge_groups[their_edge]
k = len(positions[i].tile_type.edge_points[my_edge])
pairs = []
for sig_i in groups_i:
sig_j_needed = reversed_edge_pairing(sig_i, k)
if sig_j_needed in groups_j:
idx_i = get_sig_idx(ti_id, my_edge, sig_i)
idx_j = get_sig_idx(tj_id, their_edge, sig_j_needed)
pairs.append((idx_i, idx_j))
edge_compat.append(pairs)
# Build per-tile shared edge info: which shared_edge indices touch this tile,
# and which side (i or j) is this tile on
tile_shared: list[list[tuple[int, int, int]]] = [[] for _ in positions]
# (shared_edge_idx, which_edge_of_tile, 0=i_side/1=j_side)
for se_idx, (i, my_edge, j, their_edge) in enumerate(shared_edges):
tile_shared[i].append((se_idx, my_edge, 0))
tile_shared[j].append((se_idx, their_edge, 1))
# Phase 1: Z3 picks one compatible pair per shared edge
s = Solver()
s.set("threads", os.cpu_count() or 1)
edge_vars = [Int(f"se_{idx}") for idx in range(len(shared_edges))]
for idx, pairs in enumerate(edge_compat):
s.add(Or([edge_vars[idx] == p_idx for p_idx in range(len(pairs))]))
# Per-tile realizability: the combination of chosen sigs must correspond
# to at least one actual matching
for tile_idx, pos in enumerate(positions):
if not tile_shared[tile_idx]:
continue
tt_id = id(pos.tile_type)
sd = sig_cache[tt_id]
# Get the edge indices that are shared, and for each, the sig list
shared_info = tile_shared[tile_idx] # (se_idx, edge_of_tile, side)
# Build a map: for each full sig tuple in this tile type,
# determine which edge_var values would produce it
# full_sig_groups maps (sig_e0, sig_e1, ...) -> matching indices
# We need: for each valid full sig tuple, the conjunction of edge_var constraints
# First, for shared edges, map: edge_of_tile -> (se_idx, side)
edge_constraints: dict[int, tuple[int, int]] = {}
for se_idx, edge_of_tile, side in shared_info:
edge_constraints[edge_of_tile] = (se_idx, side)
# For each full sig tuple that has matchings, check if it's consistent
# with some edge_var assignment
valid_clauses = []
for full_sig, _matching_ids in sd.full_sig_groups.items():
clause_parts = []
feasible = True
for edge_of_tile, (se_idx, side) in edge_constraints.items():
target_sig = full_sig[edge_of_tile]
target_idx = get_sig_idx(tt_id, edge_of_tile, target_sig)
# Find which pair indices in edge_compat[se_idx] have this sig on the right side
matching_pair_indices = []
for p_idx, (pi, pj) in enumerate(edge_compat[se_idx]):
if (side == 0 and pi == target_idx) or (side == 1 and pj == target_idx):
matching_pair_indices.append(p_idx)
if not matching_pair_indices:
feasible = False
break
clause_parts.append(Or([edge_vars[se_idx] == p for p in matching_pair_indices]))
if feasible:
valid_clauses.append(And(clause_parts) if clause_parts else True)
if valid_clauses:
s.add(Or(valid_clauses))
n_se = len(shared_edges)
n_compat = sum(len(pairs) for pairs in edge_compat)
print(f" [twophase] {n_se} shared edges, {n_compat} compatible pairs, "
f"{len(sig_cache)} tile types")
t0 = perf_counter()
if s.check() != sat:
raise UnsatisfiableMatchingError("Two-phase: edge signature assignment unsatisfiable")
t_phase1 = perf_counter() - t0
model = s.model()
# Decode chosen signatures per shared edge
chosen_sigs: dict[tuple[int, int], EdgeSig] = {} # (tile_idx, edge) -> sig
for se_idx, (i, my_edge, j, their_edge) in enumerate(shared_edges):
pair_idx = model[edge_vars[se_idx]].as_long()
sig_idx_i, sig_idx_j = edge_compat[se_idx][pair_idx]
ti_id = id(positions[i].tile_type)
tj_id = id(positions[j].tile_type)
chosen_sigs[(i, my_edge)] = type_edge_sig_list[(ti_id, my_edge)][sig_idx_i]
chosen_sigs[(j, their_edge)] = type_edge_sig_list[(tj_id, their_edge)][sig_idx_j]
# Phase 2: pick a random matching per tile consistent with chosen sigs
result = []
for tile_idx, pos in enumerate(positions):
tt_id = id(pos.tile_type)
sd = sig_cache[tt_id]
# Filter full_sig_groups to those matching chosen sigs on shared edges
candidates: list[int] = []
for full_sig, matching_ids in sd.full_sig_groups.items():
ok = True
for edge_of_tile in range(pos.tile_type.n_edges):
if (tile_idx, edge_of_tile) in chosen_sigs:
if full_sig[edge_of_tile] != chosen_sigs[(tile_idx, edge_of_tile)]:
ok = False
break
if ok:
candidates.extend(matching_ids)
if not candidates:
raise UnsatisfiableMatchingError(
f"Two-phase: no matching for tile {tile_idx} with chosen edge sigs")
result.append(random.choice(candidates))
print(f" [twophase] phase1={t_phase1*1000:.1f}ms")
return result
# ---------------------------------------------------------------------------
# Bezier crossing detection + swap helpers
# ---------------------------------------------------------------------------
def _bezier_polyline(p1: Point, n1: Point, p2: Point, n2: Point,
n_segments: int = 16) -> list[Point]:
"""Flatten a cubic bezier into a polyline of n_segments+1 points.
Control points computed inline: c = p + 0.4 * dist * n.
"""
dist = hypot(p2[0] - p1[0], p2[1] - p1[1])
alpha = 0.4 * dist
c1 = (p1[0] + alpha * n1[0], p1[1] + alpha * n1[1])
c2 = (p2[0] + alpha * n2[0], p2[1] + alpha * n2[1])
pts: list[Point] = []
for i in range(n_segments + 1):
t = i / n_segments
u = 1 - t
x = (u*u*u * p1[0] + 3*u*u*t * c1[0] +
3*u*t*t * c2[0] + t*t*t * p2[0])
y = (u*u*u * p1[1] + 3*u*u*t * c1[1] +
3*u*t*t * c2[1] + t*t*t * p2[1])
pts.append((x, y))
return pts
def _segments_intersect(p1: Point, p2: Point, p3: Point, p4: Point) -> bool:
"""Strict segment-segment intersection test (cross-product orientation).
Returns False for shared endpoints and collinear cases.
"""
def cross(o: Point, a: Point, b: Point) -> float:
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
d1 = cross(p3, p4, p1)
d2 = cross(p3, p4, p2)
d3 = cross(p1, p2, p3)
d4 = cross(p1, p2, p4)
if ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and \
((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)):
return True
return False
def _beziers_cross(poly1: list[Point], poly2: list[Point]) -> bool:
"""Check if two bezier polylines intersect (O(n^2) segment check)."""
for i in range(len(poly1) - 1):
for j in range(len(poly2) - 1):
if _segments_intersect(poly1[i], poly1[i+1],
poly2[j], poly2[j+1]):
return True
return False
def _chords_cross(a: int, b: int, c: int, d: int, n: int) -> bool:
"""Circle topology test: chord (a,b) crosses chord (c,d) on n points.
Returns True iff exactly one of {c,d} is strictly inside arc a..b
(going from a to b in increasing order mod n).
"""
# Normalize so a < b
if a > b:
a, b = b, a
if c > d:
c, d = d, c