-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
graph.mjs
1463 lines (1288 loc) · 41.9 KB
/
graph.mjs
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
import Edge from './edge.mjs';
import Vertex from './vertex.mjs';
import BfsResult from './algo/bfs.mjs';
import DfsResult from './algo/dfs.mjs';
import { isDefined, isUndefined } from '../common/basic.mjs';
import { ERROR_MSG_INVALID_ARGUMENT, ERROR_MSG_VERTEX_DUPLICATED, ERROR_MSG_VERTEX_NOT_FOUND } from '../common/errors.mjs';
import { consistentStringify } from '../common/strings.mjs';
import { isNumber, range } from '../common/numbers.mjs';
import { ERROR_MSG_EDGE_NOT_FOUND } from '../common/errors';
import { size } from '../common/basic.mjs';
import { ERROR_MSG_INVALID_LABEL } from '../common/errors.mjs';
import { ERROR_MSG_INVALID_DATA } from '../common/errors.mjs';
const _vertices = new WeakMap();
/** @class Graph
*
* This module exports two classes to create instances of graphs objects.
* It is possible to create both directed graphs (default Graph)
* and undirected graphs (via the UndirectedGraph class).
* Hypergraphs are not available yet, so for both directed and undirected graphs,
* parallel edges are forbidden, although loops are not.
* After creating each graph instance, a number of algorithms can be run on it:
* - DFS
* - BFS
* - Kruskal and Prim's algorithms (on undirected graphs) (ToDo)
* - Connected components
* - Strongly connected components
* - Dijkstra's (ToDo)
* - Bellman-Ford's (ToDo)
* - Floyd-Warshall's (ToDo)
* - ...
*/
class Graph {
/**
* @method fromJson
* @for Graph.class
*
* Takes a string with the JSON encoding of a graph, and creates a new Graph object based on it.
*
* @param {*} json The string with the graph's JSON encoding, as outputed by Graph.toJson.
*/
static fromJson(json) {
return Graph.fromJsonObject(JSON.parse(json));
}
/**
* @method fromJsonObject
* @for Graph.class
*
* Takes a plain object with fields for a graph's vertices and edges, each encoded as a JSON string, and
* created a new Graph matching the JSON provided.
* The argument for this method is, ideally, the output of JSON.parse(g.toJson()), where g is an instance of Graph.
*
* @param {Array} vertices An array with the JSON for the vertices to be
*/
static fromJsonObject({ vertices, edges }) {
let g = new Graph();
vertices.forEach(v => g.addVertex(MutableVertex.fromJsonObject(v)));
edges.forEach(e => g.addEdge(Edge.fromJsonObject(e)));
return g;
}
static completeGraph(n) {
if (!isNumber(n) || n < 2) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('Graph.completeGraph', 'n', n));
}
let g = new Graph();
let vertexIDs = [];
const r = range(1, n + 1);
r.forEach(i => vertexIDs[i] = g.createVertex(i));
r.forEach(i =>
range(i + 1, n + 1).forEach(j => {
g.createEdge(vertexIDs[i], vertexIDs[j]);
g.createEdge(vertexIDs[j], vertexIDs[i]);
}));
return g;
}
static completeBipartiteGraph(n, m) {
if (!isNumber(n) || n < 1) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('Graph.completeBipartiteGraph', 'n', n));
}
if (!isNumber(m) || m < 1) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('Graph.completeBipartiteGraph', 'm', m));
}
let g = new Graph();
let vertexIDs = [];
const r1 = range(1, n + 1);
const r2 = range(n + 1, n + m + 1);
r1.forEach(i => vertexIDs[i] = g.createVertex(i));
r2.forEach(j => vertexIDs[j] = g.createVertex(j));
r1.forEach(i => r2.forEach(j => {
g.createEdge(vertexIDs[i], vertexIDs[j]);
g.createEdge(vertexIDs[j], vertexIDs[i]);
}));
return g;
}
constructor() {
_vertices.set(this, new Map());
}
/**
* @property id
* @getter
* @description
* A unique ID, uniquely identifying graphs (based on vertices' and edges' IDs, not optional properties)
*/
get id() {
return `${this.vertices.map(v => `{${v.id}}`).sort().join('')}|${this.edges.map(e => e.id).sort().join('')}`;
}
/**
*
*/
get vertices() {
return [...getVertices(this)];
}
get edges() {
return [...getEdges(this)];
}
/**
* @property simpleEdges
* @getter
* @for Graph
*
* @description
* Returns a list of all edges in the graph, except loops.
*
* @return {Array<Edge>} A list of the simple edges of the graph.
*/
get simpleEdges() {
// We can just check IDs, because they are unique in a graph.
return [...getEdges(this)].filter(e => e.source.id !== e.destination.id);
}
/**
* @name isDirected
* @for Graph
* @description
* States if the graph is a directed graph (true) or an undirected one.
* @return {boolean}
*/
isDirected() {
return true;
}
isEmpty() {
return this.vertices.length === 0;
}
createVertex(name, { weight, label, data } = {}) {
if (this.hasVertex(Vertex.idFromName(name))) {
throw new Error(ERROR_MSG_VERTEX_DUPLICATED('Graph.createVertex', name));
}
const v = new MutableVertex(name, { weight: weight, label: label, data: data });
let vcs = _vertices.get(this);
vcs.set(v.id, v);
_vertices.set(this, vcs);
return v.id;
}
addVertex(vertex) {
if (!(vertex instanceof Vertex)) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('Graph.addVertex', vertex));
}
let vcs = _vertices.get(this);
if (this.hasVertex(vertex.id)) {
throw new Error(ERROR_MSG_VERTEX_DUPLICATED('Graph.addVertex', vertex));
}
const v = new MutableVertex(vertex.name, { weight: vertex.weight, label: vertex.label ?? undefined, data: vertex.data ?? undefined });
vcs.set(vertex.id, v);
_vertices.set(this, vcs);
return v.id;
}
hasVertex(vertex) {
const v = getGraphVertex(this, vertex);
return isDefined(v) && (v instanceof MutableVertex);
}
getVertex(vertex) {
return getGraphVertex(this, vertex);
}
/**
* For a regular graph, returns the size of the adjacency vector for this vertex (as to each destination,
* at most one edge is allowed).
* @returns {*}
*/
getVertexOutDegree(vertex) {
const v = getGraphVertex(this, vertex);
return v?.outDegree();
}
getVertexWeight(vertex) {
const v = getGraphVertex(this, vertex);
return v?.weight ?? throwVertexNotFoundError('Graph.getVertexWeight', vertex);
}
setVertexWeight(vertex, weight) {
if (!isNumber(weight)) {
throw new TypeError(ERROR_MSG_INVALID_ARGUMENT('Graph.setVertexWeight', 'weight', weight));
}
let v = getGraphVertex(this, vertex);
if (isDefined(v)) {
v.weight = weight;
} else {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.setVertexWeight', vertex));
}
}
getVertexLabel(vertex) {
const v = getGraphVertex(this, vertex);
return v?.label ?? throwVertexNotFoundError('Graph.getVertexLabel', vertex);
}
setVertexLabel(vertex, label) {
if (!Vertex.isValidLabel(label)) {
throw new TypeError(ERROR_MSG_INVALID_LABEL('Graph.setVertexLabel', label));
}
let v = getGraphVertex(this, vertex);
if (isDefined(v)) {
v.label = label;
} else {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.setVertexLabel', vertex));
}
}
getVertexData(vertex) {
const v = getGraphVertex(this, vertex);
return v?.data ?? throwVertexNotFoundError('Graph.getVertexData', vertex);
}
setVertexData(vertex, data) {
if (!Vertex.isValidData(data)) {
throw new TypeError(ERROR_MSG_INVALID_DATA('Graph.setVertexData', data));
}
let v = getGraphVertex(this, vertex);
if (isDefined(v)) {
v.data = data;
} else {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.setVertexData', vertex));
}
}
createEdge(source, destination, { weight, label } = {}) {
if (!this.hasVertex(source)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.createEdge', source));
}
if (!this.hasVertex(destination)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.createEdge', destination));
}
const u = getGraphVertex(this, source);
const v = getGraphVertex(this, destination);
return u.addEdgeTo(v, { edgeWeight: weight, edgeLabel: label }).id;
}
addEdge(edge) {
if (!(edge instanceof Edge)) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('Graph.addEdge', edge));
}
if (!this.hasVertex(edge.source)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.addEdge', edge.source));
}
if (!this.hasVertex(edge.destination)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.addEdge', edge.destination));
}
const u = getGraphVertex(this, edge.source);
const v = getGraphVertex(this, edge.destination);
return u.addEdgeTo(v, { edgeWeight: edge.weight, edgeLabel: edge.label }).id;
}
/**
*
* @param {Edge|string} edge Either a string with the edge's id, or an instance of Edge
*/
hasEdge(edge) {
return isDefined(this.getEdge(edge));
}
hasEdgeBetween(source, destination) {
const e = getGraphEdge(this, source, destination);
return isDefined(e) && (e instanceof Edge);
}
getEdgeBetween(source, destination) {
return getGraphEdge(this, source, destination);
}
getEdge(edge) {
edge = edgeId(edge);
for (const e of getEdges(this)) {
if (e.id === edge) {
return e;
}
}
return undefined;
}
*getEdgesFrom(vertex) {
const u = getGraphVertex(this, vertex);
if (isUndefined(u)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.getEdgesFrom', vertex));
}
yield* u.outgoingEdges();
}
/**
* @method getEdgesInPath
* @for Graph
* @description
* Takes a path, in the form of a sequence of vertices, and returns the sequence of edges in the path.
*
* @param {Array} verticesSequence The sequence of vertices in a path, from start to end.
* @return {Array<Edge>} The list of edges to get from the first to the last vertex in the path.
*/
getEdgesInPath(verticesSequence) {
if (!Array.isArray(verticesSequence)) {
throw new TypeError(ERROR_MSG_INVALID_ARGUMENT('Graph.getEdgesInPath', 'verticesSequence', verticesSequence));
}
const n = verticesSequence.length;
const edges = [];
for (let i = 0; i < n - 1; i++) {
const source = vertexId(verticesSequence[i]);
const dest = vertexId(verticesSequence[i + 1]);
const e = this.getEdgeBetween(source, dest);
if (!isDefined(e)) {
throw new Error(ERROR_MSG_EDGE_NOT_FOUND('Graph.getEdgesInPath', `${source}->${dest}`));
}
edges.push(e);
}
return edges;
}
setEdgeWeight(edge, weight) {
if (!isNumber(weight)) {
throw new TypeError(ERROR_MSG_INVALID_ARGUMENT('Graph.setEdgeWeight', 'weight', weight));
}
const e = this.getEdge(edge);
if (isDefined(e)) {
e.weight = weight;
} else {
throw new Error(ERROR_MSG_EDGE_NOT_FOUND('Graph.setEdgeWeight', edge));
}
}
/**
* Shortcut to avoid edge cloning
* @param {*} sourceName
* @param {*} destinationName
*/
getEdgeWeight(sourceName, destinationName) {
const e = getGraphEdge(this, sourceName, destinationName);
if (isDefined(e)) {
return e.weight;
} else {
throw new Error(ERROR_MSG_EDGE_NOT_FOUND('Graph.getEdgeWeight', `${sourceName} -> ${destinationName}`));
}
}
/**
* Shortcut to avoid edge cloning
* @param {*} sourceName
* @param {*} destinationName
*/
getEdgeLabel(sourceName, destinationName) {
const e = getGraphEdge(this, sourceName, destinationName);
return e?.label;
}
/**
* @method inducedSubGraph
* @for Graph
*
* @description
* Computes the induced sub-graph of this graph, given a subset of its vertices.
* The induced sub-graph of a graph G is a new graph, with only a subset of its vertices; only the edges in G
* that are adjacent to vertices in the sub-graph are included.
* @param {Set<Vertex|String>|Array<Vertex|String>} vertices A non-empty subset of this graph's vertices.
*
* @return {Graph} The sub-graph induced by vertices.
*/
inducedSubGraph(vertices) {
return inducedSubGraph(this, vertices);
}
clone() {
const g = new Graph();
for (const v of getVertices(this)) {
g.addVertex(v.clone());
}
for (const e of getEdges(this)) {
g.addEdge(e.clone());
}
return g;
}
/**
* @override
*/
toString() {
return [...this.edges].map(e => e.toString()).sort().join(', ');
}
toJson() {
return consistentStringify(this.toJsonObject());
}
toJsonObject() {
return {
vertices: [...getVertices(this)].sort().map(v => v.toJsonObject()),
edges: [...getEdges(this)].sort(Edge.compareEdges).map(e => e.toJsonObject())
};
}
equals(g) {
return (g instanceof Graph) && this.toJson() === g.toJson();
}
// ALGORITHMS
/**
* @method isConnected
* @for Graph
*
* @description
* Check if the graph is connected, i.e., for a directed graph, if its symmetric closure has a single
* connected component comprising all vertices.
* A connected component is a set CC of vertices in an undirected graph such that from each vertex in CC you can
* reach all other vertices in CC.
*
* @return {boolean} True iff the graph is connected.
*/
isConnected() {
return this.symmetricClosure().isConnected();
}
/**
* @method isStronglyConnected
* @for UndirectedGraph
*
* @description
* Check if the graph is connected, i.e. if there is a single strongly connected component comprising all vertices.
* A strongly connected component is a set CC of vertices in a directed graph such that from each vertex in CC you can
* reach all other vertices in CC. In undirected graphs, connected components are also strongly connected components.
*
* @return {boolean} True iff the graph is connected.
*/
isStronglyConnected() {
return this.stronglyConnectedComponents().size === 1;
}
/**
* @method isAcyclic
* @for Graph
* @description
* Check if a graph is acyclic, or if it has a cycle.
*
* @return {boolean} True iff the graph is acyclic.
*/
isAcyclic() {
const dfsResult = this.dfs();
return dfsResult.isAcyclic();
}
/**
* @method isBipartite
* @for Graph
*
* @description
* Check if a graph is a bipartite graph, i.e. vertices can be partitioned into two non-empty sets, say A and B,
* such that vertices in A are only connected to vertices in B: there is no edge (u,v) such that u is in A and v in B,
* or vice versa.
*
* @return {[boolean, Set<String>, Set<String>]} The first entry is true iff the graph is bipartite.
* The two partitions are null if the graph is not bipartite,
* otherwise they are two Sets with the indices of the vertices
* in the partition.
*/
isBipartite() {
// The symmetric closure of a directed graph is certainly an undirected graph.
return this.symmetricClosure().isBipartite();
}
/**
* @method isComplete
* @for Graph
*
* @description
* Check if a graph is a complete graph, i.e. every vertex is adjacent to all the other vertices.
*
* @return {boolean} True iff the graph is complete.
*/
isComplete() {
const n = this.vertices.length;
const m = this.simpleEdges.length;
return m === n * (n - 1);
}
/**
* @method isCompleteBipartite
* @for Graph
*
* @description
* Check if a graph is a complete bipartite graph, i.e. the graph is bipartite and
* every vertex on the first partition is adjacent to all, and just, the vertices in the other partition.
*
* @return {boolean} True iff the graph is complete bipartite.
*/
isCompleteBipartite() {
const [bipartite, partition1, partition2] = this.isBipartite();
const m = this.simpleEdges.length;
// In directed graphs there are 2 edges between each pair of vertices across the partitions
return bipartite && m === 2 * partition1.size * partition2.size;
}
/**
* @method symmetricClosure
* @for Graph
*
* @description
* Computes the symmetric closure of this instance.
* The symmetric closure of a graph G is a new graph G' that has both edges, (u,v) and (v,u),
* whenever graph G has either the edge (u,v) or (v,u) (or both).
* Informally, the symmetric closure of the directed graph G is an undirected graph G' with the same edges,
* but disregarding their direction.
* WARNING: edges in symmetric closure won't retain any of the original labels.
* This is because, in case a direct graph has both edges (u,v) and (v,u), but with different labels,
* then it wouldn't be possible to have a consistent undirected edge by choosing either label.
* Conversely, if both edges are present, we can use the sum of the weights as the weight of the undirected edge.
*
* @return {Graph} The symmetric closure graph of this instance, as a new graph.
*/
symmetricClosure() {
let graph = new UndirectedGraph();
for (const v of this.vertices) {
graph.addVertex(v);
}
for (const e of this.edges) {
if (!graph.hasEdge(e)) {
const eT = this.getEdgeBetween(e.destination, e.source)
let weight = e.weight + (eT?.weight ?? 0);
// Leverages the nature of undirected graphs: when you add an edge, it also adds its symmetric.
graph.createEdge(e.source, e.destination, { weight: weight });
}
}
return graph;
}
/**
* @method transpose
* @for Graph
*
* @description
* Computes the transposed graph of this instance.
* The transpose graph G' of a graph G is a new graph that has an edge (u,v) if and only if
* G has an edge (v,u).
*
* @return {Graph} The transposed graph of this instance, as a new graph.
*/
transpose() {
let graph = new Graph();
for (const v of this.vertices) {
graph.addVertex(v);
}
for (const e of this.edges) {
graph.addEdge(e.transpose());
}
return graph;
}
/**
* @method transitiveClosure
* @for Graph
*
* @description
* Computes the transitive closure of this graph.
* The transitive closure of a Graph G is a new graph G' with an edge (u,v) for each pair
* of vertices in G such that there is a path (in G) from u to v.
*
* @return {Graph} The transitive closure of this instance, as a new graph.
*/
transitiveClosure() {
throw new Error("Unimplemented");
}
/**
* @method bfs
* @for Graph
* @param {Vertex|string} start
* @return {BfsResult}
*/
bfs(start) {
const s = this.getVertex(start);
if (!isDefined(s)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.bfs', start));
}
let distance = {};
let predecessor = {};
for (const v of this.vertices) {
distance[v.id] = Infinity;
}
distance[s.id] = 0;
predecessor[s.id] = null;
let queue = [s];
while (queue.length > 0) {
const u = queue.pop(0);
const adj = u.outgoingEdges();
for (const e of adj) {
const v = e.destination;
if (distance[v.id] === Infinity) {
predecessor[v.id] = u.id;
distance[v.id] = distance[u.id] + 1;
queue.push(v);
}
}
}
return new BfsResult(distance, predecessor);
}
/**
* @method dfs
* @for Graph
*
* @return {DfsResult}
*/
dfs() {
let timeDiscovered = {};
let timeVisited = {};
let currentTime = 0;
let acyclic = true;
this.vertices.forEach(v => {
if (!timeDiscovered[v.id]) {
timeDiscovered[v.id] = ++currentTime;
[currentTime, acyclic] = dfs(this, v, timeDiscovered, timeVisited, acyclic, currentTime);
}
});
return new DfsResult(timeDiscovered, timeVisited, acyclic)
}
/**
* @method connectedComponents
* @for Graph
*
* @description
* Computes the connected components of a graph. A connected component is a set of vertices CC such that from
* each vertex u belonging CC there is a path in the symmetric closure of this graph to every other vertex v belonging
* to CC.
*
* @return {Set<Set<String>>} A collection of the connected components in the graph: each cc being returned as a set
* of the indices of the vertices in it.
*/
connectedComponents() {
return this.symmetricClosure().connectedComponents();
}
/**
* @method topologicalOrdering
* @for Graph
*
* @description
* Return one of the possible topological orderings of vertices, if the graph is a DAG (direct, acyclic graph).
* If the graph is not acyclic, returns null.
*
* @return {null|Array<String>} If a topological ordering is defined, returns a list of vertex' IDs. Otherwise, null.
*/
topologicalOrdering() {
const dfs = this.dfs();
if (dfs.isAcyclic()) {
return dfs.verticesByVisitOrder();
} else {
// Topological ordering is defined only for
return null;
}
}
/**
* @method stronglyConnectedComponents
* @for Graph
*
* @description
* Computes the strongly connected components of a graph. A connected component for a directed graph is a set of vertices
* SCC such that from each vertex u belonging CC there is a path in this graph to every other vertex v belonging to CC.
* So that, for each couple of vertices u, v, v is reachable from u and, vice versa, u is reachable from v.
*/
stronglyConnectedComponents() {
// Implements Kosaraju's algorithm
const ordering = this.transpose().dfs().verticesByVisitOrder();
let timeDiscovered = {};
let currentTime = 0;
let stronglyConnectedComponents = new Set();
ordering.forEach(vID => {
if (!timeDiscovered[vID]) {
let timeVisited = {};
let acyclic = true; // lgtm [js/useless-assignment-to-local]
timeDiscovered[vID] = ++currentTime;
[currentTime, acyclic] = dfs(this, this.getVertex(vID), timeDiscovered, timeVisited, acyclic, currentTime); // lgtm [js/useless-assignment-to-local]
// we reset timeVisited at each run of dfs, so the only vertices with an entry are the ones in this CC.
stronglyConnectedComponents.add(new Set(Object.keys(timeVisited)));
}
});
return stronglyConnectedComponents;
}
}
/**
* @class UndirectedGraph
*/
export class UndirectedGraph extends Graph {
static completeGraph(n) {
if (!isNumber(n) || n < 2) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('UndirectedGraph.completeGraph', 'n', n));
}
let g = new UndirectedGraph();
let vertexIDs = [];
const r = range(1, n + 1);
r.forEach(i => vertexIDs[i] = g.createVertex(i));
r.forEach(i =>
range(i + 1, n + 1).forEach(j => {
g.createEdge(vertexIDs[i], vertexIDs[j]);
}));
return g;
}
static completeBipartiteGraph(n, m) {
if (!isNumber(n) || n < 1) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('UndirectedGraph.completeBipartiteGraph', 'n', n));
}
if (!isNumber(m) || m < 1) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('UndirectedGraph.completeBipartiteGraph', 'm', m));
}
let g = new UndirectedGraph();
let vertexIDs = [];
const r1 = range(1, n + 1);
const r2 = range(n + 1, n + m + 1);
r1.forEach(i => vertexIDs[i] = g.createVertex(i));
r2.forEach(j => vertexIDs[j] = g.createVertex(j));
r1.forEach(i => r2.forEach(j => {
g.createEdge(vertexIDs[i], vertexIDs[j]);
}));
return g;
}
/**
* @name squareGrid
* @description
* Creates a special graph: a square mesh with `n` vertices on each side.
*
* @param {Number} n The number of vertices per side: an n by n mesh will be created.
*
* @return {UndirectedGraph} A new square mesh graph.
*/
static squareGrid(n) {
if (!isNumber(n) || n < 1) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('UndirectedGraph.squareGrid', 'n', n));
}
let g = new UndirectedGraph();
range(1, n + 1).forEach(row => {
range(1, n + 1).forEach(col => {
const v = `<${row}><${col}>`;
const vId = g.createVertex(v);
if (row > 1) {
const uId = Vertex.idFromName(`<${row - 1}><${col}>`);
g.createEdge(uId, vId);
}
if (col > 1) {
const uId = Vertex.idFromName(`<${row}><${col - 1}>`);
g.createEdge(uId, vId);
}
})
})
return g;
}
/**
* @name triangularGrid
* @description
* Creates a special graph: a triangular mesh with `n` vertices on each side.
*
* @param {Number} n The number of vertices per side: an n by n mesh will be created.
*
* @return {UndirectedGraph} A new square mesh graph.
*/
static triangularGrid(n) {
if (!isNumber(n) || n < 1) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('UndirectedGraph.squareGrid', 'n', n));
}
let g = new UndirectedGraph();
range(1, n + 1).forEach(row => {
range(1, n - row + 2).forEach(col => {
const v = `<${row}><${col}>`;
const vId = g.createVertex(v);
if (row > 1) {
let uId = Vertex.idFromName(`<${row - 1}><${col}>`);
g.createEdge(uId, vId);
uId = Vertex.idFromName(`<${row - 1}><${col + 1}>`);
g.createEdge(uId, vId);
}
if (col > 1) {
const uId = Vertex.idFromName(`<${row}><${col - 1}>`);
g.createEdge(uId, vId);
}
})
})
return g;
}
/**
* Return all edges in the graph. Since in undirected graphs the direction of an edge doesn't count,
* it deliberately order vertices such that for edge (u,v) u <= v.
*/
get edges() {
// For directed graphs, we only want one of the two directed edges back...
return [...getEdges(this)].filter(e => e.source.id <= e.destination.id);
}
/**
* Return all edges in the graph, except loops. Since in undirected graphs the direction of an edge doesn't count,
* it deliberately order vertices such that for edge (u,v) u < v.
*/
get simpleEdges() {
// For directed graphs, we only want one of the two directed edges back...
return [...getEdges(this)].filter(e => e.source.id < e.destination.id);
}
/**
* @override
*/
isDirected() {
return false;
}
/**
* @override
* @param {*} source
* @param {*} destination
* @param {*} param2
*/
createEdge(source, destination, { weight, label } = {}) {
const eId = super.createEdge(source, destination, { weight: weight, label: label });
const e = super.getEdge(eId);
// Add an each for each direction, unless it's a loop
if (!e.isLoop()) {
super.createEdge(destination, source, { weight: weight, label: label });
}
return e;
}
/**
* @override
* @param {*} edge
*/
addEdge(edge) {
if (!(edge instanceof Edge)) {
throw new Error(ERROR_MSG_INVALID_ARGUMENT('Graph.addEdge', edge));
}
if (!this.hasVertex(edge.source)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.addEdge', edge.source));
}
if (!this.hasVertex(edge.destination)) {
throw new Error(ERROR_MSG_VERTEX_NOT_FOUND('Graph.addEdge', edge.destination));
}
const u = getGraphVertex(this, edge.source);
const v = getGraphVertex(this, edge.destination);
const e = u.addEdgeTo(v, { edgeWeight: edge.weight, edgeLabel: edge.label });
if (!e.isLoop()) {
v.addEdgeTo(u, { edgeWeight: edge.weight, edgeLabel: edge.label });
}
return e;
}
setEdgeWeight(edge, weight) {
if (!isNumber(weight)) {
throw new TypeError(ERROR_MSG_INVALID_ARGUMENT('Graph.setEdgeWeight', 'weight', weight));
}
const e = this.getEdge(edge);
if (isDefined(e)) {
e.weight = weight;
} else {
throw new Error(ERROR_MSG_EDGE_NOT_FOUND('Graph.setEdgeWeight', edge));
}
const eT = this.getEdgeBetween(edge.destination, edge.source);
if (isDefined(eT)) {
eT.weight = weight;
} else {
throw new Error(ERROR_MSG_EDGE_NOT_FOUND('Graph.setEdgeWeight', edge.transpose()));
}
}
clone() {
let g = new UndirectedGraph();
for (const v of getVertices(this)) {
g.addVertex(v.clone());
}
for (const e of getEdges(this)) {
g.addEdge(e.clone());
}
return g;
}
// ALGORITHMS
/**
* @method connectedComponents
* @for UndirectedGraph
*
* @description
* Computes the connected components of a graph. A connected component is a set of vertices CC such that from
* each vertex u belonging CC there is a path in the graph to every other vertex v belonging to CC.
*
* @return {Set<Set<String>>} A collection of the connected components in the graph: each cc being returned as a set
* of the indices of the vertices in it.
*/
connectedComponents() {
let timeDiscovered = {};
let currentTime = 0;
let connectedComponents = new Set();
this.vertices.forEach(v => {
if (!timeDiscovered[v.id]) {
let timeVisited = {};
let acyclic = true; // lgtm [js/useless-assignment-to-local]
timeDiscovered[v.id] = ++currentTime;
[currentTime, acyclic] = dfs(this, v, timeDiscovered, timeVisited, acyclic, currentTime); // lgtm [js/useless-assignment-to-local]
// we reset timeVisited at each run of dfs, so the only vertices with an entry are the ones in this CC.
connectedComponents.add(new Set(Object.keys(timeVisited)));
}
});
return connectedComponents;
}
/**
* @method isConnected
* @for UndirectedGraph
*
* @description
* Check if the graph is connected, i.e. if there is a single connected component comprising all vertices.
* A connected component is a set CC of vertices in an undirected graph such that from each vertex in CC you can
* reach all other vertices in CC.
*
* @return {boolean} True iff the graph is connected.
*/
isConnected() {
return this.connectedComponents().size === 1;
}