1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
//! A module for working with graphs.
use std::{
collections::{BTreeMap, HashMap, HashSet},
hash::Hash,
ops::Sub,
};
use nalgebra::{DMatrix, DVector, SymmetricEigen};
use crate::{betweenness::compute_betweenness, closeness::compute_closeness, edge::Edge};
/// Represents the index of a vertex in various collections.
///
/// For performance reasons it is kept as small as possible.
pub(crate) type GraphIndex = u16;
const MAX_INDICES_NODES: usize = u16::MAX as usize;
/// The minimum number of threads used in multi-threaded implementations.
pub(crate) const MIN_NUM_THREADS: usize = 1;
/// The maximum number of threads used in multi-threaded implementations.
pub(crate) const MAX_NUM_THREADS: usize = 128;
/// An undirected graph, made up of edges.
#[derive(Clone, Debug)]
pub struct Graph<T> {
/// The edges in the graph.
edges: HashSet<Edge<T>>,
/// A mapping of vertices to their indices to be used when constructing the various matrices
/// representing the graph.
///
/// The use of a `BTreeMap` means we need the `Ord` bound on `T`. The sorted collection allows
/// us to maintain some form of order between computations, which can be useful for debugging.
index: Option<BTreeMap<T, usize>>,
/// Cache the degree matrix when possible.
degree_matrix: Option<DMatrix<f64>>,
/// Cache the adjacency matrix when possible.
adjacency_matrix: Option<DMatrix<f64>>,
/// Cache the laplacian matrix when possible.
laplacian_matrix: Option<DMatrix<f64>>,
/// Cache the betweenness count when possible.
betweenness_count: Option<Vec<f64>>,
/// Cache the path lengths when possible.
total_path_length: Option<Vec<u32>>,
}
impl<T> Default for Graph<T>
where
Edge<T>: Eq + Hash,
T: Copy + Eq + Hash + Ord,
{
fn default() -> Self {
Self::new()
}
}
impl<T> Graph<T>
where
Edge<T>: Eq + Hash,
T: Copy + Eq + Hash + Ord,
{
/// Creates an empty graph.
///
/// # Examples
///
/// ```
/// use spectre::graph::Graph;
///
/// let graph: Graph<&str> = Graph::new();
/// ```
pub fn new() -> Self {
Self {
edges: Default::default(),
index: None,
degree_matrix: None,
adjacency_matrix: None,
laplacian_matrix: None,
betweenness_count: None,
total_path_length: None,
}
}
pub fn edges(&mut self) -> &HashSet<Edge<T>> {
&self.edges
}
/// Inserts an edge into the graph.
pub fn insert(&mut self, edge: Edge<T>) -> bool {
let is_inserted = self.edges.insert(edge);
// Delete the cached objects if the edge was successfully inserted because we can't
// reliably update them from the new connection alone.
if is_inserted && self.index.is_some() {
self.clear_cache()
}
is_inserted
}
/// Inserts a subset of `(hub, leaf)` edges into the graph.
pub fn insert_subset(&mut self, hub: T, leaves: &[T]) {
for leaf in leaves {
self.insert(Edge::new(hub, *leaf));
}
}
/// Inserts a subset of `(hub, leaf)` edges into the graph and removes any existing edges that
/// contain the hub but aren't included in the new set.
pub fn update_subset(&mut self, hub: T, leaves: &[T]) {
let new_edges: HashSet<Edge<T>> = leaves.iter().map(|leaf| Edge::new(hub, *leaf)).collect();
// Remove hub-containing edges that aren't included in the new set.
let original_len = self.edge_count();
self.edges
.retain(|edge| new_edges.contains(edge) || !edge.contains(&hub));
// Make sure to clear the cache after removals as there may be no inserts.
// TODO: make more efficient.
if self.edge_count() != original_len {
self.clear_cache()
}
for edge in new_edges {
self.insert(edge);
}
}
/// Removes an edge from the set and returns whether it was present in the set.
///
/// # Examples
///
/// ```
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
/// graph.insert(Edge::new("a", "b"));
///
/// assert_eq!(graph.remove(&Edge::new("a", "b")), true);
/// assert_eq!(graph.remove(&Edge::new("a", "c")), false);
/// ```
pub fn remove(&mut self, edge: &Edge<T>) -> bool {
let is_removed = self.edges.remove(edge);
// Delete the cached objects if the edge was successfully removed because we can't reliably
// update them from the new connection alone.
if is_removed && self.index.is_some() {
self.clear_cache()
}
is_removed
}
/// Checks if the graph contains an edge.
pub fn contains(&self, edge: &Edge<T>) -> bool {
self.edges.contains(edge)
}
/// Returns the vertex count of the graph.
///
/// This call constructs the collection of vertices from the collection of edges. This is
/// because the vertex set can't accurately be updated on the basis of the addition or the
/// removal of an edge alone.
///
/// # Examples
///
/// ```
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
/// graph.insert(Edge::new("a", "b"));
///
/// assert_eq!(graph.vertex_count(), 2);
/// ```
pub fn vertex_count(&self) -> usize {
self.vertices_from_edges().len()
}
/// Returns the edge count of the graph.
pub fn edge_count(&self) -> usize {
self.edges.len()
}
/// Computes the density of the graph, the ratio of edges with respect to the maximum possible
/// edges.
///
/// # Examples
///
/// ```
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
///
/// graph.insert(Edge::new("a", "b"));
/// assert_eq!(graph.density(), 1.0);
///
/// graph.insert(Edge::new("a", "c"));
/// assert_eq!(graph.density(), 2.0 / 3.0);
/// ```
pub fn density(&self) -> f64 {
let vc = self.vertex_count() as f64;
let ec = self.edge_count() as f64;
// Calculate the total number of possible edges given a vertex count.
let pec = vc * (vc - 1.0) / 2.0;
// Actual edges divided by the possible edges gives the density.
ec / pec
}
/// Constructs the adjacency matrix for this graph.
///
/// # Examples
///
/// ```
/// use nalgebra::dmatrix;
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
/// graph.insert(Edge::new("a", "b"));
/// assert_eq!(
/// graph.adjacency_matrix(),
/// dmatrix![0.0, 1.0;
/// 1.0, 0.0]
/// );
/// ```
pub fn adjacency_matrix(&mut self) -> DMatrix<f64> {
// Check the cache.
if let Some(matrix) = self.adjacency_matrix.clone() {
return matrix;
}
self.generate_index();
// Safety: the previous call guarantees the index has been generated and stored.
let n = self.index.as_ref().unwrap().len();
let mut matrix = DMatrix::<f64>::zeros(n, n);
// Compute the adjacency matrix. As our we're assuming the graph is undirected, the adjacency matrix is
// symmetric.
for edge in &self.edges {
// Safety: get the indices for each edge in the graph, these must be present as the
// index was generated from this set of edges.
let i = self.index.as_ref().unwrap().get(edge.source()).unwrap();
let j = self.index.as_ref().unwrap().get(edge.target()).unwrap();
// Since edges are guaranteed to be unique, both the upper and lower triangles must be
// writted (as the graph is unidrected) for each edge.
matrix[(*i, *j)] = 1.0;
matrix[(*j, *i)] = 1.0;
}
// Cache the matrix.
self.adjacency_matrix = Some(matrix.clone());
matrix
}
/// Constructs the degree matrix for this graph.
///
/// # Examples
///
/// ```
/// use nalgebra::dmatrix;
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
/// graph.insert(Edge::new("a", "b"));
/// assert_eq!(
/// graph.degree_matrix(),
/// dmatrix![1.0, 0.0;
/// 0.0, 1.0]
/// );
/// ```
pub fn degree_matrix(&mut self) -> DMatrix<f64> {
// Check the cache.
if let Some(matrix) = self.degree_matrix.clone() {
return matrix;
}
let adjacency_matrix = self.adjacency_matrix();
// Safety: the previous call guarantees the index has been generated and stored.
let n = self.index.as_ref().unwrap().len();
let mut matrix = DMatrix::<f64>::zeros(n, n);
for (i, row) in adjacency_matrix.row_iter().enumerate() {
// Set the diagonal to be the sum of edges in that row. The index isn't necessary
// here since the rows are visited in order and the adjacency matrix is ordered after the
// index.
matrix[(i, i)] = row.sum()
}
// Cache the matrix.
self.degree_matrix = Some(matrix.clone());
matrix
}
/// Constructs the laplacian matrix for this graph.
///
/// # Examples
///
/// ```
/// use nalgebra::dmatrix;
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
/// graph.insert(Edge::new("a", "b"));
/// assert_eq!(
/// graph.laplacian_matrix(),
/// dmatrix![1.0, -1.0;
/// -1.0, 1.0]
/// );
/// ```
pub fn laplacian_matrix(&mut self) -> DMatrix<f64> {
// Check the cache.
if let Some(matrix) = self.laplacian_matrix.clone() {
return matrix;
}
let degree_matrix = self.degree_matrix();
let adjacency_matrix = self.adjacency_matrix();
let matrix = degree_matrix.sub(&adjacency_matrix);
// Cache the matrix.
self.laplacian_matrix = Some(matrix.clone());
matrix
}
/// Returns the difference between the highest and lowest degree centrality in the network.
///
/// Returns an `f64`, though the value should be a natural number.
///
/// # Examples
///
/// ```
/// use spectre::edge::Edge;
/// use spectre::graph::Graph;
///
/// let mut graph = Graph::new();
/// graph.insert(Edge::new("a", "b"));
/// graph.insert(Edge::new("a", "c"));
///
/// assert_eq!(graph.degree_centrality_delta(), 1.0);
/// ```
pub fn degree_centrality_delta(&mut self) -> f64 {
let degree_matrix = self.degree_matrix();
let max = degree_matrix.diagonal().max();
let min = degree_matrix.diagonal().min();
max - min
}
/// Returns a mapping of vertices to their degree centrality (number of connections) in the graph.
pub fn degree_centrality(&mut self) -> HashMap<T, u32> {
let degree_matrix = self.degree_matrix();
// Safety: the previous call guarantees the index has been generated and stored.
self.index
.as_ref()
.unwrap()
.keys()
.zip(degree_matrix.diagonal().iter())
.map(|(addr, dc)| (*addr, *dc as u32))
.collect()
}
/// Returns a mapping of vertices to their eigenvalue centrality (the relative importance of
/// the vertex) in the graph.
pub fn eigenvalue_centrality(&mut self) -> HashMap<T, f64> {
let adjacency_matrix = self.adjacency_matrix();
// Early return if the matrix is empty, the rest of the computation requires a matrix with
// at least a dim of 1x1.
if adjacency_matrix.is_empty() {
return HashMap::new();
}
// Compute the eigenvectors and corresponding eigenvalues and sort in descending order.
let ascending = false;
let eigenvalue_vector_pairs = sorted_eigenvalue_vector_pairs(adjacency_matrix, ascending);
let (_highest_eigenvalue, highest_eigenvector) = &eigenvalue_vector_pairs[0];
// The eigenvector is a relative score of vertex importance (normalised by the norm), to obtain an absolute score for each
// vertex, we normalise so that the sum of the components are equal to 1.
let sum = highest_eigenvector.sum() / self.index.as_ref().unwrap().len() as f64;
let normalised = highest_eigenvector.unscale(sum);
// Map addresses to their eigenvalue centrality.
self.index
.as_ref()
.unwrap()
.keys()
.zip(normalised.column(0).iter())
.map(|(addr, ec)| (*addr, *ec))
.collect()
}
/// Returns the algebraic connectivity (Fiedler eigenvalue) of the graph and a mapping of the
/// vertices to their Fiedler value (their associated component in the Fiedler eigenvector).
pub fn fiedler(&mut self) -> (f64, HashMap<T, f64>) {
let laplacian_matrix = self.laplacian_matrix();
// Early return if the matrix is empty, the rest of the computation requires a matrix with
// at least a dim of 1x1.
if laplacian_matrix.is_empty() {
return (0.0, HashMap::new());
}
// Compute the eigenvectors and corresponding eigenvalues and sort in ascending order.
let ascending = true;
let pairs = sorted_eigenvalue_vector_pairs(laplacian_matrix, ascending);
// Second-smallest eigenvalue of the Laplacian is the Fiedler value (algebraic connectivity), the associated
// eigenvector is the Fiedler vector.
let (algebraic_connectivity, fiedler_vector) = &pairs[1];
// Map addresses to their Fiedler values.
let fiedler_values_indexed = self
.index
.as_ref()
.unwrap()
.keys()
.zip(fiedler_vector.column(0).iter())
.map(|(addr, fiedler_value)| (*addr, *fiedler_value))
.collect();
(*algebraic_connectivity, fiedler_values_indexed)
}
//
// Private
//
/// Clears the computed state.
///
/// This should be called every time the set of edges is mutated since the cached state won't
/// correspond to the new graph.
fn clear_cache(&mut self) {
self.index = None;
self.degree_matrix = None;
self.adjacency_matrix = None;
self.laplacian_matrix = None;
self.betweenness_count = None;
self.total_path_length = None;
}
/// Returns the set of unique vertices contained within the set of edges.
fn vertices_from_edges(&self) -> HashSet<T> {
let mut vertices: HashSet<T> = HashSet::new();
for edge in self.edges.iter() {
// Using a hashset guarantees uniqueness.
vertices.insert(*edge.source());
vertices.insert(*edge.target());
}
vertices
}
/// Constructs and stores an index of vertices for this set of edges.
///
/// The index will be sorted by `T`'s implementation of `Ord`.
fn generate_index(&mut self) {
// It should be impossible to call this function if the cache is not empty.
debug_assert!(self.index.is_none());
let mut vertices: Vec<T> = self.vertices_from_edges().into_iter().collect();
vertices.sort();
let index: BTreeMap<T, usize> = vertices
.iter()
.enumerate()
.map(|(i, &vertex)| (vertex, i))
.collect();
self.index = Some(index);
}
/// This method returns a set connection indices for each node.
/// It a compact way to view the adjacency matrix, and therefore, is
/// used for the computation of betweenness and closeness centralities.
pub fn get_adjacency_indices(&mut self) -> Vec<Vec<GraphIndex>> {
let mut indices: Vec<Vec<GraphIndex>> = Vec::new();
let adjacency_matrix = self.adjacency_matrix();
assert!(
adjacency_matrix.nrows() <= MAX_INDICES_NODES,
"The number of nodes in the graph {} exceeds the maximum number allowed {}",
indices.len(),
MAX_INDICES_NODES
);
for m in 0..adjacency_matrix.nrows() {
let neighbors: Vec<GraphIndex> = adjacency_matrix
.row(m)
.iter()
.enumerate()
.filter(|(_n, &val)| val == 1.0)
.map(|(n, _)| n as GraphIndex)
.collect();
indices.push(neighbors);
}
indices
}
/// This method also outputs an array of index vectors, although it is created differently.
/// It is currently used if filtering of nodes is required.
pub fn get_filtered_adjacency_indices(&self, nodes_to_keep: &Vec<T>) -> Vec<Vec<usize>> {
let num_nodes = nodes_to_keep.len();
let mut indices = Vec::with_capacity(num_nodes);
let mut node_map = HashMap::with_capacity(num_nodes);
for (n, node) in nodes_to_keep.iter().enumerate().take(num_nodes) {
// make initial capacity 10% of total
indices.push(Vec::with_capacity(num_nodes / 10));
node_map.insert(node, n);
}
// For each edge, check if the source and target nodes
// are in our node HashMap. If we've obtained both
// indices, insert into the corresponding connection list
for edge in self.edges.iter() {
if let Some(source_index) = node_map.get(edge.source()) {
if let Some(target_index) = node_map.get(edge.target()) {
indices[*source_index].push(*target_index);
indices[*target_index].push(*source_index);
}
}
}
for node in indices.iter_mut() {
node.shrink_to_fit();
}
indices
}
/// This method returns the betweenness for a given Graph.
///
/// Betweenness: When a shortest path is found, for all nodes in-between (i.e., not an end
/// point), increment their betweenness value. Normalize the counts by dividing by the number
/// of shortest paths found.
pub fn betweenness_centrality(
&mut self,
num_threads: usize,
normalize: bool,
) -> HashMap<T, f64> {
if self.betweenness_count.is_none() {
let betweenness_count =
compute_betweenness(self.get_adjacency_indices(), num_threads, normalize);
self.betweenness_count = Some(betweenness_count);
}
let betweenness_count = self.betweenness_count.as_ref().unwrap();
let mut centralities = HashMap::new();
for (node, i) in self.index.as_ref().unwrap() {
let value = betweenness_count[*i];
centralities.insert(*node, value);
}
centralities
}
/// This method returns the closeness for a given Graph.
///
/// Closeness: for each node, find all shortest paths to all other nodes. Accumulate all path
/// lengths, accumulate number of paths, and then compute average path length.
pub fn closeness_centrality(&mut self, num_threads: usize) -> HashMap<T, f64> {
if self.total_path_length.is_none() {
let total_path_length = compute_closeness(self.get_adjacency_indices(), num_threads);
self.total_path_length = Some(total_path_length);
}
let total_path_length = self.total_path_length.as_ref().unwrap();
let mut centralities = HashMap::new();
let divisor: f64 = total_path_length.len() as f64 - 1.0;
for (n, node) in self.index.as_ref().unwrap().keys().enumerate() {
let value = total_path_length[n] as f64 / divisor;
centralities.insert(*node, value);
}
centralities
}
}
//
// Helpers
//
/// Computes the eigenvalues and corresponding eigenvalues from the supplied symmetric matrix.
fn sorted_eigenvalue_vector_pairs(
matrix: DMatrix<f64>,
ascending: bool,
) -> Vec<(f64, DVector<f64>)> {
// Early return if the matrix is empty, the rest of the computation requires a matrix with
// at least a dim of 1x1.
if matrix.is_empty() {
return vec![];
}
// Compute eigenvalues and eigenvectors.
let eigen = SymmetricEigen::new(matrix);
// Map eigenvalues to their eigenvectors.
let mut pairs: Vec<(f64, DVector<f64>)> = eigen
.eigenvalues
.iter()
.zip(eigen.eigenvectors.column_iter())
.map(|(value, vector)| (*value, vector.clone_owned()))
.collect();
// Sort eigenvalue-vector pairs in descending order.
pairs.sort_unstable_by(|(a, _), (b, _)| {
if ascending {
a.partial_cmp(b).unwrap()
} else {
b.partial_cmp(a).unwrap()
}
});
pairs
}
#[cfg(test)]
mod tests {
use std::fs;
use nalgebra::dmatrix;
use serde::Deserialize;
use super::*;
#[derive(Default, Clone, Deserialize, Debug)]
pub struct Sample {
pub node_ips: Vec<String>,
pub indices: Vec<Vec<usize>>,
}
// Creates a graph from a list of paths (that can overlap, the graph handles deduplication).
macro_rules! graph {
($($path:expr),*) => {{
let mut graph = Graph::new();
$(
let mut iter = $path.into_iter().peekable();
while let (Some(a), Some(b)) = (iter.next(), iter.peek()) {
graph.insert(Edge::new(a, b));
}
)*
graph
}}
}
#[test]
fn new() {
let _: Graph<()> = Graph::new();
}
#[test]
fn insert() {
let mut graph = Graph::new();
let edge = Edge::new("a", "b");
assert!(graph.insert(edge.clone()));
assert!(!graph.insert(edge));
}
#[test]
fn insert_subset() {
let mut graph = Graph::new();
let (a, b, c, d) = ("a", "b", "c", "d");
graph.insert(Edge::new(a, b));
graph.insert(Edge::new(a, c));
let edges = vec![b, d];
graph.insert_subset(a, &edges);
assert!(graph.contains(&Edge::new(a, b)));
assert!(graph.contains(&Edge::new(a, c)));
assert!(graph.contains(&Edge::new(a, d)));
assert_eq!(graph.edge_count(), 3);
}
#[test]
fn update_subset() {
let mut graph = Graph::new();
let (a, b, c, d) = ("a", "b", "c", "d");
graph.insert(Edge::new(a, b));
graph.insert(Edge::new(a, c));
graph.insert(Edge::new(b, c));
let edges = vec![b, d];
graph.update_subset(a, &edges);
assert!(graph.contains(&Edge::new(a, b)));
assert!(!graph.contains(&Edge::new(a, c)));
assert!(graph.contains(&Edge::new(b, c)));
assert!(graph.contains(&Edge::new(a, d)));
assert_eq!(graph.edge_count(), 3);
}
#[test]
fn remove() {
let edge = Edge::new("a", "b");
let uninserted_edge = Edge::new("a", "c");
let mut graph = Graph::new();
graph.insert(edge.clone());
assert!(graph.remove(&edge));
assert!(!graph.remove(&uninserted_edge));
}
#[test]
fn contains() {
let mut graph = Graph::new();
let edge = Edge::new("a", "b");
graph.insert(edge.clone());
assert!(graph.contains(&edge));
assert!(!graph.contains(&Edge::new("b", "c")));
}
#[test]
fn vertex_count() {
let mut graph = Graph::new();
assert_eq!(graph.vertex_count(), 0);
// Verify two new vertices get added when they don't yet exist in the graph.
graph.insert(Edge::new("a", "b"));
assert_eq!(graph.vertex_count(), 2);
// Verify only one new vertex is added when one of them already exists in the graph.
graph.insert(Edge::new("a", "c"));
assert_eq!(graph.vertex_count(), 3);
}
#[test]
fn edge_count() {
let mut graph = Graph::new();
assert_eq!(graph.edge_count(), 0);
graph.insert(Edge::new("a", "b"));
assert_eq!(graph.edge_count(), 1);
}
#[test]
fn density() {
let mut graph = Graph::new();
assert!(graph.density().is_nan());
graph.insert(Edge::new("a", "b"));
assert_eq!(graph.density(), 1.0);
graph.insert(Edge::new("a", "c"));
assert_eq!(graph.density(), 2.0 / 3.0);
}
#[test]
fn adjacency_matrix() {
let mut graph = Graph::new();
assert_eq!(graph.adjacency_matrix(), dmatrix![]);
graph.insert(Edge::new("a", "b"));
assert_eq!(
graph.adjacency_matrix(),
dmatrix![0.0, 1.0;
1.0, 0.0]
);
graph.insert(Edge::new("a", "c"));
assert_eq!(
graph.adjacency_matrix(),
dmatrix![0.0, 1.0, 1.0;
1.0, 0.0, 0.0;
1.0, 0.0, 0.0]
);
// Sanity check the index gets stored.
assert!(graph.index.is_some());
}
#[test]
fn degree_matrix() {
let mut graph = Graph::new();
assert_eq!(graph.degree_matrix(), dmatrix![]);
graph.insert(Edge::new("a", "b"));
assert_eq!(
graph.degree_matrix(),
dmatrix![1.0, 0.0;
0.0, 1.0]
);
graph.insert(Edge::new("a", "c"));
assert_eq!(
graph.degree_matrix(),
dmatrix![2.0, 0.0, 0.0;
0.0, 1.0, 0.0;
0.0, 0.0, 1.0]
);
// Sanity check the index gets stored.
assert!(graph.index.is_some());
}
#[test]
fn laplacian_matrix() {
let mut graph = Graph::new();
assert_eq!(graph.laplacian_matrix(), dmatrix![]);
graph.insert(Edge::new("a", "b"));
assert_eq!(
graph.laplacian_matrix(),
dmatrix![1.0, -1.0;
-1.0, 1.0]
);
graph.insert(Edge::new("a", "c"));
assert_eq!(
graph.laplacian_matrix(),
dmatrix![2.0, -1.0, -1.0;
-1.0, 1.0, 0.0;
-1.0, 0.0, 1.0]
);
// Sanity check the index gets stored.
assert!(graph.index.is_some());
}
#[test]
fn degree_centrality_delta() {
let mut graph = Graph::new();
assert_eq!(graph.degree_centrality_delta(), 0.0);
graph.insert(Edge::new("a", "b"));
assert_eq!(graph.degree_centrality_delta(), 0.0);
graph.insert(Edge::new("a", "c"));
assert_eq!(graph.degree_centrality_delta(), 1.0);
}
#[test]
fn degree_centrality() {
let mut graph = Graph::new();
assert!(graph.degree_centrality().is_empty());
// One connection, centrality measures for each vertex should be 1.
let (a, b, c) = ("a", "b", "c");
graph.insert(Edge::new(a, b));
let degree_centrality = graph.degree_centrality();
assert_eq!(degree_centrality.get_key_value(a), Some((&a, &1)));
assert_eq!(degree_centrality.get_key_value(b), Some((&b, &1)));
// Sanity check the length.
assert_eq!(degree_centrality.len(), 2);
// Two connections, degree centrality for A should increase.
graph.insert(Edge::new(a, c));
let degree_centrality = graph.degree_centrality();
assert_eq!(degree_centrality.get_key_value(a), Some((&a, &2)));
assert_eq!(degree_centrality.get_key_value(b), Some((&b, &1)));
assert_eq!(degree_centrality.get_key_value(c), Some((&c, &1)));
// Sanity check the length.
assert_eq!(degree_centrality.len(), 3);
}
#[test]
fn eigenvalue_centrality() {
let mut graph = Graph::new();
assert!(graph.eigenvalue_centrality().is_empty());
// One connection, centrality measures for each vertex should be 1.
let (a, b, c) = ("a", "b", "c");
graph.insert(Edge::new(a, b));
let eigenvalue_centrality = graph.eigenvalue_centrality();
assert_eq!(eigenvalue_centrality.get_key_value(a), Some((&a, &1.0)));
assert_eq!(eigenvalue_centrality.get_key_value(b), Some((&b, &1.0)));
// Sanity check the length.
assert_eq!(eigenvalue_centrality.len(), 2);
// Two connections, degree centrality for A should increase.
graph.insert(Edge::new(a, c));
let eigenvalue_centrality = graph.eigenvalue_centrality();
assert_eq!(
eigenvalue_centrality.get_key_value(a),
Some((&a, &1.2426406871192854))
);
assert_eq!(
eigenvalue_centrality.get_key_value(b),
Some((&b, &0.8786796564403571))
);
assert_eq!(
eigenvalue_centrality.get_key_value(c),
Some((&c, &0.8786796564403576))
);
// Sanity check the length.
assert_eq!(eigenvalue_centrality.len(), 3);
}
#[test]
fn fiedler() {
let mut graph = Graph::new();
let (a, b, c, d) = ("a", "b", "c", "d");
// Disconnected graph.
graph.insert(Edge::new(a, b));
graph.insert(Edge::new(c, d));
// Algebraic connectivity should be 0.
let (algebraic_connectivity, fiedler_values_indexed) = graph.fiedler();
assert_eq!(algebraic_connectivity, 0.0);
assert_eq!(fiedler_values_indexed.get_key_value(a), Some((&a, &0.0)));
assert_eq!(fiedler_values_indexed.get_key_value(b), Some((&b, &0.0)));
assert_eq!(
fiedler_values_indexed.get_key_value(c),
Some((&c, &-0.7071067811865475))
);
assert_eq!(
fiedler_values_indexed.get_key_value(d),
Some((&d, &-0.7071067811865475))
);
// Connect the graph.
graph.insert(Edge::new(b, c));
let (algebraic_connectivity, fiedler_values_indexed) = graph.fiedler();
assert_eq!(algebraic_connectivity, 0.5857864376269044);
assert_eq!(
fiedler_values_indexed.get_key_value(a),
Some((&a, &0.6532814824381882))
);
assert_eq!(
fiedler_values_indexed.get_key_value(b),
Some((&b, &0.27059805007309845))
);
assert_eq!(
fiedler_values_indexed.get_key_value(c),
Some((&c, &-0.2705980500730985))
);
assert_eq!(
fiedler_values_indexed.get_key_value(d),
Some((&d, &-0.6532814824381881))
);
}
//
// Private
//
#[test]
fn clear_cache_on_insert() {
let mut graph = Graph::new();
graph.insert(Edge::new("a", "b"));
// The laplacian requires the computation of the index, the degree matrix and the adjacency
// matrix.
graph.laplacian_matrix();
// Check the objects have been cached.
assert!(graph.index.is_some());
assert!(graph.adjacency_matrix.is_some());
assert!(graph.degree_matrix.is_some());
assert!(graph.laplacian_matrix.is_some());
// Update the graph with an insert.
graph.insert(Edge::new("a", "c"));
// Check the cache has been cleared.
assert!(graph.index.is_none());
assert!(graph.adjacency_matrix.is_none());
assert!(graph.degree_matrix.is_none());
assert!(graph.laplacian_matrix.is_none());
}
#[test]
fn clear_cache_on_subset_insert() {
let mut graph = Graph::new();
graph.insert(Edge::new("a", "b"));
// The laplacian requires the computation of the index, the degree matrix and the adjacency
// matrix.
graph.laplacian_matrix();
// Check the objects have been cached.
assert!(graph.index.is_some());
assert!(graph.adjacency_matrix.is_some());
assert!(graph.degree_matrix.is_some());
assert!(graph.laplacian_matrix.is_some());
// Update the graph with a subset insert.
graph.insert_subset("a", &["b", "d"]);
// Check the cache has been cleared.
assert!(graph.index.is_none());
assert!(graph.adjacency_matrix.is_none());
assert!(graph.degree_matrix.is_none());
assert!(graph.laplacian_matrix.is_none());
}
#[test]
fn clear_cache_on_subset_update() {
let mut graph = Graph::new();
graph.insert(Edge::new("a", "b"));
// The laplacian requires the computation of the index, the degree matrix and the adjacency
// matrix.
graph.laplacian_matrix();
// Check the objects have been cached.
assert!(graph.index.is_some());
assert!(graph.adjacency_matrix.is_some());
assert!(graph.degree_matrix.is_some());
assert!(graph.laplacian_matrix.is_some());
// Update the graph with a subset update.
graph.update_subset("a", &["b", "d"]);
// Check the cache has been cleared.
assert!(graph.index.is_none());
assert!(graph.adjacency_matrix.is_none());
assert!(graph.degree_matrix.is_none());
assert!(graph.laplacian_matrix.is_none());
}
#[test]
fn clear_cache_on_subset_update_w_only_removals() {
let mut graph = Graph::new();
graph.insert(Edge::new("a", "b"));
graph.insert(Edge::new("a", "c"));
// The laplacian requires the computation of the index, the degree matrix and the adjacency
// matrix.
graph.laplacian_matrix();
// Check the objects have been cached.
assert!(graph.index.is_some());
assert!(graph.adjacency_matrix.is_some());
assert!(graph.degree_matrix.is_some());
assert!(graph.laplacian_matrix.is_some());
// Update the graph with a subset update.
graph.update_subset("a", &["b"]);
// Check the cache has been cleared.
assert!(graph.index.is_none());
assert!(graph.adjacency_matrix.is_none());
assert!(graph.degree_matrix.is_none());
assert!(graph.laplacian_matrix.is_none());
}
#[test]
fn clear_cache_on_remove() {
let edge = Edge::new("a", "b");
let mut graph = Graph::new();
graph.insert(edge.clone());
// The laplacian requires the computation of the index, the degree matrix and the adjacency
// matrix.
graph.laplacian_matrix();
// Check the objects have been cached.
assert!(graph.index.is_some());
assert!(graph.adjacency_matrix.is_some());
assert!(graph.degree_matrix.is_some());
assert!(graph.laplacian_matrix.is_some());
// Update the graph with remove.
graph.remove(&edge);
// Check the cache has been cleared.
assert!(graph.index.is_none());
assert!(graph.adjacency_matrix.is_none());
assert!(graph.degree_matrix.is_none());
assert!(graph.laplacian_matrix.is_none());
}
#[test]
fn vertices_from_edges() {
let mut graph = Graph::new();
assert!(graph.vertices_from_edges().is_empty());
let (a, b) = ("a", "b");
graph.insert(Edge::new(a, b));
let vertices = graph.vertices_from_edges();
assert!(vertices.contains(a));
assert!(vertices.contains(b));
// Sanity check the length.
assert_eq!(vertices.len(), 2);
}
#[test]
fn generate_index() {
let mut graph = Graph::new();
// Check for an empty graph.
graph.generate_index();
assert!(graph.index.is_some());
assert!(graph.index.as_ref().unwrap().is_empty());
let (a, b) = ("a", "b");
graph.insert(Edge::new(a, b));
graph.generate_index();
assert!(graph.index.is_some());
assert_eq!(
graph.index.as_ref().unwrap().get_key_value(a),
Some((&a, &0))
);
assert_eq!(
graph.index.as_ref().unwrap().get_key_value(b),
Some((&b, &1))
);
assert_eq!(graph.index.as_ref().unwrap().len(), 2);
}
#[test]
fn bhatia_graph() {
let mut graph: Graph<usize> = Graph::new();
// this graph reproduces the image at:
// https://www.youtube.com/watch?v=ptqt2zr9ZRE
graph.insert(Edge::new(0, 1));
graph.insert(Edge::new(1, 3));
graph.insert(Edge::new(3, 4));
graph.insert(Edge::new(4, 2));
graph.insert(Edge::new(2, 0));
graph.insert(Edge::new(4, 5));
graph.insert(Edge::new(5, 3));
let between_map = graph.betweenness_centrality(1, false);
let close_map = graph.closeness_centrality(1);
const N: usize = 6;
let mut betweenness = [0.0; N];
let mut closeness = [0.0; N];
for i in 0..N {
betweenness[i] = *between_map.get(&i).unwrap();
closeness[i] = *close_map.get(&i).unwrap();
}
let total_path_length = [9, 8, 8, 7, 7, 9];
let mut expected_closeness = [0.0; N];
let expected_betweenness: [f64; 6] = [1.0, 1.5, 1.5, 2.5, 2.5, 0.0];
for i in 0..N {
expected_closeness[i] = total_path_length[i] as f64 / (N - 1) as f64;
}
assert_eq!(betweenness, expected_betweenness);
assert_eq!(closeness, expected_closeness);
}
#[test]
fn bhatia_graph_normalized() {
let mut graph: Graph<usize> = Graph::new();
// this graph reproduces the image at:
// https://www.youtube.com/watch?v=ptqt2zr9ZRE
graph.insert(Edge::new(0, 1));
graph.insert(Edge::new(1, 3));
graph.insert(Edge::new(3, 4));
graph.insert(Edge::new(4, 2));
graph.insert(Edge::new(2, 0));
graph.insert(Edge::new(4, 5));
graph.insert(Edge::new(5, 3));
let between_map = graph.betweenness_centrality(1, true);
let close_map = graph.closeness_centrality(1);
const N: usize = 6;
let mut betweenness = [0.0; N];
let mut closeness = [0.0; N];
for i in 0..N {
betweenness[i] = *between_map.get(&i).unwrap();
closeness[i] = *close_map.get(&i).unwrap();
}
let total_path_length = [9, 8, 8, 7, 7, 9];
let mut expected_closeness = [0.0; N];
let mut expected_betweenness = [1.0, 1.5, 1.5, 2.5, 2.5, 0.0];
const DIVISOR: f64 = ((N - 1) * (N - 2) / 2) as f64;
for i in 0..N {
expected_closeness[i] = total_path_length[i] as f64 / (N - 1) as f64;
expected_betweenness[i] /= DIVISOR;
}
assert_eq!(betweenness, expected_betweenness);
assert_eq!(closeness, expected_closeness);
}
#[test]
fn randomish_graph() {
let mut graph: Graph<usize> = Graph::new();
graph.insert(Edge::new(0, 3));
graph.insert(Edge::new(0, 5));
graph.insert(Edge::new(5, 1));
graph.insert(Edge::new(1, 2));
graph.insert(Edge::new(2, 4));
graph.insert(Edge::new(2, 6));
graph.insert(Edge::new(1, 3));
// passing in zero as num_threads will be clamped to 1 thread
let between_map = graph.betweenness_centrality(0, false);
let close_map = graph.closeness_centrality(0);
const N: usize = 7;
let mut betweenness = [0.0; N];
let mut closeness = [0.0; N];
for i in 0..N {
betweenness[i] = *between_map.get(&i).unwrap();
closeness[i] = *close_map.get(&i).unwrap();
}
let total_path_length = [15, 9, 10, 12, 15, 12, 15];
let mut expected_closeness = [0.0; N];
let expected_betweenness = [0.5, 9.5, 9.0, 2.0, 0.0, 2.0, 0.0];
for i in 0..N {
expected_closeness[i] = total_path_length[i] as f64 / (N - 1) as f64;
}
assert_eq!(betweenness, expected_betweenness);
assert_eq!(closeness, expected_closeness);
}
#[test]
fn randomish_graph_normalized() {
let mut graph: Graph<usize> = Graph::new();
graph.insert(Edge::new(0, 3));
graph.insert(Edge::new(0, 5));
graph.insert(Edge::new(5, 1));
graph.insert(Edge::new(1, 2));
graph.insert(Edge::new(2, 4));
graph.insert(Edge::new(2, 6));
graph.insert(Edge::new(1, 3));
const N: usize = 7;
let between_map = graph.betweenness_centrality(1, true);
let close_map = graph.closeness_centrality(1);
let mut betweenness = [0.0; N];
let mut closeness = [0.0; N];
for i in 0..N {
betweenness[i] = *between_map.get(&i).unwrap();
closeness[i] = *close_map.get(&i).unwrap();
}
let total_path_length = [15, 9, 10, 12, 15, 12, 15];
let mut expected_closeness = [0.0; N];
let mut expected_betweenness = [0.5, 9.5, 9.0, 2.0, 0.0, 2.0, 0.0];
const DIVISOR: f64 = ((N - 1) * (N - 2) / 2) as f64;
for i in 0..N {
expected_closeness[i] = total_path_length[i] as f64 / (N - 1) as f64;
expected_betweenness[i] /= DIVISOR;
}
assert_eq!(betweenness, expected_betweenness);
assert_eq!(closeness, expected_closeness);
}
// Helper function to create a sample from a json file.
// The file will begin like this:
// {"indices":[[2630,3217,1608,1035,...
// and end like this:
// ...2316,1068,1238,704,2013]]}
pub fn load_sample(filepath: &str) -> Sample {
let jstring = fs::read_to_string(filepath).unwrap();
let sample: Sample = serde_json::from_str(&jstring).unwrap();
sample
}
#[test]
#[ignore = "slow to run"]
fn loaded_sample_graph() {
let sample = load_sample("testdata/sample.json");
// graph 1 uses integers as node value
let mut graph1 = Graph::new();
let mut n = 0;
for node in &sample.indices {
for connection in node {
if *connection > n {
graph1.insert(Edge::new(n, *connection));
}
}
n += 1;
}
let betweenness_centrality1 = graph1.betweenness_centrality(3, false);
let closeness_centrality1 = graph1.closeness_centrality(3);
// graph2 uses ip address as node value
let mut graph2: Graph<&str> = Graph::new();
let mut n = 0;
for node in &sample.indices {
for connection in node {
if *connection > n {
graph2.insert(Edge::new(
&sample.node_ips[n],
&sample.node_ips[*connection],
));
}
}
n += 1;
}
let betweenness_centrality2 = graph2.betweenness_centrality(8, false);
let closeness_centrality2 = graph2.closeness_centrality(8);
let b1 = betweenness_centrality1.get(&0).unwrap();
let b2 = betweenness_centrality2.get("65.21.141.242").unwrap();
let c1 = closeness_centrality1.get(&0).unwrap();
let c2 = closeness_centrality2.get("65.21.141.242").unwrap();
assert!((b1 - b2).abs() < 0.0000001);
assert!((c1 - c2).abs() < 0.0000001);
let b3 = betweenness_centrality1.get(&1837).unwrap();
let b4 = betweenness_centrality2.get("85.15.179.171").unwrap();
let c3 = closeness_centrality1.get(&1837).unwrap();
let c4 = closeness_centrality2.get("85.15.179.171").unwrap();
assert!((b3 - b4).abs() < 0.0000001);
assert!((c3 - c4).abs() < 0.0000001);
// these should not be equal
let b1 = betweenness_centrality1.get(&1836).unwrap();
let b2 = betweenness_centrality2.get("85.15.179.171").unwrap();
assert_ne!(b1, b2);
}
#[test]
fn betweenness_line_topology() {
let (a, b, c, d) = ("a", "b", "c", "d");
let mut graph = graph!([a, b, c, d]);
let betweenness_centrality = graph.betweenness_centrality(2, false);
assert_eq!(betweenness_centrality.get_key_value(a), Some((&a, &0.0)));
assert_eq!(betweenness_centrality.get_key_value(b), Some((&b, &2.0)));
assert_eq!(betweenness_centrality.get_key_value(c), Some((&c, &2.0)));
assert_eq!(betweenness_centrality.get_key_value(d), Some((&d, &0.0)));
}
#[test]
fn betweenness_star_topology() {
let (a, b, c, d, e) = ("a", "b", "c", "d", "e");
let mut graph = graph!([a, b, c], [e, b, d]);
let betweenness_centrality = graph.betweenness_centrality(2, false);
assert_eq!(betweenness_centrality.get_key_value(a), Some((&a, &0.0)));
assert_eq!(betweenness_centrality.get_key_value(b), Some((&b, &6.0)));
assert_eq!(betweenness_centrality.get_key_value(c), Some((&c, &0.0)));
assert_eq!(betweenness_centrality.get_key_value(d), Some((&d, &0.0)));
assert_eq!(betweenness_centrality.get_key_value(e), Some((&e, &0.0)));
}
}