-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph-theory.js
1497 lines (1362 loc) · 55.3 KB
/
graph-theory.js
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
Numbas.addExtension('graph-theory',['jme','jme-display','svgjs'],function(extension) {
const scope = extension.scope;
var jme = Numbas.jme;
class WorkingOut {
constructor(num_columns, add_step_cb, render_cb) {
this.steps = [];
this.num_columns = num_columns;
this.add_step_cb = add_step_cb;
this.render_cb = render_cb;
}
add_step(data) {
const extra = this.add_step_cb(data);
Object.assign(extra,data);
this.steps.push(extra);
}
render() {
const container = document.createElement('div');
container.classList.add('working-out');
container.style.setProperty('--num-columns',this.num_columns);
this.steps.forEach(step => {
//const li = document.createElement('li');
//li.classList.add('step');
//ul.appendChild(li);
this.render_cb(container,step);
});
return container;
}
}
class Edge {
constructor(from, to, weight, directed=false, label='',style={}) {
this.from = from;
this.to = to;
this.weight = weight === undefined ? Numbas.math.randomrange(1,1.1) : weight;
this.directed = directed;
this.set_label(label);
this.set_style(style);
}
/** Make a copy of this edge.
*
* @returns {Edge}
*/
copy() {
return new Edge(this.from, this.to, this.weight, this.directed, this.label);
}
/** Is this edge identical to the given edge?
* From, to, weight directedness and label must be the same.
*
* @param {edge} b
* @returns {boolean}
*/
eq(b) {
return this.from == b.from && this.to == b.to && this.directed == b.directed && this.label == b.label && this.weight == b.weight;
}
set_label(label) {
this.label = ((label===undefined ? '' : label)+'').trim();
return this;
}
set_style(style) {
this.style = style || {};
return this;
}
}
extension.Edge = Edge;
class Vertex {
constructor(x,y,label='') {
this.x = x;
this.y = y;
this.set_label(label);
}
/** Make a copy of this vertex.
*
* @returns {Vertex}
*/
copy() {
return new Vertex(this.x, this.y, this.label);
}
/** Is this vertex identical to the given vertex?
* Position and label must be the same.
*
* @param {Vertex} b
* @returns {boolean}
*/
eq(b) {
return this.x==b.x && this.y==b.y && this.label==b.label;
}
set_label(label) {
this.label = ((label===undefined ? '' : label)+'').trim();
return this;
}
}
extension.Vertex = Vertex;
class Graph {
constructor(adjacency_matrix, vertices, edges) {
this.adjacency_matrix = adjacency_matrix;
this.vertices = vertices;
this.edges = edges;
}
/** Make a copy of this graph.
*
* @returns {Graph}
*/
copy() {
const g = new Graph(this.adjacency_matrix,this.vertices,this.edges);
g.loop_positions = this.loop_positions;
return g;
}
get vertices() {
if(this._vertices===undefined) {
const vertices = this._vertices = [];
const m = this.adjacency_matrix;
for(let i=0;i<m.length;i++) {
vertices.push(new Vertex(Math.random(), Math.random()));
}
}
return this._vertices;
}
set vertices(v) {
this._vertices = v;
if(!this._vertices) {
return;
}
const n = this._vertices.length;
const d = n - this.adjacency_matrix.length;
if(d < 0) {
this.adjacency_matrix = this.adjacency_matrix.slice(0,n).map(row => row.slice(0,n));
} else if (d > 0) {
this.adjacency_matrix.forEach(row => {
for(let i=0;i<d;i++) {
row.push(0);
}
});
for(let i=0;i<d;i++) {
const row = [];
for(let i=0;i<n;i++) {
row.push(0);
}
this.adjacency_matrix.push(row);
}
}
this.adjacency_matrix.rows = n;
this.adjacency_matrix.columns = n;
}
/** Is this graph identical to the given graph?
* Vertices and edges must be the same.
*
* @param {Graph} b
* @returns {boolean}
*/
eq(b) {
if(this.vertices.length != b.vertices.length || this.edges.length != b.edges.length) {
return false;
}
for(let v of this.vertices) {
if(!b.vertices.find(v2 => v2.eq(v))) {
return false;
}
}
for(let e of this.edges) {
if(!b.edges.find(e2 => e2.eq(e))) {
return false;
}
}
return true;
}
/** Add a vertex to this graph. Modifies the adjacency matrix.
*
* @param {Vertex} v
*/
add_vertex(v) {
const {adjacency_matrix, vertices} = this;
const row = [];
adjacency_matrix.forEach(r => {r.push(0); row.push(0);});
adjacency_matrix.push(row);
this.vertices.push(v);
const n = vertices.length;
this.adjacency_matrix.rows = n;
this.adjacency_matrix.columns = n;
}
/** Add an edge to this graph. Modifies the adjacency matrix.
*
* @param {Edge} e
*/
add_edge(e) {
this.edges.push(e);
this.adjacency_matrix[e.from][e.to] = 1;
if(!e.directed) {
this.adjacency_matrix[e.to][e.from] = 1;
}
}
get edges() {
if(this._edges === undefined) {
const edges = this._edges = [];
const m = this.adjacency_matrix;
for(let i=0;i<m.length;i++) {
for(let j=0;j<=i;j++) {
if(m[i][j]) {
edges.push(new Edge(i, j, Math.abs(m[i][j]), !m[j][i]));
} else if(m[j][i]) {
edges.push(new Edge(j, i, Math.abs(m[j][i])));
}
}
}
}
return this._edges;
}
set edges(edges) {
this._edges = edges;
if(!edges) {
return;
}
const n = this.adjacency_matrix.rows;
this.adjacency_matrix = this.adjacency_matrix.map(row => row.map(() => 0));
for(let e of edges) {
this.adjacency_matrix[e.from][e.to] = 1;
if(!e.directed) {
this.adjacency_matrix[e.to][e.from] = 1;
}
}
this.adjacency_matrix.rows = n;
this.adjacency_matrix.columns = n;
}
/** Get the connected components of this graph.
*
* @returns {Array.<number>} - A list of components. Each component is a list giving the indices of the vertices in that component.
*/
connected_components() {
const adjacency = this.adjacency_matrix;
let components = adjacency.map((_,i) => i);
for(let i=0;i<components.length;i++) {
for(let j=0;j<components.length;j++) {
if(i!=j && adjacency[i][j]) {
const keep = Math.min(components[i],components[j]);
const remove = Math.max(components[i],components[j]);
components = components.map(function(c) { return c==remove ? keep : c; });
}
}
}
const dict = {};
components.forEach((c,i) => {
if(dict[c]===undefined) {
dict[c] = [];
}
dict[c].push(i);
});
return Object.values(dict);
}
/** Is this graph connected?
*
* @returns {boolean}
*/
is_connected() {
return this.connected_components().length<=1;
}
/** Get the subgraph containing the given vertices, and all edges between them.
* Omit vertices not in the given list, and all edges with either end on an omitted vertex.
*
* @param {Array.<number>} verts - The indices of the vertices in the subgraph.
* @returns {Graph}
*/
subgraph(verts) {
const m = verts.map(a => {
return verts.map(b => {
return this.adjacency_matrix[a][b];
})
});
m.rows = m.columns = verts.length;
let vertices, edges;
if(this.vertices) {
vertices = verts.map(i => this.vertices[i]);
}
if(this.edges) {
edges = this.edges.filter(e=>verts.indexOf(e.from)>=0 && verts.indexOf(e.to)>=0).map(e => {
const e2 = e.copy();
e2.from = verts.indexOf(e.from);
e2.to = verts.indexOf(e.to);
return e2;
});
}
const g = new Graph(m, vertices, edges);
const loop_positions = {};
if(this.loop_positions) {
verts.forEach((vi,i) => {
loop_positions[i] = this.loop_positions[vi];
});
}
g.loop_positions = loop_positions;
return g;
}
/** Get the subgraph containing only the given edges, and the vertices they connect.
*
* @param {Array.<Edge>}
* @returns {Graph}
*/
subgraph_by_edges(edges) {
const vertset = new Set([]);
for(let e of edges) {
vertset.add(e.from);
vertset.add(e.to);
}
const verts = Array.from(vertset);
const g = this.subgraph(verts);
g.edges = edges.map(e => {
const e2 = e.copy();
e2.from = verts.indexOf(e.from);
e2.to = verts.indexOf(e.to);
return e2;
});
return g;
}
/** Get the largest connected component of the given graph.
*
* @returns {Graph}
*/
largest_connected_component() {
const components = this.connected_components();
let biggest = [];
for(let c of components) {
if(c.length>biggest.length) {
biggest = c;
}
}
return this.subgraph(biggest);
}
/** Get an adjacency matrix corresponding to a graph with the given edges.
*
* @param {Array.Edge} edges
* @returns {Graph}
*/
static from_edges(edges) {
let size = 0;
for(let e of edges) {
size = Math.max(e.from+1,Math.max(e.to+1,size));
}
const m = [];
for(let i=0;i<size;i++) {
const row = [];
for(let j=0;j<size;j++) {
row.push(0);
}
m.push(row);
}
edges.forEach(function(e) {
const {from, to} = e;
m[from][to] = 1;
if(!e.directed) {
m[to][from] = 1;
}
});
m.rows = m.columns = size;
return new Graph(m, undefined, edges);
}
/** Make an SVG drawing of this graph.
*
* @returns {SVG}
*/
draw() {
const draw = SVG();
draw.addClass('graph');
/** Draw an arrow between a and b
*/
function arrow(a,b) {
let dx = b.x-a.x;
let dy = b.y-a.y;
const d = Math.sqrt(dx*dx+dy*dy);
const l = 0.5*scale;
const w = 0.4*scale;
let [nx,ny] = [-dy,dx];
dx *= l/d;
dy *= l/d;
nx *= w/d;
ny *= w/d;
const [cx,cy] = [(a.x+b.x)/2, (a.y+b.y)/2];
return draw.polygon([[cx+dx,cy+dy],[cx-dx+nx,cy-dy+ny],[cx-dx/2,cy-dy/2],[cx-dx-nx,cy-dy-ny]]);
}
const {vertices, edges, adjacency_matrix} = this;
let minx = Infinity, miny = Infinity, maxx = -Infinity, maxy = -Infinity;
vertices.forEach((n,i) => {
minx = Math.min(minx,n.x);
miny = Math.min(miny,n.y);
maxx = Math.max(maxx,n.x);
maxy = Math.max(maxy,n.y);
});
const margin = 4;
const scale = 1;
let extra = 0;
for(let e of edges) {
const a = vertices[e.from];
const b = vertices[e.to];
let curve;
if(e.from == e.to) {
const c = this.loop_positions[e.from] || {x: a.x+1, y:a.y};
extra += 1;
const dx = c.x-a.x;
const dy = c.y-a.y;
const d = Math.sqrt(dx*dx+dy*dy);
const r = 2*scale;
curve = draw.circle(r).center(a.x+dx/d*r/2,a.y+dy/d*r/2);
} else {
curve = draw.line(a.x, a.y, b.x, b.y);
}
const width = (e.style.width===undefined ? 1 : e.style.width) * 0.1 * scale;
curve.fill('none').stroke({width: 3*width,color:'white',opacity:0.8}).attr({role:'img'});
const top = curve.clone();
top.addTo(draw);
top.fill('none').stroke({width: width,color:'black',opacity:1})
if(e.directed) {
arrow(a,b);
}
if(a.label && b.label) {
let label;
if(e.directed) {
label = `Edge from vertex ${a.label} to vertex ${b.label}`;
} else {
label = `Edge between vertices ${a.label} and ${a.label}`;
}
top.attr({'aria-label': label});
}
if(e.label) {
const [l,r] = b.x > a.x ? [a,b] : [b,a];
const dx = r.x - l.x;
const dy = r.y - l.y;
const d = Math.sqrt(dx*dx+dy*dy);
const [nx,ny] = [-dy/d, dx/d];
const ldist = 0.5;
const [lx, ly] = [l.x + dx/2 + nx*ldist, l.y + dy/2 + ny*ldist];
const text = draw.text(e.label).font({size:1*scale}).center(lx,ly).rotate(Math.atan2(dy,dx)*180/Math.PI);
if(e.style.opacity!==undefined) {
text.fill({opacity: e.style.opacity});
}
}
if(e.style.dash!==undefined) {
const pattern = e.style.dash===true ? '0.5 0.5' : e.style.dash;
top.stroke({'dasharray': pattern});
}
if(e.style.opacity!==undefined) {
top.stroke({opacity: e.style.opacity});
}
}
const real_vertices = vertices.slice(0,adjacency_matrix.length);
real_vertices.forEach((n,i) => {
const c = draw.circle(1*scale).center(n.x,n.y).attr({role:'img'});
if(vertices[i].label) {
c.attr({'aria-label':'Vertex labelled '+vertices[i].label});
}
})
real_vertices.forEach((n,i) => {
if(!n.label) {
return;
}
let nx = 0;
let ny = 0;
adjacency_matrix[i].forEach(function(a,j) {
if(i!=j && a) {
const n2 = vertices[j];
const dx = n2.x-n.x;
const dy = n2.y-n.y;
const d = dx*dx+dy*dy;
nx += dx/d;
ny += dy/d;
}
});
if(nx==0 && ny==0) {
nx = 1;
ny = 1;
}
const nd = Math.sqrt(nx*nx+ny*ny);
const r = 1.5;
const [cx,cy] = [n.x-r*nx/nd,n.y-r*ny/nd];
const t = draw.text(n.label).font({size:1*scale,anchor:'top'}).center(cx,cy);
const b = t.bbox();
const pad = 0;
t.before(draw.line(cx,cy,n.x,n.y).stroke({width:0.05*scale,color:'gray'}));
t.before(draw.ellipse(b.w+2*pad,b.h+2*pad).move(b.x-pad,b.y-pad).fill('white'))
});
draw.viewbox(minx-margin,miny-margin,maxx-minx+2*margin,maxy-miny+2*margin)
return draw.node;
}
/** Lay out the graph as nicely as possible, so that vertices are spaced apart and edges try not to cross.
* It still makes edges cross unnecessarily sometimes.
*
*/
auto_layout() {
const w = 2;
const vertices = this.vertices.map(v => { return {x: v.x, y: v.y, width: w, height: w} });
const edges = this.edges.map(e => { return { source: e.from, target: e.to, weight: e.weight} });
const m = this.adjacency_matrix;
const loops = [];
for(let i=0;i<m.length;i++) {
if(m[i][i]) {
vertices.push({x:Math.random(),y:Math.random(), width: 0.2, height: 0.2});
edges.push({source:i,target:vertices.length-1,weight:0.1})
loops.push(i);
}
}
const adaptor = cola.adaptor({})
.avoidOverlaps(true)
.linkDistance(5)
// .jaccardLinkLengths(5)
;
adaptor.nodes(vertices);
adaptor.links(edges)
adaptor.start();
// spend at most 100ms laying out the graph
const t1 = new Date();
while(!adaptor.tick() && (new Date())-t1<100) {
}
const n = this.vertices.length;
const nodes = adaptor.nodes();
const positions = nodes.slice(0,n);
const loop_positions = {};
loops.forEach((vn,i) => {
loop_positions[vn] = nodes[n+i];
});
this.set_vertex_positions(positions, loop_positions);
}
/** Lay out this graph as bipartite, with the vertices arranged in two vertical rows.
*
* @param {Array.<boolean>} left - For each vertex, whether it is on the left-hand side or not.
*/
bipartite_layout(left) {
const num_vertices = this.vertices.length;
const numleft = left.filter(x=>x).length;
const numright = num_vertices - numleft;
const yspace = 5;
const xspace = 5;
let ly = 0;
let ry = (numleft-numright)*yspace/2;
const positions = [];
for(let i=0;i<num_vertices;i++) {
if(left[i]) {
positions.push({x: 0, y: ly});
ly += yspace;
} else {
positions.push({x: xspace, y: ry});
ry += yspace;
}
}
this.set_vertex_positions(positions);
}
/** Set positions for the vertices in this graph.
*
* @param {Array.<Object>} positions - Objects with properties `x` and `y`.
* @param {Array.<Object>} loop_positions - Objects with properties `x` and `y`, for positioning the virtual vertices made for drawing loops.
* @returns {Graph} - this
*/
set_vertex_positions(positions, loop_positions) {
this.vertices.forEach((v,i) => { v.x = positions[i].x; v.y = positions[i].y; });
this.loop_positions = loop_positions || {};
return this;
}
/** Set labels for vertices in this graph.
*
* @param {Array.<string>} labels
* @returns {Graph} - this
*/
set_vertex_labels(labels) {
this.vertices.forEach((v,i) => v.set_label(labels[i]));
return this;
}
/** Set the weights of the edges in this graph.
*
* @param {Array.<number>} weights
* @returns {Graph} - this
*/
set_edge_weights(weights) {
this.edges.forEach((e,i) => e.weight = weights[i]);
return this;
}
/** Set the labels of the edges in this graph.
*
* @param {Array.<string>} labels
* @returns {Graph} - this
*/
set_edge_labels(labels) {
this.edges.forEach((e,i) => e.set_label(labels[i]));
return this;
}
/** Set the styles of the edges in this graph.
*
* @param <Array.<Object>} styles
* @returns {Graph} - this
*/
set_edge_styles(styles) {
this.edges.forEach((e,i) => e.set_style(styles[i]));
return this;
}
/** Get the degree of each of the vertices in this graph.
*
* @returns {Array.<number>}
*/
vertex_degrees() {
const adjacency = this.adjacency_matrix;
const degrees = [];
for(let i=0;i<adjacency.rows;i++) {
let d = 0;
for(let j=0;j<adjacency.columns;j++) {
d += adjacency[i][j] != 0 ? 1 : 0;
}
degrees.push(d);
}
return degrees;
}
/** Make the union of several graphs.
*
* @param {...Array.<Graph>} arguments
* @returns {Graph}
*/
static union(g) {
let {vertices, edges, adjacency_matrix} = g;
for(let i=1;i<arguments.length;i++) {
const b = arguments[i];
const n = [];
n.rows = adjacency_matrix.rows + b.adjacency_matrix.rows;
n.columns = adjacency_matrix.columns + b.adjacency_matrix.columns;
for(let y=0;y<n.rows;y++) {
const row = [];
n.push(row);
for(let x=0;x<n.columns;x++) {
let a = 0;
if(x<adjacency_matrix.columns && y<adjacency_matrix.rows) {
a = adjacency_matrix[y][x];
} else if(x>=adjacency_matrix.columns && y>=adjacency_matrix.rows) {
a = b.adjacency_matrix[y-adjacency_matrix.rows][x-adjacency_matrix.columns];
}
row.push(a);
}
}
adjacency_matrix = n;
const osize = vertices.length;
vertices = vertices.concat(b.vertices.map(v=>{
v = v.copy();
v.x += 1;
return v;
}));
edges = edges.concat(b.edges.map(e => {
const e2 = e.copy();
e2.from = e.from + osize;
e2.to = e.to + osize;
return e2;
}));
}
return new Graph(adjacency_matrix, vertices, edges);
}
/** Make the Cartesian product of several graphs.
* The Cartesian product of two graphs A and B has:
* * a vertex for each pair (a,b) of vertices from A and B.
* * an edge between (a1,b1) and (a2,b2) iff a1==a2 and b1 is adjacent to b2 in B, or b1==b2 and a1 is adjacent to a2 in A.
*
* Vertex and edge labels are lost until I have time to work out how to make them match up!
*
* @param {...Array.<Graph>} arguments
* @returns {Graph}
*/
static cartesian_product(g) {
let {vertices, edges, adjacency_matrix} = g;
for(let i=1;i<arguments.length;i++) {
const b = arguments[i];
const n = [];
const sm = adjacency_matrix.rows;
const size = adjacency_matrix.rows*b.adjacency_matrix.rows;
n.rows = n.columns = size;
for(let y=0;y<size;y++) {
const row = [];
n.push(row);
const yk = (y-(y%sm))/sm;
for(let x=0;x<size;x++) {
const xk = (x-(x%sm))/sm;
let a = b.adjacency_matrix[yk][xk] && (x%sm)==(y%sm) ? 1 : 0;
if(xk==yk) {
a = adjacency_matrix[y-yk*sm][x-xk*sm];
}
row.push(a);
}
}
adjacency_matrix = n;
}
return new Graph(adjacency_matrix);
}
/** Make the direct product of several graphs.
* The direct product of two graphs A and B has:
* * a vertex for each pair (a,b) of vertices from A and B.
* * an edge between (a1,b1) and (a2,b2) iff there is an edge between a1 and a2 in A, and an edge between b1 and b2 in B.
*
* @param {...Array.<adjacency_matrix>} arguments
* @returns {adjacency_matrix}
*/
static direct_product(g) {
let {vertices, edges, adjacency_matrix} = g;
for(let i=1;i<arguments.length;i++) {
const b = arguments[i];
const n = [];
const sm = adjacency_matrix.rows;
const size = adjacency_matrix.rows*b.adjacency_matrix.rows;
n.rows = n.columns = size;
for(let y=0;y<size;y++) {
const row = [];
n.push(row);
const yk = (y-(y%sm))/sm;
for(let x=0;x<size;x++) {
const xk = (x-(x%sm))/sm;
let a = b.adjacency_matrix[yk][xk] && adjacency_matrix[y%sm][x%sm] ? 1 : 0;
row.push(a);
}
}
adjacency_matrix = n;
}
return new Graph(adjacency_matrix);
}
/** Permute the graph's vertices.
*
* @param {permutation} p - For each vertex in the graph, its index in the permuted graph.
* @returns {Graph}
*/
permute_vertices(p) {
const adjacency_matrix = this.adjacency_matrix.map((row,y) => { return row.map((c,x) => { return this.adjacency_matrix[p[y]][p[x]]; }) });
adjacency_matrix.rows = this.adjacency_matrix.rows;
adjacency_matrix.columns = this.adjacency_matrix.columns;
const vertices = p.map(x => this.vertices[x]);
const edges = this.edges.map(e => {
const e2 = e.copy();
e2.from = p[e.from];
e2.to = p[e.to];
return e2;
});
return new Graph(adjacency_matrix, vertices, edges);
}
/** Is the given permutation an isomorphism of this graph?
* True if there is an edge `(p(a),p(b))` iff there is an edge `(a,b)`.
*
* @param {permutation} p
* @returns {boolean}
*/
is_isomorphism(p) {
const m = this.adjacency_matrix;
if(p.length != m.rows) {
throw(new Error("Error testing if a permutation is a graph isomorphism: the permutation must have the same size as the graph."));
}
const pm = this.permute_vertices(p).adjacency_matrix;
for(let y=0;y<m.rows;m++) {
for(let x=0;x<m.columns;x++) {
if(m[y][x] - pm[y][x]!=0) {
return false;
}
}
}
return true;
}
/** A matrix showing the weights of edges between vertices, based on the edges.
*
* @returns {Array.<Array.<number>>}
*/
weight_matrix() {
const matrix = this.adjacency_matrix.map(row=>row.map(()=>null));
for(let e of this.edges) {
matrix[e.from][e.to] = e.weight;
if(!e.directed) {
matrix[e.to][e.from] = e.weight;
}
}
matrix.rows = this.adjacency_matrix.rows;
matrix.columns = this.adjacency_matrix.columns;
return matrix;
}
/** An HTML table showing the weights of the edges between vertices in this graph.
*
* @returns {Element}
*/
weight_table() {
const {vertices, edges} = this;
const table = document.createElement('table');
table.classList.add('weight-matrix');
const header_row = document.createElement('tr');
header_row.appendChild(document.createElement('th'));
table.appendChild(header_row);
this.vertices.forEach(v => {
const th = document.createElement('th');
th.textContent = v.label;
header_row.appendChild(th);
});
this.weight_matrix().forEach((row,i) => {
const tr = document.createElement('tr');
table.appendChild(tr);
const th = document.createElement('th');
th.textContent = vertices[i].label;
tr.appendChild(th);
row.forEach((x,i) => {
const td = document.createElement('td');
td.textContent = x===null ? '' : x;
tr.appendChild(td);
});
});
return table;
}
/** Find a minimum spanning forest of a weighted graph, using Kruskal's algorithm.
*
* @returns {Object.<Graph,WorkingOut>} - A copy of this graph with only the edges in the minimum spanning forest.
*/
annotated_kruskals_algorithm() {
let {edges, vertices} = this;
edges = edges.slice();
edges.sort(Numbas.util.sortBy('weight'));
const n = this.vertices.length;
let forest = [];
const out = [];
const working = new WorkingOut(
4,
data => {
return {
remaining_edges: edges.filter(e => forest[e.from] != forest[e.to]),
included_edges: out.slice(),
forest: Numbas.util.copyobj(forest)
}
},
(container,step) => {
const explanation = document.createElement('p');
explanation.classList.add('explanation');
explanation.innerHTML = step.explanation || '';
container.appendChild(explanation);
const g = this.copy();
const forest_list = document.createElement('ul');
for(let c of new Set(Object.values(step.forest))) {
const li = document.createElement('li');
const vs = [];
for(let [i,j] of Object.entries(step.forest)) {
if(j==c) {
vs.push(vertices[i]);
}
}
li.textContent = vs.map(v => v.label).join(', ');
forest_list.appendChild(li);
}
const edge_table = document.createElement('table');
step.remaining_edges.forEach(e => {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${vertices[e.from].label}</td><td>${vertices[e.to].label}</td><td>${e.weight}</td>`;
edge_table.appendChild(tr);
});
g.edges = this.edges.map(e => {
const e2 = e.copy();
if(step.included_edges.contains(e)) {
e2.set_style({width:2});
} else if(step.remaining_edges.contains(e)) {
e2.set_style({opacity:0.5, dash:true});
} else {
e2.set_style({opacity:0.1});
}
return e2;
}).filter(e=>e);
if(!step.no_graph) {
container.appendChild(g.draw());
}
container.appendChild(edge_table);
if(!step.no_forest) {
container.appendChild(forest_list);
}
}
);
working.add_step({
explanation: 'Sort the edges by weight.',
no_forest: true
});
for(let i=0;i<n;i++) {
forest.push(i);
}
working.add_step({
explanation: 'Initially, each vertex is in its own component.'
});
for(let e of edges) {
if(forest[e.from]!=forest[e.to]) {
out.push(e);
working.add_step({
explanation: `Find the edge with the lowest weight. This is the edge from ${vertices[e.from].label} to ${vertices[e.to].label}. Connect the two trees containing ${vertices[e.from].label} and ${vertices[e.to].label}.`
});
const [from,to] = [forest[e.from], forest[e.to]];
const removing_edges = [];
for(let e2 of edges) {
if(e2 != e && ((forest[e2.from]==from && forest[e2.to]==to) || (forest[e2.to]==from && forest[e2.from]==to))) {
removing_edges.push(e2);
}
}
forest = forest.map(i => i==from ? to : i);
if(removing_edges.length) {
working.add_step({
explanation: `Remove any other edges joining those two trees.`,
removing_edges: removing_edges
});
}
}
}
working.add_step({
explanation: "All edges have been considered, so the algorithm stops.",
no_forest: true,
no_graph: true
});
return {graph: this.subgraph_by_edges(out), working: working};
}
/** Find a minimum spanning forest of a weighted graph, using Kruskal's algorithm.
*
* @returns {Graph} - A copy of this graph with only the edges in the minimum spanning forest.
*/
kruskals_algorithm() {
return this.annotated_kruskals_algorithm().graph;
}
/** Find a minimum spanning tree of a weighted graph, using Prim's algorithm.
* The graph must be connected.
*
* @returns {Object.<Graph,WorkingOut>} - A copy of this graph with only the edges in the minimum spanning tree.
*/
annotated_prims_algorithm() {
let {edges, vertices} = this;
edges = edges.slice();
edges.sort(Numbas.util.sortBy('weight'));
const n = this.vertices.length;
const out = [];
const included = {};
const working = new WorkingOut(
3,
data => {
return {
included_edges: out.slice(),
included_vertices: Numbas.util.copyobj(included),
n: n,
}
},
(container,step) => {
if(step.explanation) {
const explanation = document.createElement('p');