-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphPlanarity_and_Embedding.html
More file actions
3177 lines (2686 loc) · 160 KB
/
GraphPlanarity_and_Embedding.html
File metadata and controls
3177 lines (2686 loc) · 160 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
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Симулятор: Планарність, 3-зв'язність та Укладання Тутте</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
processEscapes: true
},
svg: {
fontCache: 'global'
}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<style>
:root {
--primary-color: #3f51b5; /* Indigo */
--primary-hover: #303f9f;
--secondary-color: #17a2b8; /* Tutte Outer */
--tertiary-color: #28a745; /* Tutte Inner */
--planar-color: #4CAF50; /* Green */
--non-planar-color: #F44336; /* Red */
--highlight-color: #ffc107; /* Amber */
--highlight-secondary-color: #03a9f4; /* Light Blue */
--flash-color: #e91e63; /* Pink */
--removed-color: #bdbdbd;
--light-bg: #f4f7f9;
--white-bg: #ffffff;
--border-color: #e0e0e0;
--text-color: #333;
--comment-color: #111;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
padding: 20px;
background-color: var(--light-bg);
color: var(--text-color);
margin: 0;
line-height: 1.6;
}
h1, h2 {
color: var(--primary-color);
text-align: center;
}
.main-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
width: 100%;
max-width: 1200px;
}
/* --- Стилі для вкладок --- */
.stage-tabs {
display: flex;
background: #e0e0e0;
border-radius: 8px;
padding: 5px;
width: 100%;
max-width: 800px;
box-sizing: border-box;
justify-content: space-around;
}
.stage-tab {
flex: 1;
padding: 12px 15px;
text-align: center;
font-weight: 600;
font-size: 1.1em;
color: #777;
background: #f0f0f0;
border-radius: 6px;
border: 2px solid transparent;
cursor: not-allowed;
transition: all 0.3s ease;
}
.stage-tab.active {
background: var(--white-bg);
color: var(--primary-color);
border-color: var(--primary-color);
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.stage-tab.enabled {
color: #333;
cursor: pointer;
}
.stage-tab.enabled:not(.active):hover {
background: #d5d5d5;
}
.stage-tab.completed {
color: var(--planar-color);
border-color: var(--planar-color);
}
.stage-tab.failed {
color: var(--non-planar-color);
border-color: var(--non-planar-color);
}
/* --- Контейнери етапів --- */
.stage-container {
width: 100%;
background-color: var(--white-bg);
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
overflow: hidden;
}
.controls-panel {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 10px;
padding: 15px;
border-bottom: 1px solid var(--border-color);
}
.control-group {
display: flex;
align-items: center;
gap: 8px;
}
.control-group label {
font-weight: 500;
}
.control-group input[type="number"],
.control-group input[type="range"] {
width: 70px;
padding: 5px 8px;
border: 1px solid var(--border-color);
border-radius: 6px;
}
.control-group input[type="range"] { width: 100px; padding: 0; }
button {
padding: 10px 15px;
font-size: 14px;
font-weight: 600;
border: none;
border-radius: 6px;
background-color: var(--primary-color);
color: white;
cursor: pointer;
transition: background-color 0.2s ease;
}
button:hover { background-color: var(--primary-hover); }
button:disabled { background-color: #adb5bd; cursor: not-allowed; }
button.success { background-color: var(--planar-color); }
button.success:hover { background-color: #388E3C; }
button.danger { background-color: var(--non-planar-color); }
button.danger:hover { background-color: #D32F2F; }
button.secondary { background-color: #6c757d; }
button.secondary:hover { background-color: #5a6268; }
#graph-svg-container {
width: 100%;
position: relative;
}
#graph-svg {
width: 100%;
min-height: 500px;
display: block;
background-color: #fdfdfd;
}
/* --- Стилі для графа (D3/SVG) --- */
.edge {
stroke: #999;
stroke-width: 3;
transition: stroke 0.3s, stroke-width 0.3s, opacity 0.3s;
}
.edge.highlight { stroke: var(--non-planar-color); stroke-width: 5; }
.edge.highlight-new { stroke: var(--primary-color); stroke-width: 4; stroke-dasharray: 5 5; }
.edge.edge-new.highlight { stroke: var(--non-planar-color); stroke-width: 5; stroke-dasharray: none; }
.edge.removed { opacity: 0.5; }
/* Спеціальні стилі для Тутте */
.edge.tutte-outer { stroke: var(--secondary-color); stroke-width: 4; }
.edge.tutte-highlight { stroke: var(--non-planar-color); stroke-width: 4; }
.node {
cursor: move;
transition: fill 0.3s, stroke 0.3s, opacity 0.3s;
}
.node-circle {
stroke: var(--white-bg);
stroke-width: 3;
fill: var(--primary-color);
r: 16; /* Збільшено для номерів */
}
.node-label {
font-size: 14px;
font-weight: bold;
fill: white;
text-anchor: middle;
dy: ".35em";
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.node.highlight .node-circle { fill: var(--highlight-color); }
.node.highlight .node-label { fill: #333; }
.node.highlight-secondary .node-circle { fill: var(--highlight-secondary-color); }
.node.highlight-secondary .node-label { fill: #333; }
.node.flash .node-circle { fill: var(--flash-color); stroke: #333; }
.node.selected .node-circle { fill: var(--flash-color); stroke: #333; }
.node.removed .node-circle { fill: var(--removed-color); opacity: 0.8; }
.node.removed .node-label { opacity: 0.4; }
/* Спеціальні стилі для Тутте */
.node.tutte-outer .node-circle { fill: var(--secondary-color); r: 14; }
.node.tutte-inner .node-circle { fill: var(--tertiary-color); }
.node.tutte-highlight .node-circle { fill: var(--non-planar-color); r: 14; }
.node.tutte-neighbor .node-circle { fill: var(--highlight-color); }
.node.tutte-neighbor .node-label { fill: #333; }
/* Кластери для Тутте */
.tutte-cluster {
stroke-width: 3;
stroke: white;
fill: var(--non-planar-color);
opacity: 0.8;
}
.tutte-cluster-label {
font-size: 16px;
font-weight: bold;
fill: white;
text-anchor: middle;
dy: ".35em";
pointer-events: none;
}
/* Центроїди для Тутте */
.tutte-centroid {
fill: var(--highlight-color);
stroke: #333;
stroke-width: 2px;
opacity: 0.9;
pointer-events: none;
}
.tutte-centroid-line {
stroke: var(--highlight-color);
stroke-width: 2;
stroke-dasharray: 3 3;
opacity: 0.9;
pointer-events: none;
}
.simulation-footer {
padding: 15px 20px;
background-color: #fafafa;
border-top: 1px solid var(--border-color);
}
#step-commentary, #connectivity-commentary, #tutte-commentary {
min-height: 5em;
font-size: 1.1em;
line-height: 1.5;
color: var(--comment-color);
padding: 15px;
border-radius: 6px;
background: #eee;
margin-bottom: 15px;
text-align: center;
}
#step-commentary .result, #connectivity-commentary .result, #tutte-commentary .result {
font-weight: bold;
font-size: 1.2em;
}
.result.planar { color: var(--planar-color); }
.result.non-planar { color: var(--non-planar-color); }
.step-controls {
display: flex;
justify-content: center;
gap: 10px;
}
.step-controls button { background-color: #6c757d; }
.step-controls button:hover { background-color: #5a6268; }
.step-controls button:disabled { background-color: #adb5bd; cursor: not-allowed; }
#stage-transition-controls {
padding: 20px;
text-align: center;
}
.theory-spoiler {
width: 100%;
max-width: 1200px;
background: var(--white-bg);
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
margin-top: 20px;
}
.theory-spoiler summary {
font-size: 1.2em;
font-weight: 600;
padding: 15px 20px;
cursor: pointer;
color: var(--primary-color);
}
.theory-spoiler div { padding: 0 20px 20px 20px; line-height: 1.6; }
.theory-spoiler h4 { color: var(--text-color); border-bottom: 2px solid var(--primary-color); padding-bottom: 5px; margin-top: 20px; }
</style>
</head>
<body>
<h3>Планарність, 3-зв'язність та Укладання Тутте</h3>
<div class="main-container">
<div class="stage-tabs">
<div class="stage-tab active" id="tab-stage-1">Етап 1: Планарність</div>
<div class="stage-tab" id="tab-stage-2">Етап 2: 3-Зв'язність</div>
<div class="stage-tab" id="tab-stage-3">Етап 3: Укладання Тутте</div>
</div>
<div class="stage-container" id="stage-1-planarity">
<div class="controls-panel">
<div class="control-group">
<label>Приклади графів:</label>
<button id="gen-planar-btn">Тестовий Граф Петерсона</button>
<button id="gen-planar-2cut-btn">Планарний (2-зв'язний)</button>
<button id="gen-icosahedron-btn">Ікосаєдр (-1)</button> <button id="gen-k5-btn">K5</button>
<button id="gen-k33-btn">K3,3</button>
<button id="gen-homeo-k5-btn">Непланарний (Ейлер OК)</button>
<button id="gen-random-btn">Випадковий</button>
<button id="toggle-physics-btn" class="secondary">🔌 Вимкнути фізику</button>
</div>
<div class="control-group">
<label for="node-count-input">Вершини:</label>
<input type="number" id="node-count-input" value="10" min="4" max="12">
</div>
<div class="control-group">
<label for="edge-prob-input">Щільність:</label>
<input type="range" id="edge-prob-input" value="0.5" min="0.1" max="1.0" step="0.05">
<p>Редагування (при вимкненій "фізиці"): Подвійний клік створіє вершину, клік з ctrl видаляє, натискання з Shift на 2 вершини створює ребро</p>
</div>
</div>
<div class="simulation-footer">
<div id="step-commentary">Завантажте граф для початку симуляції...</div>
<div class="step-controls">
<button id="prev-step-btn" disabled>◄ Попередній крок</button>
<button id="next-step-btn" disabled>Наступний крок ►</button>
</div>
</div>
</div>
<div class="stage-container" id="stage-2-connectivity" style="display: none;">
<div class="controls-panel">
<button id="start-connectivity-test-btn">Почати тест на 3-зв'язність</button>
</div>
<div class="simulation-footer">
<div id="connectivity-commentary">
Граф планарний. Натисніть кнопку, щоб перевірити його на 3-зв'язність.
<br>Це необхідно для коректного укладання за теоремою Тутте.
</div>
<div class="step-controls" id="tutte-options" style="display: none; flex-direction: column; gap: 10px;">
</div>
</div>
</div>
<div class="stage-container" id="stage-3-tutte" style="display: none;">
<div class="controls-panel">
<label>Керування укладанням:</label>
<button id="tutte-toggle-physics-btn" class="secondary">🔌 Увімкнути фізику</button>
<button id="tutte-prev-step-btn" disabled>◄ Крок Назад</button>
<button id="tutte-next-step-btn" disabled>2. Крок Вперед ►</button>
<button id="tutte-run-auto-btn" disabled>Авто (10 ітерацій)</button>
</div>
<div class="simulation-footer">
<div id="tutte-commentary">
Налаштування укладання Тутте...
</div>
</div>
</div>
<div id="graph-svg-container">
<svg id="graph-svg"></svg>
</div>
<details class="theory-spoiler" open>
<summary>Теорія: Планарність, Зв'язність та Укладання Тутте</summary>
<div>
<h4>Етап 1: Критерій планарності</h4>
<p>Граф називається <strong>планарним</strong>, якщо його можна зобразити на площині так, щоб його ребра перетиналися лише у вершинах.</p>
<p><strong>Критерій Ейлера (Наслідок):</strong> Для $v \ge 3$ та $e$ ребер, планарний граф повинен задовольняти $e \le 3v - 6$. Це швидка перевірка "на ні".</p>
<p><strong>Теорема Куратовського:</strong> Граф планарний $\iff$ він не містить підграфа, гомеоморфного $K_5$ або $K_{3,3}$.</p>
<h4>Деталі Етапу 1: Пошук K₅ та K₃,₃ (Реалізація)</h4>
<p>
Щоб довести, що граф непланарний, нам потрібно знайти підграф,
<em>гомеоморфний</em> K₅ або K₃,₃. Це означає, що ми шукаємо 5 (або 6) "термінальних"
вершин і 10 (або 9) шляхів між ними, які є <strong>внутрішньо-неперетинними</strong>
(тобто, вони можуть ділити між собою лише "термінальні" вершини, але
жодні дві пари шляхів не можуть використовувати один і той самий <em>внутрішній</em>
вузол).
</p>
<p>
Цей симулятор використовує для цього "чесний" алгоритм
<strong>рекурсивного пошуку з бектрекінгом (DFS)</strong>.
Він працює так:
</p>
<ol>
<li>Вибирає пару терміналів (наприклад, $A$ і $B$).</li>
<li>
Знаходить <em>перший</em> простий шлях між ними,
використовуючи лише вільні внутрішні вузли.
</li>
<li>
"Блокує" внутрішні вузли цього шляху.
</li>
<li>
Рекурсивно намагається знайти решту 9 (або 8) шляхів.
</li>
<li>
Якщо на якомусь етапі рекурсія зазнає невдачі (шлях не знайдено),
вона "відкочується" (backtracks), розблоковує вузли і
пробує <em>інший</em> шлях для пари $A$ і $B$.
</li>
</ol>
<p>
Цей метод гарантує знаходження гомеоморфного підграфу, якщо
він існує, але він має високу комбінаторну складність.
</p>
<h4>Комбінаторна складність (Чому це повільно)</h4>
<p>
"Жадібний" алгоритм (пошух шляхів без перевірки незалежності) працює
швидко, але може помилятися. Повний перебір
є коректним, але повільним, оскільки кількість комбінацій для
перевірки величезна.
</p>
<ul>
<li>
<strong>Для K₅:</strong> Ми маємо перевірити кожну комбінацію з 5 вершин у графі.
Кількість таких комбінацій:
$$
\binom{v}{5} = \frac{v!}{5!(v-5)!}
$$
Для $v=10$ (як у графі Петерсона) це $\binom{10}{5} = 252$ комбінації.
Для $v=12$ це вже $\binom{12}{5} = 792$ комбінації.
</li>
<li>
<strong>Для K₃,₃:</strong> Це ще гірше. Ми маємо вибрати 6 вершин, а потім
розділити їх на 2 групи по 3 (це можна зробити 10-ма способами):
$$
\binom{v}{6} \times \frac{1}{2}\binom{6}{3} = \binom{v}{6} \times 10
$$
Для $v=10$ це $\binom{10}{6} \times 10 = 2100$ комбінацій.
Для $v=12$ це $\binom{12}{6} \times 10 = 9240$ комбінацій.
</li>
</ul>
<p>
Саме тому симулятор обмежує кількість вершин до 12.
</p>
<h4>Сучасні алгоритми планарності</h4>
<p>
У професійних застосунках <strong>ніхто не</strong> використовує такий
"грубий" пошук K₅/K₃,₃. Це неефективно. Сучасні алгоритми
тестування планарності, такі як класичний
<strong>алгоритм Хопкрофта-Тарджана (1974)</strong> або більш нові методи
(наприклад, <strong>алгоритм Бойєра-Мірвольда</strong>, що базується на PQ-деревах),
працюють за лінійний час $O(v)$ (тобто, неймовірно швидко).
</p>
<p>
Вони не "шукають" K₅, а намагаються побудувати планарне укладання
"шматок за шматком". Якщо на якомусь етапі вони не можуть додати
нове ребро, не порушивши вже побудовану структуру, вони можуть
(завдяки складній структурі даних) гарантовано заявити, що
перешкодою є гомеоморфний K₅ або K₃,₃, і зупинити процес.
</p>
<h4 id="theory-stage-2">Етап 2: 3-Зв'язність</h4>
<p><strong>Зв'язність</strong> графа $k$ означає, що потрібно видалити щонайменше $k$ вершин, щоб розбити граф на компоненти.</p>
<ul>
<li><strong>Шарнір (Cut Vertex):</strong> Вершина, видалення якої збільшує кількість компонент. Граф з шарніром є <strong>1-зв'язним</strong>.</li>
<li><strong>Пара-розділювач (Separation Pair):</strong> Пара вершин, видалення яких роз'єднує граф. Граф без шарнірів, але з парою-розділювачем, є <strong>2-зв'язним</strong>.</li>
<li><strong>3-зв'язний граф:</strong> Граф, що не має ані шарнірів, ані пар-розділювачів.</li>
</ul>
<p>Цей симулятор візуально перевіряє наявність шарнірів та пар-розділювачів, "розтягуючи" граф фізичною симуляцією після видалення кандидатів.</p>
<h4 id="theory-stage-3">Етап 3: Укладання Тутте (Spring Embedding)</h4>
<p>Теорема Тутте (1963) стверджує, що будь-який <strong>3-зв'язний планарний граф</strong> можна укласти на площині так, що:</p>
<ol>
<li>Одна з його граней (циклів) утворює опуклий багатокутник (це наш "зовнішній" цикл).</li>
<li>Кожна "внутрішня" вершина розміщується в <strong>центрі мас (баріцентрі)</strong> своїх сусідів.</li>
</ol>
<p>Це гарантує планарне укладання без перетинів. Алгоритм моделює "систему пружин", де кожне ребро - це пружина з однаковим коефіцієнтом жорсткості. Позиції вершин зовнішнього циклу фіксовані, а внутрішні "знаходять" своє положення рівноваги.</p>
<p><strong>Чому 3-зв'язність критична?</strong> Якщо граф не 3-зв'язний (має шарнір або пару-розділювач), система "пружин" стає нестабільною. Внутрішні вершини, що належать до одного "шматка", "сколапсують" в одну точку, оскільки їхні позиції залежать лише одна від одної, а не від фіксованого зовнішнього циклу.</p>
</div>
<h4>Теорема Тутте як СЛАР (Система Лінійних Алгебраїчних Рівнянь)</h4>
<p>
Умова, що кожна внутрішня вершина $v_i$ є барицентром (центром мас) своїх сусідів,
насправді є системою лінійних рівнянь. Ми можемо розв'язати її,
щоб <em>миттєво</em> знайти фінальні позиції, замість ітерацій.
</p>
<p>
Розглянемо окремо $x$ та $y$ координати. Для $x$-координат кожної
<strong>внутрішньої</strong> вершини $v_i$ (з невідомою $x_i$) маємо:
</p>
$$
x_i = \frac{1}{\text{deg}(v_i)} \sum_{j \in N(v_i)} x_j
$$
<p>
де $N(v_i)$ — це множина сусідів $v_i$.
Перегрупуємо це у стандартну форму СЛАР (<code>Ax = b</code>),
перенісши всі <em>невідомі</em> (інші внутрішні вершини $I$) ліворуч,
а <em>відомі</em> (фіксовані зовнішні вершини $O$) залишивши праворуч:
</p>
$$
\text{deg}(v_i) \cdot x_i - \sum_{j \in N(v_i) \cap I} x_j = \sum_{k \in N(v_i) \cap O} \bar{x}_k
$$
<p>
Де:
</p>
<ul>
<li>$v_i$ - внутрішня вершина, $I$ - множина всіх внутрішніх вершин.</li>
<li>$O$ - множина всіх зовнішніх (фіксованих) вершин.</li>
<li>$x_i$ та $x_j$ - <strong>невідомі</strong> $x$-координати внутрішніх вершин.</li>
<li>$\bar{x}_k$ - <strong>відомі</strong> (фіксовані) $x$-координати сусідів на зовнішній грані.</li>
<li>$\text{deg}(v_i)$ - повний степінь вершини $v_i$.</li>
</ul>
<p>
Аналогічна, але незалежна система рівнянь існує і для $y$-координат.
</p>
<h4>Укладання як Метод Якобі</h4>
<p>
Ітераційна процедура укладання, яку ви бачите на Етапі 3,
насправді є візуалізацією <strong>методу Якобі</strong> для розв'язання
цієї СЛАР.
</p>
<p>
Метод Якобі — це ітераційний алгоритм, де нове положення $(k+1)$ для <em>кожної</em> вершини
обчислюється <strong>виключно</strong> на основі положень <em>усіх</em> вершин
на попередньому кроці $(k)$.
</p>
$$
x_i^{(k+1)} = \frac{1}{\text{deg}(v_i)} \left( \sum_{j \in N(v_i) \cap I} x_j^{(k)} + \sum_{k \in N(v_i) \cap O} \bar{x}_k \right)
$$
<p>
Це <em>точно</em> те, що робить симулятор: на кожному "кроці" він
перераховує барицентр для кожного вузла на основі "старих"
позицій, а потім переміщує їх усі одночасно.
</p>
<p>
Матриця цієї системи (яка є частиною матриці Лапласа)
має властивості (вона є <strong> діагонально домінуючою</strong>),
які <strong>гарантують</strong>, що метод Якобі (і ітераційне укладання Тутте)
завжди буде збігатися до єдиного коректного, планарного розв'язку.
</p>
</details>
</div>
<script type="module">
// --- DOM Елементи ---
const svgEl = d3.select("#graph-svg");
const svgContainer = d3.select("#graph-svg-container");
// Етап 1 (Планарність)
const stage1Container = d3.select("#stage-1-planarity");
const tabStage1 = d3.select("#tab-stage-1");
const commentaryEl = d3.select("#step-commentary");
const nextBtn = d3.select("#next-step-btn");
const prevBtn = d3.select("#prev-step-btn");
const nodeCountInput = d3.select("#node-count-input");
const edgeProbInput = d3.select("#edge-prob-input");
const genPlanarBtn = d3.select("#gen-planar-btn");
const genPlanar2CutBtn = d3.select("#gen-planar-2cut-btn");
const genIcosahedronBtn = d3.select("#gen-icosahedron-btn"); // ДОДАНО
const genK5Btn = d3.select("#gen-k5-btn");
const genK33Btn = d3.select("#gen-k33-btn");
const genHomeoK5Btn = d3.select("#gen-homeo-k5-btn");
const genRandomBtn = d3.select("#gen-random-btn");
const togglePhysicsBtn = d3.select("#toggle-physics-btn");
const allGenButtons = [genPlanarBtn, genPlanar2CutBtn, genIcosahedronBtn, genK5Btn, genK33Btn, genHomeoK5Btn, genRandomBtn, nodeCountInput, edgeProbInput];
// Етап 2 (Зв'язність)
const stage2Container = d3.select("#stage-2-connectivity");
const tabStage2 = d3.select("#tab-stage-2");
const connectivityCommentaryEl = d3.select("#connectivity-commentary");
const startConnectivityTestBtn = d3.select("#start-connectivity-test-btn");
const tutteOptionsContainer = d3.select("#tutte-options");
// Етап 3 (Тутте)
const stage3Container = d3.select("#stage-3-tutte");
const tabStage3 = d3.select("#tab-stage-3");
const tutteCommentaryEl = d3.select("#tutte-commentary");
const tuttePrevBtn = d3.select("#tutte-prev-step-btn");
const tutteNextBtn = d3.select("#tutte-next-step-btn");
const tutteAutoBtn = d3.select("#tutte-run-auto-btn");
const tutteTogglePhysicsBtn = d3.select("#tutte-toggle-physics-btn"); // ЗМІНЕНО
let tutteSimulation = null; // Окрема симуляція для Тутте
// --- Константи ---
const NODE_RADIUS = 12;
let width, height;
// --- Глобальний стан ---
let mainGraph = { nodes: [], edges: [] }; // {id, x, y}, {source: id, target: id}
let d3Nodes = []; // Масив для D3 симуляції
let d3Edges = []; // Масив для D3 симуляції
let simulation;
let selectedNodesForEdge = new Set();
let currentStage = 'planarity'; // 'planarity', 'connectivity', 'tutte'
// --- D3 Елементи ---
let linkGroup, nodeGroup, labelGroup, newEdgeGroup;
// Для Тутте
let tutteClusterGroup;
let tutteCentroidGroup;
// --- Стан Етапу 1 (Планарність) ---
let planarityState = {
steps: [],
currentStep: 0,
originalGraphD3: { nodes: [], edges: [] } // {id}, {source: {id}, target: {id}}
};
// --- Стан Етапу 3 (Тутте) ---
let tutteState = {
history: [],
currentStep: -1,
adj: [], // Список суміжності (по id)
outerFaceIds: [],
innerNodeIds: []
};
// ====================================================================
// --- ІНІЦІАЛІЗАЦІЯ ТА КЕРУВАННЯ ЕТАПАМИ ---
// ====================================================================
function switchStage(stageName) {
currentStage = stageName;
stage1Container.style('display', 'none');
stage2Container.style('display', 'none');
stage3Container.style('display', 'none');
tabStage1.classed('active', false);
tabStage2.classed('active', false);
tabStage3.classed('active', false);
// Зупиняємо симуляцію Тутте, якщо вона була
if (tutteSimulation) {
tutteSimulation.stop();
tutteSimulation = null;
tutteTogglePhysicsBtn.text("🔌 Увімкнути фізику");
}
if (stageName === 'planarity') {
stage1Container.style('display', 'block');
tabStage1.classed('active', true);
// resetToPlanarityStage(); // Не викликаємо звідси, щоб уникнути рекурсії
} else if (stageName === 'connectivity') {
stage2Container.style('display', 'block');
tabStage2.classed('active', true);
initConnectivityStage();
} else if (stageName === 'tutte') {
stage3Container.style('display', 'block');
tabStage3.classed('active', true);
// Ініціалізація Тутте викликається з кнопок Етапу 2
}
// Скидання симуляції, якщо вона є (для етапів 1 і 2)
if (simulation && stageName !== 'tutte') {
simulation.stop();
simulation = null;
}
// Запуск відповідної візуалізації
if (stageName === 'planarity') {
// При поверненні на 1 етап, ми маємо відновити симуляцію
// Використовуємо *збережені* d3Nodes/d3Edges, які вже мають позиції
if (d3Nodes.length === 0) { // Якщо це перший запуск
d3Nodes = planarityState.originalGraphD3.nodes.map(n => ({...n, x: 0, y: 0}));
d3Edges = planarityState.originalGraphD3.edges.map(e => ({
id: e.id,
source: d3Nodes.find(n => n.id === e.source.id),
target: d3Nodes.find(n => n.id === e.target.id)
}));
}
// Ми маємо зберегти позиції, якщо вони є з mainGraph
if (mainGraph.nodes.length > 0) {
d3Nodes.forEach(d3n => {
const mainN = mainGraph.nodes.find(mn => mn.id === d3n.id);
if (mainN && mainN.x) { // Якщо позиції вже були
d3n.x = mainN.x;
d3n.y = mainN.y;
}
});
}
initPlanaritySimulation(d3Nodes, d3Edges);
updatePlanarityView();
} else if (stageName === 'connectivity') {
// Використовуємо d3Nodes/d3Edges, оновлені з mainGraph
d3Nodes = mainGraph.nodes.map(n => ({...n}));
d3Edges = mainGraph.edges.map((e, i) => ({
id: `e${i}`, // Переконаємось, що є ID
source: d3Nodes.find(n => n.id === e.source),
target: d3Nodes.find(n => n.id === e.target)
}));
initConnectivityStage(); // initConnectivityStage тепер сам малює
} else if (stageName === 'tutte') {
// Ініціалізація візуалізації Тутте (без симуляції)
if(simulation) {
simulation.stop(); // Зупиняємо головну симуляцію
simulation = null;
}
initTutteVisuals();
updateTutteView();
}
}
// !!! ВИПРАВЛЕНО (ДОДАНО ОБРОБНИКИ НАТИСКАННЯ) !!!
tabStage1.on('click', () => {
// При натисканні на Етап 1, ми скидаємо все до початкового стану
resetToPlanarityStage();
});
tabStage2.on('click', () => {
// На Етап 2 можна перейти, тільки якщо він "enabled"
if (tabStage2.classed('enabled')) {
switchStage('connectivity');
}
});
tabStage3.on('click', () => {
// На Етап 3 можна перейти, тільки якщо він "enabled"
if (tabStage3.classed('enabled')) {
switchStage('tutte');
}
});
function resetToPlanarityStage() {
currentStage = 'planarity'; // Встановлюємо примусово
// Скидаємо стани 2 і 3
tabStage1.classed('active', true);
tabStage2.classed('active', false).classed('enabled', false).classed('completed', false).classed('failed', false);
tabStage3.classed('active', false).classed('enabled', false).classed('completed', false).classed('failed', false);
stage1Container.style('display', 'block');
stage2Container.style('display', 'none');
stage3Container.style('display', 'none');
mainGraph = { nodes: [], edges: [] };
d3Nodes = [];
d3Edges = [];
tutteState = { history: [], currentStep: -1, adj: [], outerFaceIds: [], innerNodeIds: [] };
tutteOptionsContainer.style('display', 'none').html('');
startConnectivityTestBtn.property('disabled', false);
allGenButtons.forEach(btn => btn.property('disabled', false));
generatePlanarityGraph('planar');
}
// ====================================================================
// --- D3 СИМУЛЯЦІЯ (СПІЛЬНА) ---
// ====================================================================
function initBaseSimulation(nodes, edges) {
if (simulation) {
simulation.stop();
}
// Очищення SVG
svgEl.selectAll("*").remove();
// Групи для елементів (ребра під вершинами)
linkGroup = svgEl.append("g").attr("class", "links-group");
newEdgeGroup = svgEl.append("g").attr("class", "new-edges-group");
nodeGroup = svgEl.append("g").attr("class", "nodes-group");
labelGroup = svgEl.append("g").attr("class", "labels-group");
tutteClusterGroup = svgEl.append("g").attr("class", "tutte-clusters-group");
tutteCentroidGroup = svgEl.append("g").attr("class", "tutte-centroids-group");
// Очищуємо виділення при кожному перемальовуванні
selectedNodesForEdge.clear();
// 1. Подвійний клік на канві (Додати Вершину)
svgEl.on('dblclick', (event) => {
event.preventDefault();
// Працює тільки на Етапі 1 з вимкненою фізикою
if (currentStage !== 'planarity' || physicsEnabled === true) return;
if (d3Nodes.length >= 12) {
alert("Досягнуто ліміту в 12 вершин.");
return;
}
const [x, y] = d3.pointer(event);
// Знаходимо новий унікальний ID
const newId = (d3Nodes.length > 0 ? Math.max(...d3Nodes.map(n => n.id)) : 0) + 1;
const newNode = { id: newId, x: x, y: y, fx: x, fy: y }; // fx/fy, щоб він не рухався
// Додаємо вузол до ВСІХ джерел даних
d3Nodes.push(newNode);
mainGraph.nodes.push({ id: newId, x: x, y: y });
planarityState.originalGraphD3.nodes.push({ id: newId });
// Перезапускаємо тест (це оновить все, в т.ч. d3Edges)
initPlanaritySimulation(d3Nodes, d3Edges);
runPlanarityTest();
});
// 2. Клік на Вершині (Виділити / Видалити)
// Використовуємо делегування на групі-батьку
nodeGroup.on('click', (event) => {
// Знаходимо дані вузла, на який клікнули
const d = d3.select(event.target.closest('.node'))?.datum();
if (!d) return; // Клікнули не на вузол
if (currentStage !== 'planarity' || physicsEnabled === true) return;
const clickedNodeId = d.id;
if (event.ctrlKey) {
// --- ВИДАЛИТИ ВЕРШИНУ ---
event.preventDefault();
event.stopPropagation();
// Видаляємо з усіх джерел даних
d3Nodes = d3Nodes.filter(n => n.id !== clickedNodeId);
d3Edges = d3Edges.filter(e => e.source.id !== clickedNodeId && e.target.id !== clickedNodeId);
mainGraph.nodes = mainGraph.nodes.filter(n => n.id !== clickedNodeId);
mainGraph.edges = mainGraph.edges.filter(e => e.source !== clickedNodeId && e.target !== clickedNodeId);
planarityState.originalGraphD3.nodes = planarityState.originalGraphD3.nodes.filter(n => n.id !== clickedNodeId);
planarityState.originalGraphD3.edges = planarityState.originalGraphD3.edges.filter(e => e.source.id !== clickedNodeId && e.target.id !== clickedNodeId);
selectedNodesForEdge.clear();
initPlanaritySimulation(d3Nodes, d3Edges);
runPlanarityTest(); // Перезапускаємо
} else if (event.shiftKey) {
// --- ДОДАТИ РЕБРО (Виділення) ---
event.preventDefault();
event.stopPropagation();
selectedNodesForEdge.add(clickedNodeId);
// Оновлюємо виділення візуально
nodeGroup.selectAll('.node').classed('selected', n => selectedNodesForEdge.has(n.id));
if (selectedNodesForEdge.size === 2) {
const [id1, id2] = Array.from(selectedNodesForEdge);
// Перевірка, чи ребро вже існує
const exists = d3Edges.some(e => (e.source.id === id1 && e.target.id === id2) || (e.source.id === id2 && e.target.id === id1));
if (!exists) {
const newEdgeId = `e_${Date.now()}`;
const newEdge = {
id: newEdgeId,
source: d3Nodes.find(n => n.id === id1),
target: d3Nodes.find(n => n.id === id2)
};
// Додаємо ребро до ВСІХ джерел
d3Edges.push(newEdge);
mainGraph.edges.push({ source: id1, target: id2 });
planarityState.originalGraphD3.edges.push({ id: newEdgeId, source: {id: id1}, target: {id: id2} });
initPlanaritySimulation(d3Nodes, d3Edges);
runPlanarityTest(); // Перезапуск зніме виділення
} else {
selectedNodesForEdge.clear();
nodeGroup.selectAll('.node').classed('selected', false);
}
}
} else {
// Простий клік (без Shift/Ctrl) знімає виділення
selectedNodesForEdge.clear();
nodeGroup.selectAll('.node').classed('selected', false);
}
});
// 3. Клік на Ребрі (Видалити)
linkGroup.on('click', (event) => {
const d = d3.select(event.target.closest('.edge'))?.datum();
if (!d) return; // Клікнули не на ребро
if (currentStage !== 'planarity' || physicsEnabled === true || !event.ctrlKey) return;
event.preventDefault();
event.stopPropagation();
const edgeIdToDelete = d.id;
const sourceId = d.source.id;
const targetId = d.target.id;
// Видаляємо з усіх джерел
d3Edges = d3Edges.filter(e => e.id !== edgeIdToDelete);
mainGraph.edges = mainGraph.edges.filter(e => !((e.source === sourceId && e.target === targetId) || (e.source === targetId && e.target === sourceId)));
planarityState.originalGraphD3.edges = planarityState.originalGraphD3.edges.filter(e => e.id !== edgeIdToDelete);
initPlanaritySimulation(d3Nodes, d3Edges);
runPlanarityTest(); // Перезапускаємо
});
simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(edges).id(d => d.id).distance(100))
.force("charge", d3.forceManyBody().strength(-400))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("collision", d3.forceCollide().radius(NODE_RADIUS * 2.5))
.on("tick", ticked);
initNodeDrag(nodes);
return simulation;
}
// --- Toggle physics та оновлені drag-хендлери ---
let physicsEnabled = true;
if (!togglePhysicsBtn.empty()) {
togglePhysicsBtn.on("click", () => {
physicsEnabled = !physicsEnabled;
if (physicsEnabled) {
// Увімкнути сили з потрібними параметрами
simulation.force("charge", d3.forceManyBody().strength(-400));
simulation.force("link", d3.forceLink(d3Edges).id(d => d.id).distance(100).strength(1));
simulation.force("collision", d3.forceCollide().radius(NODE_RADIUS * 2.5));
// ВИПРАВЛЕННЯ 2: Зменшуємо "поштовх" при перезапуску
simulation.alpha(0.1).restart();
togglePhysicsBtn.text("🔌 Вимкнути фізику");
} else {
// Вимкнути вплив сил
simulation.force("charge", d3.forceManyBody().strength(0));
simulation.force("link", d3.forceLink(d3Edges).id(d => d.id).distance(100).strength(() => 0));
simulation.force("collision", null);
simulation.alpha(0);
simulation.stop();
togglePhysicsBtn.text("⚡ Увімкнути фізику");
}
});
}
// Оновлені drag-хендлери
function initNodeDrag(nodes) {
const drag = d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
nodeGroup.selectAll('.node')
.data(nodes, d => d.id)