1use std::collections::{HashMap, HashSet};
8use std::hash::Hash;
9
10use scirs2_core::ndarray::{Array1, Array2};
11
12use crate::algorithms::{dijkstra_path, dijkstra_path_digraph};
13use crate::base::{DiGraph, EdgeWeight, Graph, Node};
14use crate::error::{GraphError, Result};
15use petgraph::graph::IndexType;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum CentralityType {
20 Degree,
22 Betweenness,
24 Closeness,
26 Eigenvector,
28 Katz,
30 PageRank,
32 WeightedDegree,
34 WeightedBetweenness,
36 WeightedCloseness,
38}
39
40#[allow(dead_code)]
60pub fn centrality<N, E, Ix>(
61 graph: &Graph<N, E, Ix>,
62 centrality_type: CentralityType,
63) -> Result<HashMap<N, f64>>
64where
65 N: Node + std::fmt::Debug,
66 E: EdgeWeight
67 + scirs2_core::numeric::Zero
68 + scirs2_core::numeric::One
69 + std::ops::Add<Output = E>
70 + PartialOrd
71 + Into<f64>
72 + std::marker::Copy
73 + std::fmt::Debug
74 + std::default::Default,
75 Ix: petgraph::graph::IndexType,
76{
77 let nodes = graph.nodes();
78 let n = nodes.len();
79
80 if n == 0 {
81 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
82 }
83
84 match centrality_type {
85 CentralityType::Degree => degree_centrality(graph),
86 CentralityType::Betweenness => betweenness_centrality(graph),
87 CentralityType::Closeness => closeness_centrality(graph),
88 CentralityType::Eigenvector => eigenvector_centrality(graph),
89 CentralityType::Katz => katz_centrality(graph, 0.1, 1.0), CentralityType::PageRank => pagerank_centrality(graph, 0.85, 1e-6), CentralityType::WeightedDegree => weighted_degree_centrality(graph),
92 CentralityType::WeightedBetweenness => weighted_betweenness_centrality(graph),
93 CentralityType::WeightedCloseness => weighted_closeness_centrality(graph),
94 }
95}
96
97#[allow(dead_code)]
106pub fn centrality_digraph<N, E, Ix>(
107 graph: &DiGraph<N, E, Ix>,
108 centrality_type: CentralityType,
109) -> Result<HashMap<N, f64>>
110where
111 N: Node + std::fmt::Debug,
112 E: EdgeWeight
113 + scirs2_core::numeric::Zero
114 + scirs2_core::numeric::One
115 + std::ops::Add<Output = E>
116 + PartialOrd
117 + Into<f64>
118 + std::marker::Copy
119 + std::fmt::Debug
120 + std::default::Default,
121 Ix: petgraph::graph::IndexType,
122{
123 let nodes = graph.nodes();
124 let n = nodes.len();
125
126 if n == 0 {
127 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
128 }
129
130 match centrality_type {
131 CentralityType::Degree => degree_centrality_digraph(graph),
132 CentralityType::Betweenness => betweenness_centrality_digraph(graph),
133 CentralityType::Closeness => closeness_centrality_digraph(graph),
134 CentralityType::Eigenvector => eigenvector_centrality_digraph(graph),
135 CentralityType::Katz => katz_centrality_digraph(graph, 0.1, 1.0), CentralityType::PageRank => pagerank_centrality_digraph(graph, 0.85, 1e-6), CentralityType::WeightedDegree => weighted_degree_centrality_digraph(graph),
138 CentralityType::WeightedBetweenness => weighted_betweenness_centrality_digraph(graph),
139 CentralityType::WeightedCloseness => weighted_closeness_centrality_digraph(graph),
140 }
141}
142
143#[allow(dead_code)]
151fn degree_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
152where
153 N: Node + std::fmt::Debug,
154 E: EdgeWeight,
155 Ix: petgraph::graph::IndexType,
156{
157 let nodes = graph.nodes();
158 let n = nodes.len() as f64;
159 let degrees = graph.degree_vector();
160
161 let mut centrality = HashMap::new();
162 let normalization = if n <= 1.0 { 1.0 } else { n - 1.0 };
163
164 for (i, node) in nodes.iter().enumerate() {
165 let degree = degrees[i] as f64;
166 centrality.insert((*node).clone(), degree / normalization);
167 }
168
169 Ok(centrality)
170}
171
172#[allow(dead_code)]
174fn degree_centrality_digraph<N, E, Ix>(graph: &DiGraph<N, E, Ix>) -> Result<HashMap<N, f64>>
175where
176 N: Node + std::fmt::Debug,
177 E: EdgeWeight,
178 Ix: petgraph::graph::IndexType,
179{
180 let nodes = graph.nodes();
181 let n = nodes.len() as f64;
182 let in_degrees = graph.in_degree_vector();
183 let out_degrees = graph.out_degree_vector();
184
185 let mut centrality = HashMap::new();
186 let normalization = if n <= 1.0 { 1.0 } else { n - 1.0 };
187
188 for (i, node) in nodes.iter().enumerate() {
189 let degree = (in_degrees[i] + out_degrees[i]) as f64;
191 centrality.insert((*node).clone(), degree / normalization);
192 }
193
194 Ok(centrality)
195}
196
197#[allow(dead_code)]
206fn betweenness_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
207where
208 N: Node + std::fmt::Debug,
209 E: EdgeWeight
210 + scirs2_core::numeric::Zero
211 + scirs2_core::numeric::One
212 + std::ops::Add<Output = E>
213 + PartialOrd
214 + Into<f64>
215 + std::marker::Copy
216 + std::fmt::Debug
217 + std::default::Default,
218 Ix: petgraph::graph::IndexType,
219{
220 let nodes = graph.nodes();
221 let n = nodes.len();
222
223 if n <= 1 {
224 let mut result = HashMap::new();
225 for node in nodes {
226 result.insert(node.clone(), 0.0);
227 }
228 return Ok(result);
229 }
230
231 let mut betweenness = HashMap::new();
232 for node in nodes.iter() {
233 betweenness.insert((*node).clone(), 0.0);
234 }
235
236 for (i, &s) in nodes.iter().enumerate() {
238 for (j, &t) in nodes.iter().enumerate() {
239 if i == j {
240 continue;
241 }
242
243 if let Ok(Some(path)) = dijkstra_path(graph, s, t) {
245 for node in &path.nodes[1..path.nodes.len() - 1] {
247 *betweenness.entry(node.clone()).or_insert(0.0) += 1.0;
248 }
249 }
250 }
251 }
252
253 let scale = 1.0 / ((n - 1) * (n - 2)) as f64;
255 for val in betweenness.values_mut() {
256 *val *= scale;
257 }
258
259 Ok(betweenness)
260}
261
262#[allow(dead_code)]
264fn betweenness_centrality_digraph<N, E, Ix>(graph: &DiGraph<N, E, Ix>) -> Result<HashMap<N, f64>>
265where
266 N: Node + std::fmt::Debug,
267 E: EdgeWeight
268 + scirs2_core::numeric::Zero
269 + scirs2_core::numeric::One
270 + std::ops::Add<Output = E>
271 + PartialOrd
272 + Into<f64>
273 + std::marker::Copy
274 + std::fmt::Debug
275 + std::default::Default,
276 Ix: petgraph::graph::IndexType,
277{
278 let nodes = graph.nodes();
279 let n = nodes.len();
280
281 if n <= 1 {
282 let mut result = HashMap::new();
283 for node in nodes {
284 result.insert(node.clone(), 0.0);
285 }
286 return Ok(result);
287 }
288
289 let mut betweenness = HashMap::new();
290 for node in nodes.iter() {
291 betweenness.insert((*node).clone(), 0.0);
292 }
293
294 for (i, &s) in nodes.iter().enumerate() {
296 for (j, &t) in nodes.iter().enumerate() {
297 if i == j {
298 continue;
299 }
300
301 if let Ok(Some(path)) = dijkstra_path_digraph(graph, s, t) {
303 for node in &path.nodes[1..path.nodes.len() - 1] {
305 *betweenness.entry(node.clone()).or_insert(0.0) += 1.0;
306 }
307 }
308 }
309 }
310
311 let scale = 1.0 / ((n - 1) * (n - 2)) as f64;
313 for val in betweenness.values_mut() {
314 *val *= scale;
315 }
316
317 Ok(betweenness)
318}
319
320#[allow(dead_code)]
322fn closeness_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
323where
324 N: Node + std::fmt::Debug,
325 E: EdgeWeight
326 + scirs2_core::numeric::Zero
327 + scirs2_core::numeric::One
328 + std::ops::Add<Output = E>
329 + PartialOrd
330 + Into<f64>
331 + std::marker::Copy
332 + std::fmt::Debug
333 + std::default::Default,
334 Ix: petgraph::graph::IndexType,
335{
336 let nodes = graph.nodes();
337 let n = nodes.len();
338
339 if n <= 1 {
340 let mut result = HashMap::new();
341 for node in nodes {
342 result.insert(node.clone(), 1.0);
343 }
344 return Ok(result);
345 }
346
347 let mut closeness = HashMap::new();
348
349 for &node in nodes.iter() {
351 let mut sum_distances = 0.0;
352 let mut reachable_nodes = 0;
353
354 for &other in nodes.iter() {
355 if node == other {
356 continue;
357 }
358
359 if let Ok(Some(path)) = dijkstra_path(graph, node, other) {
361 sum_distances += path.total_weight.into();
362 reachable_nodes += 1;
363 }
364 }
365
366 if reachable_nodes > 0 {
368 let closeness_value = reachable_nodes as f64 / sum_distances;
370 let normalized = closeness_value * (reachable_nodes as f64 / (n - 1) as f64);
372 closeness.insert(node.clone(), normalized);
373 } else {
374 closeness.insert(node.clone(), 0.0);
375 }
376 }
377
378 Ok(closeness)
379}
380
381#[allow(dead_code)]
383fn closeness_centrality_digraph<N, E, Ix>(graph: &DiGraph<N, E, Ix>) -> Result<HashMap<N, f64>>
384where
385 N: Node + std::fmt::Debug,
386 E: EdgeWeight
387 + scirs2_core::numeric::Zero
388 + scirs2_core::numeric::One
389 + std::ops::Add<Output = E>
390 + PartialOrd
391 + Into<f64>
392 + std::marker::Copy
393 + std::fmt::Debug
394 + std::default::Default,
395 Ix: petgraph::graph::IndexType,
396{
397 let nodes = graph.nodes();
398 let n = nodes.len();
399
400 if n <= 1 {
401 let mut result = HashMap::new();
402 for node in nodes {
403 result.insert(node.clone(), 1.0);
404 }
405 return Ok(result);
406 }
407
408 let mut closeness = HashMap::new();
409
410 for &node in nodes.iter() {
412 let mut sum_distances = 0.0;
413 let mut reachable_nodes = 0;
414
415 for &other in nodes.iter() {
416 if node == other {
417 continue;
418 }
419
420 if let Ok(Some(path)) = dijkstra_path_digraph(graph, node, other) {
422 sum_distances += path.total_weight.into();
423 reachable_nodes += 1;
424 }
425 }
426
427 if reachable_nodes > 0 {
429 let closeness_value = reachable_nodes as f64 / sum_distances;
431 let normalized = closeness_value * (reachable_nodes as f64 / (n - 1) as f64);
433 closeness.insert(node.clone(), normalized);
434 } else {
435 closeness.insert(node.clone(), 0.0);
436 }
437 }
438
439 Ok(closeness)
440}
441
442#[allow(dead_code)]
446fn eigenvector_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
447where
448 N: Node + std::fmt::Debug,
449 E: EdgeWeight
450 + scirs2_core::numeric::Zero
451 + scirs2_core::numeric::One
452 + PartialOrd
453 + Into<f64>
454 + std::marker::Copy,
455 Ix: petgraph::graph::IndexType,
456{
457 let nodes = graph.nodes();
458 let n = nodes.len();
459
460 if n == 0 {
461 return Err(GraphError::InvalidGraph("Empty _graph".to_string()));
462 }
463
464 let adj_mat = graph.adjacency_matrix();
466 let mut adj_f64 = Array2::<f64>::zeros((n, n));
467 for i in 0..n {
468 for j in 0..n {
469 adj_f64[[i, j]] = adj_mat[[i, j]].into();
470 }
471 }
472
473 let mut x = Array1::<f64>::ones(n);
475 x.mapv_inplace(|v| v / (n as f64).sqrt()); let max_iter = 100;
479 let tol = 1e-6;
480
481 for _ in 0..max_iter {
482 let y = adj_f64.dot(&x);
484
485 let norm = (y.iter().map(|v| v * v).sum::<f64>()).sqrt();
487 if norm < 1e-10 {
488 return Err(GraphError::AlgorithmError(
490 "Eigenvector centrality computation failed: zero eigenvalue".to_string(),
491 ));
492 }
493
494 let y_norm = y / norm;
496
497 let diff = (&y_norm - &x).iter().map(|v| v.abs()).sum::<f64>();
499 if diff < tol {
500 let mut result = HashMap::new();
502 for (i, &node) in nodes.iter().enumerate() {
503 result.insert(node.clone(), y_norm[i]);
504 }
505 return Ok(result);
506 }
507
508 x = y_norm;
510 }
511
512 Err(GraphError::AlgorithmError(
514 "Eigenvector centrality computation did not converge".to_string(),
515 ))
516}
517
518#[allow(dead_code)]
522fn eigenvector_centrality_digraph<N, E, Ix>(graph: &DiGraph<N, E, Ix>) -> Result<HashMap<N, f64>>
523where
524 N: Node + std::fmt::Debug,
525 E: EdgeWeight
526 + scirs2_core::numeric::Zero
527 + scirs2_core::numeric::One
528 + PartialOrd
529 + Into<f64>
530 + std::marker::Copy,
531 Ix: petgraph::graph::IndexType,
532{
533 let nodes = graph.nodes();
534 let n = nodes.len();
535
536 if n == 0 {
537 return Err(GraphError::InvalidGraph("Empty _graph".to_string()));
538 }
539
540 let adj_mat = graph.adjacency_matrix();
542 let mut adj_f64 = Array2::<f64>::zeros((n, n));
543 for i in 0..n {
544 for j in 0..n {
545 adj_f64[[i, j]] = adj_mat[[i, j]];
546 }
547 }
548
549 let mut x = Array1::<f64>::ones(n);
551 x.mapv_inplace(|v| v / (n as f64).sqrt()); let max_iter = 100;
555 let tol = 1e-6;
556
557 for _ in 0..max_iter {
558 let y = adj_f64.dot(&x);
560
561 let norm = (y.iter().map(|v| v * v).sum::<f64>()).sqrt();
563 if norm < 1e-10 {
564 return Err(GraphError::AlgorithmError(
566 "Eigenvector centrality computation failed: zero eigenvalue".to_string(),
567 ));
568 }
569
570 let y_norm = y / norm;
572
573 let diff = (&y_norm - &x).iter().map(|v| v.abs()).sum::<f64>();
575 if diff < tol {
576 let mut result = HashMap::new();
578 for (i, &node) in nodes.iter().enumerate() {
579 result.insert(node.clone(), y_norm[i]);
580 }
581 return Ok(result);
582 }
583
584 x = y_norm;
586 }
587
588 Err(GraphError::AlgorithmError(
590 "Eigenvector centrality computation did not converge".to_string(),
591 ))
592}
593
594#[allow(dead_code)]
604pub fn clustering_coefficient<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
605where
606 N: Node + std::fmt::Debug,
607 E: EdgeWeight,
608 Ix: petgraph::graph::IndexType,
609{
610 let mut coefficients = HashMap::new();
611
612 for (idx, &node) in graph.nodes().iter().enumerate() {
613 let node_idx = petgraph::graph::NodeIndex::new(idx);
615 let neighbors: HashSet<_> = graph.inner().neighbors(node_idx).collect();
616
617 let k = neighbors.len();
618
619 if k < 2 {
621 coefficients.insert(node.clone(), 0.0);
622 continue;
623 }
624
625 let mut edge_count = 0;
627
628 for &n1 in &neighbors {
629 for &n2 in &neighbors {
630 if n1 != n2 && graph.inner().contains_edge(n1, n2) {
631 edge_count += 1;
632 }
633 }
634 }
635
636 edge_count /= 2;
638
639 let possible_edges = k * (k - 1) / 2;
641 let coefficient = edge_count as f64 / possible_edges as f64;
642
643 coefficients.insert(node.clone(), coefficient);
644 }
645
646 Ok(coefficients)
647}
648
649#[allow(dead_code)]
659pub fn graph_density<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<f64>
660where
661 N: Node + std::fmt::Debug,
662 E: EdgeWeight,
663 Ix: petgraph::graph::IndexType,
664{
665 let n = graph.node_count();
666
667 if n <= 1 {
668 return Err(GraphError::InvalidGraph(
669 "Graph density undefined for graphs with 0 or 1 nodes".to_string(),
670 ));
671 }
672
673 let m = graph.edge_count();
674 let possible_edges = n * (n - 1) / 2;
675
676 Ok(m as f64 / possible_edges as f64)
677}
678
679#[allow(dead_code)]
687pub fn graph_density_digraph<N, E, Ix>(graph: &DiGraph<N, E, Ix>) -> Result<f64>
688where
689 N: Node + std::fmt::Debug,
690 E: EdgeWeight,
691 Ix: petgraph::graph::IndexType,
692{
693 let n = graph.node_count();
694
695 if n <= 1 {
696 return Err(GraphError::InvalidGraph(
697 "Graph density undefined for graphs with 0 or 1 nodes".to_string(),
698 ));
699 }
700
701 let m = graph.edge_count();
702 let possible_edges = n * (n - 1); Ok(m as f64 / possible_edges as f64)
705}
706
707#[allow(dead_code)]
720pub fn katz_centrality<N, E, Ix>(
721 graph: &Graph<N, E, Ix>,
722 alpha: f64,
723 beta: f64,
724) -> Result<HashMap<N, f64>>
725where
726 N: Node + std::fmt::Debug,
727 E: EdgeWeight + scirs2_core::numeric::Zero + scirs2_core::numeric::One + Into<f64> + Copy,
728 Ix: petgraph::graph::IndexType,
729{
730 let nodes = graph.nodes();
731 let n = nodes.len();
732
733 if n == 0 {
734 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
735 }
736
737 let adj_mat = graph.adjacency_matrix();
739 let mut adj_f64 = Array2::<f64>::zeros((n, n));
740 for i in 0..n {
741 for j in 0..n {
742 adj_f64[[i, j]] = adj_mat[[i, j]].into();
743 }
744 }
745
746 let mut identity = Array2::<f64>::zeros((n, n));
748 for i in 0..n {
749 identity[[i, i]] = 1.0;
750 }
751
752 let _factor_matrix = &identity - &(alpha * &adj_f64);
754
755 let beta_vec = Array1::<f64>::from_elem(n, beta);
757
758 let mut centrality_vec = Array1::<f64>::ones(n);
761 let max_iter = 100;
762 let tol = 1e-6;
763
764 for _ in 0..max_iter {
765 let new_centrality = alpha * adj_f64.dot(¢rality_vec) + &beta_vec;
767
768 let diff = (&new_centrality - ¢rality_vec)
770 .iter()
771 .map(|v| v.abs())
772 .sum::<f64>();
773 if diff < tol {
774 centrality_vec = new_centrality;
775 break;
776 }
777
778 centrality_vec = new_centrality;
779 }
780
781 let mut result = HashMap::new();
783 for (i, &node) in nodes.iter().enumerate() {
784 result.insert(node.clone(), centrality_vec[i]);
785 }
786
787 Ok(result)
788}
789
790#[allow(dead_code)]
800pub fn katz_centrality_digraph<N, E, Ix>(
801 graph: &DiGraph<N, E, Ix>,
802 alpha: f64,
803 beta: f64,
804) -> Result<HashMap<N, f64>>
805where
806 N: Node + std::fmt::Debug,
807 E: EdgeWeight + scirs2_core::numeric::Zero + scirs2_core::numeric::One + Into<f64> + Copy,
808 Ix: petgraph::graph::IndexType,
809{
810 let nodes = graph.nodes();
811 let n = nodes.len();
812
813 if n == 0 {
814 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
815 }
816
817 let adj_mat = graph.adjacency_matrix();
819 let mut adj_f64 = Array2::<f64>::zeros((n, n));
820 for i in 0..n {
821 for j in 0..n {
822 adj_f64[[i, j]] = adj_mat[[i, j]];
823 }
824 }
825
826 let beta_vec = Array1::<f64>::from_elem(n, beta);
828
829 let mut centrality_vec = Array1::<f64>::ones(n);
831 let max_iter = 100;
832 let tol = 1e-6;
833
834 for _ in 0..max_iter {
835 let new_centrality = alpha * adj_f64.t().dot(¢rality_vec) + &beta_vec;
837
838 let diff = (&new_centrality - ¢rality_vec)
840 .iter()
841 .map(|v| v.abs())
842 .sum::<f64>();
843 if diff < tol {
844 centrality_vec = new_centrality;
845 break;
846 }
847
848 centrality_vec = new_centrality;
849 }
850
851 let mut result = HashMap::new();
853 for (i, &node) in nodes.iter().enumerate() {
854 result.insert(node.clone(), centrality_vec[i]);
855 }
856
857 Ok(result)
858}
859
860#[allow(dead_code)]
873pub fn pagerank_centrality<N, E, Ix>(
874 graph: &Graph<N, E, Ix>,
875 damping: f64,
876 tolerance: f64,
877) -> Result<HashMap<N, f64>>
878where
879 N: Node + std::fmt::Debug,
880 E: EdgeWeight,
881 Ix: petgraph::graph::IndexType,
882{
883 let nodes = graph.nodes();
884 let n = nodes.len();
885
886 if n == 0 {
887 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
888 }
889
890 let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
892 let max_iter = 100;
893
894 let degrees = graph.degree_vector();
896
897 for _ in 0..max_iter {
898 let mut new_pagerank = Array1::<f64>::from_elem(n, (1.0 - damping) / n as f64);
899
900 for (i, node_idx) in graph.inner().node_indices().enumerate() {
902 let node_degree = degrees[i] as f64;
903 if node_degree > 0.0 {
904 let contribution = damping * pagerank[i] / node_degree;
905
906 for neighbor_idx in graph.inner().neighbors(node_idx) {
908 let neighbor_i = neighbor_idx.index();
909 new_pagerank[neighbor_i] += contribution;
910 }
911 }
912 }
913
914 let diff = (&new_pagerank - &pagerank)
916 .iter()
917 .map(|v| v.abs())
918 .sum::<f64>();
919 if diff < tolerance {
920 pagerank = new_pagerank;
921 break;
922 }
923
924 pagerank = new_pagerank;
925 }
926
927 let mut result = HashMap::new();
929 for (i, &node) in nodes.iter().enumerate() {
930 result.insert(node.clone(), pagerank[i]);
931 }
932
933 Ok(result)
934}
935
936#[allow(dead_code)]
963pub fn parallel_pagerank_centrality<N, E, Ix>(
964 graph: &Graph<N, E, Ix>,
965 damping: f64,
966 tolerance: f64,
967 max_iterations: Option<usize>,
968) -> Result<HashMap<N, f64>>
969where
970 N: Node + Send + Sync + std::fmt::Debug,
971 E: EdgeWeight + Send + Sync,
972 Ix: petgraph::graph::IndexType + Send + Sync,
973{
974 use scirs2_core::parallel_ops::*;
975 use std::sync::{Arc, Mutex};
976
977 let nodes = graph.nodes();
978 let n = nodes.len();
979
980 if n == 0 {
981 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
982 }
983
984 if n < 1000 {
986 return pagerank_centrality(graph, damping, tolerance);
987 }
988
989 let max_iter = max_iterations.unwrap_or(100);
990
991 let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
993
994 let degrees = graph.degree_vector();
996
997 let neighbor_lists: Vec<Vec<usize>> = (0..n)
999 .map(|i| {
1000 let node_idx = petgraph::graph::NodeIndex::new(i);
1001 graph
1002 .inner()
1003 .neighbors(node_idx)
1004 .map(|neighbor_idx| neighbor_idx.index())
1005 .collect()
1006 })
1007 .collect();
1008
1009 for _iteration in 0..max_iter {
1010 let new_pagerank = Arc::new(Mutex::new(Array1::<f64>::from_elem(
1012 n,
1013 (1.0 - damping) / n as f64,
1014 )));
1015
1016 (0..n).into_par_iter().for_each(|i| {
1018 let node_degree = degrees[i] as f64;
1019 if node_degree > 0.0 {
1020 let contribution = damping * pagerank[i] / node_degree;
1021
1022 let mut local_updates = Vec::new();
1024 for &neighbor_i in &neighbor_lists[i] {
1025 local_updates.push((neighbor_i, contribution));
1026 }
1027
1028 if !local_updates.is_empty() {
1030 let mut new_pr = new_pagerank.lock().unwrap();
1031 for (neighbor_i, contrib) in local_updates {
1032 new_pr[neighbor_i] += contrib;
1033 }
1034 }
1035 }
1036 });
1037
1038 let new_pagerank = Arc::try_unwrap(new_pagerank).unwrap().into_inner().unwrap();
1039
1040 let diff = pagerank
1042 .iter()
1043 .zip(new_pagerank.iter())
1044 .map(|(old, new)| (new - old).abs())
1045 .sum::<f64>();
1046
1047 if diff < tolerance {
1048 pagerank = new_pagerank;
1049 break;
1050 }
1051
1052 pagerank = new_pagerank;
1053 }
1054
1055 let result: HashMap<N, f64> = nodes
1057 .iter()
1058 .enumerate()
1059 .map(|(i, node)| ((*node).clone(), pagerank[i]))
1060 .collect();
1061
1062 Ok(result)
1063}
1064
1065#[derive(Debug, Clone)]
1067pub struct HitsScores<N: Node> {
1068 pub authorities: HashMap<N, f64>,
1070 pub hubs: HashMap<N, f64>,
1072}
1073
1074#[allow(dead_code)]
1088pub fn hits_algorithm<N, E, Ix>(
1089 graph: &DiGraph<N, E, Ix>,
1090 max_iter: usize,
1091 tolerance: f64,
1092) -> Result<HitsScores<N>>
1093where
1094 N: Node + Clone + Hash + Eq + std::fmt::Debug,
1095 E: EdgeWeight,
1096 Ix: IndexType,
1097{
1098 let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1099 let n = nodes.len();
1100
1101 if n == 0 {
1102 return Ok(HitsScores {
1103 authorities: HashMap::new(),
1104 hubs: HashMap::new(),
1105 });
1106 }
1107
1108 let mut authorities = vec![1.0 / (n as f64).sqrt(); n];
1110 let mut hubs = vec![1.0 / (n as f64).sqrt(); n];
1111 let mut new_authorities = vec![0.0; n];
1112 let mut new_hubs = vec![0.0; n];
1113
1114 let node_to_idx: HashMap<N, usize> = nodes
1116 .iter()
1117 .enumerate()
1118 .map(|(i, n)| (n.clone(), i))
1119 .collect();
1120
1121 for _ in 0..max_iter {
1123 new_authorities.fill(0.0);
1125 for (i, node) in nodes.iter().enumerate() {
1126 if let Ok(predecessors) = graph.predecessors(node) {
1128 for pred in predecessors {
1129 if let Some(&pred_idx) = node_to_idx.get(&pred) {
1130 new_authorities[i] += hubs[pred_idx];
1131 }
1132 }
1133 }
1134 }
1135
1136 new_hubs.fill(0.0);
1138 for (i, node) in nodes.iter().enumerate() {
1139 if let Ok(successors) = graph.successors(node) {
1141 for succ in successors {
1142 if let Some(&succ_idx) = node_to_idx.get(&succ) {
1143 new_hubs[i] += authorities[succ_idx];
1144 }
1145 }
1146 }
1147 }
1148
1149 let auth_norm: f64 = new_authorities.iter().map(|x| x * x).sum::<f64>().sqrt();
1151 let hub_norm: f64 = new_hubs.iter().map(|x| x * x).sum::<f64>().sqrt();
1152
1153 if auth_norm > 0.0 {
1154 for score in &mut new_authorities {
1155 *score /= auth_norm;
1156 }
1157 }
1158
1159 if hub_norm > 0.0 {
1160 for score in &mut new_hubs {
1161 *score /= hub_norm;
1162 }
1163 }
1164
1165 let auth_diff: f64 = authorities
1167 .iter()
1168 .zip(&new_authorities)
1169 .map(|(old, new)| (old - new).abs())
1170 .sum();
1171 let hub_diff: f64 = hubs
1172 .iter()
1173 .zip(&new_hubs)
1174 .map(|(old, new)| (old - new).abs())
1175 .sum();
1176
1177 if auth_diff < tolerance && hub_diff < tolerance {
1178 break;
1179 }
1180
1181 authorities.copy_from_slice(&new_authorities);
1183 hubs.copy_from_slice(&new_hubs);
1184 }
1185
1186 let authority_map = nodes
1188 .iter()
1189 .enumerate()
1190 .map(|(i, n)| (n.clone(), authorities[i]))
1191 .collect();
1192 let hub_map = nodes
1193 .iter()
1194 .enumerate()
1195 .map(|(i, n)| (n.clone(), hubs[i]))
1196 .collect();
1197
1198 Ok(HitsScores {
1199 authorities: authority_map,
1200 hubs: hub_map,
1201 })
1202}
1203
1204#[allow(dead_code)]
1214pub fn pagerank_centrality_digraph<N, E, Ix>(
1215 graph: &DiGraph<N, E, Ix>,
1216 damping: f64,
1217 tolerance: f64,
1218) -> Result<HashMap<N, f64>>
1219where
1220 N: Node + std::fmt::Debug,
1221 E: EdgeWeight,
1222 Ix: petgraph::graph::IndexType,
1223{
1224 let nodes = graph.nodes();
1225 let n = nodes.len();
1226
1227 if n == 0 {
1228 return Err(GraphError::InvalidGraph("Empty graph".to_string()));
1229 }
1230
1231 let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
1233 let max_iter = 100;
1234
1235 let out_degrees = graph.out_degree_vector();
1237
1238 for _ in 0..max_iter {
1239 let mut new_pagerank = Array1::<f64>::from_elem(n, (1.0 - damping) / n as f64);
1240
1241 for (i, node_idx) in graph.inner().node_indices().enumerate() {
1243 let node_out_degree = out_degrees[i] as f64;
1244 if node_out_degree > 0.0 {
1245 let contribution = damping * pagerank[i] / node_out_degree;
1246
1247 for neighbor_idx in graph
1249 .inner()
1250 .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
1251 {
1252 let neighbor_i = neighbor_idx.index();
1253 new_pagerank[neighbor_i] += contribution;
1254 }
1255 } else {
1256 let contribution = damping * pagerank[i] / n as f64;
1258 for j in 0..n {
1259 new_pagerank[j] += contribution;
1260 }
1261 }
1262 }
1263
1264 let diff = (&new_pagerank - &pagerank)
1266 .iter()
1267 .map(|v| v.abs())
1268 .sum::<f64>();
1269 if diff < tolerance {
1270 pagerank = new_pagerank;
1271 break;
1272 }
1273
1274 pagerank = new_pagerank;
1275 }
1276
1277 let mut result = HashMap::new();
1279 for (i, &node) in nodes.iter().enumerate() {
1280 result.insert(node.clone(), pagerank[i]);
1281 }
1282
1283 Ok(result)
1284}
1285
1286#[allow(dead_code)]
1290fn weighted_degree_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
1291where
1292 N: Node + std::fmt::Debug,
1293 E: EdgeWeight + Into<f64> + Clone,
1294 Ix: IndexType,
1295{
1296 let mut centrality = HashMap::new();
1297
1298 for node in graph.nodes() {
1299 let mut weight_sum = 0.0;
1300
1301 if let Ok(neighbors) = graph.neighbors(node) {
1302 for neighbor in neighbors {
1303 if let Ok(weight) = graph.edge_weight(node, &neighbor) {
1304 weight_sum += weight.into();
1305 }
1306 }
1307 }
1308
1309 centrality.insert(node.clone(), weight_sum);
1310 }
1311
1312 Ok(centrality)
1313}
1314
1315#[allow(dead_code)]
1317fn weighted_degree_centrality_digraph<N, E, Ix>(
1318 graph: &DiGraph<N, E, Ix>,
1319) -> Result<HashMap<N, f64>>
1320where
1321 N: Node + std::fmt::Debug,
1322 E: EdgeWeight + Into<f64> + Clone,
1323 Ix: IndexType,
1324{
1325 let mut centrality = HashMap::new();
1326
1327 for node in graph.nodes() {
1328 let mut in_weight = 0.0;
1329 let mut out_weight = 0.0;
1330
1331 if let Ok(predecessors) = graph.predecessors(node) {
1333 for pred in predecessors {
1334 if let Ok(weight) = graph.edge_weight(&pred, node) {
1335 in_weight += weight.into();
1336 }
1337 }
1338 }
1339
1340 if let Ok(successors) = graph.successors(node) {
1342 for succ in successors {
1343 if let Ok(weight) = graph.edge_weight(node, &succ) {
1344 out_weight += weight.into();
1345 }
1346 }
1347 }
1348
1349 centrality.insert(node.clone(), in_weight + out_weight);
1350 }
1351
1352 Ok(centrality)
1353}
1354
1355#[allow(dead_code)]
1359fn weighted_betweenness_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
1360where
1361 N: Node + std::fmt::Debug,
1362 E: EdgeWeight
1363 + Into<f64>
1364 + scirs2_core::numeric::Zero
1365 + scirs2_core::numeric::One
1366 + std::ops::Add<Output = E>
1367 + PartialOrd
1368 + Copy
1369 + std::fmt::Debug
1370 + Default,
1371 Ix: IndexType,
1372{
1373 let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1374 let n = nodes.len();
1375 let mut centrality: HashMap<N, f64> = nodes.iter().map(|n| (n.clone(), 0.0)).collect();
1376
1377 for source in &nodes {
1379 for target in &nodes {
1380 if source != target {
1381 if let Ok(Some(path)) = dijkstra_path(graph, source, target) {
1383 for intermediate in &path.nodes[1..path.nodes.len() - 1] {
1385 *centrality.get_mut(intermediate).unwrap() += 1.0;
1386 }
1387 }
1388 }
1389 }
1390 }
1391
1392 if n > 2 {
1394 let normalization = ((n - 1) * (n - 2)) as f64;
1395 for value in centrality.values_mut() {
1396 *value /= normalization;
1397 }
1398 }
1399
1400 Ok(centrality)
1401}
1402
1403#[allow(dead_code)]
1405fn weighted_betweenness_centrality_digraph<N, E, Ix>(
1406 graph: &DiGraph<N, E, Ix>,
1407) -> Result<HashMap<N, f64>>
1408where
1409 N: Node + std::fmt::Debug,
1410 E: EdgeWeight
1411 + Into<f64>
1412 + scirs2_core::numeric::Zero
1413 + scirs2_core::numeric::One
1414 + std::ops::Add<Output = E>
1415 + PartialOrd
1416 + Copy
1417 + std::fmt::Debug
1418 + Default,
1419 Ix: IndexType,
1420{
1421 let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1422 let n = nodes.len();
1423 let mut centrality: HashMap<N, f64> = nodes.iter().map(|n| (n.clone(), 0.0)).collect();
1424
1425 for source in &nodes {
1427 for target in &nodes {
1428 if source != target {
1429 if let Ok(Some(path)) = dijkstra_path_digraph(graph, source, target) {
1431 for intermediate in &path.nodes[1..path.nodes.len() - 1] {
1433 *centrality.get_mut(intermediate).unwrap() += 1.0;
1434 }
1435 }
1436 }
1437 }
1438 }
1439
1440 if n > 2 {
1442 let normalization = ((n - 1) * (n - 2)) as f64;
1443 for value in centrality.values_mut() {
1444 *value /= normalization;
1445 }
1446 }
1447
1448 Ok(centrality)
1449}
1450
1451#[allow(dead_code)]
1455fn weighted_closeness_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
1456where
1457 N: Node + std::fmt::Debug,
1458 E: EdgeWeight
1459 + Into<f64>
1460 + scirs2_core::numeric::Zero
1461 + scirs2_core::numeric::One
1462 + std::ops::Add<Output = E>
1463 + PartialOrd
1464 + Copy
1465 + std::fmt::Debug
1466 + Default,
1467 Ix: IndexType,
1468{
1469 let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1470 let n = nodes.len();
1471 let mut centrality = HashMap::new();
1472
1473 for node in &nodes {
1474 let mut total_distance = 0.0;
1475 let mut reachable_count = 0;
1476
1477 for other in &nodes {
1479 if node != other {
1480 if let Ok(Some(path)) = dijkstra_path(graph, node, other) {
1481 let distance: f64 = path.total_weight.into();
1482 total_distance += distance;
1483 reachable_count += 1;
1484 }
1485 }
1486 }
1487
1488 if reachable_count > 0 && total_distance > 0.0 {
1489 let closeness = reachable_count as f64 / total_distance;
1490 let normalized_closeness = if n > 1 {
1492 closeness * (reachable_count as f64 / (n - 1) as f64)
1493 } else {
1494 closeness
1495 };
1496 centrality.insert(node.clone(), normalized_closeness);
1497 } else {
1498 centrality.insert(node.clone(), 0.0);
1499 }
1500 }
1501
1502 Ok(centrality)
1503}
1504
1505#[allow(dead_code)]
1507fn weighted_closeness_centrality_digraph<N, E, Ix>(
1508 graph: &DiGraph<N, E, Ix>,
1509) -> Result<HashMap<N, f64>>
1510where
1511 N: Node + std::fmt::Debug,
1512 E: EdgeWeight
1513 + Into<f64>
1514 + scirs2_core::numeric::Zero
1515 + scirs2_core::numeric::One
1516 + std::ops::Add<Output = E>
1517 + PartialOrd
1518 + Copy
1519 + std::fmt::Debug
1520 + Default,
1521 Ix: IndexType,
1522{
1523 let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1524 let n = nodes.len();
1525 let mut centrality = HashMap::new();
1526
1527 for node in &nodes {
1528 let mut total_distance = 0.0;
1529 let mut reachable_count = 0;
1530
1531 for other in &nodes {
1533 if node != other {
1534 if let Ok(Some(path)) = dijkstra_path_digraph(graph, node, other) {
1535 let distance: f64 = path.total_weight.into();
1536 total_distance += distance;
1537 reachable_count += 1;
1538 }
1539 }
1540 }
1541
1542 if reachable_count > 0 && total_distance > 0.0 {
1543 let closeness = reachable_count as f64 / total_distance;
1544 let normalized_closeness = if n > 1 {
1546 closeness * (reachable_count as f64 / (n - 1) as f64)
1547 } else {
1548 closeness
1549 };
1550 centrality.insert(node.clone(), normalized_closeness);
1551 } else {
1552 centrality.insert(node.clone(), 0.0);
1553 }
1554 }
1555
1556 Ok(centrality)
1557}
1558
1559#[cfg(test)]
1560mod tests {
1561 use super::*;
1562
1563 #[test]
1564 fn test_degree_centrality() {
1565 let mut graph: Graph<char, f64> = Graph::new();
1566
1567 graph.add_edge('A', 'B', 1.0).unwrap();
1574 graph.add_edge('A', 'C', 1.0).unwrap();
1575 graph.add_edge('C', 'D', 1.0).unwrap();
1576
1577 let centrality = centrality(&graph, CentralityType::Degree).unwrap();
1578
1579 assert_eq!(centrality[&'A'], 2.0 / 3.0);
1585 assert_eq!(centrality[&'B'], 1.0 / 3.0);
1586 assert_eq!(centrality[&'C'], 2.0 / 3.0);
1587 assert_eq!(centrality[&'D'], 1.0 / 3.0);
1588 }
1589
1590 #[test]
1591 fn test_clustering_coefficient() {
1592 let mut graph: Graph<i32, f64> = Graph::new();
1593
1594 graph.add_edge(1, 2, 1.0).unwrap();
1602 graph.add_edge(2, 3, 1.0).unwrap();
1603 graph.add_edge(3, 4, 1.0).unwrap();
1604 graph.add_edge(4, 1, 1.0).unwrap();
1605 graph.add_edge(4, 5, 1.0).unwrap();
1606
1607 let coefficients = clustering_coefficient(&graph).unwrap();
1608
1609 assert_eq!(coefficients[&1], 0.0);
1611
1612 assert_eq!(coefficients[&2], 0.0);
1614
1615 assert_eq!(coefficients[&3], 0.0);
1617
1618 assert_eq!(coefficients[&4], 0.0);
1622
1623 assert_eq!(coefficients[&5], 0.0);
1625
1626 graph.add_edge(1, 3, 1.0).unwrap();
1628
1629 let coefficients = clustering_coefficient(&graph).unwrap();
1630
1631 assert!((coefficients[&4] - 1.0 / 3.0).abs() < 1e-10);
1636 }
1637
1638 #[test]
1639 fn test_graph_density() {
1640 let mut graph: Graph<i32, f64> = Graph::new();
1641
1642 assert!(graph_density(&graph).is_err());
1644
1645 graph.add_node(1);
1647
1648 assert!(graph_density(&graph).is_err());
1650
1651 graph.add_node(2);
1653 graph.add_node(3);
1654 graph.add_node(4);
1655
1656 graph.add_edge(1, 2, 1.0).unwrap();
1657 graph.add_edge(2, 3, 1.0).unwrap();
1658 graph.add_edge(3, 4, 1.0).unwrap();
1659
1660 let density = graph_density(&graph).unwrap();
1662 assert_eq!(density, 0.5);
1663
1664 graph.add_edge(1, 3, 1.0).unwrap();
1666 graph.add_edge(1, 4, 1.0).unwrap();
1667 graph.add_edge(2, 4, 1.0).unwrap();
1668
1669 let density = graph_density(&graph).unwrap();
1671 assert_eq!(density, 1.0);
1672 }
1673
1674 #[test]
1675 fn test_katz_centrality() {
1676 let mut graph: Graph<char, f64> = Graph::new();
1677
1678 graph.add_edge('A', 'B', 1.0).unwrap();
1680 graph.add_edge('A', 'C', 1.0).unwrap();
1681 graph.add_edge('A', 'D', 1.0).unwrap();
1682
1683 let centrality = katz_centrality(&graph, 0.1, 1.0).unwrap();
1684
1685 assert!(centrality[&'A'] > centrality[&'B']);
1687 assert!(centrality[&'A'] > centrality[&'C']);
1688 assert!(centrality[&'A'] > centrality[&'D']);
1689
1690 assert!((centrality[&'B'] - centrality[&'C']).abs() < 0.1);
1692 assert!((centrality[&'B'] - centrality[&'D']).abs() < 0.1);
1693 }
1694
1695 #[test]
1696 fn test_pagerank_centrality() {
1697 let mut graph: Graph<char, f64> = Graph::new();
1698
1699 graph.add_edge('A', 'B', 1.0).unwrap();
1701 graph.add_edge('B', 'C', 1.0).unwrap();
1702 graph.add_edge('C', 'A', 1.0).unwrap();
1703
1704 let centrality = pagerank_centrality(&graph, 0.85, 1e-6).unwrap();
1705
1706 let values: Vec<f64> = centrality.values().cloned().collect();
1708 let expected = 1.0 / 3.0; for &value in &values {
1711 assert!((value - expected).abs() < 0.1);
1712 }
1713
1714 let sum: f64 = values.iter().sum();
1716 assert!((sum - 1.0).abs() < 0.01);
1717 }
1718
1719 #[test]
1720 fn test_pagerank_centrality_digraph() {
1721 let mut graph: DiGraph<char, f64> = DiGraph::new();
1722
1723 graph.add_edge('A', 'B', 1.0).unwrap();
1725 graph.add_edge('B', 'C', 1.0).unwrap();
1726
1727 let centrality = pagerank_centrality_digraph(&graph, 0.85, 1e-6).unwrap();
1728
1729 assert!(centrality[&'C'] > centrality[&'B']);
1732 assert!(centrality[&'B'] > centrality[&'A']);
1733 }
1734
1735 #[test]
1736 fn test_centrality_enum_katz_pagerank() {
1737 let mut graph: Graph<char, f64> = Graph::new();
1738
1739 graph.add_edge('A', 'B', 1.0).unwrap();
1740 graph.add_edge('A', 'C', 1.0).unwrap();
1741
1742 let katz_result = centrality(&graph, CentralityType::Katz).unwrap();
1744 let pagerank_result = centrality(&graph, CentralityType::PageRank).unwrap();
1745
1746 assert_eq!(katz_result.len(), 3);
1748 assert_eq!(pagerank_result.len(), 3);
1749
1750 for value in katz_result.values() {
1752 assert!(*value > 0.0);
1753 }
1754 for value in pagerank_result.values() {
1755 assert!(*value > 0.0);
1756 }
1757 }
1758
1759 #[test]
1760 fn test_hits_algorithm() {
1761 let mut graph: DiGraph<char, f64> = DiGraph::new();
1762
1763 graph.add_edge('A', 'C', 1.0).unwrap();
1767 graph.add_edge('A', 'D', 1.0).unwrap();
1768 graph.add_edge('B', 'C', 1.0).unwrap();
1769 graph.add_edge('B', 'D', 1.0).unwrap();
1770 graph.add_edge('E', 'C', 1.0).unwrap();
1772 graph.add_edge('B', 'E', 1.0).unwrap();
1773
1774 let hits = hits_algorithm(&graph, 100, 1e-6).unwrap();
1775
1776 assert_eq!(hits.authorities.len(), 5);
1778 assert_eq!(hits.hubs.len(), 5);
1779
1780 assert!(hits.authorities[&'C'] > hits.authorities[&'A']);
1782 assert!(hits.authorities[&'D'] > hits.authorities[&'A']);
1783
1784 assert!(hits.hubs[&'A'] > hits.hubs[&'C']);
1786 assert!(hits.hubs[&'B'] > hits.hubs[&'C']);
1787
1788 let auth_norm: f64 = hits.authorities.values().map(|&x| x * x).sum::<f64>();
1790 let hub_norm: f64 = hits.hubs.values().map(|&x| x * x).sum::<f64>();
1791 assert!((auth_norm - 1.0).abs() < 0.01);
1792 assert!((hub_norm - 1.0).abs() < 0.01);
1793 }
1794
1795 #[test]
1796 fn test_weighted_degree_centrality() {
1797 let mut graph = crate::generators::create_graph::<&str, f64>();
1798
1799 graph.add_edge("A", "B", 2.0).unwrap();
1801 graph.add_edge("A", "C", 3.0).unwrap();
1802 graph.add_edge("B", "C", 1.0).unwrap();
1803
1804 let centrality = centrality(&graph, CentralityType::WeightedDegree).unwrap();
1805
1806 assert_eq!(centrality[&"A"], 5.0);
1808
1809 assert_eq!(centrality[&"B"], 3.0);
1811
1812 assert_eq!(centrality[&"C"], 4.0);
1814 }
1815
1816 #[test]
1817 fn test_weighted_closeness_centrality() {
1818 let mut graph = crate::generators::create_graph::<&str, f64>();
1819
1820 graph.add_edge("A", "B", 1.0).unwrap();
1822 graph.add_edge("B", "C", 2.0).unwrap();
1823
1824 let centrality = centrality(&graph, CentralityType::WeightedCloseness).unwrap();
1825
1826 for value in centrality.values() {
1828 assert!(*value > 0.0);
1829 }
1830
1831 assert!(centrality[&"B"] > centrality[&"A"]);
1833 assert!(centrality[&"B"] > centrality[&"C"]);
1834 }
1835
1836 #[test]
1837 fn test_weighted_betweenness_centrality() {
1838 let mut graph = crate::generators::create_graph::<&str, f64>();
1839
1840 graph.add_edge("A", "B", 1.0).unwrap();
1842 graph.add_edge("B", "C", 1.0).unwrap();
1843
1844 let centrality = centrality(&graph, CentralityType::WeightedBetweenness).unwrap();
1845
1846 assert!(centrality[&"B"] > 0.0);
1848
1849 assert_eq!(centrality[&"A"], 0.0);
1851 assert_eq!(centrality[&"C"], 0.0);
1852 }
1853
1854 #[test]
1855 fn test_weighted_centrality_digraph() {
1856 let mut graph = crate::generators::create_digraph::<&str, f64>();
1857
1858 graph.add_edge("A", "B", 2.0).unwrap();
1860 graph.add_edge("B", "C", 3.0).unwrap();
1861 graph.add_edge("A", "C", 1.0).unwrap();
1862
1863 let degree_centrality = centrality_digraph(&graph, CentralityType::WeightedDegree).unwrap();
1864 let closeness_centrality =
1865 centrality_digraph(&graph, CentralityType::WeightedCloseness).unwrap();
1866
1867 for value in degree_centrality.values() {
1869 assert!(*value >= 0.0);
1870 }
1871 for value in closeness_centrality.values() {
1872 assert!(*value >= 0.0);
1873 }
1874
1875 assert!(degree_centrality[&"B"] > degree_centrality[&"A"]);
1880 assert!(degree_centrality[&"B"] > degree_centrality[&"C"]);
1881 }
1882}