scirs2_graph/
measures.rs

1//! Graph measures and metrics
2//!
3//! This module provides functions for measuring various properties
4//! of graphs, including centrality measures, clustering coefficients,
5//! and other graph metrics.
6
7use 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/// Centrality measure type
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum CentralityType {
20    /// Degree centrality: number of connections
21    Degree,
22    /// Betweenness centrality: number of shortest paths going through a node
23    Betweenness,
24    /// Closeness centrality: inverse of the sum of shortest paths to all other nodes
25    Closeness,
26    /// Eigenvector centrality: nodes connected to important nodes are important
27    Eigenvector,
28    /// Katz centrality: influenced by all paths, with exponentially decaying weights
29    Katz,
30    /// PageRank centrality: Google's PageRank algorithm
31    PageRank,
32    /// Weighted degree centrality: sum of edge weights
33    WeightedDegree,
34    /// Weighted betweenness centrality: betweenness with edge weights
35    WeightedBetweenness,
36    /// Weighted closeness centrality: closeness with edge weights
37    WeightedCloseness,
38}
39
40/// Calculates centrality measures for nodes in an undirected graph
41///
42/// # Arguments
43/// * `graph` - The graph to analyze
44/// * `centrality_type` - The type of centrality to calculate
45///
46/// # Returns
47/// * `Result<HashMap<N, f64>>` - A map from nodes to their centrality values
48///
49/// # Time Complexity
50/// - Degree: O(V + E)
51/// - Betweenness: O(V * E) for unweighted, O(V² + VE) for weighted
52/// - Closeness: O(V * (V + E)) using BFS for each node
53/// - Eigenvector: O(V + E) per iteration, typically converges in O(log V) iterations
54/// - Katz: O(V + E) per iteration, typically converges quickly
55/// - PageRank: O(V + E) per iteration, typically converges in ~50 iterations
56///
57/// # Space Complexity
58/// O(V) for storing centrality values plus algorithm-specific requirements
59#[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), // Default parameters
90        CentralityType::PageRank => pagerank_centrality(graph, 0.85, 1e-6), // Default parameters
91        CentralityType::WeightedDegree => weighted_degree_centrality(graph),
92        CentralityType::WeightedBetweenness => weighted_betweenness_centrality(graph),
93        CentralityType::WeightedCloseness => weighted_closeness_centrality(graph),
94    }
95}
96
97/// Calculates centrality measures for nodes in a directed graph
98///
99/// # Arguments
100/// * `graph` - The directed graph to analyze
101/// * `centrality_type` - The type of centrality to calculate
102///
103/// # Returns
104/// * `Result<HashMap<N, f64>>` - A map from nodes to their centrality values
105#[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), // Default parameters
136        CentralityType::PageRank => pagerank_centrality_digraph(graph, 0.85, 1e-6), // Default parameters
137        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/// Calculates degree centrality for nodes in an undirected graph
144///
145/// # Time Complexity
146/// O(V + E) where V is vertices and E is edges
147///
148/// # Space Complexity
149/// O(V) for storing the centrality values
150#[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/// Calculates degree centrality for nodes in a directed graph
173#[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        // We use the sum of in-degree and out-degree as the total degree
190        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/// Calculates betweenness centrality for nodes in an undirected graph
198///
199/// # Time Complexity
200/// O(V * E) for unweighted graphs using Brandes' algorithm
201/// O(V² + VE) for weighted graphs
202///
203/// # Space Complexity
204/// O(V + E) for the algorithm's data structures
205#[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 each pair of nodes, find the shortest paths
237    for (i, &s) in nodes.iter().enumerate() {
238        for (j, &t) in nodes.iter().enumerate() {
239            if i == j {
240                continue;
241            }
242
243            // Find shortest path from s to t
244            if let Ok(Some(path)) = dijkstra_path(graph, s, t) {
245                // Skip source and target nodes
246                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    // Normalize by the number of possible paths (excluding the node itself)
254    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/// Calculates betweenness centrality for nodes in a directed graph
263#[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 each pair of nodes, find the shortest paths
295    for (i, &s) in nodes.iter().enumerate() {
296        for (j, &t) in nodes.iter().enumerate() {
297            if i == j {
298                continue;
299            }
300
301            // Find shortest path from s to t
302            if let Ok(Some(path)) = dijkstra_path_digraph(graph, s, t) {
303                // Skip source and target nodes
304                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    // Normalize by the number of possible paths (excluding the node itself)
312    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/// Calculates closeness centrality for nodes in an undirected graph
321#[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 each node, calculate the sum of shortest paths to all other nodes
350    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            // Find shortest path from node to other
360            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 the node can reach other nodes
367        if reachable_nodes > 0 {
368            // Closeness is 1 / average path length
369            let closeness_value = reachable_nodes as f64 / sum_distances;
370            // Normalize by the fraction of nodes that are reachable
371            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/// Calculates closeness centrality for nodes in a directed graph
382#[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 each node, calculate the sum of shortest paths to all other nodes
411    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            // Find shortest path from node to other
421            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 the node can reach other nodes
428        if reachable_nodes > 0 {
429            // Closeness is 1 / average path length
430            let closeness_value = reachable_nodes as f64 / sum_distances;
431            // Normalize by the fraction of nodes that are reachable
432            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/// Calculates eigenvector centrality for nodes in an undirected graph
443///
444/// Uses the power iteration method.
445#[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    // Get adjacency matrix with weights converted to f64
465    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    // Start with uniform vector
474    let mut x = Array1::<f64>::ones(n);
475    x.mapv_inplace(|v| v / (n as f64).sqrt()); // Normalize
476
477    // Power iteration
478    let max_iter = 100;
479    let tol = 1e-6;
480
481    for _ in 0..max_iter {
482        // y = A * x
483        let y = adj_f64.dot(&x);
484
485        // Compute the norm
486        let norm = (y.iter().map(|v| v * v).sum::<f64>()).sqrt();
487        if norm < 1e-10 {
488            // If the norm is too small, we have a zero vector
489            return Err(GraphError::AlgorithmError(
490                "Eigenvector centrality computation failed: zero eigenvalue".to_string(),
491            ));
492        }
493
494        // Normalize y
495        let y_norm = y / norm;
496
497        // Check for convergence
498        let diff = (&y_norm - &x).iter().map(|v| v.abs()).sum::<f64>();
499        if diff < tol {
500            // We've converged, create the result
501            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        // Update x for next iteration
509        x = y_norm;
510    }
511
512    // We've reached max iterations without converging
513    Err(GraphError::AlgorithmError(
514        "Eigenvector centrality computation did not converge".to_string(),
515    ))
516}
517
518/// Calculates eigenvector centrality for nodes in a directed graph
519///
520/// Uses the power iteration method.
521#[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    // Get adjacency matrix with weights converted to f64
541    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    // Start with uniform vector
550    let mut x = Array1::<f64>::ones(n);
551    x.mapv_inplace(|v| v / (n as f64).sqrt()); // Normalize
552
553    // Power iteration
554    let max_iter = 100;
555    let tol = 1e-6;
556
557    for _ in 0..max_iter {
558        // y = A * x
559        let y = adj_f64.dot(&x);
560
561        // Compute the norm
562        let norm = (y.iter().map(|v| v * v).sum::<f64>()).sqrt();
563        if norm < 1e-10 {
564            // If the norm is too small, we have a zero vector
565            return Err(GraphError::AlgorithmError(
566                "Eigenvector centrality computation failed: zero eigenvalue".to_string(),
567            ));
568        }
569
570        // Normalize y
571        let y_norm = y / norm;
572
573        // Check for convergence
574        let diff = (&y_norm - &x).iter().map(|v| v.abs()).sum::<f64>();
575        if diff < tol {
576            // We've converged, create the result
577            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        // Update x for next iteration
585        x = y_norm;
586    }
587
588    // We've reached max iterations without converging
589    Err(GraphError::AlgorithmError(
590        "Eigenvector centrality computation did not converge".to_string(),
591    ))
592}
593
594/// Calculates the local clustering coefficient for each node in an undirected graph
595///
596/// The clustering coefficient measures how close a node's neighbors are to being a clique.
597///
598/// # Arguments
599/// * `graph` - The graph to analyze
600///
601/// # Returns
602/// * `Result<HashMap<N, f64>>` - A map from nodes to their clustering coefficients
603#[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        // Get the neighbors of this node
614        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 the node has less than 2 neighbors, its clustering coefficient is 0
620        if k < 2 {
621            coefficients.insert(node.clone(), 0.0);
622            continue;
623        }
624
625        // Count the number of edges between neighbors
626        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        // Each edge is counted twice (once from each direction)
637        edge_count /= 2;
638
639        // Calculate the clustering coefficient
640        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/// Calculates the global clustering coefficient (transitivity) of a graph
650///
651/// This is the ratio of the number of closed triplets to the total number of triplets.
652///
653/// # Arguments
654/// * `graph` - The graph to analyze
655///
656/// # Returns
657/// * `Result<f64>` - The global clustering coefficient
658#[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/// Calculates the density of a directed graph
680///
681/// # Arguments
682/// * `graph` - The directed graph to analyze
683///
684/// # Returns
685/// * `Result<f64>` - The graph density
686#[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); // In directed graphs, there can be n(n-1) edges
703
704    Ok(m as f64 / possible_edges as f64)
705}
706
707/// Calculates Katz centrality for nodes in an undirected graph
708///
709/// Katz centrality is a variant of eigenvector centrality that considers all paths between nodes,
710/// with paths of longer length given exponentially decreasing weights.
711///
712/// # Arguments
713/// * `graph` - The graph to analyze
714/// * `alpha` - Attenuation factor (must be smaller than the reciprocal of the largest eigenvalue)
715/// * `beta` - Weight attributed to the immediate neighborhood
716///
717/// # Returns
718/// * `Result<HashMap<N, f64>>` - Katz centrality values
719#[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    // Get adjacency matrix
738    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    // Create identity matrix
747    let mut identity = Array2::<f64>::zeros((n, n));
748    for i in 0..n {
749        identity[[i, i]] = 1.0;
750    }
751
752    // Compute (I - α*A) - not used in iterative method but kept for reference
753    let _factor_matrix = &identity - &(alpha * &adj_f64);
754
755    // Create beta vector (all entries = beta)
756    let beta_vec = Array1::<f64>::from_elem(n, beta);
757
758    // We need to solve (I - α*A) * c = β*1
759    // For simplicity, we'll use an iterative approach (power method variant)
760    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        // c_new = α*A*c + β*1
766        let new_centrality = alpha * adj_f64.dot(&centrality_vec) + &beta_vec;
767
768        // Check for convergence
769        let diff = (&new_centrality - &centrality_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    // Convert to HashMap
782    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/// Calculates Katz centrality for nodes in a directed graph
791///
792/// # Arguments
793/// * `graph` - The directed graph to analyze
794/// * `alpha` - Attenuation factor
795/// * `beta` - Weight attributed to the immediate neighborhood
796///
797/// # Returns
798/// * `Result<HashMap<N, f64>>` - Katz centrality values
799#[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    // Get adjacency matrix
818    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    // Create beta vector
827    let beta_vec = Array1::<f64>::from_elem(n, beta);
828
829    // Iterative approach
830    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        // c_new = α*A^T*c + β*1 (transpose for incoming links)
836        let new_centrality = alpha * adj_f64.t().dot(&centrality_vec) + &beta_vec;
837
838        // Check for convergence
839        let diff = (&new_centrality - &centrality_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    // Convert to HashMap
852    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/// Calculates PageRank centrality for nodes in an undirected graph
861///
862/// PageRank is Google's famous algorithm for ranking web pages.
863/// For undirected graphs, we treat each edge as bidirectional.
864///
865/// # Arguments
866/// * `graph` - The graph to analyze
867/// * `damping` - Damping parameter (typically 0.85)
868/// * `tolerance` - Convergence tolerance
869///
870/// # Returns
871/// * `Result<HashMap<N, f64>>` - PageRank values
872#[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    // Initialize PageRank values
891    let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
892    let max_iter = 100;
893
894    // Get degree of each node for normalization
895    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        // Calculate PageRank contribution from each node
901        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                // Distribute to all neighbors
907                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        // Check for convergence
915        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    // Convert to HashMap
928    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/// Calculates PageRank centrality using parallel processing for large graphs
937///
938/// This parallel implementation of PageRank uses scirs2-core parallel operations
939/// to accelerate computation on large graphs. It's particularly effective when
940/// the graph has >10,000 nodes and sufficient CPU cores are available.
941///
942/// # Arguments
943/// * `graph` - The graph to analyze
944/// * `damping` - Damping parameter (typically 0.85)
945/// * `tolerance` - Convergence tolerance
946/// * `max_iterations` - Maximum number of iterations (default: 100)
947///
948/// # Returns
949/// * `Result<HashMap<N, f64>>` - PageRank values
950///
951/// # Time Complexity
952/// O((V + E) * k / p) where V is nodes, E is edges, k is iterations,
953/// and p is the number of parallel threads.
954///
955/// # Space Complexity
956/// O(V + t) where t is the number of threads for thread-local storage.
957///
958/// # Performance Notes
959/// - Best performance gain on graphs with >10,000 nodes
960/// - Requires multiple CPU cores for meaningful speedup
961/// - Memory access patterns optimized for cache efficiency
962#[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    // For small graphs, use sequential implementation
985    if n < 1000 {
986        return pagerank_centrality(graph, damping, tolerance);
987    }
988
989    let max_iter = max_iterations.unwrap_or(100);
990
991    // Initialize PageRank values
992    let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
993
994    // Get degree of each node for normalization
995    let degrees = graph.degree_vector();
996
997    // Pre-compute neighbor indices for efficient parallel access
998    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        // Parallel computation of new PageRank values
1011        let new_pagerank = Arc::new(Mutex::new(Array1::<f64>::from_elem(
1012            n,
1013            (1.0 - damping) / n as f64,
1014        )));
1015
1016        // Use parallel iteration for PageRank calculation
1017        (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                // Distribute to all neighbors
1023                let mut local_updates = Vec::new();
1024                for &neighbor_i in &neighbor_lists[i] {
1025                    local_updates.push((neighbor_i, contribution));
1026                }
1027
1028                // Apply updates atomically
1029                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        // Convergence check
1041        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    // Conversion to HashMap
1056    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/// HITS (Hyperlink-Induced Topic Search) algorithm result
1066#[derive(Debug, Clone)]
1067pub struct HitsScores<N: Node> {
1068    /// Authority scores for each node
1069    pub authorities: HashMap<N, f64>,
1070    /// Hub scores for each node
1071    pub hubs: HashMap<N, f64>,
1072}
1073
1074/// Compute HITS algorithm for a directed graph
1075///
1076/// The HITS algorithm computes two scores for each node:
1077/// - Authority score: nodes that are pointed to by many hubs
1078/// - Hub score: nodes that point to many authorities
1079///
1080/// # Arguments
1081/// * `graph` - The directed graph
1082/// * `max_iter` - Maximum number of iterations
1083/// * `tolerance` - Convergence tolerance
1084///
1085/// # Returns
1086/// * HitsScores containing authority and hub scores for each node
1087#[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    // Initialize scores
1109    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    // Create node index mapping
1115    let node_to_idx: HashMap<N, usize> = nodes
1116        .iter()
1117        .enumerate()
1118        .map(|(i, n)| (n.clone(), i))
1119        .collect();
1120
1121    // Iterate until convergence
1122    for _ in 0..max_iter {
1123        // Update authority scores
1124        new_authorities.fill(0.0);
1125        for (i, node) in nodes.iter().enumerate() {
1126            // Authority score is sum of hub scores of nodes pointing to it
1127            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        // Update hub scores
1137        new_hubs.fill(0.0);
1138        for (i, node) in nodes.iter().enumerate() {
1139            // Hub score is sum of authority scores of nodes it points to
1140            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        // Normalize scores
1150        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        // Check convergence
1166        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        // Update scores
1182        authorities.copy_from_slice(&new_authorities);
1183        hubs.copy_from_slice(&new_hubs);
1184    }
1185
1186    // Convert to HashMap
1187    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/// Calculates PageRank centrality for nodes in a directed graph
1205///
1206/// # Arguments
1207/// * `graph` - The directed graph to analyze
1208/// * `damping` - Damping parameter (typically 0.85)
1209/// * `tolerance` - Convergence tolerance
1210///
1211/// # Returns
1212/// * `Result<HashMap<N, f64>>` - PageRank values
1213#[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    // Initialize PageRank values
1232    let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
1233    let max_iter = 100;
1234
1235    // Get out-degree of each node for normalization
1236    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        // Calculate PageRank contribution from each node
1242        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                // Distribute to all outgoing neighbors
1248                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                // Handle dangling nodes by distributing equally to all nodes
1257                let contribution = damping * pagerank[i] / n as f64;
1258                for j in 0..n {
1259                    new_pagerank[j] += contribution;
1260                }
1261            }
1262        }
1263
1264        // Check for convergence
1265        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    // Convert to HashMap
1278    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/// Calculates weighted degree centrality for undirected graphs
1287///
1288/// Weighted degree centrality is the sum of the weights of all edges incident to a node.
1289#[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/// Calculates weighted degree centrality for directed graphs
1316#[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        // Sum incoming edge weights
1332        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        // Sum outgoing edge weights
1341        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/// Calculates weighted betweenness centrality for undirected graphs
1356///
1357/// Uses Dijkstra's algorithm to find shortest weighted paths between all pairs of nodes.
1358#[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 each pair of nodes, find shortest weighted paths
1378    for source in &nodes {
1379        for target in &nodes {
1380            if source != target {
1381                // Find shortest weighted path
1382                if let Ok(Some(path)) = dijkstra_path(graph, source, target) {
1383                    // Count how many times each intermediate node appears
1384                    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    // Normalize by (n-1)(n-2) for undirected graphs
1393    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/// Calculates weighted betweenness centrality for directed graphs
1404#[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 each pair of nodes, find shortest weighted paths
1426    for source in &nodes {
1427        for target in &nodes {
1428            if source != target {
1429                // Find shortest weighted path in directed graph
1430                if let Ok(Some(path)) = dijkstra_path_digraph(graph, source, target) {
1431                    // Count how many times each intermediate node appears
1432                    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    // Normalize by (n-1)(n-2) for directed graphs
1441    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/// Calculates weighted closeness centrality for undirected graphs
1452///
1453/// Weighted closeness centrality uses the shortest weighted path distances.
1454#[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        // Calculate shortest weighted paths to all other nodes
1478        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            // Normalize by (n-1) to get values between 0 and 1
1491            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/// Calculates weighted closeness centrality for directed graphs
1506#[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        // Calculate shortest weighted paths to all other nodes
1532        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            // Normalize by (n-1) to get values between 0 and 1
1545            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        // Create a star graph with A in the center
1568        // A -- B
1569        // |
1570        // |
1571        // C -- D
1572
1573        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        // A has 2 connections out of 3 possible, so centrality = 2/3
1580        // B has 1 connection out of 3 possible, so centrality = 1/3
1581        // C has 2 connections out of 3 possible, so centrality = 2/3
1582        // D has 1 connection out of 3 possible, so centrality = 1/3
1583
1584        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        // Create a graph:
1595        // 1 -- 2 -- 3
1596        // |         |
1597        // +----4----+
1598        //      |
1599        //      5
1600
1601        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        // Node 1 has neighbors 2 and 4, and they're not connected, so coefficient = 0/1 = 0
1610        assert_eq!(coefficients[&1], 0.0);
1611
1612        // Node 2 has neighbors 1 and 3, and they're not connected, so coefficient = 0/1 = 0
1613        assert_eq!(coefficients[&2], 0.0);
1614
1615        // Node 3 has neighbors 2 and 4, and they're not connected, so coefficient = 0/1 = 0
1616        assert_eq!(coefficients[&3], 0.0);
1617
1618        // Node 4 has neighbors 1, 3, and 5.
1619        // Neighbors 1 and 3 are not directly connected, and 5 is not connected to either 1 or 3
1620        // So coefficient = 0/3 = 0
1621        assert_eq!(coefficients[&4], 0.0);
1622
1623        // Node 5 has only one neighbor (4), so coefficient = 0
1624        assert_eq!(coefficients[&5], 0.0);
1625
1626        // Now let's add an edge to create a triangle
1627        graph.add_edge(1, 3, 1.0).unwrap();
1628
1629        let coefficients = clustering_coefficient(&graph).unwrap();
1630
1631        // Now nodes 1, 3, and 4 form a triangle
1632        // Node 4 has 3 neighbors (1, 3, 5) with 1 edge between them (1-3)
1633        // Possible edges: 3 choose 2 = 3
1634        // So coefficient = 1/3
1635        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        // Empty graph should error
1643        assert!(graph_density(&graph).is_err());
1644
1645        // Add one node
1646        graph.add_node(1);
1647
1648        // Graph with one node should error
1649        assert!(graph_density(&graph).is_err());
1650
1651        // Create a graph with 4 nodes and 3 edges
1652        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        // 3 edges out of 6 possible edges (4 choose 2 = 6)
1661        let density = graph_density(&graph).unwrap();
1662        assert_eq!(density, 0.5);
1663
1664        // Add 3 more edges to make a complete graph
1665        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        // 6 edges out of 6 possible edges
1670        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        // Create a simple star graph with A in the center
1679        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        // The center node should have higher Katz centrality
1686        assert!(centrality[&'A'] > centrality[&'B']);
1687        assert!(centrality[&'A'] > centrality[&'C']);
1688        assert!(centrality[&'A'] > centrality[&'D']);
1689
1690        // All leaf nodes should have similar centrality
1691        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        // Create a simple triangle
1700        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        // All nodes should have equal PageRank in a symmetric triangle
1707        let values: Vec<f64> = centrality.values().cloned().collect();
1708        let expected = 1.0 / 3.0; // Should sum to 1, so each gets 1/3
1709
1710        for &value in &values {
1711            assert!((value - expected).abs() < 0.1);
1712        }
1713
1714        // Check that PageRank values sum to approximately 1
1715        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        // Create a directed path: A -> B -> C
1724        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        // C should have the highest PageRank (receives links but doesn't give any)
1730        // A should have the lowest (gives links but doesn't receive any except random jumps)
1731        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        // Test that the enum-based centrality function works for new types
1743        let katz_result = centrality(&graph, CentralityType::Katz).unwrap();
1744        let pagerank_result = centrality(&graph, CentralityType::PageRank).unwrap();
1745
1746        // Both should return valid results
1747        assert_eq!(katz_result.len(), 3);
1748        assert_eq!(pagerank_result.len(), 3);
1749
1750        // All values should be positive
1751        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        // Create a small web graph
1764        // A and B are hubs (point to many pages)
1765        // C and D are authorities (pointed to by many pages)
1766        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        // E is both a hub and authority
1771        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        // Check that we have scores for all nodes
1777        assert_eq!(hits.authorities.len(), 5);
1778        assert_eq!(hits.hubs.len(), 5);
1779
1780        // C and D should have high authority scores
1781        assert!(hits.authorities[&'C'] > hits.authorities[&'A']);
1782        assert!(hits.authorities[&'D'] > hits.authorities[&'A']);
1783
1784        // A and B should have high hub scores
1785        assert!(hits.hubs[&'A'] > hits.hubs[&'C']);
1786        assert!(hits.hubs[&'B'] > hits.hubs[&'C']);
1787
1788        // Check that scores are normalized (sum of squares = 1)
1789        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        // Create a simple weighted graph
1800        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        // A has edges with weights 2.0 + 3.0 = 5.0
1807        assert_eq!(centrality[&"A"], 5.0);
1808
1809        // B has edges with weights 2.0 + 1.0 = 3.0
1810        assert_eq!(centrality[&"B"], 3.0);
1811
1812        // C has edges with weights 3.0 + 1.0 = 4.0
1813        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        // Create a simple weighted graph
1821        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        // All centrality values should be positive
1827        for value in centrality.values() {
1828            assert!(*value > 0.0);
1829        }
1830
1831        // Node B should have highest closeness (shortest paths to others)
1832        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        // Create a path graph A-B-C
1841        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        // B should have positive betweenness (lies on path from A to C)
1847        assert!(centrality[&"B"] > 0.0);
1848
1849        // A and C should have zero betweenness (no paths pass through them)
1850        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        // Create a simple directed weighted graph
1859        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        // All centrality values should be non-negative
1868        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        // A has weighted degree 2.0 + 1.0 = 3.0 (outgoing only)
1876        // B has weighted degree 2.0 (incoming) + 3.0 (outgoing) = 5.0 total
1877        // C has weighted degree 3.0 + 1.0 = 4.0 (incoming only)
1878        // So B should have the highest total weighted degree
1879        assert!(degree_centrality[&"B"] > degree_centrality[&"A"]);
1880        assert!(degree_centrality[&"B"] > degree_centrality[&"C"]);
1881    }
1882}