Repository navigation
Expand file tree
/
Copy pathplot_winding_graph.py
More file actions
1411 lines (1292 loc) · 75.7 KB
/
Copy pathplot_winding_graph.py
File metadata and controls
1411 lines (1292 loc) · 75.7 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
"""Stylised visualisation of a find_inconsistent_windings.py result.
find_inconsistent_windings traces a high-level graph -- quadmesh *patches* are
nodes, point-collections (pcls) are edges where their attached points link two
patches -- outward from a seed patch, accumulating relative winding numbers and
voting (via absolute-winding anchors) on the seed patch's absolute winding. This
tool draws that graph.
The drawn subgraph is the union of every voter's path: a tree rooted at the seed
patch, whose edges are the relative-winding pcls actually traversed and whose
terminal patches carry the absolute anchors that voted.
find_inconsistent_windings also records "loops": non-tree relative edges whose
winding holonomy is nonzero (the cycle they close does not return to the same
winding -- an inconsistency in the relative annotations themselves). Rather than
overlay these on the (already busy) main graph, we render them in a separate
output as vertical patch stacks. Every fundamental cycle is `spine + closing edge`
and the BFS tree is fixed, so loops that share an ordered patch spine differ only
in their closing edge; we collapse each such set into one diagram (keyed on the
spine) to spend display slots on distinct spines rather than repeating the shared
part. Each diagram is a vertical stack of the spine's patches, with the relative-pcl
tree edges as downward arrows between consecutive patches and -- bowing from the
bottom patch back up to the top -- one "closing" arrow per loop sharing the spine
(the non-tree edge whose holonomy makes that loop inconsistent), fanned out and each
labelled with its pcl id, winding delta and holonomy. Each tree edge is labelled with
its winding delta; each patch is labelled (in crimson, to the right of its line) with
the within-patch winding delta between its two cycle points, when the strip across it
crosses theta=0 (at the two endpoint patches, only when every closing edge agrees).
The per-loop cycle reconstruction (patches + pcls in order, with the per-patch strip
deltas) is precomputed by find_inconsistent_windings and stored under "loop_cycles" in
the votes json; the spine grouping happens here at render time. This view is always
produced alongside the main graph.
Layout (the stylised picture the result implies):
* x-axis = absolute model winding number. A patch's *entry* point has winding
`seed_model_winding - acc`, where acc = winding(seed) - winding(entry) is
rebuilt by walking the path hops (acc -= intra_patch_strip_delta + edge_delta
per hop, exactly as the BFS accumulates it). Every recorded winding delta is
an integer seam count, so a point's winding number is the integer w0 - acc.
Integer x are the theta=0 seams (the transitions between windings); a winding
is the *range* between two consecutive seams. We therefore draw each point
half a winding in from its seam -- at its band centre, x = winding + 0.5 --
and label each winding number there too. Points (entries, departures,
anchors) thus sit *inside* their winding, never on a boundary; the seams
carry only tick marks.
* y = one row per patch. Rows are ordered by BFS depth (the seed on top); the
patches at a given depth each take their own slot, stacked just below one
another, so a depth occupies several slightly-offset rows and no two patches
ever share a row. Depth bands are shaded alternately and depth numbers run
down the right edge.
* Each patch is a short horizontal line spanning its known points (entry, the
departure point of each outgoing edge, any anchors), each placed at its band
centre. The line pokes seg_min_width past the extreme stars on each side, so it
extends a little beyond its end points while staying inside the bounding
windings (with the default it reaches the 1/4 and 3/4 marks of its first and
last winding box); a single-winding patch becomes a short stub centred in its
one band. A crimson tick marks each integer winding (theta=0 seam) genuinely
crossed *between* those known points; the crossings come from the integer
seam-count deltas recorded on the within-patch strips (intra_patch_strip_delta
/ anchor_to_entry_delta), so a single-winding patch shows none. Its full patch
id is listed in a left-hand column, aligned to its row.
* Each relative-pcl edge runs from the parent's departure point (entry winding +
intra_patch_strip_delta) to the child's entry point; its horizontal run equals
the edge's winding delta (e minus d), so it stays near-vertical in x.
* Each absolute anchor is a star on its patch at `entry - anchor_to_entry_delta`,
coloured by the seed winding its annotation implies, so disagreeing votes show
up as different colours scattered across the tree.
Outputs: a static PNG of the main graph, a static PNG of the per-loop view, and --
unless --no-html -- a single interactive HTML5 page holding both as tabs. In the
"Winding graph" tab the main plot region scrolls while the patch names (left),
absolute-winding axis (bottom), title (top) and BFS-depth scale (right) stay
pinned; the "Loop cycles" tab shows each inconsistent loop as its own patch/pcl
stack. Both are SVG whose elements carry data-* attributes with hover tooltips, and
they live in isolated <iframe> panes inside the page so their styles never collide.
Run, e.g.:
python plot_winding_graph.py --votes winding_votes.json --output winding_graph.png
"""
import os
import json
import math
import html as html_lib
from collections import defaultdict
import click
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import FancyArrowPatch
from matplotlib.transforms import blended_transform_factory
def load_graph(votes, full_graph=True):
"""Rebuild the patch graph from a find_inconsistent_windings votes dict.
Returns (nodes, edges, anchors, meta) where:
nodes: patch_id -> {'depth', 'acc'} (acc = winding(seed) - winding(entry))
edges: child_patch_id -> hop record (the parent edge; child is `to_patch`)
anchors: list of voter dicts (each carries abs_patch_id / annotation / vote)
meta: handy scalars pulled off the top level
With `full_graph` (the default), the graph is the *entire* seed-rooted BFS tree:
every reached patch and the relative-pcl edge that first reached it, taken straight
from the votes file's `tree` field. This shows the inferred winding of all reached
patches and their connections, including patches no voter passed through.
With `full_graph` false (or when the votes file predates the `tree` field), the
graph is instead the union of every voter's path: the subtree rooted at the seed
whose leaves carry the absolute anchors that voted -- patches that lead to no vote
are omitted.
Either way the absolute anchors (the voted stars) come from `votes['votes']`; in
full-graph mode, reached patches that carry no anchor simply get no star. (The
detected loops are not drawn on this graph -- they get their own per-loop view; see
plot_loop_cycles.)
"""
seed = votes['patch_id']
all_voters = [v for vs in votes['votes'].values() for v in vs]
tree = votes.get('tree')
if full_graph and tree:
# The full BFS tree: every reached patch (depth + acc) and the hop record of the
# relative-pcl edge that first reached it (keyed by child patch).
nodes = {pid: {'depth': nd['depth'], 'acc': nd['acc']}
for pid, nd in tree['nodes'].items()}
edges = dict(tree['edges'])
else:
if full_graph:
print('warning: votes file has no "tree" field (predates full-graph support); '
'falling back to the anchor-subtree view')
nodes = {seed: {'depth': 0, 'acc': 0.0}}
edges = {}
for v in all_voters:
acc = 0.0
for hop_i, h in enumerate(v['path']):
acc = acc - h['intra_patch_strip_delta'] - h['edge_winding_delta']
child = h['to_patch']
# BFS reaches each patch once, so this is idempotent across voters.
nodes.setdefault(child, {'depth': hop_i + 1, 'acc': acc})
edges.setdefault(child, h)
meta = {
'seed': seed,
'seed_model_winding': votes['model_raw_winding_at_seed'],
'dr_per_winding': votes['dr_per_winding'],
'num_patches_reached': votes['num_patches_reached'],
'num_direct_votes': votes['num_direct_votes'],
'num_long_range_votes': votes['num_long_range_votes'],
'votes_agree': votes['votes_agree'],
'max_hops': votes['max_hops'],
}
return nodes, edges, all_voters, meta
def assign_slots(depth_to_nodes, node_extent, slot_height, depth_gap):
"""Give every patch its own row: one patch per slot, depth-major.
Walks depths top-down; within a depth the patches are sorted by winding and
each dropped into the next slot below (so a depth occupies several adjacent,
slightly-offset rows and no two patches share a row). A `depth_gap` of extra
space separates one depth's block of rows from the next.
Returns (node_y, depth_band) where node_y maps patch_id -> y, and depth_band
maps depth -> (y_top, y_bottom) of its block (for shading / depth ticks)."""
node_y = {}
depth_band = {}
cur = 0.0 # grows downward; negated into y so the seed (depth 0) sits at y=0
for depth in sorted(depth_to_nodes):
ids = sorted(depth_to_nodes[depth], key=lambda p: node_extent[p][0])
top = cur
for pid in ids:
node_y[pid] = -cur
cur += slot_height
depth_band[depth] = (-top + slot_height / 2, -(cur - slot_height) - slot_height / 2)
cur += depth_gap
return node_y, depth_band
def integer_ticks(lo, hi):
"""Integer values strictly inside (lo, hi) -- the theta=0 crossings."""
return [n for n in range(int(np.ceil(lo)), int(np.floor(hi)) + 1) if lo < n < hi]
def _star_points(cx, cy, r):
"""Points string for a 5-point SVG star polygon centred at (cx, cy)."""
ri = r * 0.45
pts = []
for i in range(10):
ang = -math.pi / 2 + i * math.pi / 5
rr = r if i % 2 == 0 else ri
pts.append(f'{cx + rr * math.cos(ang):.2f},{cy + rr * math.sin(ang):.2f}')
return ' '.join(pts)
# CSS / JS kept as plain strings (lots of braces / template literals) so they
# don't fight with the f-strings that assemble the dynamic markup.
_HTML_CSS = r"""
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
body { display: flex; flex-direction: column; background: #fff; color: #222; }
.header { flex: none; padding: 8px 12px; border-bottom: 1px solid #ddd; }
.header .title { font-size: 13px; font-weight: 600; white-space: pre-line; line-height: 1.35; }
.legend { margin-top: 6px; font-size: 12px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; }
.legend .item { display: inline-flex; align-items: center; gap: 5px; }
.layout { flex: 1 1 auto; min-height: 0; display: grid; }
.leftcol, .rightcol, .bottomaxis { overflow: hidden; background: #fff; }
.plotwrap { overflow: auto; }
.leftcol { border-right: 1px solid #ddd; }
.rightcol { border-left: 1px solid #ddd; }
.bottomaxis { border-top: 1px solid #ddd; }
.corner { background: #fafafa; display: flex; align-items: center; justify-content: center;
font-size: 11px; color: #666; padding: 2px 6px; text-align: center; }
svg.plot { display: block; background: #fff; }
svg.inner { display: block; will-change: transform; }
.band { fill: #f2f2f2; }
.seam { stroke: #ededed; stroke-width: 1; }
.edgeline { stroke: #999; stroke-width: 1.1; fill: none; }
.loopline { stroke: #c026d3; stroke-width: 1.3; fill: none; opacity: .7; stroke-dasharray: 5 3; }
.depdot { fill: #888; }
.hitdot { fill: transparent; }
.patchline { stroke: #000; stroke-width: 1.8; }
.cap { stroke: #000; stroke-width: 1.8; }
.patch.seed .patchline, .patch.seed .cap { stroke-width: 2.8; }
.seamtick { stroke: crimson; stroke-width: 1.4; }
.star { stroke: none; }
.votelabel { font-size: 10px; font-weight: 700; }
.hit { stroke: transparent; stroke-width: 12; fill: none; }
.lbl { font-size: 11px; fill: #555; dominant-baseline: middle; }
.lbl.seed { fill: #111; font-weight: 700; }
.dlbl { font-size: 11px; fill: #444; dominant-baseline: middle; }
.albl { font-size: 11px; fill: #333; }
.atick { stroke: #333; stroke-width: 1; }
.band, .seam, .votelabel, .lbl, .dlbl, .albl, .atick { pointer-events: none; }
.patch, .edge, .anchor, .dot, .loop { cursor: pointer; }
.patch.hl .patchline, .patch.hl .cap { stroke: #ff8c00; }
.edge.hl .edgeline { stroke: #ff8c00; stroke-width: 2.4; }
.loop.hl .loopline { stroke: #ff8c00; stroke-width: 2.6; opacity: 1; }
.anchor.hl .star { stroke: #ff8c00; stroke-width: 2; }
.dot.hl .depdot { fill: #ff8c00; }
.tooltip { position: fixed; pointer-events: none; display: none; z-index: 10;
background: rgba(20,20,20,.92); color: #fff; font-size: 11px;
padding: 5px 7px; border-radius: 4px; max-width: 420px; white-space: pre-line; }
"""
_HTML_JS = r"""
const wrap = document.querySelector('.plotwrap');
const li = document.querySelector('.leftcol .inner');
const ri = document.querySelector('.rightcol .inner');
const bi = document.querySelector('.bottomaxis .inner');
function sync() {
const tx = -wrap.scrollLeft, ty = -wrap.scrollTop;
li.style.transform = 'translateY(' + ty + 'px)';
ri.style.transform = 'translateY(' + ty + 'px)';
bi.style.transform = 'translateX(' + tx + 'px)';
}
wrap.addEventListener('scroll', sync);
sync();
const tip = document.querySelector('.tooltip');
function xyz(d) {
if (d.x === undefined) return '\nxyz (not recorded in this votes file)';
return '\nxyz ' + Math.round(+d.x) + ', ' + Math.round(+d.y) + ', ' + Math.round(+d.z);
}
function deltaInfo(d) {
let s = '\nΔwinding ' + d.edgeDelta;
if (d.rawDelta !== undefined)
s += ' (raw ' + d.rawDelta + ', pcl ' + d.pclBranchDelta + ')';
return s;
}
function info(el) {
const d = el.dataset;
if (d.kind === 'patch') {
const lo = +d.windingLo, hi = +d.windingHi;
const w = (lo === hi) ? ('winding ' + lo)
: ('windings ' + lo + '–' + hi + ' (crosses theta=0)');
return 'patch ' + d.patch + '\ndepth ' + d.depth + ' ' + w;
}
if (d.kind === 'edge')
return 'edge — rel pcl ' + d.pcl + ' "' + (d.pclName || '') + '"'
+ '\npoint ' + d.fromPoint + ' on ' + d.from
+ '\n → point ' + d.toPoint + ' on ' + d.to
+ deltaInfo(d) + ' strip ' + d.stripDelta;
if (d.kind === 'loop')
return 'inconsistent loop — rel pcl ' + d.pcl + ' "' + (d.pclName || '') + '"'
+ '\npoint ' + d.fromPoint + ' on ' + d.from
+ '\n ↔ point ' + d.toPoint + ' on ' + d.to
+ '\nwinding holonomy ' + d.holo + ' (edge Δwinding ' + d.edgeDelta + ')'
+ (d.rawDelta !== undefined ? '\nraw ' + d.rawDelta + ', pcl ' + d.pclBranchDelta : '');
if (d.kind === 'anchor')
return 'abs anchor — pcl ' + d.pcl + ' "' + (d.pclName || '') + '" point ' + d.point
+ '\nannotation ' + d.annotation + ' → seed ' + d.vote + xyz(d) + '\non patch ' + d.patch;
if (d.kind === 'dot')
return 'rel-pcl point — pcl ' + d.pcl + ' "' + (d.pclName || '') + '" point ' + d.point
+ '\non patch ' + d.patch + xyz(d);
return '';
}
// Per-element mouse handling. The data-* attributes are the hook for richer
// behaviour later; for now we highlight + show a tooltip and log clicks.
document.querySelectorAll('.patch, .edge, .anchor, .dot, .loop').forEach(el => {
el.addEventListener('mouseenter', () => {
el.classList.add('hl');
tip.textContent = info(el);
tip.style.display = 'block';
});
el.addEventListener('mousemove', e => {
tip.style.left = (e.clientX + 12) + 'px';
tip.style.top = (e.clientY + 12) + 'px';
});
el.addEventListener('mouseleave', () => {
el.classList.remove('hl');
tip.style.display = 'none';
});
el.addEventListener('click', () => { console.log('clicked', el.dataset.kind, el.dataset); });
});
"""
def build_main_html(geom):
"""Build the interactive main-graph HTML document (frozen panes + per-element
SVG) and return it as a string -- embedded as a tab in the combined page."""
nodes = geom['nodes']
edges = geom['edges']
voters = geom['voters']
seed = geom['seed']
w0 = geom['w0']
ex = geom['entry_x']
departure_x = geom['departure_x']
anchors_by_patch = geom['anchors_by_patch']
node_extent = geom['node_extent']
node_raw_extent = geom['node_raw_extent']
node_y = geom['node_y']
depth_band = geom['depth_band']
vote_color = geom['vote_color']
vote_windings = geom['vote_windings']
vote_counts = geom['vote_counts']
node_id = geom['node_id']
title = geom['title']
x_lo, x_hi, y_min = geom['x_lo'], geom['x_hi'], geom['y_min']
slot_height, depth_gap = geom['slot_height'], geom['depth_gap']
annotate_votes, label_mode = geom['annotate_votes'], geom['label_mode']
sx = geom['px_per_winding']
row_px = geom['row_px']
LW = geom['label_width']
RW, BH = 92, 46
# --- data -> pixel transform (SVG y grows downward; matplotlib y up). ---
Xmin, Xmax = x_lo - 1, x_hi + 1
Ymax, Ymin = slot_height, y_min - slot_height
sy = row_px / slot_height
def X(x):
return (x - Xmin) * sx
def Y(y):
return (Ymax - y) * sy
PW = (Xmax - Xmin) * sx
PH = (Ymax - Ymin) * sy
cap = 0.18 * row_px
esc = html_lib.escape
def a(s):
return esc(str(s), quote=True)
def xyz_attrs(zyx):
"""data-x/y/z (full-res volume xyz) from a raw, un-downsampled [z, y, x] triple, if present."""
if not zyx or len(zyx) != 3:
return ''
z, y, x = zyx
return f' data-x="{x:.2f}" data-y="{y:.2f}" data-z="{z:.2f}"'
def edge_delta_attrs(h):
if 'raw_edge_winding_delta' not in h:
return ''
return (
f' data-raw-delta="{h["raw_edge_winding_delta"]:+d}"'
f' data-pcl-branch-delta="{h["pcl_branch_delta"]:+d}"'
f' data-pcl-unwrap-adjustment="{h["pcl_unwrap_adjustment"]:+d}"'
)
def odd_bands(width):
"""Shaded rects for odd depths, spanning `width` px -- reused per panel."""
out = []
for d, (yt, yb) in depth_band.items():
if d % 2 == 1:
ry = Y(yt + depth_gap / 2)
rh = (yt - yb + depth_gap) * sy
out.append(f'<rect class="band" x="0" y="{ry:.1f}" width="{width:.0f}" height="{rh:.1f}"/>')
return out
seam_lo, seam_hi = int(np.floor(x_lo)), int(np.ceil(x_hi))
# ---------------------------------------------------------------- plot svg
P = [f'<svg class="plot" width="{PW:.0f}" height="{PH:.0f}" '
f'viewBox="0 0 {PW:.0f} {PH:.0f}" xmlns="http://www.w3.org/2000/svg">']
P += odd_bands(PW)
for n in range(seam_lo, seam_hi + 1):
xx = X(n)
P.append(f'<line class="seam" x1="{xx:.1f}" y1="0" x2="{xx:.1f}" y2="{PH:.1f}"/>')
# edges: parent departure point -> child entry point.
for child, h in edges.items():
parent = h['from_patch']
x1, y1 = X(departure_x[child]), Y(node_y[parent])
x2, y2 = X(ex[child]), Y(node_y[child])
P.append(f'<g class="edge" data-kind="edge" data-from="{a(parent)}" data-to="{a(child)}" '
f'data-pcl="{a(h["rel_pcl_id"])}" data-pcl-name="{a(h.get("rel_pcl_name") or "")}" '
f'data-from-point="{a(h["from_point_id"])}" data-to-point="{a(h["to_point_id"])}" '
f'data-edge-delta="{h["edge_winding_delta"]:g}" data-strip-delta="{h["intra_patch_strip_delta"]:g}"'
f'{edge_delta_attrs(h)}>')
P.append(f'<line class="hit" x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}"/>')
P.append(f'<line class="edgeline" x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}"/>')
P.append('</g>')
# patches: horizontal line + end caps + crimson seam ticks.
for pid in nodes:
lo, hi = node_extent[pid]
y = node_y[pid]
xl, xr, yc = X(lo), X(hi), Y(y)
is_seed = pid == seed
# winding span of the known points. Points sit at band centres (winding +
# 0.5), so the winding number a centre belongs to is floor(x). A patch whose
# span covers more than one winding crosses theta=0, so a single winding
# number is meaningless -- the hover reports the range instead.
rlo, rhi = node_raw_extent[pid]
wlo, whi = int(math.floor(rlo)), int(math.floor(rhi))
P.append(f'<g class="patch{" seed" if is_seed else ""}" data-kind="patch" data-patch="{a(pid)}" '
f'data-depth="{nodes[pid]["depth"]}" data-winding-lo="{wlo}" data-winding-hi="{whi}">')
P.append(f'<line class="hit" x1="{xl:.1f}" y1="{yc:.1f}" x2="{xr:.1f}" y2="{yc:.1f}"/>')
P.append(f'<line class="patchline" x1="{xl:.1f}" y1="{yc:.1f}" x2="{xr:.1f}" y2="{yc:.1f}"/>')
for xe in (xl, xr):
P.append(f'<line class="cap" x1="{xe:.1f}" y1="{yc - cap:.1f}" x2="{xe:.1f}" y2="{yc + cap:.1f}"/>')
for n in integer_ticks(rlo, rhi):
xx = X(n)
P.append(f'<line class="seamtick" x1="{xx:.1f}" y1="{yc - cap * 1.3:.1f}" '
f'x2="{xx:.1f}" y2="{yc + cap * 1.3:.1f}"/>')
P.append('</g>')
# departure dots: where each relative-pcl edge leaves its parent patch. Drawn
# after the patches so they sit on top and own the hover at that point; each
# carries the source rel-pcl / point id and the point's volume xyz.
for child, h in edges.items():
parent = h['from_patch']
cx, cy = X(departure_x[child]), Y(node_y[parent])
P.append(f'<g class="dot" data-kind="dot" data-patch="{a(parent)}" data-to="{a(child)}" '
f'data-pcl="{a(h["rel_pcl_id"])}" data-pcl-name="{a(h.get("rel_pcl_name") or "")}" '
f'data-point="{a(h["from_point_id"])}"{xyz_attrs(h.get("from_zyx_raw"))}>')
P.append(f'<circle class="hitdot" cx="{cx:.1f}" cy="{cy:.1f}" r="6"/>')
P.append(f'<circle class="depdot" cx="{cx:.1f}" cy="{cy:.1f}" r="2.4"/>')
P.append('</g>')
# absolute anchors: stars coloured by the seed winding they imply.
for pid, anchs in anchors_by_patch.items():
yc = Y(node_y[pid])
for ax_x, v in anchs:
cx = X(ax_x)
col = vote_color[v['expected_seed_winding_rounded']]
P.append(f'<g class="anchor" data-kind="anchor" data-patch="{a(pid)}" '
f'data-pcl="{a(v["abs_pcl_id"])}" data-pcl-name="{a(v.get("abs_pcl_name") or "")}" '
f'data-point="{a(v["abs_point_id"])}" '
f'data-annotation="{v["abs_winding_annotation"]:g}" '
f'data-vote="{v["expected_seed_winding_rounded"]}"'
f'{xyz_attrs(v.get("abs_zyx_raw"))}>')
P.append(f'<polygon class="star" points="{_star_points(cx, yc, 8)}" fill="{col}"/>')
if annotate_votes:
P.append(f'<text class="votelabel" x="{cx:.1f}" y="{yc - 11:.1f}" fill="{col}" '
f'text-anchor="middle">{v["abs_winding_annotation"]:g}→'
f'{v["expected_seed_winding_rounded"]}</text>')
P.append('</g>')
P.append('</svg>')
# --------------------------------------------------------------- left col
Lp = [f'<svg class="inner" width="{LW}" height="{PH:.0f}" xmlns="http://www.w3.org/2000/svg">']
Lp += odd_bands(LW)
if label_mode != 'none':
for pid in nodes:
txt = str(node_id[pid]) if label_mode == 'id' else pid
cls = 'lbl seed' if pid == seed else 'lbl'
Lp.append(f'<text class="{cls}" x="{LW - 8}" y="{Y(node_y[pid]):.1f}" '
f'text-anchor="end" data-patch="{a(pid)}">{esc(txt)}</text>')
Lp.append('</svg>')
# --------------------------------------------------------------- right col
Rp = [f'<svg class="inner" width="{RW}" height="{PH:.0f}" xmlns="http://www.w3.org/2000/svg">']
Rp += odd_bands(RW)
for d, (yt, yb) in depth_band.items():
mid = 0.5 * (yt + yb)
Rp.append(f'<text class="dlbl" x="{RW / 2:.0f}" y="{Y(mid):.1f}" text-anchor="middle">{d}</text>')
Rp.append('</svg>')
# --------------------------------------------------------------- bottom axis
Bp = [f'<svg class="inner" width="{PW:.0f}" height="{BH}" xmlns="http://www.w3.org/2000/svg">']
# Tick marks sit on the integer seams (theta=0, the transitions between
# windings)...
for n in range(seam_lo, seam_hi + 1):
xx = X(n)
Bp.append(f'<line class="atick" x1="{xx:.1f}" y1="0" x2="{xx:.1f}" y2="7"/>')
# ...but the winding number labels the *range* between two seams, so it is
# centred in the gap (at n + 0.5), not on the seam at the winding's start.
for n in range(seam_lo, seam_hi):
xx = X(n + 0.5)
Bp.append(f'<text class="albl" x="{xx:.1f}" y="21" text-anchor="middle">{n}</text>')
Bp.append('</svg>')
# --------------------------------------------------------------- legend
leg = [
'<span class="item"><svg width="22" height="12"><line x1="1" y1="6" x2="21" y2="6" '
'stroke="#000" stroke-width="2"/></svg>patch</span>',
'<span class="item"><svg width="14" height="14"><line x1="7" y1="1" x2="7" y2="13" '
'stroke="crimson" stroke-width="1.6"/></svg>theta=0 seam crossing</span>',
'<span class="item"><svg width="22" height="12"><line x1="1" y1="6" x2="21" y2="6" '
'stroke="#999" stroke-width="1.4"/></svg>relative-pcl edge</span>',
]
for w in vote_windings:
col = vote_color[w]
leg.append(f'<span class="item"><svg width="16" height="16"><polygon '
f'points="{_star_points(8, 8, 7)}" fill="{col}"/></svg>seed = {w} '
f'({vote_counts[w]}× anchors)</span>')
grid_style = (f'grid-template-columns:{LW}px 1fr {RW}px;'
f'grid-template-rows:1fr {BH}px;')
html_doc = (
'<!DOCTYPE html>\n'
f'<html lang="en"><head><meta charset="utf-8">'
f'<title>winding graph {esc(seed)}</title>\n'
f'<style>{_HTML_CSS}</style></head>\n<body>\n'
f'<div class="header"><div class="title">{esc(title)}</div>'
f'<div class="legend">{"".join(leg)}</div></div>\n'
f'<div class="layout" style="{grid_style}">\n'
f' <div class="leftcol">{"".join(Lp)}</div>\n'
f' <div class="plotwrap">{"".join(P)}</div>\n'
f' <div class="rightcol">{"".join(Rp)}</div>\n'
f' <div class="corner corner-bl">absolute winding →</div>\n'
f' <div class="bottomaxis">{"".join(Bp)}</div>\n'
f' <div class="corner corner-br">BFS depth</div>\n'
f'</div>\n'
f'<div class="tooltip"></div>\n'
f'<script>{_HTML_JS}</script>\n'
f'</body></html>\n'
)
return html_doc
def _short_patch(pid, n=16):
"""Patch id trimmed to fit a loop-stack cell (keep the tail, where ids differ)."""
s = str(pid)
return s if len(s) <= n else '…' + s[-(n - 1):]
def _edge_delta_label(edge):
"""Compact visible edge delta label."""
return f"Δ{edge['edge_winding_delta']:+d}"
def _group_loop_cycles(loop_cycles, max_groups):
"""Collapse the inconsistent loops that share an identical BFS-tree spine into one
diagram apiece, so N loops that differ only in their closing edge cost one display
slot instead of N.
Every fundamental cycle is `spine + closing edge`, and the BFS tree is fixed, so two
loops with the same ordered `patches` list share their entire spine: the patches, the
tree `steps`, and the *interior* per-patch strip deltas are identical (only the two
endpoint patches' strip deltas differ, since they depend on where the closing edge
attaches). We therefore key by `tuple(patches)`, draw the shared spine once, and fan
that spine's several closing edges as several purple bows. (Two distinct edges between
the same patch pair reached from opposite BFS sides would give reversed `patches`
tuples and stay separate; that does not arise in practice and is left unmerged.)
Returns (groups, total_loops, total_groups, truncated):
* groups: spine-group dicts. The set is *selected* by max |holonomy| (largest first)
and capped to `max_groups` (0 = all), then *ordered for display* by ascending spine
patch count (shortest loops first, worst holonomy breaking ties). Each carries the
shared `patches` / `steps` and a
`patch_strip_deltas` whose interior entries are the shared within-patch deltas and
whose [0] / [-1] (the endpoint patches P / R) hold the common value only when all
the group's closing edges agree there, else None. `variants` is one entry per
closing edge (sorted by |holonomy|), each with its `closing_step`,
`loop_winding_delta`, `loop_winding_residual` and the closing-edge-specific
`top_strip_delta` (patch P) / `bot_strip_delta` (patch R).
* total_loops: inconsistent-loop count before grouping (== len(loop_cycles)).
* total_groups: distinct-spine count before the `max_groups` cap.
* truncated: whether the cap dropped any spine.
"""
groups_by_spine = {}
order = []
for c in loop_cycles:
key = tuple(c['patches'])
g = groups_by_spine.get(key)
if g is None:
g = {
'patches': c['patches'],
'steps': c['steps'],
# interior entries are the shared within-patch deltas; [0]/[-1] are
# resolved per group below (common value if the variants agree, else None).
'patch_strip_deltas': list(c.get('patch_strip_deltas') or [None] * len(c['patches'])),
'variants': [],
}
groups_by_spine[key] = g
order.append(key)
psd = c.get('patch_strip_deltas') or [None] * len(c['patches'])
g['variants'].append({
'closing_step': c['closing_step'],
'loop_winding_delta': c['loop_winding_delta'],
'loop_winding_residual': c.get('loop_winding_residual'),
'top_strip_delta': psd[0],
'bot_strip_delta': psd[-1],
})
groups = [groups_by_spine[k] for k in order]
for g in groups:
g['variants'].sort(key=lambda v: -abs(v.get('loop_winding_delta', 0)))
g['max_abs_holonomy'] = max(abs(v.get('loop_winding_delta', 0)) for v in g['variants'])
# Endpoint patch deltas (P at top, R at bottom) are closing-edge-specific; show
# one on the patch line only when every closing edge agrees, else leave it to the
# per-bow tooltip.
tops = {v['top_strip_delta'] for v in g['variants']}
bots = {v['bot_strip_delta'] for v in g['variants']}
g['patch_strip_deltas'][0] = next(iter(tops)) if len(tops) == 1 else None
g['patch_strip_deltas'][-1] = next(iter(bots)) if len(bots) == 1 else None
# Select which spines to show by max |holonomy| (largest first), then cap...
groups.sort(key=lambda g: -g['max_abs_holonomy'])
total_groups = len(groups)
total_loops = len(loop_cycles)
truncated = bool(max_groups and total_groups > max_groups)
if truncated:
groups = groups[:max_groups]
# ...but display the chosen spines by ascending patch count (shortest, simplest loops
# first), worst holonomy breaking ties.
groups.sort(key=lambda g: (len(g['patches']), -g['max_abs_holonomy']))
return groups, total_loops, total_groups, truncated
def plot_loop_cycles(groups, total_loops, total_groups, output, ncols=6, dpi=150):
"""Render each shared-spine group on its own, as a vertical patch stack (matplotlib
PNG). `groups` are the (already selected) spine groups to draw; `total_loops` /
`total_groups` are the full counts before any cap, used only for the caption.
Each diagram is a vertical stack of the spine's patches (the departure patch P at the
top, the arrival patch R at the bottom), the relative-pcl tree edges as downward
arrows between consecutive patches (labelled with the pcl id and its Δwinding), and
-- bowing to the right, clear of the patch names -- one magenta 'closing' arrow per
loop that shares this spine: each is a non-tree edge whose nonzero holonomy makes
that loop fail to close, fanned by radius and listed (pcl id, Δwinding, holonomy) down
the right. The crimson per-patch Δwinding (within-patch theta=0 crossing) is shown
where defined; at the two endpoint patches it appears only when every closing edge in
the group agrees on it."""
n = len(groups)
ncols = max(1, min(ncols, n))
nrows = math.ceil(n / ncols)
max_patches = max(len(g['patches']) for g in groups)
max_variants = max(len(g['variants']) for g in groups)
LOOP_COLOR = '#c026d3'
cell_w = 2.8 + 0.18 * max(0, max_variants - 1)
cell_h = 0.34 * max_patches + 0.13 * max(0, max_variants - 1) + 1.1
fig, axes = plt.subplots(nrows, ncols, squeeze=False,
figsize=(ncols * cell_w, nrows * cell_h))
for k in range(nrows * ncols):
ax = axes[k // ncols][k % ncols]
ax.axis('off')
if k >= n:
continue
g = groups[k]
patches, steps, variants = g['patches'], g['steps'], g['variants']
m, nv = len(patches), len(variants)
pdeltas = g.get('patch_strip_deltas') or [None] * m
ys = [-i for i in range(m)]
# patches: a dot per row, id labelled to the left; the within-patch winding
# delta (when the strip across the patch crosses theta=0) in crimson to the right.
for i, pid in enumerate(patches):
ax.plot([0], [ys[i]], marker='o', ms=4, color='black', zorder=3)
ax.text(-0.16, ys[i], _short_patch(pid), fontsize=6, va='center', ha='right',
zorder=4, fontweight='bold' if i in (0, m - 1) else 'normal')
if pdeltas[i]:
ax.text(0.12, ys[i], f"Δ{pdeltas[i]:+d}", fontsize=5, color='crimson',
va='center', ha='left', zorder=4, fontweight='bold')
# tree-edge pcls: downward arrows, label centred on the arrow (white bbox).
for i, st in enumerate(steps):
ax.annotate('', xy=(0, ys[i + 1]), xytext=(0, ys[i]),
arrowprops=dict(arrowstyle='-|>', color='0.45', lw=1.0,
shrinkA=5, shrinkB=5), zorder=2)
ax.text(0.0, 0.5 * (ys[i] + ys[i + 1]),
f"pcl {st['rel_pcl_id']} {_edge_delta_label(st)}",
fontsize=5, color='0.3', va='center', ha='center', zorder=4,
bbox=dict(boxstyle='round,pad=0.1', facecolor='white',
edgecolor='none', alpha=0.85))
# closing edges: one magenta arrow per loop sharing this spine, each bowing to the
# RIGHT from the bottom patch back up to the top. arc3 'rad' is a fraction of the
# chord (scaled by stack height for a roughly constant width), fanned out per loop;
# each loop is also listed (pcl id, Δwinding, holonomy) down the right.
rad0 = 0.7 / max(1, m - 1)
y_top, y_bot = ys[0], ys[-1]
# the loop list is a magenta block centred vertically on the spine midpoint (a
# lone label sits exactly at the centre), spaced by lbl_step rows.
mid = 0.5 * (y_top + y_bot)
lbl_step = 0.6
lbl_ys = [mid + (t - (nv - 1) / 2.0) * lbl_step for t in range(nv)]
for t, var in enumerate(variants):
cs = var['closing_step']
rad = rad0 * (1.0 + 0.8 * t)
ax.add_patch(FancyArrowPatch(
(0, y_bot), (0, y_top), connectionstyle=f'arc3,rad={rad}',
arrowstyle='-|>', mutation_scale=11, color=LOOP_COLOR,
lw=1.3 if nv == 1 else 1.0, shrinkA=6, shrinkB=6, zorder=2,
alpha=1.0 if nv == 1 else 0.8))
ax.text(0.95, lbl_ys[t],
f"pcl {cs['rel_pcl_id']} {_edge_delta_label(cs)} h{var['loop_winding_delta']:+d}",
fontsize=5.5 if nv == 1 else 5.0, color=LOOP_COLOR, va='center',
ha='left', fontweight='bold', zorder=4)
ax.set_xlim(-1.5, 2.4 + 0.12 * max(0, nv - 1))
ax.set_ylim(min(y_bot, min(lbl_ys)) - 0.6, max(y_top, max(lbl_ys)) + 0.6)
cap_note = '' if n == total_groups else f' (showing the {n} with the largest |holonomy|)'
drawn_loops = sum(len(g['variants']) for g in groups)
fig.suptitle(f'{total_loops} inconsistent loop(s) in {total_groups} shared spine(s){cap_note} -- '
f'patches stacked top-to-bottom, relative-pcl edges as arrows (with Δwinding); '
f'each magenta bow = one closing edge (holonomy ≠ 0), fanned per spine; '
f'crimson Δ = within-patch winding delta (theta=0 crossing)',
fontsize=10)
fig.tight_layout(rect=(0, 0, 1, 0.99))
fig.savefig(output, dpi=dpi, bbox_inches='tight')
plt.close(fig)
print(f'wrote {output} ({n} spine diagram(s) of {total_groups}, '
f'covering {drawn_loops} of {total_loops} loop(s))')
# CSS / JS for the per-loop HTML view (kept as plain strings; same pattern as the
# main-graph page above).
_LOOPS_CSS = r"""
* { box-sizing: border-box; }
html, body { margin: 0; font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background: #fff; color: #222; }
.header { padding: 8px 12px; border-bottom: 1px solid #ddd; }
.header .title { font-size: 13px; font-weight: 600; }
.legend { margin-top: 6px; font-size: 12px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; }
.legend .item { display: inline-flex; align-items: center; gap: 5px; }
/* flow layout: tiles keep their natural (per-spine) width/height and wrap to fit
the window, packed left-to-right so the |holonomy| ordering still reads in order. */
.grid { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 10px; padding: 12px; }
.cell { flex: 0 0 auto; border: 1px solid #eee; border-radius: 6px; padding: 4px 6px 8px; }
svg.loop { display: block; margin: 0 auto; }
.plbl { font-size: 11px; fill: #333; dominant-baseline: middle; }
.plbl.end { font-weight: 700; fill: #111; }
.elbl { font-size: 9.5px; fill: #444; dominant-baseline: middle; }
.clbl { font-size: 10px; fill: #c026d3; font-weight: 700; dominant-baseline: middle; }
.pslbl { font-size: 9px; fill: crimson; font-weight: 700; dominant-baseline: middle; pointer-events: none; }
.patchv { stroke: #000; stroke-width: 1.8; }
.patchv.end { stroke-width: 2.6; }
.tedge { stroke: #999; stroke-width: 1; fill: none; }
.closing { stroke: #c026d3; stroke-width: 1.6; fill: none; }
.pdot { fill: #000; }
.phit { fill: transparent; }
.ledge, .lclose, .lpatch, .ldot { cursor: pointer; }
.ledge:hover .tedge { stroke: #ff8c00; stroke-width: 2; }
.lclose:hover .closing { stroke: #ff8c00; stroke-width: 2.6; }
.lpatch:hover .patchv { stroke: #ff8c00; }
.lpatch:hover .plbl { fill: #ff8c00; }
.ldot:hover .pdot { fill: #ff8c00; }
.tooltip { position: fixed; pointer-events: none; display: none; z-index: 10;
background: rgba(20,20,20,.92); color: #fff; font-size: 11px;
padding: 5px 7px; border-radius: 4px; max-width: 420px; white-space: pre-line; }
"""
_LOOPS_JS = r"""
const tip = document.querySelector('.tooltip');
function xyz(px, py, pz) {
if (px === undefined) return ' (xyz not recorded)';
return ' xyz ' + Math.round(+px) + ', ' + Math.round(+py) + ', ' + Math.round(+pz);
}
function deltaInfo(d) {
let s = '\nΔwinding ' + d.delta;
if (d.rawDelta !== undefined)
s += ' (raw ' + d.rawDelta + ', pcl ' + d.pclBranchDelta + ')';
return s;
}
function info(el) {
const d = el.dataset;
if (d.kind === 'patch') return 'patch ' + d.patch
+ (d.stripDelta !== undefined ? '\nΔwinding across patch ' + d.stripDelta : '');
if (d.kind === 'dot') return 'rel-pcl point — pcl ' + d.pcl + ' "' + (d.pclName || '') + '" point ' + d.point
+ '\non patch ' + d.patch + xyz(d.x, d.y, d.z);
if (d.kind === 'edge') return 'rel-pcl edge ' + d.pcl + ' "' + (d.pclName || '') + '"'
+ '\npoint ' + d.fromPoint + ' on ' + d.from + xyz(d.fromX, d.fromY, d.fromZ)
+ '\n → point ' + d.toPoint + ' on ' + d.to + xyz(d.toX, d.toY, d.toZ)
+ deltaInfo(d);
if (d.kind === 'closing') return 'closing edge — rel-pcl ' + d.pcl + ' "' + (d.pclName || '') + '"'
+ '\npoint ' + d.fromPoint + ' on ' + d.from + xyz(d.fromX, d.fromY, d.fromZ)
+ '\n → point ' + d.toPoint + ' on ' + d.to + xyz(d.toX, d.toY, d.toZ)
+ deltaInfo(d) + '\nwinding holonomy ' + d.holo + ' (loop does not close)'
+ (d.topStripDelta !== undefined ? '\nΔ across ' + d.to + ' (top) ' + d.topStripDelta : '')
+ (d.botStripDelta !== undefined ? '\nΔ across ' + d.from + ' (bottom) ' + d.botStripDelta : '');
return '';
}
document.querySelectorAll('.lpatch, .ledge, .lclose, .ldot').forEach(el => {
el.addEventListener('mouseenter', () => { tip.textContent = info(el); tip.style.display = 'block'; });
el.addEventListener('mousemove', e => { tip.style.left = (e.clientX + 12) + 'px'; tip.style.top = (e.clientY + 12) + 'px'; });
el.addEventListener('mouseleave', () => { tip.style.display = 'none'; });
});
"""
def build_loops_html(groups, total_loops, total_groups):
"""Build the per-loop view as an HTML document string -- embedded as a tab in the
combined page. One small inline SVG per *spine group*, flowed (flex-wrap) to fit the
window rather than forced into a rigid grid, since the tiles vary in width/height: the
shared spine's
patches stacked vertically, each a short bold black vertical line with a black dot at
either end for the pcl-points attaching there (the upper from the edge above, the
lower from the edge below; each hoverable for its volume xyz). Each relative-pcl tree
edge is two fine gray fragments running between adjacent patches' dots, with its pcl id
+ Δwinding in the gap between them. The loops that share this spine differ only in their
closing edge, so those are fanned as several magenta bows -- one per loop -- to the
right, each listed (pcl id, Δwinding, holonomy) down the side. When the strip across a
patch between its two cycle points crosses theta=0, its winding delta is shown in
crimson just right of the patch line (at the two endpoint patches, only when every
closing edge agrees). Each patch / edge / point / closing edge is its own <g> carrying
data-* attributes, with a hover tooltip."""
esc = html_lib.escape
def a(s):
return esc(str(s), quote=True)
def xyz_attrs(zyx, prefix=''):
"""data-[prefix]x/y/z (full-res volume xyz) from a raw, un-downsampled [z, y, x]
triple, if present. prefix='from-'/'to-' tags the two ends of a pcl edge."""
if not zyx or len(zyx) != 3:
return ''
z, y, x = zyx
return f' data-{prefix}x="{x:.2f}" data-{prefix}y="{y:.2f}" data-{prefix}z="{z:.2f}"'
def edge_delta_attrs(edge):
if 'raw_edge_winding_delta' not in edge:
return ''
return (
f' data-raw-delta="{edge["raw_edge_winding_delta"]:+d}"'
f' data-pcl-branch-delta="{edge["pcl_branch_delta"]:+d}"'
f' data-pcl-unwrap-adjustment="{edge["pcl_unwrap_adjustment"]:+d}"'
)
def strip_delta_attrs(var):
"""The closing-edge-specific within-patch deltas at the spine's two endpoint
patches (P at the top, R at the bottom) -- carried on the bow for its tooltip."""
out = ''
if var.get('top_strip_delta') is not None:
out += f' data-top-strip-delta="{var["top_strip_delta"]:+d}"'
if var.get('bot_strip_delta') is not None:
out += f' data-bot-strip-delta="{var["bot_strip_delta"]:+d}"'
return out
ROW, TOP, BOT, CX, BOW = 34, 16, 16, 150, 58
# patch half-line height; pcl-point dot radius; half-gap left for the name.
PHH, PR, NAMEGAP = 5.0, 2.6, 7
LBLX = CX - 14
# each extra closing bow widens by this fraction of BOW; the stacked closing labels
# (when there is more than one) step down by LBLSTEP.
BOW_STEP, LBLSTEP = 0.7, 14
cells = []
for g in groups:
patches, steps, variants = g['patches'], g['steps'], g['variants']
m, nv = len(patches), len(variants)
# within-patch winding delta between each patch's two cycle points (endpoint
# entries are None unless every closing edge agrees; older files: no labels).
pdeltas = g.get('patch_strip_deltas') or [None] * m
ys = [TOP + i * ROW for i in range(m)]
midc = 0.5 * (ys[0] + ys[-1])
max_bow = BOW * (1.0 + BOW_STEP * (nv - 1))
rlbl = CX + max_bow + 8 # left edge of the closing-label column
# closing-edge labels: a vertical block centred on the spine midpoint (a lone label
# sits exactly at midc), so several read as a centred stack rather than top-anchored.
lbl_ys = [midc + (t - (nv - 1) / 2.0) * LBLSTEP for t in range(nv)]
# grow the canvas (shifting all y down) so a tall label block on a short spine is
# never clipped at the top; LBL_PAD covers the label text's own height.
LBL_PAD = 7
content_top = min(ys[0] - PHH, min(lbl_ys) - LBL_PAD)
content_bot = max(ys[-1] + PHH, max(lbl_ys) + LBL_PAD)
y_off = TOP - content_top
ys = [y + y_off for y in ys]
lbl_ys = [y + y_off for y in lbl_ys]
H = int(content_bot - content_top) + TOP + BOT
W = int(rlbl + 120)
# the pcl-point attaching at each patch's top end (edge from above) and bottom
# end (edge below), from the shared tree steps. The two endpoint patches' outer
# ends belong to the closing edges; with a single closing edge that point is
# unambiguous and drawn as a dot, otherwise the bows + their tooltips carry it.
top_pt, bot_pt = [None] * m, [None] * m
for j, st in enumerate(steps):
bot_pt[j] = (st['rel_pcl_id'], st.get('rel_pcl_name'), st['from_point_id'],
patches[j], st.get('from_zyx_raw'))
top_pt[j + 1] = (st['rel_pcl_id'], st.get('rel_pcl_name'), st['to_point_id'],
patches[j + 1], st.get('to_zyx_raw'))
if nv == 1:
cs0 = variants[0]['closing_step']
bot_pt[m - 1] = (cs0['rel_pcl_id'], cs0.get('rel_pcl_name'), cs0['from_point_id'],
patches[m - 1], cs0.get('from_zyx_raw'))
top_pt[0] = (cs0['rel_pcl_id'], cs0.get('rel_pcl_name'), cs0['to_point_id'],
patches[0], cs0.get('to_zyx_raw'))
S = [f'<svg class="loop" width="{W}" height="{H}" viewBox="0 0 {W} {H}" '
f'xmlns="http://www.w3.org/2000/svg">']
# tree-edge pcls: two fine gray fragments (above and below the centred name)
# running between the bottom dot of the upper patch and the top dot of the
# lower one, so the name sits in a clear gap rather than over the line.
for i, st in enumerate(steps):
ya, yb = ys[i] + PHH, ys[i + 1] - PHH # the adjacent patches' end-dots
mid = 0.5 * (ys[i] + ys[i + 1])
txt = f"pcl {st['rel_pcl_id']} {_edge_delta_label(st)}"
S.append(f'<g class="ledge" data-kind="edge" data-pcl="{a(st["rel_pcl_id"])}" '
f'data-pcl-name="{a(st.get("rel_pcl_name") or "")}" '
f'data-from="{a(st["from_patch"])}" data-to="{a(st["to_patch"])}" '
f'data-from-point="{a(st["from_point_id"])}" data-to-point="{a(st["to_point_id"])}" '
f'data-delta="{st["edge_winding_delta"]:+d}"'
f'{edge_delta_attrs(st)}'
f'{xyz_attrs(st.get("from_zyx_raw"), "from-")}'
f'{xyz_attrs(st.get("to_zyx_raw"), "to-")}>')
S.append(f'<line class="tedge" x1="{CX}" y1="{ya:.1f}" x2="{CX}" y2="{mid - NAMEGAP:.1f}"/>')
S.append(f'<line class="tedge" x1="{CX}" y1="{mid + NAMEGAP:.1f}" x2="{CX}" y2="{yb:.1f}"/>')
S.append(f'<text class="elbl" x="{CX}" y="{mid:.1f}" text-anchor="middle">{esc(txt)}</text>')
S.append('</g>')
# closing edges: one magenta bow per loop sharing this spine, fanned to the right
# (wider per loop) from the bottom patch's bottom dot up into the top patch's top
# dot, each listed (pcl id, Δwinding, holonomy) down the right. Each is its own <g>.
yb0, yt0 = ys[-1] + PHH, ys[0] - PHH
for t, var in enumerate(variants):
cs = var['closing_step']
bw = BOW * (1.0 + BOW_STEP * t)
ctxt = f"pcl {cs['rel_pcl_id']} {_edge_delta_label(cs)} h{var['loop_winding_delta']:+d}"
S.append(f'<g class="lclose" data-kind="closing" data-pcl="{a(cs["rel_pcl_id"])}" '
f'data-pcl-name="{a(cs.get("rel_pcl_name") or "")}" '
f'data-from="{a(cs["from_patch"])}" data-to="{a(cs["to_patch"])}" '
f'data-from-point="{a(cs["from_point_id"])}" data-to-point="{a(cs["to_point_id"])}" '
f'data-delta="{cs["edge_winding_delta"]:+d}" data-holo="{var["loop_winding_delta"]:+d}"'
f'{strip_delta_attrs(var)}'
f'{edge_delta_attrs(cs)}'
f'{xyz_attrs(cs.get("from_zyx_raw"), "from-")}'
f'{xyz_attrs(cs.get("to_zyx_raw"), "to-")}>')
S.append(f'<path class="closing" d="M {CX},{yb0:.1f} C {CX + bw:.1f},{yb0:.1f} '
f'{CX + bw:.1f},{yt0:.1f} {CX},{yt0:.1f}" marker-end="url(#ahm)"/>')
S.append(f'<text class="clbl" x="{rlbl:.1f}" y="{lbl_ys[t]:.1f}">{esc(ctxt)}</text>')
S.append('</g>')
# patches: a short bold black vertical line, a black pcl-point dot at each end
# (top = edge from above, bottom = edge below; each hoverable for its xyz), and
# the id label to the left (departure/arrival ends bold).
for i, pid in enumerate(patches):
is_end = i in (0, m - 1)
pcls = 'patchv end' if is_end else 'patchv'
lcls = 'plbl end' if is_end else 'plbl'
pd = pdeltas[i]
pd_attr = f' data-strip-delta="{pd:+d}"' if pd is not None else ''
S.append(f'<g class="lpatch" data-kind="patch" data-patch="{a(pid)}"{pd_attr}>')
S.append(f'<line class="{pcls}" x1="{CX}" y1="{ys[i] - PHH:.1f}" '
f'x2="{CX}" y2="{ys[i] + PHH:.1f}"/>')
S.append(f'<text class="{lcls}" x="{LBLX}" y="{ys[i]}" text-anchor="end">{esc(_short_patch(pid))}</text>')
# crimson within-patch Δwinding, just right of the line (only when nonzero:
# the strip across the patch crosses theta=0).
if pd:
S.append(f'<text class="pslbl" x="{CX + PHH + 3}" y="{ys[i]}" '
f'text-anchor="start">Δ{pd:+d}</text>')
S.append('</g>')
for yy, pt in ((ys[i] - PHH, top_pt[i]), (ys[i] + PHH, bot_pt[i])):
if pt is None:
continue
pcl_id, pcl_name, pt_id, patch_id, zyx = pt
S.append(f'<g class="ldot" data-kind="dot" data-pcl="{a(pcl_id)}" '
f'data-pcl-name="{a(pcl_name or "")}" '
f'data-point="{a(pt_id)}" data-patch="{a(patch_id)}"{xyz_attrs(zyx)}>')
S.append(f'<circle class="phit" cx="{CX}" cy="{yy:.1f}" r="4"/>')
S.append(f'<circle class="pdot" cx="{CX}" cy="{yy:.1f}" r="{PR}"/>')
S.append('</g>')
S.append('</svg>')
cells.append(f'<div class="cell">{"".join(S)}</div>')
note = ('' if len(groups) == total_groups
else f' (showing the {len(groups)} spine(s) with the largest |holonomy|)')
title = (f'{total_loops} inconsistent loop(s) in {total_groups} shared spine(s){note} — each: '
f'patches (bold black lines) stacked top-to-bottom, relative-pcl tree edges as fine gray '
f'links (with Δwinding); each magenta bow = one closing edge sharing the spine (holonomy ≠ 0)')
legend = (
'<span class="item"><svg width="20" height="14">'
'<line x1="10" y1="2" x2="10" y2="12" stroke="#000" stroke-width="2.2"/>'
'<circle cx="10" cy="2" r="2" fill="#000"/><circle cx="10" cy="12" r="2" fill="#000"/>'
'</svg>patch (with its two pcl-points)</span>'
'<span class="item"><svg width="24" height="12"><line x1="4" y1="6" x2="20" y2="6" '