-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlarge-graph.html
More file actions
818 lines (724 loc) · 29.3 KB
/
large-graph.html
File metadata and controls
818 lines (724 loc) · 29.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WASMTea — Large Graph</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: #1a1a2e;
color: #eee;
font-family: system-ui, sans-serif;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
header {
display: flex;
align-items: center;
gap: 1.5rem;
padding: 0.6rem 1.2rem;
background: #16213e;
border-bottom: 1px solid #0f3460;
flex-shrink: 0;
}
header h1 { font-size: 1rem; font-weight: 600; color: #e94560; }
header a { font-size: 0.75rem; color: #555; text-decoration: none; margin-left: auto; }
header a:hover { color: #888; }
.toolbar { display: flex; gap: 0.4rem; }
.tool-btn {
padding: 0.3rem 0.8rem;
border-radius: 4px;
border: 1px solid #0f3460;
background: #0f3460;
color: #ccc;
cursor: pointer;
font-size: 0.8rem;
transition: background 0.15s, color 0.15s;
}
.tool-btn:hover { background: #1a4a8a; color: #fff; }
.tool-btn.active { background: #e94560; border-color: #e94560; color: #fff; }
.tool-btn.on { background: #4a9eff; border-color: #4a9eff; color: #fff; }
#stats { font-size: 0.75rem; color: #555; }
#hint { font-size: 0.75rem; color: #444; }
/* ── main ─────────────────────────────────────────────────────────── */
.main { display: flex; flex: 1; overflow: hidden; }
#graph-container {
flex: 1;
position: relative;
overflow: hidden;
min-width: 0;
background: #1a1a2e;
}
/* VivaGraph injects a canvas/svg here; make it fill the container */
#graph-container > * {
position: absolute !important;
top: 0 !important; left: 0 !important;
}
/* ── sidebar ──────────────────────────────────────────────────────── */
#sidebar {
width: 260px;
flex-shrink: 0;
background: #16213e;
border-left: 1px solid #0f3460;
display: flex;
flex-direction: column;
overflow: hidden;
}
.sidebar-tabs {
display: flex;
flex-shrink: 0;
border-bottom: 1px solid #0f3460;
}
.tab-btn {
flex: 1;
padding: 0.55rem 0;
background: none;
border: none;
color: #555;
font-size: 0.78rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
cursor: pointer;
transition: color 0.15s;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
}
.tab-btn:hover { color: #aaa; }
.tab-btn.active { color: #4a9eff; border-bottom-color: #4a9eff; }
.tab-panel { display: flex; flex-direction: column; flex: 1; overflow: hidden; }
.tab-panel[hidden] { display: none; }
/* generate tab */
#tab-generate { padding: 0.7rem 0.9rem; gap: 0.5rem; overflow-y: auto; }
.gen-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.4rem;
}
.gen-item {
padding: 0.45rem 0.5rem;
border-radius: 4px;
border: 1px solid #0f3460;
background: #0f3460;
color: #aaa;
font-size: 0.73rem;
cursor: pointer;
text-align: center;
transition: background 0.12s, color 0.12s;
user-select: none;
}
.gen-item:hover { background: #1a4a8a; color: #fff; }
.gen-item.active { background: #4a9eff; border-color: #4a9eff; color: #fff; }
.field-row {
display: flex;
align-items: center;
gap: 0.5rem;
margin-top: 0.4rem;
}
.field-row label { font-size: 0.78rem; color: #888; flex-shrink: 0; min-width: 2rem; }
.field-row input {
flex: 1;
padding: 0.3rem 0.4rem;
background: #0f3460;
border: 1px solid #1a4a8a;
border-radius: 4px;
color: #eee;
font-size: 0.8rem;
text-align: center;
}
.gen-note { font-size: 0.7rem; color: #555; margin-top: 0.2rem; min-height: 1rem; }
#btn-gen {
width: 100%;
padding: 0.45rem;
margin-top: 0.5rem;
background: #e94560;
border: none;
border-radius: 4px;
color: #fff;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
transition: background 0.15s;
}
#btn-gen:hover { background: #c73652; }
/* physics tab */
#tab-physics { padding: 0.7rem 0.9rem; gap: 0.6rem; overflow-y: auto; }
.section-title {
font-size: 0.65rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #4a9eff;
margin: 0.5rem 0 0.3rem;
padding-bottom: 0.2rem;
border-bottom: 1px solid #0f3460;
}
.phys-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.3rem 0;
}
.phys-row label { font-size: 0.78rem; color: #888; }
.phys-row input[type=range] { width: 100px; accent-color: #4a9eff; }
.phys-row span { font-size: 0.75rem; color: #aaa; width: 3rem; text-align: right; }
/* analyze tab */
.analyze-head {
display: flex;
justify-content: flex-end;
padding: 0.5rem 0.9rem;
border-bottom: 1px solid #0f3460;
flex-shrink: 0;
}
#btn-analyze {
padding: 0.25rem 0.7rem;
background: #e94560;
border: none;
border-radius: 4px;
color: #fff;
font-size: 0.75rem;
cursor: pointer;
transition: background 0.15s;
}
#btn-analyze:hover { background: #c73652; }
#btn-analyze:disabled { background: #555; cursor: default; }
#analysis-scroll {
flex: 1;
overflow-y: auto;
padding: 0.6rem 0.9rem;
}
.a-row {
display: flex;
justify-content: space-between;
align-items: baseline;
padding: 0.18rem 0;
font-size: 0.78rem;
}
.a-row .lbl { color: #888; }
.a-row .val { color: #eee; font-variant-numeric: tabular-nums; }
.val.yes { color: #4caf50; }
.val.no { color: #e94560; }
.val.na { color: #666; font-style: italic; }
.deg-seq {
font-size: 0.7rem; color: #666;
word-break: break-all; line-height: 1.6; margin-top: 0.15rem;
}
#empty-msg { font-size: 0.78rem; color: #555; text-align: center; margin-top: 2rem; }
</style>
</head>
<body>
<header>
<h1>WASMTea — Large Graph</h1>
<div class="toolbar">
<button class="tool-btn active" id="btn-vertex" title="Click canvas to add vertex">Vertex</button>
<button class="tool-btn" id="btn-edge" title="Click two vertices to add edge">Edge</button>
<button class="tool-btn" id="btn-delete" title="Click vertex to delete">Delete</button>
</div>
<button class="tool-btn on" id="btn-sim">Pause</button>
<span id="stats">0 vertices · 0 edges</span>
<span id="hint">Generate a graph or click to add vertices</span>
<a href="index.html">← Back</a>
</header>
<div class="main">
<div id="graph-container"></div>
<aside id="sidebar">
<div class="sidebar-tabs">
<button class="tab-btn active" data-tab="generate">Generate</button>
<button class="tab-btn" data-tab="physics">Physics</button>
<button class="tab-btn" data-tab="analyze">Analyze</button>
</div>
<div id="tab-generate" class="tab-panel">
<div class="gen-grid">
<div class="gen-item active" data-kind="random">Random</div>
<div class="gen-item" data-kind="barabasi">Barabási–Albert</div>
<div class="gen-item" data-kind="complete">Complete</div>
<div class="gen-item" data-kind="cycle">Cycle</div>
<div class="gen-item" data-kind="path">Path</div>
<div class="gen-item" data-kind="star">Star</div>
<div class="gen-item" data-kind="wheel">Wheel</div>
<div class="gen-item" data-kind="petersen">Petersen</div>
<div class="gen-item" data-kind="bipartite">Bipartite</div>
<div class="gen-item" data-kind="grid">Grid (n×n)</div>
</div>
<div class="field-row">
<label>n =</label>
<input type="number" id="gen-n" value="80" min="2" max="500">
</div>
<div class="field-row" id="p-row">
<label>p =</label>
<input type="number" id="gen-p" value="0.05" min="0.01" max="1" step="0.01">
</div>
<div class="gen-note" id="gen-note">Erdős–Rényi: n vertices, each edge with probability p</div>
<button id="btn-gen">Generate</button>
</div>
<div id="tab-physics" class="tab-panel" hidden>
<div class="section-title">Spring</div>
<div class="phys-row">
<label>Spring length</label>
<input type="range" id="sl" min="10" max="200" value="80">
<span id="sl-val">80</span>
</div>
<div class="phys-row">
<label>Spring coeff</label>
<input type="range" id="sc" min="1" max="50" value="8">
<span id="sc-val">0.0008</span>
</div>
<div class="section-title">Gravity / Drag</div>
<div class="phys-row">
<label>Gravity</label>
<input type="range" id="grav" min="-50" max="-1" value="-12">
<span id="grav-val">-1.2</span>
</div>
<div class="phys-row">
<label>Drag coeff</label>
<input type="range" id="drag" min="1" max="100" value="2">
<span id="drag-val">0.02</span>
</div>
<div class="phys-row">
<label>Theta</label>
<input type="range" id="theta" min="1" max="20" value="8">
<span id="theta-val">0.8</span>
</div>
</div>
<div id="tab-analyze" class="tab-panel" hidden>
<div class="analyze-head">
<button id="btn-analyze">Analyze</button>
</div>
<div id="analysis-scroll">
<p id="empty-msg">Build a graph, then click Analyze.</p>
</div>
</div>
</aside>
</div>
<script src="js/vivagraph.min.js"></script>
<script>
// ── state ─────────────────────────────────────────────────────────────────
let vivaGraph = null;
let renderer = null;
let layout = null;
let graphics = null;
let running = true;
let nextId = 0;
let mode = 'vertex';
let edgeSource = null; // node id waiting for edge target
const container = document.getElementById('graph-container');
const statsEl = document.getElementById('stats');
const hintEl = document.getElementById('hint');
// ── physics settings ──────────────────────────────────────────────────────
function physicsSettings() {
return {
springLength: parseInt(document.getElementById('sl').value),
springCoeff: parseInt(document.getElementById('sc').value) / 10000,
gravity: parseInt(document.getElementById('grav').value) / 10,
dragCoeff: parseInt(document.getElementById('drag').value) / 100,
theta: parseInt(document.getElementById('theta').value) / 10,
};
}
// ── build / rebuild renderer ──────────────────────────────────────────────
function buildRenderer(g) {
if (renderer) { renderer.dispose(); }
container.innerHTML = '';
vivaGraph = g;
nextId = g.getNodesCount();
graphics = Viva.Graph.View.webglGraphics();
graphics.node(function() {
return Viva.Graph.View.webglSquare(10, '#e94560');
});
graphics.link(function() {
return Viva.Graph.View.webglLine('#4a9eff');
});
layout = Viva.Graph.Layout.forceDirected(vivaGraph, physicsSettings());
renderer = Viva.Graph.View.renderer(vivaGraph, {
graphics : graphics,
layout : layout,
container: container,
renderLinks: true,
});
renderer.run();
if (!running) renderer.pause();
// node click events
const nodeEvents = Viva.Graph.webglInputEvents(graphics, vivaGraph);
nodeEvents.click(function(node) {
if (mode === 'delete') {
vivaGraph.removeNode(node.id);
updateStats();
} else if (mode === 'edge') {
if (edgeSource === null) {
edgeSource = node.id;
hintEl.textContent = `Source: ${node.id} — now click the target vertex`;
} else {
if (edgeSource !== node.id && !vivaGraph.hasLink(edgeSource, node.id)) {
vivaGraph.addLink(edgeSource, node.id);
updateStats();
}
edgeSource = null;
hintEl.textContent = modeHints.edge;
}
}
});
updateStats();
}
function updateStats() {
statsEl.textContent =
`${vivaGraph.getNodesCount()} vertices · ${vivaGraph.getLinksCount()} edges`;
}
// ── generators ────────────────────────────────────────────────────────────
function buildGraph(kind, n, p) {
const g = Viva.Graph.graph();
n = Math.max(2, n);
switch (kind) {
case 'random':
for (let i = 0; i < n; i++) g.addNode(i);
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
if (Math.random() < p) g.addLink(i, j);
break;
case 'barabasi': {
g.addNode(0); g.addNode(1); g.addLink(0, 1);
const deg = new Array(n).fill(0);
deg[0] = 1; deg[1] = 1; let total = 2;
for (let i = 2; i < n; i++) {
g.addNode(i);
const m = Math.min(2, i);
const attached = new Set();
let tries = 0;
while (attached.size < m && tries++ < 200) {
let r = Math.random() * total, cum = 0;
for (let j = 0; j < i; j++) {
cum += deg[j];
if (cum >= r && !attached.has(j)) { attached.add(j); break; }
}
}
attached.forEach(j => {
g.addLink(i, j);
deg[i]++; deg[j]++; total += 2;
});
}
break;
}
case 'complete':
for (let i = 0; i < n; i++) g.addNode(i);
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++) g.addLink(i, j);
break;
case 'cycle':
for (let i = 0; i < n; i++) g.addNode(i);
for (let i = 0; i < n; i++) g.addLink(i, (i + 1) % n);
break;
case 'path':
for (let i = 0; i < n; i++) g.addNode(i);
for (let i = 0; i < n - 1; i++) g.addLink(i, i + 1);
break;
case 'star':
g.addNode(0);
for (let i = 1; i <= n; i++) { g.addNode(i); g.addLink(0, i); }
break;
case 'wheel':
g.addNode(0);
for (let i = 1; i <= n; i++) { g.addNode(i); g.addLink(0, i); }
for (let i = 1; i <= n; i++) g.addLink(i, i % n + 1);
break;
case 'petersen':
for (let i = 0; i < 10; i++) g.addNode(i);
for (let i = 0; i < 5; i++) g.addLink(i, (i + 1) % 5);
for (let i = 0; i < 5; i++) g.addLink(5 + i, 5 + (i + 2) % 5);
for (let i = 0; i < 5; i++) g.addLink(i, 5 + i);
break;
case 'bipartite':
for (let i = 0; i < 2 * n; i++) g.addNode(i);
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++) g.addLink(i, n + j);
break;
case 'grid':
for (let r = 0; r < n; r++)
for (let c = 0; c < n; c++) {
g.addNode(r * n + c);
if (c > 0) g.addLink(r * n + c, r * n + c - 1);
if (r > 0) g.addLink(r * n + c, (r - 1) * n + c);
}
break;
}
return g;
}
// ── generator UI ──────────────────────────────────────────────────────────
let genKind = 'random';
const nNotes = {
random: 'Erdős–Rényi: n vertices, each edge with probability p',
barabasi: 'Preferential attachment — scale-free network (p ignored)',
complete: 'K_n: every pair connected (keep n small)',
bipartite:'K(n,n): two groups, all cross-edges (keep n small)',
grid: 'n×n lattice',
star: 'n leaves + 1 centre',
wheel: 'n rim vertices + 1 hub',
};
const pVisible = new Set(['random']);
document.querySelectorAll('.gen-item').forEach(item => {
item.addEventListener('click', () => {
document.querySelectorAll('.gen-item').forEach(i => i.classList.remove('active'));
item.classList.add('active');
genKind = item.dataset.kind;
document.getElementById('p-row').style.display = pVisible.has(genKind) ? '' : 'none';
document.getElementById('gen-note').textContent = nNotes[genKind] ?? '';
document.getElementById('gen-n').style.visibility = genKind === 'petersen' ? 'hidden' : '';
});
});
document.getElementById('gen-note').textContent = nNotes['random'];
document.getElementById('btn-gen').addEventListener('click', () => {
const n = Math.max(2, Math.min(500, parseInt(document.getElementById('gen-n').value) || 80));
const p = Math.max(0.001, Math.min(1, parseFloat(document.getElementById('gen-p').value) || 0.05));
buildRenderer(buildGraph(genKind, n, p));
});
// ── physics sliders ───────────────────────────────────────────────────────
[
['sl', v => v, 'sl-val'],
['sc', v => (v/10000).toFixed(4), 'sc-val'],
['grav', v => (v/10).toFixed(1), 'grav-val'],
['drag', v => (v/100).toFixed(2), 'drag-val'],
['theta',v => (v/10).toFixed(1), 'theta-val'],
].forEach(([id, fmt, labelId]) => {
document.getElementById(id).addEventListener('input', e => {
document.getElementById(labelId).textContent = fmt(e.target.value);
if (layout) {
const s = physicsSettings();
layout.simulator.springLength(s.springLength);
layout.simulator.springCoeff(s.springCoeff);
layout.simulator.gravity(s.gravity);
layout.simulator.dragCoeff(s.dragCoeff);
layout.simulator.theta(s.theta);
}
});
});
// ── sidebar tabs ──────────────────────────────────────────────────────────
const TAB_IDS = ['generate', 'physics', 'analyze'];
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const t = btn.dataset.tab;
TAB_IDS.forEach(id => {
document.getElementById('tab-' + id).hidden = id !== t;
});
});
});
// ── pause / resume ────────────────────────────────────────────────────────
document.getElementById('btn-sim').addEventListener('click', function() {
running = !running;
this.textContent = running ? 'Pause' : 'Resume';
this.classList.toggle('on', running);
if (renderer) running ? renderer.resume() : renderer.pause();
});
// ── toolbar modes ─────────────────────────────────────────────────────────
const modeHints = {
vertex: 'Click empty canvas to add a vertex',
edge: 'Click a vertex, then another to add an edge',
delete: 'Click a vertex to delete it',
};
['btn-vertex', 'btn-edge', 'btn-delete'].forEach(id => {
document.getElementById(id).addEventListener('click', function() {
mode = id.replace('btn-', '');
document.querySelectorAll('#btn-vertex, #btn-edge, #btn-delete')
.forEach(b => b.classList.remove('active'));
this.classList.add('active');
hintEl.textContent = modeHints[mode];
edgeSource = null;
});
});
// ── add vertex on canvas click ─────────────────────────────────────────
container.addEventListener('click', function(e) {
if (mode !== 'vertex' || !renderer) return;
// ignore if a node was clicked (webglInputEvents handles that)
if (e.target !== container && e.target.tagName === 'CANVAS') {
// check if click was on empty space via a small delay to let node events fire first
}
const id = nextId++;
if (vivaGraph) {
vivaGraph.addNode(id);
updateStats();
}
});
// ── graph analysis (pure JS, mirrors Rust algorithms in graph.html) ───────
function analyzeGraph(g) {
const n = g.getNodesCount();
const m = g.getLinksCount();
if (n === 0) return null;
// Build index + adjacency list
const ids = [];
const idxOf = new Map();
g.forEachNode(node => { idxOf.set(node.id, ids.length); ids.push(node.id); });
const adj = Array.from({length: n}, () => []);
g.forEachLink(link => {
const i = idxOf.get(link.fromId), j = idxOf.get(link.toId);
if (i !== undefined && j !== undefined) { adj[i].push(j); adj[j].push(i); }
});
// Degrees
const degrees = adj.map(a => a.length);
const degSeq = [...degrees].sort((a, b) => b - a);
// BFS utility
function bfs(start) {
const dist = new Int32Array(n).fill(-1);
dist[start] = 0;
const q = [start];
for (let h = 0; h < q.length; h++) {
const v = q[h];
for (const u of adj[v]) {
if (dist[u] === -1) { dist[u] = dist[v] + 1; q.push(u); }
}
}
return dist;
}
// Connected components
const comp = new Int32Array(n).fill(-1);
let numComp = 0;
for (let s = 0; s < n; s++) {
if (comp[s] !== -1) continue;
bfs(s).forEach((d, i) => { if (d >= 0) comp[i] = numComp; });
numComp++;
}
const isConnected = numComp === 1;
// Bipartite
const color = new Int8Array(n).fill(-1);
let bipartite = true;
outer: for (let s = 0; s < n; s++) {
if (color[s] !== -1) continue;
color[s] = 0;
const q = [s];
for (let h = 0; h < q.length; h++) {
const v = q[h];
for (const u of adj[v]) {
if (color[u] === -1) { color[u] = 1 - color[v]; q.push(u); }
else if (color[u] === color[v]) { bipartite = false; break outer; }
}
}
}
// Eulerian
const oddDeg = degrees.filter(d => d % 2 !== 0).length;
const eulerCircuit = isConnected && oddDeg === 0 && m > 0;
const eulerPath = isConnected && oddDeg === 2;
// Diameter (cap at n≤300 to avoid UI freeze)
let diameter = -1;
if (isConnected && n <= 300) {
for (let s = 0; s < n; s++) {
const d = Math.max(...bfs(s));
if (d > diameter) diameter = d;
}
}
// Greedy chromatic number
const col = new Int32Array(n);
for (let v = 0; v < n; v++) {
const used = new Set(adj[v].map(u => col[u]).filter(c => c > 0));
let c = 1; while (used.has(c)) c++;
col[v] = c;
}
const chromatic = Math.max(...col);
// NP-hard exact (n ≤ 25 only)
const exact = n <= 25;
let mis = 0, clique = 0;
if (exact) {
const amat = Array.from({length: n}, (_, i) => {
const row = new Uint8Array(n);
adj[i].forEach(j => { row[j] = 1; });
return row;
});
function computeMIS(cands, sz) {
if (!cands.length) return sz;
const v = cands[0], rest = cands.slice(1);
return Math.max(
computeMIS(rest.filter(u => !amat[v][u]), sz + 1),
computeMIS(rest, sz)
);
}
function computeClique(cands, sz) {
if (!cands.length) return sz;
let best = sz;
for (let i = 0; i < cands.length; i++) {
if (sz + cands.length - i <= best) break;
const v = cands[i];
best = Math.max(best, computeClique(cands.slice(i+1).filter(u => amat[v][u]), sz+1));
}
return best;
}
const all = [...Array(n).keys()];
mis = computeMIS(all, 0);
clique = computeClique(all, 0);
}
return {
vertex_count: n, edge_count: m,
density: n > 1 ? (2 * m) / (n * (n - 1)) : 0,
is_connected: isConnected, connected_components: numComp,
min_degree: Math.min(...degrees), max_degree: Math.max(...degrees),
avg_degree: degrees.reduce((a,b)=>a+b,0) / n,
degree_sequence: degSeq,
is_bipartite: bipartite,
has_eulerian_circuit: eulerCircuit, has_eulerian_path: eulerPath,
diameter, chromatic_number_greedy: chromatic,
max_independent_set: mis, min_vertex_cover: n - mis, max_clique: clique,
exact_computed: exact, diameter_computed: isConnected && n <= 300,
};
}
// ── analysis rendering ────────────────────────────────────────────────────
const analyzeBtn = document.getElementById('btn-analyze');
const scrollEl = document.getElementById('analysis-scroll');
function bool(v) {
return v ? '<span class="val yes">Yes</span>' : '<span class="val no">No</span>';
}
function naIf(cond, val) {
return cond ? `<span class="val">${val}</span>` : '<span class="val na">N/A</span>';
}
function row(lbl, valHtml) {
return `<div class="a-row"><span class="lbl">${lbl}</span>${valHtml}</div>`;
}
analyzeBtn.addEventListener('click', () => {
if (!vivaGraph || vivaGraph.getNodesCount() === 0) {
scrollEl.innerHTML = '<p id="empty-msg">Build a graph, then click Analyze.</p>';
return;
}
analyzeBtn.disabled = true;
analyzeBtn.textContent = '…';
setTimeout(() => {
const a = analyzeGraph(vivaGraph);
if (!a) { analyzeBtn.disabled = false; analyzeBtn.textContent = 'Analyze'; return; }
const diamStr = !a.diameter_computed
? '<span class="val na">N/A (n > 300)</span>'
: a.diameter === -1
? '<span class="val na">∞ (disconnected)</span>'
: `<span class="val">${a.diameter}</span>`;
const exactNote = a.exact_computed ? '' :
'<div class="a-row"><span class="lbl" style="color:#e94560;font-size:0.7rem">Graph >25 — NP-hard skipped</span></div>';
scrollEl.innerHTML = `
<div class="section-title" style="margin-top:0">Basic</div>
${row('Vertices', `<span class="val">${a.vertex_count}</span>`)}
${row('Edges', `<span class="val">${a.edge_count}</span>`)}
${row('Density', `<span class="val">${(a.density*100).toFixed(1)}%</span>`)}
<div class="section-title">Connectivity</div>
${row('Connected', bool(a.is_connected))}
${row('Components', `<span class="val">${a.connected_components}</span>`)}
${row('Diameter', diamStr)}
<div class="section-title">Degrees</div>
${row('Min', `<span class="val">${a.min_degree}</span>`)}
${row('Max', `<span class="val">${a.max_degree}</span>`)}
${row('Avg', `<span class="val">${a.avg_degree.toFixed(2)}</span>`)}
<div class="deg-seq">(${a.degree_sequence.slice(0,30).join(', ')}${a.degree_sequence.length>30?', …':''})</div>
<div class="section-title">Properties</div>
${row('Bipartite', bool(a.is_bipartite))}
${row('Eulerian circuit', bool(a.has_eulerian_circuit))}
${row('Eulerian path', bool(a.has_eulerian_path))}
<div class="section-title">Coloring</div>
${row('Chromatic # (greedy)', `<span class="val">${a.chromatic_number_greedy}</span>`)}
<div class="section-title">NP-Hard (Exact)</div>
${exactNote}
${row('Max independent set', naIf(a.exact_computed, a.max_independent_set))}
${row('Min vertex cover', naIf(a.exact_computed, a.min_vertex_cover))}
${row('Max clique', naIf(a.exact_computed, a.max_clique))}
`;
analyzeBtn.disabled = false;
analyzeBtn.textContent = 'Analyze';
}, 10);
});
// ── initial empty graph ───────────────────────────────────────────────────
buildRenderer(Viva.Graph.graph());
</script>
</body>
</html>