File size: 55,126 Bytes
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
fcb2510
 
e43a9c1
 
 
 
 
 
 
 
 
 
d1daf18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118fdde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8754dc6
 
 
 
 
 
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118fdde
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
e6c805a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67f9ca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7855826
e43a9c1
03a57d4
 
7855826
03a57d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f7644c
10a2475
1452d31
76d4316
 
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b210f2
e43a9c1
960fed9
e43a9c1
1a39d77
a8c1ce0
 
004e0b4
78aba19
e43a9c1
 
 
 
a8c1ce0
 
e43a9c1
 
 
 
 
 
 
 
b4e0b40
 
 
 
 
 
 
 
 
0d2d502
b4e0b40
 
 
 
 
 
 
e43a9c1
4f9113b
 
 
 
 
 
 
a593493
4f9113b
 
27d1a74
d704ca7
27d1a74
d7cbc4b
 
4f9113b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423e80f
 
 
 
78f6a87
423e80f
 
 
10763d2
9cd7a8f
 
03a57d4
e43a9c1
c30f58a
e43a9c1
 
576abee
 
 
10763d2
 
 
 
 
 
 
 
 
 
9cd7a8f
 
 
d1daf18
 
9cd7a8f
d1daf18
 
 
afdfed5
 
 
d1daf18
 
afdfed5
d1daf18
 
 
 
 
 
 
 
 
 
 
 
 
afdfed5
9cd7a8f
10763d2
78f6a87
b6b233e
 
 
 
 
 
 
 
 
78f6a87
b6b233e
22bc336
78f6a87
 
 
 
 
576abee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e43a9c1
576abee
e43a9c1
 
 
576abee
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576abee
e43a9c1
 
 
576abee
 
 
 
 
 
fc12fa9
e43a9c1
 
576abee
e43a9c1
 
 
 
 
 
 
 
c54e8fa
e43a9c1
 
 
 
 
 
576abee
 
 
 
 
 
 
 
 
 
c54e8fa
576abee
 
 
 
 
e43a9c1
10763d2
 
 
 
 
 
 
 
 
 
 
c54e8fa
10763d2
 
 
 
 
 
d1daf18
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd7a8f
d1daf18
afdfed5
9cd7a8f
10763d2
576abee
e43a9c1
 
d4476a5
 
 
 
 
 
 
 
 
 
 
 
 
e43a9c1
 
 
 
 
353697a
10763d2
 
c54e8fa
9cd7a8f
c54e8fa
10763d2
c54e8fa
353697a
c54e8fa
423e80f
10763d2
 
 
9cd7a8f
 
10763d2
 
576abee
c387d40
10763d2
c387d40
10763d2
78f6a87
10763d2
e43a9c1
576abee
e43a9c1
10763d2
 
e43a9c1
d4476a5
 
 
e43a9c1
d4476a5
e43a9c1
 
 
d4476a5
e43a9c1
 
d4476a5
e43a9c1
 
 
9acea3e
e43a9c1
 
2c8c08b
e43a9c1
 
576abee
 
 
 
 
 
e43a9c1
 
 
 
 
576abee
e43a9c1
 
 
122bce1
e43a9c1
 
00dffc1
e43a9c1
fd07f84
2a5f473
e43a9c1
 
8754dc6
e43a9c1
 
794eb5e
e43a9c1
 
 
 
 
 
 
 
 
 
794eb5e
 
 
 
 
 
 
 
 
 
 
 
e43a9c1
 
 
d4476a5
 
 
 
 
970d111
e43a9c1
 
423e80f
 
 
 
 
94a64fb
78f6a87
c387d40
47cde55
 
 
 
 
 
 
 
 
 
 
78f6a87
423e80f
8754dc6
98a9fa8
8754dc6
 
 
d4d5ede
8754dc6
98a9fa8
 
 
 
8754dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a9fa8
 
 
d1daf18
98a9fa8
 
9acea3e
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
b4e0b40
 
dd9bb0d
7411d4c
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03a57d4
 
3319d31
03a57d4
 
 
 
bde1026
03a57d4
 
 
e43a9c1
 
 
 
 
 
 
 
 
9cc659c
 
 
 
e43a9c1
 
 
 
 
 
abe589d
 
 
 
 
 
 
 
 
 
e43a9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a9fa8
 
e43a9c1
 
 
b4e0b40
4f9113b
e43a9c1
 
 
98a9fa8
 
e43a9c1
 
 
 
 
 
98a9fa8
 
 
e43a9c1
 
 
 
1e3a17a
b4e0b40
1e3a17a
e43a9c1
 
 
8754dc6
98a9fa8
e43a9c1
 
 
 
 
8754dc6
 
98a9fa8
 
8754dc6
e43a9c1
 
 
 
8754dc6
 
98a9fa8
 
e43a9c1
 
 
98a9fa8
e43a9c1
4f9113b
e43a9c1
98a9fa8
e43a9c1
b4e0b40
 
98a9fa8
b4e0b40
 
 
aa3fd09
98a9fa8
4f9113b
e43a9c1
 
 
98a9fa8
e43a9c1
8754dc6
e43a9c1
 
 
 
 
98a9fa8
e43a9c1
54fabdd
e43a9c1
98a9fa8
 
e43a9c1
8754dc6
e43a9c1
 
 
 
98a9fa8
e43a9c1
98a9fa8
 
8754dc6
 
 
 
 
 
 
 
98a9fa8
8754dc6
 
 
 
 
 
 
 
98a9fa8
8754dc6
 
 
 
 
98a9fa8
8754dc6
 
d4d5ede
 
 
 
 
 
8754dc6
98a9fa8
8754dc6
98a9fa8
 
 
 
d1daf18
98a9fa8
d1daf18
d4d5ede
98a9fa8
 
e43a9c1
 
 
 
98a9fa8
d1daf18
98a9fa8
 
d1daf18
afdfed5
 
 
d1daf18
afdfed5
d1daf18
 
 
afdfed5
d1daf18
afdfed5
98a9fa8
d1daf18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afdfed5
98a9fa8
afdfed5
8754dc6
 
 
 
 
98a9fa8
8754dc6
 
 
 
 
 
98a9fa8
8754dc6
 
 
 
 
 
98a9fa8
8754dc6
 
 
 
 
98a9fa8
8754dc6
 
98a9fa8
8754dc6
 
e43a9c1
 
 
 
98a9fa8
e43a9c1
 
98a9fa8
e43a9c1
 
98a9fa8
e43a9c1
 
98a9fa8
e43a9c1
98a9fa8
e43a9c1
 
 
 
98a9fa8
e43a9c1
 
98a9fa8
e43a9c1
98a9fa8
 
8754dc6
98a9fa8
e43a9c1
 
 
 
 
 
 
423e80f
78f6a87
03a57d4
9cd7a8f
03a57d4
e43a9c1
54fabdd
d4476a5
0afedbe
 
 
423e80f
0afedbe
 
78f6a87
 
 
e43a9c1
 
0afedbe
 
 
78f6a87
e43a9c1
 
 
423e80f
03a57d4
9cd7a8f
 
e43a9c1
 
 
d4476a5
e43a9c1
 
 
 
 
 
 
e6c805a
e43a9c1
 
 
 
5b9757d
e43a9c1
 
5b9757d
e43a9c1
 
 
 
118fdde
e43a9c1
 
 
 
67f9ca2
 
 
5b9757d
 
67f9ca2
 
5b9757d
 
e6c805a
 
 
 
5b9757d
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c805a
5b9757d
e6c805a
5b9757d
 
e6c805a
5b9757d
e43a9c1
e6c805a
 
 
 
 
5b9757d
e6c805a
 
 
 
 
 
 
 
 
 
e43a9c1
5b9757d
abe589d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e1938a
8754dc6
2e1938a
8754dc6
 
2e1938a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03a57d4
2e1938a
 
ed4f17c
2e1938a
 
03a57d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47cde55
 
 
 
 
 
 
 
 
 
03a57d4
47cde55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a9fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abe589d
98a9fa8
 
e43a9c1
 
 
46413c5
e43a9c1
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
import math
from typing import List

from dash import Dash, html, dcc, Input, Output, State, ctx, no_update
import plotly.graph_objects as go


# ------------------------------------------------------------
# Default settings for the Hypercube visualizer
# ------------------------------------------------------------
DEFAULTS = {
    "dimension": 3,          # start with Q4
    "scale": 1600.0,          # base layout scale
    "node_radius": 6,        # node size (radius)
    "edge_width": 4,         # edge thickness
    "show_labels": False,    # show binary labels on nodes # True / False
    "label_fontsize": 12,    # font size of labels
    "max_dimension": 12,     # slider max
    "min_dimension": 1,      # slider min
}



# ---------- Hypercube utilities ----------


def consecutive_triple_start(indices: list[int], n: int, is_closed: bool) -> int | None:
    """
    Given 3 indices, return the start index s such that {s,s+1,s+2} (mod n if closed)
    equals the given set. If not possible, return None.
    """
    if len(indices) != 3 or n <= 0:
        return None

    S = set(indices)

    if is_closed:
        for s in range(n):
            if {(s) % n, (s + 1) % n, (s + 2) % n} == S:
                return s
        return None
    else:
        # open path: must be literal consecutive indices
        mn = min(S)
        if S == {mn, mn + 1, mn + 2} and (mn + 2) < n:
            return mn
        return None



def cycle_edge_dims(cycle: List[int], d: int) -> List[int] | None:
    """
    cycle is vertex list WITHOUT repeating start at end.
    Returns list of edge dimensions around the cycle (length n),
    or None if any step is non-adjacent.
    """
    n = len(cycle)
    dims = []
    for i in range(n):
        a = cycle[i]
        b = cycle[(i + 1) % n]
        dim = edge_dimension(a, b)
        if dim is None:
            return None
        dims.append(dim)
    return dims


def is_symmetric_coil(path: List[int], d: int, allow_reverse: bool = True) -> bool:
    """
    A "doubled coil": valid coil whose second half repeats the structure of the first half.
    We detect this via the cyclic edge-dimension sequence.

    allow_reverse=True also accepts that the second half is the reverse traversal
    of the first half (often happens depending on where you cut the cycle).
    """
    if not path or len(path) < 4:
        return False
    if path[0] != path[-1]:
        return False  # must be explicitly closed

    cycle = path[:-1]
    n = len(cycle)
    if n % 2 != 0:
        return False

    dims = cycle_edge_dims(cycle, d)
    if dims is None:
        return False

    half = n // 2
    first = dims[:half]
    second = dims[half:]

    if second == first:
        return True

    if allow_reverse:
        # If the second half traverses the "same structure" but reversed,
        # edge-dim sequence matches reversed order.
        if second == list(reversed(first)):
            return True

    return False


def index_in_path(path: List[int], vid: int):
    """Return the index of vid in path (first occurrence), or None."""
    try:
        return path.index(vid)
    except ValueError:
        return None


def swap_dims_vertex(v: int, i: int, j: int) -> int:
    """
    Swap bits i and j in the vertex id v.
    (Coordinate permutation on Q_d.)
    """
    if i == j:
        return v
    bi = (v >> i) & 1
    bj = (v >> j) & 1
    if bi != bj:
        # flip both bits: 01 -> 10 or 10 -> 01
        v ^= (1 << i) | (1 << j)
    return v


def flip_dim_vertex(v: int, k: int) -> int:
    """
    Flip bit k in the vertex id v.
    (Translation by the unit vector in coordinate k.)
    """
    return v ^ (1 << k)


def swap_dims_path(path, d: int, i: int, j: int):
    """Apply swap_dims_vertex to every vertex in the path."""
    if i < 0 or j < 0 or i >= d or j >= d:
        return path
    return [swap_dims_vertex(v, i, j) for v in path]


def flip_dim_path(path, d: int, k: int):
    """Apply flip_dim_vertex to every vertex in the path."""
    if k < 0 or k >= d:
        return path
    return [flip_dim_vertex(v, k) for v in path]


def classify_path(path, d: int):
    """
    Classify a path in Q_d as one of:
      - "snake"        (induced simple path)
      - "coil"         (induced simple cycle)
      - "almost coil"  (open path that would be a coil if closed)
      - "not snake"    otherwise
    Returns: (label, is_valid)
    """

    if not path or len(path) <= 1:
        return "snake", True  # trivial path treated as snake

    # Is the path explicitly closed (first == last)?
    is_closed = (path[0] == path[-1])

    # Work with a version without duplicate endpoint when closed
    cycle = path[:-1] if is_closed else path[:]
    n = len(cycle)

    # --- 1) all vertices must be distinct ---
    if len(set(cycle)) != n:
        return "not snake", False

    # --- 2) consecutive vertices must be adjacent ---
    for i in range(n - 1):
        if hamming_dist(cycle[i], cycle[i + 1]) != 1:
            return "not snake", False

    # Whether the endpoints (0, n-1) are adjacent in Q_d
    closing_adjacent = (hamming_dist(cycle[0], cycle[-1]) == 1)

    # If the user claims a cycle (is_closed), that closing edge must exist
    if is_closed and not closing_adjacent:
        return "not snake", False

    # --- 3) inducedness: no chords among internal pairs ---
    # We forbid adjacency for any non-consecutive pair (i,j),
    # BUT we always skip (0, n-1) because that edge is either:
    #    - the actual closing edge of a coil, or
    #    - the would-be closing edge of an "almost coil".
    for i in range(n):
        for j in range(i + 1, n):
            # Skip the path edges
            if j == i + 1:
                continue
            # Skip endpoints pair (0, n-1) in both open/closed cases
            if i == 0 and j == n - 1:
                continue
            if hamming_dist(cycle[i], cycle[j]) == 1:
                return "not snake", False

    # --- 4) classification based on closure + endpoint adjacency ---

    if is_closed:
        # distinct, consecutive adjacent, closed by an edge, no chords
        # If it is also a doubled coil, label it as symmetric coil
        if is_symmetric_coil(path, d, allow_reverse=True):
            return "symmetric coil", True
        return "coil", True

    # Open path, induced
    if closing_adjacent:
        # Endpoints adjacent → would be a coil if closed
        return "almost coil", True

    return "snake", True


def snake_violations(path: List[int], d: int):
    """
    Return a dict with violating pairs for the snake/coil inducedness + adjacency rules.

    We follow the same conventions as classify_path:
    - If path is closed (path[0]==path[-1]), work with cycle = path[:-1]
    - Consecutive edges must be adjacent
    - Inducedness forbids any chord between non-consecutive vertices,
      except we always allow the endpoints pair (0, n-1)
      (closing edge for coil, or would-be closing edge for almost coil)
    """
    if not path or len(path) <= 1:
        return {
            "dup_vertices": [],
            "non_adjacent_steps": [],
            "chords": [],
            "bad_closing_edge": [],
        }

    is_closed = (path[0] == path[-1])
    cycle = path[:-1] if is_closed else path[:]
    n = len(cycle)

    dup_vertices = []
    non_adjacent_steps = []
    chords = []
    bad_closing_edge = []

    # 1) duplicates (report as pairs of positions, but return as vertex pairs for display)
    # We'll report every duplicate occurrence pair (v, v).
    pos = {}
    for i, v in enumerate(cycle):
        if v in pos:
            dup_vertices.append((v, v))
        else:
            pos[v] = i

    # 2) consecutive non-adjacent steps (pairs of vertices)
    for i in range(n - 1):
        a, b = cycle[i], cycle[i + 1]
        if hamming_dist(a, b) != 1:
            non_adjacent_steps.append((a, b))

    # closing edge required only if explicitly closed
    if n >= 2:
        closing_adjacent = (hamming_dist(cycle[0], cycle[-1]) == 1)
        if is_closed and not closing_adjacent:
            bad_closing_edge.append((cycle[-1], cycle[0]))

    # 3) inducedness chords: any non-consecutive adjacent pair, skipping (0,n-1)
    # To avoid O(n^2) scans on long paths, we use bit-neighbor checks.
    # For each vertex v, check all its d neighbors u; if u appears in the path,
    # and the indices are not consecutive (modulo nothing; this is snake logic),
    # then it's a chord (unless it's endpoints pair).
    idx_of = {v: i for i, v in enumerate(cycle)}
    for v, i in idx_of.items():
        for bit in range(d):
            u = v ^ (1 << bit)
            j = idx_of.get(u)
            if j is None:
                continue

            # skip actual path edges
            if abs(i - j) == 1:
                continue

            # skip endpoints pair (0, n-1) always
            if (i == 0 and j == n - 1) or (i == n - 1 and j == 0):
                continue

            # record chord once (as an unordered pair)
            a, b = (v, u) if v < u else (u, v)
            chords.append((a, b))

    # de-duplicate chords list
    chords = sorted(set(chords))

    return {
        "dup_vertices": dup_vertices,
        "non_adjacent_steps": non_adjacent_steps,
        "chords": chords,
        "bad_closing_edge": bad_closing_edge,
    }



def edge_dimension(a: int, b: int) -> int | None:
    """
    Return the dimension index of the edge (a,b) if they are adjacent,
    otherwise return None.
    """
    x = a ^ b
    if x == 0 or (x & (x - 1)) != 0:
        # either same vertex or differ in more than one bit
        return None
    dim = 0
    while x > 1:
        x >>= 1
        dim += 1
    return dim


def hamming_dist(a: int, b: int) -> int:
    x, c = a ^ b, 0
    while x:
        c += x & 1
        x >>= 1
    return c


def build_hypercube(d: int):
    n = 1 << d
    nodes = list(range(n))
    edges = []
    for u in range(n):
        for bit in range(d):
            v = u ^ (1 << bit)
            if u < v:
                edges.append((u, v, bit))
    return nodes, edges


def dim_color(k: int) -> str:
    hues = [210, 20, 140, 80, 0, 260, 40, 180, 320, 120]
    h = hues[k % len(hues)]
    return f"hsl({h},65%,45%)"


def int_to_bin(n: int, d: int) -> str:
    return format(n, f"0{d}b")

# ---------- Deterministic 2D layout (no rotation) ----------
# Even bits → X offsets, odd bits → Y offsets, decreasing magnitudes.
def layout_positions(d: int, base: float = 900.0, mode: str = "default"):
    n = 1 << d # number of nodes = 2^d

    if mode == "bipartite":
        # Left: odd parity, Right: even parity
        odds  = [v for v in range(n) if (bin(v).count("1") % 2) == 1]
        evens = [v for v in range(n) if (bin(v).count("1") % 2) == 0]

        # Deterministic order (by integer id)
        odds.sort()
        evens.sort()

        col_gap = max(400.0, base * 0.9)   # horizontal distance between columns
        y_gap = max(12.0, base / max(1, (n // 2)))  # vertical spacing

        pts = []

        # Put odds on the left (x=0)
        for idx, v in enumerate(odds):
            x = 0.0
            y = idx * y_gap
            pts.append((v, x, y))

        # Put evens on the right (x=col_gap)
        for idx, v in enumerate(evens):
            x = col_gap
            y = idx * y_gap
            pts.append((v, x, y))

        # normalize to start at (0,0) like your current function
        minx = min(x for _, x, _ in pts)
        miny = min(y for _, _, y in pts)
        pts2 = [(vid, x - minx, y - miny) for vid, x, y in pts]

        width = col_gap
        height = (len(odds) - 1) * y_gap if odds else 0.0
        return pts2, width, height

    
    dx, dy = [0.0] * d, [0.0] * d # per-dimension offsets
    for k in range(d): # dimension k
        tier = k // 2 # tier 0,1,2,...
        mag = (2 ** max(0, (d - 1) - tier)) * (base / (2 ** d)) # magnitude
        if k % 2 == 0:
            dx[k] = mag
        else:
            dy[k] = mag

    pts = []
    minx = miny = float("inf")
    maxx = maxy = float("-inf")
    for vid in range(n):
        x = sum(dx[k] for k in range(d) if (vid >> k) & 1)
        y = sum(dy[k] for k in range(d) if (vid >> k) & 1)
        if (vid >> 2) & 1:
            x += 100
            y += 250
        if (vid >> 3) & 1:
            x += 1800
            y -= 200
        if (vid >> 4) & 1:
            x += 200
            y += 1800
        if (vid >> 5) & 1:
            x += 3800
            y += 3200
        if (vid >> 6) & 1:
            x += 3400
            y -= 200
        if (vid >> 7) & 1:
            x += 8000
            y += 150
        if (vid >> 8) & 1:
            x += 15000
            y -= 9000


        pts.append((vid, x, y))
        minx, maxx = min(minx, x), max(maxx, x)
        miny, maxy = min(miny, y), max(maxy, y)

    pts2 = [(vid, x - minx, y - miny) for vid, x, y in pts]
    width = maxx - minx
    height = maxy - miny
    return pts2, width, height


def longest_cib(d: int):
    """
    Return a predefined coil/snake for certain dimensions,
    otherwise fall back to a standard Gray-code path.
    """
    presets = {
        2: [0, 1, 3, 2, 0],
        3: [0, 1, 3, 7, 6, 4, 0],
        4: [0, 1, 3, 7, 15, 13, 12, 4, 0],
        5: [0, 1, 3, 7, 6, 14, 12, 13, 29, 31, 27, 26, 18, 16, 0],
        6: [0, 1, 3, 7, 15, 31, 29, 25, 24, 26, 10, 42, 43, 59, 51, 49, 53, 37, 45, 44, 60, 62, 54, 22, 20, 4, 0],
        7: [0, 1, 3, 7, 15, 13, 12, 28, 30, 26, 27, 25, 57, 56, 40, 104, 72, 73, 75, 107, 111, 110, 46, 38, 36, 52,116, 124, 125, 93, 95, 87, 119, 55, 51, 50, 114, 98, 66, 70, 68, 69, 101, 97, 113, 81, 80, 16, 0],
        8: [0, 1, 3, 7, 6, 14, 12, 13, 29, 31, 27, 26, 18, 50, 54, 62, 60, 56, 57, 49, 53, 37, 101, 69, 68, 196, 132, 133, 149, 151, 150, 158, 156, 220, 92, 94, 86, 87, 119, 115, 123, 122, 250, 254, 255, 191, 187, 179, 163, 167, 231, 230, 226, 98, 66, 74, 202, 200, 136, 137, 139, 143, 207, 205, 237, 173, 172, 174, 170, 42, 43, 47, 111, 110, 108, 104, 105, 73, 89, 217, 219, 211, 195, 193, 225, 241, 245, 244, 116, 112, 80, 208, 144, 176, 160, 32, 0],
        9: [0, 1, 3, 7, 15, 14, 30, 22, 18, 50, 34, 38, 36, 44, 60, 56, 24, 88, 80, 112, 116, 118, 126, 122, 106, 74, 66, 70, 68, 69, 101, 103, 99, 115, 83, 87, 95, 93, 125, 121, 105, 41, 43, 59, 63, 55, 53, 21, 149, 151, 147, 155, 153, 185, 189, 173, 175, 167, 163, 161, 160, 176, 180, 182, 190, 186, 170, 138, 130, 134, 132, 140, 156, 220, 222, 218, 210, 242, 226, 230, 228, 236, 232, 200, 192, 193, 209, 241, 245, 247, 255, 251, 235, 203, 459, 458, 450, 454, 452, 453, 485, 487, 483, 499, 467, 471, 479, 477, 509, 505, 489, 425, 427, 443, 447, 439, 437, 433, 401, 385, 387, 391, 399, 398, 414, 406, 402, 434, 418, 422, 420, 428, 444, 440, 408, 472, 464, 496, 500, 502, 510, 494, 366, 358, 354, 352, 360, 376, 380, 348, 340, 342, 338, 346, 347, 379, 383, 375, 373, 369, 337, 321, 323, 327, 335, 333, 365, 301, 293, 289, 291, 307, 275, 279, 287, 285, 281, 265, 267, 266, 298, 314, 318, 310, 308, 304, 272, 256, 0],
        10: [0, 1, 3, 7, 15, 14, 30, 62, 63, 55, 51, 50, 34, 42, 43, 41, 45, 37, 36, 52, 116, 117, 125, 121, 123, 122, 90, 74, 75, 73, 77, 76, 108, 104, 96, 97, 99, 103, 102, 70, 86, 87, 83, 81, 80, 208, 240, 241, 243, 247, 255, 254, 222, 206, 207, 199, 195, 194, 226, 234, 235, 233, 237, 229, 228, 196, 132, 133, 141, 137, 139, 138, 154, 186, 187, 185, 189, 188, 172, 168, 160, 161, 163, 167, 166, 182, 150, 151, 147, 403, 275, 279, 278, 310, 294, 295, 291, 289, 288, 296, 300, 316, 317, 313, 315, 314, 282, 266, 267, 265, 269, 261, 260, 324, 356, 357, 365, 361, 363, 362, 354, 322, 323, 327, 335, 334, 350, 382, 383, 375, 371, 369, 368, 376, 344, 345, 349, 341, 469, 471, 470, 502, 500, 508, 509, 505, 507, 506, 474, 458, 459, 457, 461, 460, 396, 412, 408, 440, 432, 433, 437, 421, 429, 425, 427, 426, 430, 494, 495, 487, 483, 481, 480, 448, 384, 386, 390, 391, 399, 415, 927, 919, 918, 950, 934, 935, 931, 929, 928, 936, 940, 956, 957, 953, 955, 954, 922, 906, 907, 905, 909, 901, 900, 964, 996, 997, 1005, 1001, 1003, 1002, 994, 962, 963, 967, 975, 974, 990, 1022, 1023, 1015, 1011, 1009, 1008, 976, 848, 849, 851, 855, 854, 838, 870, 871, 867, 865, 864, 872, 876, 844, 845, 841, 843, 842, 858, 890, 891, 889, 893, 885, 884, 820, 804, 805, 813, 809, 811, 810, 802, 818, 819, 823, 831, 830, 798, 782, 783, 775, 771, 769, 768, 776, 792, 793, 797, 789, 533, 661, 669, 665, 664, 656, 640, 641, 643, 647, 655, 654, 670, 702, 703, 695, 691, 690, 674, 682, 683, 681, 685, 677, 676, 692, 756, 757, 765, 761, 763, 762, 730, 714, 715, 713, 717, 716, 748, 744, 736, 737, 739, 743, 742, 710, 726, 727, 735, 607, 591, 583, 579, 578, 594, 530, 534, 518, 550, 551, 547, 545, 544, 552, 568, 632, 624, 625, 627, 631, 630, 638, 622, 618, 619, 617, 621, 613, 612, 580, 596, 604, 540, 524, 525, 521, 523, 539, 27, 25, 24, 8, 0],
    }

    if d in presets:
        return presets[d][:]  # copy, so we don't mutate the original
        
    return [0]
    # Fallback: Gray-code Hamiltonian path for other dimensions
    n = 1 << d
    seq = []
    for i in range(n):
        g = i ^ (i >> 1)
        seq.append(g)
    return seq

def longest_sym_cib(d: int):
    """
    Return a predefined longest symmetric coil-in-the-box
    for certain dimensions, otherwise fall back to a trivial path.
    """
    presets = {
        4: [0, 1, 3, 7, 15, 14, 12, 8, 0],
        5: [0, 1, 3, 7, 15, 31, 29, 21, 20, 22, 18, 26, 10, 8, 0],
        6: [0, 1, 3, 7, 15, 13, 29, 28, 20, 22, 18, 50, 48, 56, 57, 59, 63, 55, 53, 37, 36, 44, 46, 42, 10, 8, 0],
        7: [0, 1, 3, 7, 15, 31, 63, 127, 119, 103, 99, 107, 75, 73, 77, 69, 68, 100, 116, 124, 120, 121, 113, 81, 80, 82, 86, 94, 78, 110, 46, 38, 54, 50, 58, 26, 24, 28, 20, 21, 53, 37, 45, 41, 40, 32, 0],
    }

    if d in presets:
        return presets[d][:]  # return a copy

    return [0]


def shorter_cib(d: int):
    """
    Return a predefined coil/snake for certain dimensions,
    otherwise fall back to a standard Gray-code path.
    """
    presets = {
        2: [0, 1, 3, 2, 0],
        3: [0, 1, 3, 2, 0],
        4: [0, 1, 3, 7, 6, 4, 0],
        5: [0, 1, 3, 7, 6, 14, 12, 13, 29, 21, 20, 16, 0],
        6: [0, 1, 3, 35, 39, 38, 6, 14, 12, 44, 45, 61, 29, 31, 27, 59, 58, 50, 18, 16, 0],
        #
        # [0, 1, 3, 7, 6, 14, 10, 26, 18, 50, 54, 52, 20, 28, 29, 13, 45, 47, 43, 59, 57, 56, 40, 32, 0],
        7: [0],
        8: [0],
    }

    if d in presets:
        return presets[d][:]  # copy, so we don't mutate the original
        
    return [0]
    # Fallback: Gray-code Hamiltonian path for other dimensions
    n = 1 << d
    seq = []
    for i in range(n):
        g = i ^ (i >> 1)
        seq.append(g)
    return seq



def parse_path(text: str, d: int) -> List[int]:
    if not text:
        return []
    out = []
    for tok in [t for t in text.replace(",", " ").split() if t]:
        if False and all(c in "01" for c in tok): # Disabled bit representation
            val = int(tok, 2)
        elif tok.isdigit():
            val = int(tok)
        else:
            continue
        if 0 <= val < (1 << d):
            out.append(val)
    return out

# ---------- Figure builder (fixed UnboundLocalError) ----------

def make_figure(d: int,
                show_bits: bool,
                show_ints: bool,
                mark_negations: bool,
                mark_distances: bool,
                node_r: int,
                edge_w: int,
                path: List[int],
                scale_base: float,
                subsel: dict | None = None,
                switchsel: dict | None = None,
                layout_mode: str = "default"):
    nodes, edges = build_hypercube(d)
    pts, width, height = layout_positions(d, base=scale_base, mode=layout_mode)
    pos = {vid: (x, y) for vid, x, y in pts}

    path = path or []
    in_path = set(path)

    # ---------- selected vertices for a dimension patch ----------
    subsel = subsel or {}
    sel_active = bool(subsel.get("active"))
    sel_s = subsel.get("start_idx")
    sel_e = subsel.get("end_idx")

    selected_vertices = set()
    if sel_active and sel_s is not None and sel_e is not None and path:
        selected_vertices = set(path[sel_s:sel_e + 1])

    # ---------- selected vertices for switch-dims (3 consecutive vertices) ----------
    switchsel = switchsel or {}
    switch_active = bool(switchsel.get("active"))
    picked = switchsel.get("picked") or []
    
    switch_vertices = set()
    switch_segment_edges = []  # list of (a,b) edges to highlight if we can infer the triple segment
    
    if switch_active and path:
        is_closed = (len(path) >= 2 and path[0] == path[-1])
        cycle = path[:-1] if is_closed else path[:]
        n = len(cycle)
    
        # picked are indices into cycle/path
        if n > 0:
            for idx in picked:
                if isinstance(idx, int):
                    switch_vertices.add(cycle[idx % n] if is_closed else cycle[idx])
    
            # If exactly 3 picked and they form a consecutive triple, highlight the 2 edges of that triple
            if len(picked) == 3:
                s0 = consecutive_triple_start([int(i) for i in picked], n, is_closed)
                if s0 is not None:
                    a = cycle[s0 % n] if is_closed else cycle[s0]
                    b = cycle[(s0 + 1) % n] if is_closed else cycle[s0 + 1]
                    c = cycle[(s0 + 2) % n] if is_closed else cycle[s0 + 2]
                    switch_segment_edges = [(a, b), (b, c)]



    
    # ---------- neighbors of path vertices ----------
    #neighbor_set = set()
    #if mark_distances and path:
    #    for v in in_path:
    #        for bit in range(d):
    #            u = v ^ (1 << bit)
    #            if u not in in_path:
    #                neighbor_set.add(u)

    # ---------- neighbors of path vertices without the 2 ends ----------
    neighbor_set = set()
    if mark_distances and path and len(path)>2:
        for v in path[1:-1]:
            for bit in range(d):
                u = v ^ (1 << bit)
                if u not in in_path:
                    neighbor_set.add(u)
    
    # ---------- negations (vertices + edges) ----------
    neg_set = set()
    neg_edges = set()
    if mark_negations and path:
        mask = (1 << d) - 1

        # negated vertices of the path
        for v in path:
            neg_set.add(mask ^ v)

        # negated edges of the path
        for i in range(len(path) - 1):
            a = path[i]
            b = path[i + 1]
            na = mask ^ a
            nb = mask ^ b
            key = (min(na, nb), max(na, nb))
            neg_edges.add(key)

    # ---------- base edges (by dimension) ----------
    edge_traces = []

    for bit in range(d):
        xs, ys, cd = [], [], []
        for (u, v, b) in edges:
            if b != bit:
                continue
            x1, y1 = pos[u]
            x2, y2 = pos[v]
            xs += [x1, x2, None]
            ys += [y1, y2, None]
            cd += [[u, v], [u, v], None]
        edge_traces.append(
            go.Scatter(
                x=xs,
                y=ys,
                mode="lines",
                line=dict(width=edge_w, color=dim_color(bit)),
                opacity=0.35,
                hoverinfo="skip",
                name=f"bit {bit}",
                customdata=cd,   # lets us detect edge clicks
            )
        )

    # ---------- emphasize path edges ----------
    path_edges = set()
    for i in range(len(path) - 1):
        a, b = path[i], path[i + 1]
        key = (min(a, b), max(a, b))
        path_edges.add(key)

    if path_edges:
        for (u, v, b) in edges:
            key = (min(u, v), max(u, v))
            if key in path_edges:
                x1, y1 = pos[u]
                x2, y2 = pos[v]
                edge_traces.append(
                    go.Scatter(
                        x=[x1, x2],
                        y=[y1, y2],
                        mode="lines",
                        line=dict(width=max(1, edge_w * 1.6), color=dim_color(b)),
                        opacity=1.0,
                        hoverinfo="skip",
                        name=f"path bit {b}",
                    )
                )

    # ---------- draw negated path edges in red ----------
    if mark_negations and neg_edges:
        for (u, v) in neg_edges:
            x1, y1 = pos[u]
            x2, y2 = pos[v]
            edge_traces.append(
                go.Scatter(
                    x=[x1, x2],
                    y=[y1, y2],
                    mode="lines",
                    line=dict(width=max(1, edge_w * 1.6), color="red"),
                    opacity=1.0,
                    hoverinfo="skip",
                    name="negated path",
                )
            )

    # ---------- highlight selected subpath edges ----------
    if sel_active and sel_s is not None and sel_e is not None and sel_e > sel_s:
        for i in range(sel_s, sel_e):
            a, b = path[i], path[i + 1]
            x1, y1 = pos[a]
            x2, y2 = pos[b]
            edge_traces.append(
                go.Scatter(
                    x=[x1, x2],
                    y=[y1, y2],
                    mode="lines",
                    line=dict(width=max(2, edge_w * 2), color="#2563EB"),
                    opacity=1.0,
                    hoverinfo="skip",
                    name="selected subpath",
                )
            )

    # ---------- highlight switch-dims selection edges (only when triple is valid) ----------
    if switch_active and switch_segment_edges:
        for (a, b) in switch_segment_edges:
            x1, y1 = pos[a]
            x2, y2 = pos[b]
            edge_traces.append(
                go.Scatter(
                    x=[x1, x2],
                    y=[y1, y2],
                    mode="lines",
                    line=dict(width=max(2, edge_w * 2), color="#DC2626"),
                    opacity=1.0,
                    hoverinfo="skip",
                    name="switch dims selection",
                )
            )


    
    # ---------- nodes ----------
    xs = [pos[v][0] for v in nodes]
    ys = [pos[v][1] for v in nodes]

    bit_labels = [int_to_bin(v, d) for v in nodes]
    int_labels = [str(v) for v in nodes]

    show_any_label = show_bits or show_ints
    if show_bits and show_ints:
        texts = [f"{iv}\n{bv}" for iv, bv in zip(int_labels, bit_labels)]
    elif show_bits:
        texts = bit_labels
    elif show_ints:
        texts = int_labels
    else:
        texts = None

    sizes = []
    colors = []
    for v in nodes:
        base_size = node_r * 2

        # --- size ---
        if sel_active and v in selected_vertices:
            sizes.append(base_size * 2.2)
        elif switch_active and v in switch_vertices:
            sizes.append(base_size * 2.2)
        elif mark_distances and v in neighbor_set:
            sizes.append(base_size * 1.2)
        else:
            sizes.append(base_size * (1.6 if v in in_path else 1))

        # --- color ---
        if sel_active and v in selected_vertices:
            colors.append("#2563EB")           # strong blue for selection
        elif switch_active and v in switch_vertices:
            colors.append("#DC2626")           # red for switch selection
        elif path and (v == path[0] or v == path[-1]):
            colors.append("#111")
        elif mark_negations and v in neg_set:
            if mark_distances and v in neighbor_set:
                colors.append("#F8650C")
            else:
                colors.append("red")
        elif mark_distances and v in neighbor_set:
            colors.append("yellow")
        else:
            colors.append("#222")



    node_trace = go.Scatter(
        x=xs,
        y=ys,
        mode="markers+text" if show_any_label else "markers",
        marker=dict(size=sizes, color=colors, line=dict(width=1, color="#333")),
        text=texts,
        textposition="middle right",
        textfont=dict(size=12, color="#333"),
        hovertemplate=(
            "id=%{customdata}<br>label=%{text}<extra></extra>" if show_any_label
            else "id=%{customdata}<extra></extra>"
        ),
        customdata=nodes,
        name="vertices",
    )

    fig = go.Figure(edge_traces + [node_trace])
    pad = max(40, 0.08 * max(width, height))
    fig.update_layout(
        showlegend=False,
        margin=dict(l=20, r=20, t=40, b=20),
        xaxis=dict(visible=False, range=[-pad, width + pad]),
        yaxis=dict(
            visible=False,
            scaleanchor="x",
            scaleratio=1,
            range=[-pad, height + pad],
        ),
        dragmode=False,
        template="plotly_white",
    )
    return fig


# ---------- Dash App ----------

app = Dash(__name__)
app.title = "Hypercube Visualization and Path Exploration Tool"

app.layout = html.Div(
    style={"maxWidth": "1200px", "margin": "0 auto", "padding": "0px"},
    children=[
        html.H2("Hypercube Visualization and Path Exploration Tool"),
        html.Div(id="stats", style={"opacity": 0.7, "marginBottom": "0px"}),

        html.Div(
            style={"display": "grid", "gridTemplateColumns": "1fr 1fr 1fr 1fr", "gap": "8px", "marginTop": "20px"},
            children=[
                html.Div([
                    html.Label("Dimension d"),
                    dcc.Slider(
                        id="dim",
                        min=1,
                        max=12,
                        step=1,
                        value=DEFAULTS["dimension"],
                        marks=None,
                        tooltip={"always_visible": True},
                    ),
                ]),
                #html.Div([
                #    html.Label("Layout scale"),
                #    dcc.Slider(
                #        id="scale",
                #        min=800,          # larger range
                #        max=2600,
                #        step=50,
                #        value=int(DEFAULTS["scale"]),   # 1600 by default
                #        marks=None,
                #        tooltip={"always_visible": True},
                #    ),
                #]),
                html.Div([
                    dcc.Checklist(
                        id="show_labels",
                        options=[
                            {"label": " Show bit labels", "value": "bits"},
                            {"label": " Show int labels", "value": "ints"},
                        ],
                        value=[],  # or ["bits"] if you want bits shown by default
                        style={"marginTop": "0px"},
                    )
                ]),
                html.Div([
                    dcc.Checklist(
                        id="mark_negations",
                        options=[{"label": " Mark negations", "value": "neg"}],
                        value=[],  # unchecked by default
                        style={"marginTop": "0px", "color": "red"},
                    ),
                    html.Div(style={"height": "2px"}),  # small gap
                    html.Div(
                        id="mark_neighbors_wrap",
                        children=[
                            dcc.Checklist(
                                id="mark_distances",
                                options=[{"label": " Mark neighbors", "value": "dist"}],
                                value=[],
                                style={"marginTop": "0px"},
                                labelStyle={"display": "inline-block", "background-color": "yellow"},
                            )
                        ],
                    ),
                ]),
                
                # --- Subpath flip controls + Switch dimensions ---
                html.Div(
                    style={"display": "flex", "gap": "8px", "alignItems": "center", "marginBottom": "8px"},
                    children=[
                        html.Button("Flip subpath", id="btn_flip_subpath", n_clicks=0,
                                    style={"background": "#2563EB", "color": "white"}),
                
                        html.Button("Switch dimensions", id="btn_switch_dims", n_clicks=0,
                                    style={"background": "#6B7280", "color": "white"}),
                
                        dcc.Input(
                            id="subpath_dim",
                            type="number",
                            min=0,
                            step=1,
                            value=0,
                            placeholder="dimension i",
                            style={"width": "130px"},
                        ),
                    ],
                ),
                
                dcc.Store(
                    id="subpath_select_store",
                    data={"active": False, "start_idx": None, "end_idx": None}
                ),
                
                dcc.Store(
                    id="switch_dims_store",
                    data={"active": False, "picked": []}   # picked holds indices into cycle/path
                ),

                html.Div(),  # empty cell just to keep the grid tidy
            ],
        ),


        html.Div(
            style={"display": "flex", "gap": "8px", "alignItems": "center", "marginBottom": "8px"},
            children=[
                dcc.Input(id="manual_path",
                          placeholder="Enter path (e.g. 0,1,3)",
                          style={"flex": 1}, debounce=True),
                html.Button("Set path", id="btn_set", n_clicks=0),
                html.Button("Longest CIB", id="btn_longest_cib", n_clicks=0,
                            style={"background": "#059669", "color": "white"}),
                html.Button("Longest Symmetric CIB", id="btn_longest_sym_cib", n_clicks=0,
                            style={"background": "#7DD3FC", "color": "#0B1220"}),
                html.Button("Shorter CIB", id="btn_shorter_cib", n_clicks=0,
                            style={"background": "#00C04B", "color": "white"}),
                html.Button("Clear", id="btn_clear", n_clicks=0),
            ]
        ),

        # Automorphism controls (swap / flip dimensions)
        html.Div(
            style={"display": "flex", "gap": "8px", "alignItems": "center", "marginBottom": "8px"},
            children=[
                html.Span("Swap dimensions:", style={"fontSize": "0.9rem"}),
                dcc.Input(
                    id="swap_i",
                    type="number",
                    min=0,
                    step=1,
                    value=0,
                    placeholder="i",
                    style={"width": "60px"},
                ),
                dcc.Input(
                    id="swap_j",
                    type="number",
                    min=0,
                    step=1,
                    value=0,
                    placeholder="j",
                    style={"width": "60px"},
                ),
                html.Button("Swap", id="btn_swap", n_clicks=0),

                html.Span("Flip dimension:", style={"fontSize": "0.9rem", "marginLeft": "16px"}),
                dcc.Input(
                    id="flip_k",
                    type="number",
                    min=0,
                    step=1,
                    value=0,
                    placeholder="k",
                    style={"width": "60px"},
                ),
                html.Button("Flip", id="btn_flip", n_clicks=0),

                # Bipartite Layout Button
                html.Span("   ", style={"fontSize": "0.9rem", "marginLeft": "16px"}),
                html.Button(
                    "Bipartite layout",
                    id="btn_bipartite_layout",
                    n_clicks=0,
                    style={"background": "#6B7280", "color": "white", "marginHorizontal": "48px"},
                ),
                dcc.Store(id="layout_mode_store", data="default"),

            ],
        ),


        html.Div(
            id="path_info",
            style={
                "marginBottom": "8px",
                "fontFamily": "monospace",
                "whiteSpace": "normal",   # allow wrapping
                "overflow": "visible",    # no clipping
                "textOverflow": "clip",   # no ellipsis
                "lineHeight": "1.3",      # optional: nicer spacing
            },
        ),


        dcc.Graph(id="fig", style={"height": "800px"}, config={"displayModeBar": True}),
        dcc.Store(id="path_store", data=[]),

        html.Div(
            id="path_bits",
            style={
                "marginTop": "12px",
                "fontFamily": "monospace",
                "whiteSpace": "pre-wrap",  # keep line breaks, allow wrapping
                "fontSize": "12px",
            },
        ),
    ]
)

@app.callback(
    Output("stats", "children"),
    Input("dim", "value"),
    Input("path_store", "data"),
)
def stats(d, path):
    n = 1 << d
    m = d * (1 << (d - 1))
    plen = len(path) if path else 0
    return f"Q_{d} · vertices: {n} · edges: {m} · path length: {max(0, plen - 1)}"

@app.callback(
    Output("path_store", "data"),
    Output("subpath_select_store", "data"),
    Output("switch_dims_store", "data"),
    Input("fig", "clickData"),
    Input("btn_clear", "n_clicks"),
    Input("btn_longest_cib", "n_clicks"),
    Input("btn_longest_sym_cib", "n_clicks"),
    Input("btn_shorter_cib", "n_clicks"),
    Input("btn_set", "n_clicks"),
    Input("btn_swap", "n_clicks"),
    Input("btn_flip", "n_clicks"),
    Input("btn_flip_subpath", "n_clicks"),
    Input("btn_switch_dims", "n_clicks"),
    State("path_store", "data"),
    State("manual_path", "value"),
    State("dim", "value"),
    State("swap_i", "value"),
    State("swap_j", "value"),
    State("flip_k", "value"),
    State("subpath_select_store", "data"),
    State("subpath_dim", "value"), 
    State("switch_dims_store", "data"),
    prevent_initial_call=True
)
def update_path(clickData,
                n_clear,
                n_longest,
                n_longest_sym,
                n_shorter,
                n_set,
                n_swap,
                n_flip,
                n_flip_subpath,
                n_switch_dims,
                path,
                manual_text,
                d,
                swap_i,
                swap_j,
                flip_k,
                subsel,
                subpath_dim,
                switchsel):

    trigger = ctx.triggered_id
    path = path or []
    d = int(d)

    # default selection store
    subsel = subsel or {"active": False, "start_idx": None, "end_idx": None}
    switchsel = switchsel or {"active": False, "start_idx": None, "end_idx": None}


    # 1) Clear
    if trigger == "btn_clear":
        return [], {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

    # 2a) Longest CIB
    if trigger == "btn_longest_cib":
        return longest_cib(d), {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

    # 2b) Longest Symmetric CIB
    if trigger == "btn_longest_sym_cib":
        return longest_sym_cib(d), {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

    
    # 2c) Shorter CIB
    if trigger == "btn_shorter_cib":
        return shorter_cib(d), {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

    # 3) Manual set path
    if trigger == "btn_set":
        newp = parse_path(manual_text or "", d)
        return (newp if newp else path), {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

    # 4) Swap two dimensions
    if trigger == "btn_swap":
        try:
            i = int(swap_i) if swap_i is not None else None
            j = int(swap_j) if swap_j is not None else None
        except (TypeError, ValueError):
            return path, subsel, switchsel
        if i is None or j is None:
            return path, subsel, switchsel
        if not (0 <= i < d and 0 <= j < d):
            return path, subsel, switchsel
        return swap_dims_path(path, d, i, j), subsel, switchsel

    # 5) Flip one dimension (whole path)
    if trigger == "btn_flip":
        try:
            k = int(flip_k) if flip_k is not None else None
        except (TypeError, ValueError):
            return path, subsel, switchsel
        if k is None or not (0 <= k < d):
            return path, subsel, switchsel
        return flip_dim_path(path, d, k), subsel, switchsel

    # 6) The new two-click button:
    #    First click: enter selection mode.
    #    Second click: apply flip on the selected subpath and exit mode.
    if trigger == "btn_flip_subpath":
        active = bool(subsel.get("active"))
        if not active:
            # enter selection mode
            return path, {"active": True, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

        # active == True, so this is the "second click": apply
        try:
            i = int(subpath_dim) if subpath_dim is not None else None
        except (TypeError, ValueError):
            i = None
        if i is None or not (0 <= i < d):
            # invalid dimension, just exit selection mode
            return path, {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

        s = subsel.get("start_idx")
        e = subsel.get("end_idx")
        if s is None or e is None or e <= s:
            # nothing meaningful selected, exit
            return path, {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

        # subpath is path[s:e+1] = (v1,...,vk)
        # desired: keep prefix (..., v1), keep suffix (vk, ...),
        # and insert flipped(v1..vk) between them.
        head = path[:s + 1]                 # includes v1
        flipped_subpath = [flip_dim_vertex(v, i) for v in path[s:e + 1]]
        rest = path[e:]                     # starts at vk
        new_path = head + flipped_subpath + rest

        return new_path, {"active": False, "start_idx": None, "end_idx": None}, {"active": False, "start_idx": None, "end_idx": None}

    # 7) Switch dimensions mode toggle
    if trigger == "btn_switch_dims":
        active = bool(switchsel.get("active"))
        if not active:
            return path, subsel, {"active": True, "picked": []}
        else:
            return path, subsel, {"active": False, "picked": []}

    
    # 8) Figure clicks
    if trigger == "fig" and clickData and clickData.get("points"):
        p = clickData["points"][0]
        cd = p.get("customdata")

        # If we're in switch-dims mode, vertex clicks define exactly 3 consecutive vertices
        # If we're in switch-dims mode, user can pick 3 consecutive vertices in ANY order
        if switchsel.get("active") and isinstance(cd, (int, float)):
            vid = int(cd)
        
            is_closed = (len(path) >= 2 and path[0] == path[-1])
            cycle = path[:-1] if is_closed else path[:]
            n = len(cycle)
        
            if n < 3:
                return path, subsel, {"active": False, "picked": []}
        
            # find index of clicked vertex inside cycle/path
            try:
                idx = cycle.index(vid)  # vertices assumed unique in a valid snake/coil
            except ValueError:
                return path, subsel, switchsel
        
            picked = list(switchsel.get("picked") or [])
        
            # toggle behavior: click again removes it
            if idx in picked:
                picked = [i for i in picked if i != idx]
                return path, subsel, {"active": True, "picked": picked}
        
            # add it (up to 3)
            if len(picked) >= 3:
                # start over from this click
                picked = [idx]
                return path, subsel, {"active": True, "picked": picked}
        
            picked.append(idx)
        
            # if not yet 3, just store
            if len(picked) < 3:
                return path, subsel, {"active": True, "picked": picked}
        
            # now we have 3: check if they form a consecutive triple
            s0 = consecutive_triple_start([int(i) for i in picked], n, is_closed)
            if s0 is None:
                # not a valid triple, keep them so user can adjust (toggle)
                return path, subsel, {"active": True, "picked": picked}
        
            # canonical triple order along the cycle/path
            x = cycle[s0 % n] if is_closed else cycle[s0]
            y = cycle[(s0 + 1) % n] if is_closed else cycle[s0 + 1]
            z = cycle[(s0 + 2) % n] if is_closed else cycle[s0 + 2]
        
            a = edge_dimension(x, y)
            b = edge_dimension(y, z)
            if a is None or b is None:
                return path, subsel, {"active": False, "picked": []}
        
            # new middle vertex to traverse b then a
            y2 = x ^ (1 << b)
        
            # verify the new 2-edge path really reaches z via dimensions b then a
            if edge_dimension(y2, z) != a:
                return path, subsel, {"active": False, "picked": []}
        
            # avoid duplicates in the cycle/path (allow x and z)
            if y2 in set(cycle) and y2 not in {x, z}:
                return path, subsel, {"active": False, "picked": []}
        
            cycle2 = cycle[:]
            cycle2[(s0 + 1) % n if is_closed else (s0 + 1)] = y2
        
            new_path = cycle2 + [cycle2[0]] if is_closed else cycle2
            return new_path, subsel, {"active": False, "picked": []}



        # If we're in subpath selection mode, vertex clicks define (start_idx, end_idx)
        if subsel.get("active") and isinstance(cd, (int, float)):
            vid = int(cd)
            idx = index_in_path(path, vid)
            if idx is None:
                return path, subsel, switchsel

            s = subsel.get("start_idx")
            e = subsel.get("end_idx")

            # first selected vertex
            if s is None:
                return path, {"active": True, "start_idx": idx, "end_idx": idx}, {"active": False, "start_idx": None, "end_idx": None}

            # enforce consecutive forward selection along the path
            # user must click idx == e+1 to extend
            if e is None:
                e = s
            if idx == e + 1:
                return path, {"active": True, "start_idx": s, "end_idx": idx}, {"active": False, "start_idx": None, "end_idx": None}

            # allow shrinking by clicking the current end again
            if idx == e:
                # pop last selected (shrink by 1) if possible
                new_e = e - 1 if e > s else s
                return path, {"active": True, "start_idx": s, "end_idx": new_e}, {"active": False, "start_idx": None, "end_idx": None}

            # otherwise ignore
            return path, subsel, switchsel

        # Normal mode: your existing click-to-build-path behavior
        if isinstance(cd, (int, float)):
            vid = int(cd)

            if not path:
                return [vid], subsel, switchsel

            if vid == path[-1]:
                return path[:-1], subsel, switchsel

            if len(path) >= 2 and vid == path[-2]:
                return path[:-1], subsel, switchsel

            if hamming_dist(vid, path[-1]) == 1:
                return path + [vid], subsel, switchsel

            return [vid], subsel, switchsel

        if isinstance(cd, (list, tuple)) and len(cd) == 2:
            u, v = int(cd[0]), int(cd[1])
            if not path:
                return [u, v], subsel, switchsel
            last = path[-1]
            if last == u:
                return path + [v], subsel, switchsel
            if last == v:
                return path + [u], subsel, switchsel
            return [u, v], subsel, switchsel

    return path, subsel, switchsel


@app.callback(
    Output("fig", "figure"),
    Input("dim", "value"),
    Input("show_labels", "value"),
    Input("path_store", "data"),
    Input("mark_negations", "value"),
    Input("mark_distances", "value"),
    Input("subpath_select_store", "data"),
    Input("switch_dims_store", "data"),
    Input("layout_mode_store", "data"),
)
def render(d, show_labels_vals, path, mark_vals, mark_dist_vals, subsel, switchsel, layout_mode):
    labels_vals = show_labels_vals or []
    show_bits = "bits" in labels_vals
    show_ints = "ints" in labels_vals

    mark_vals = mark_vals or []
    mark_negations = "neg" in mark_vals

    mark_dist_vals = mark_dist_vals or []
    mark_distances = "dist" in mark_dist_vals

    fig = make_figure(
        d=int(d),
        show_bits=show_bits,
        show_ints=show_ints,
        mark_negations=mark_negations,
        mark_distances=mark_distances,
        node_r=DEFAULTS["node_radius"],
        edge_w=DEFAULTS["edge_width"],
        path=path or [],
        scale_base=float(DEFAULTS["scale"]),
        subsel=subsel or {},
        switchsel=switchsel or {},
        layout_mode=layout_mode or "default",
    )
    return fig


@app.callback(
    Output("path_info", "children"),
    Input("dim", "value"),
    Input("path_store", "data"),
)
def path_info(d, path):
    path = path or []
    d = int(d)

    if not path:
        return html.Span("Path: (empty)")

    # Vertex list
    path_str = ", ".join(str(v) for v in path)

    # Classification
    label, valid = classify_path(path, d)
    color = {
        "snake": "green",
        "coil": "green",
        "symmetric coil": "green",
        "almost coil": "green",
        "not snake": "red",
    }[label]

    # Dimensions of consecutive edges
    dims = []
    for i in range(len(path) - 1):
        ed = edge_dimension(path[i], path[i + 1])
        dims.append(ed if ed is not None else "?")
    dims_str = ", ".join(str(x) for x in dims) if dims else "(none)"

    # If not snake, append violations inside the same bracket label
    label_text = label
    if label == "not snake":
        viol = snake_violations(path, d)

        pairs = []
        pairs.extend(viol.get("dup_vertices", []))
        pairs.extend(viol.get("non_adjacent_steps", []))
        pairs.extend(viol.get("bad_closing_edge", []))
        pairs.extend(viol.get("chords", []))

        # De-duplicate exact pairs (keep order)
        seen = set()
        uniq = []
        for a, b in pairs:
            key = (a, b)
            if key not in seen:
                seen.add(key)
                uniq.append((a, b))

        MAX_SHOW = 30
        shown = uniq[:MAX_SHOW]
        pairs_str = ", ".join(f"({a},{b})" for a, b in shown)
        if len(uniq) > MAX_SHOW:
            pairs_str += f", ... (+{len(uniq) - MAX_SHOW} more)"

        label_text = f"not snake. violations: {pairs_str if pairs_str else '(none)'}"

    return html.Div(
        [
            html.Div(
                [
                    html.Span(f"Path: {path_str} "),
                    html.Span(f"[{label_text}]", style={"color": color, "fontWeight": "bold"}),
                ]
            ),
            html.Div(
                [
                    html.Span("Dimensions: "),
                    html.Span(dims_str, style={"fontFamily": "monospace"}),
                ]
            ),
        ]
    )


@app.callback(
    Output("path_bits", "children"),
    Input("dim", "value"),
    Input("path_store", "data"),
    Input("show_labels", "value"),
)
def path_bits_view(d, path, show_labels_vals):
    path = path or []
    labels_vals = show_labels_vals or []

    # Only show when "Show bit labels" is checked and path is non-empty
    if not path or "bits" not in labels_vals:
        return ""

    d = int(d)
    lines = []
    for v in path:
        b = int_to_bin(v, d)
        ones = b.count("1")
        lines.append(f"{b} ({ones})")

    # Single pre-formatted block
    return html.Pre(
        "\n".join(lines),
        style={"margin": 0},
    )


@app.callback(
    Output("btn_flip_subpath", "style"),
    Input("subpath_select_store", "data"),
)
def style_flip_subpath_button(subsel):
    subsel = subsel or {}
    active = bool(subsel.get("active"))

    # common style
    base = {
        "color": "white",
        "border": "none",
        "padding": "6px 12px",
        "borderRadius": "8px",
        "cursor": "pointer",
    }

    if active:
        # selection mode ON
        return {**base, "background": "#2563EB"}  # strong blue for selection
    else:
        # selection mode OFF
        return {**base, "background": "#6B7280"}  # gray


@app.callback(
    Output("layout_mode_store", "data"),
    Input("btn_bipartite_layout", "n_clicks"),
    State("layout_mode_store", "data"),
    prevent_initial_call=True
)
def toggle_layout(n, mode):
    mode = mode or "default"
    return "bipartite" if mode == "default" else "default"


@app.callback(
    Output("btn_bipartite_layout", "style"),
    Input("layout_mode_store", "data"),
)
def style_layout_button(mode):
    base = {"color": "white", "border": "none", "padding": "6px 12px", "borderRadius": "8px", "cursor": "pointer"}
    if mode == "bipartite":
        return {**base, "background": "#059669"}  # green
    return {**base, "background": "#6B7280"}      # gray


@app.callback(
    Output("mark_neighbors_wrap", "children"),
    Input("dim", "value"),
    Input("path_store", "data"),
    Input("mark_distances", "value"),
)
def mark_neighbors_label(d, path, mark_dist_vals):
    d = int(d)
    path = path or []
    in_path = set(path)

    # same neighbor definition as in make_figure (excluding endpoints)
    neighbor_set = set()
    if path and len(path) > 2:
        for v in path[1:-1]:
            for bit in range(d):
                u = v ^ (1 << bit)
                if u not in in_path:
                    neighbor_set.add(u)

    cnt = len(neighbor_set)

    # preserve checked state
    mark_dist_vals = mark_dist_vals or []

    return dcc.Checklist(
        id="mark_distances",
        options=[{"label": f" Mark neighbors ({cnt})", "value": "dist"}],
        value=mark_dist_vals,
        style={"marginTop": "0px"},
        labelStyle={"display": "inline-block", "background-color": "yellow"},
    )

@app.callback(
    Output("btn_switch_dims", "style"),
    Input("switch_dims_store", "data"),
)
def style_switch_dims_button(switchsel):
    switchsel = switchsel or {}
    active = bool(switchsel.get("active"))

    base = {
        "color": "white",
        "border": "none",
        "padding": "6px 12px",
        "borderRadius": "8px",
        "cursor": "pointer",
    }

    return {**base, "background": "#DC2626"} if active else {**base, "background": "#6B7280"}
    
if __name__ == "__main__":
    import os
    port = int(os.environ.get("PORT", "7860"))  # HF uses 7860
    app.run(host="0.0.0.0", port=port, debug=False)