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().expect("Failed to acquire lock");
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)
1039            .expect("Failed to unwrap Arc")
1040            .into_inner()
1041            .expect("Failed to get inner value");
1042
1043        // Convergence check
1044        let diff = pagerank
1045            .iter()
1046            .zip(new_pagerank.iter())
1047            .map(|(old, new)| (new - old).abs())
1048            .sum::<f64>();
1049
1050        if diff < tolerance {
1051            pagerank = new_pagerank;
1052            break;
1053        }
1054
1055        pagerank = new_pagerank;
1056    }
1057
1058    // Conversion to HashMap
1059    let result: HashMap<N, f64> = nodes
1060        .iter()
1061        .enumerate()
1062        .map(|(i, node)| ((*node).clone(), pagerank[i]))
1063        .collect();
1064
1065    Ok(result)
1066}
1067
1068/// HITS (Hyperlink-Induced Topic Search) algorithm result
1069#[derive(Debug, Clone)]
1070pub struct HitsScores<N: Node> {
1071    /// Authority scores for each node
1072    pub authorities: HashMap<N, f64>,
1073    /// Hub scores for each node
1074    pub hubs: HashMap<N, f64>,
1075}
1076
1077/// Compute HITS algorithm for a directed graph
1078///
1079/// The HITS algorithm computes two scores for each node:
1080/// - Authority score: nodes that are pointed to by many hubs
1081/// - Hub score: nodes that point to many authorities
1082///
1083/// # Arguments
1084/// * `graph` - The directed graph
1085/// * `max_iter` - Maximum number of iterations
1086/// * `tolerance` - Convergence tolerance
1087///
1088/// # Returns
1089/// * HitsScores containing authority and hub scores for each node
1090#[allow(dead_code)]
1091pub fn hits_algorithm<N, E, Ix>(
1092    graph: &DiGraph<N, E, Ix>,
1093    max_iter: usize,
1094    tolerance: f64,
1095) -> Result<HitsScores<N>>
1096where
1097    N: Node + Clone + Hash + Eq + std::fmt::Debug,
1098    E: EdgeWeight,
1099    Ix: IndexType,
1100{
1101    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1102    let n = nodes.len();
1103
1104    if n == 0 {
1105        return Ok(HitsScores {
1106            authorities: HashMap::new(),
1107            hubs: HashMap::new(),
1108        });
1109    }
1110
1111    // Initialize scores
1112    let mut authorities = vec![1.0 / (n as f64).sqrt(); n];
1113    let mut hubs = vec![1.0 / (n as f64).sqrt(); n];
1114    let mut new_authorities = vec![0.0; n];
1115    let mut new_hubs = vec![0.0; n];
1116
1117    // Create node index mapping
1118    let node_to_idx: HashMap<N, usize> = nodes
1119        .iter()
1120        .enumerate()
1121        .map(|(i, n)| (n.clone(), i))
1122        .collect();
1123
1124    // Iterate until convergence
1125    for _ in 0..max_iter {
1126        // Update authority scores
1127        new_authorities.fill(0.0);
1128        for (i, node) in nodes.iter().enumerate() {
1129            // Authority score is sum of hub scores of nodes pointing to it
1130            if let Ok(predecessors) = graph.predecessors(node) {
1131                for pred in predecessors {
1132                    if let Some(&pred_idx) = node_to_idx.get(&pred) {
1133                        new_authorities[i] += hubs[pred_idx];
1134                    }
1135                }
1136            }
1137        }
1138
1139        // Update hub scores
1140        new_hubs.fill(0.0);
1141        for (i, node) in nodes.iter().enumerate() {
1142            // Hub score is sum of authority scores of nodes it points to
1143            if let Ok(successors) = graph.successors(node) {
1144                for succ in successors {
1145                    if let Some(&succ_idx) = node_to_idx.get(&succ) {
1146                        new_hubs[i] += authorities[succ_idx];
1147                    }
1148                }
1149            }
1150        }
1151
1152        // Normalize scores
1153        let auth_norm: f64 = new_authorities.iter().map(|x| x * x).sum::<f64>().sqrt();
1154        let hub_norm: f64 = new_hubs.iter().map(|x| x * x).sum::<f64>().sqrt();
1155
1156        if auth_norm > 0.0 {
1157            for score in &mut new_authorities {
1158                *score /= auth_norm;
1159            }
1160        }
1161
1162        if hub_norm > 0.0 {
1163            for score in &mut new_hubs {
1164                *score /= hub_norm;
1165            }
1166        }
1167
1168        // Check convergence
1169        let auth_diff: f64 = authorities
1170            .iter()
1171            .zip(&new_authorities)
1172            .map(|(old, new)| (old - new).abs())
1173            .sum();
1174        let hub_diff: f64 = hubs
1175            .iter()
1176            .zip(&new_hubs)
1177            .map(|(old, new)| (old - new).abs())
1178            .sum();
1179
1180        if auth_diff < tolerance && hub_diff < tolerance {
1181            break;
1182        }
1183
1184        // Update scores
1185        authorities.copy_from_slice(&new_authorities);
1186        hubs.copy_from_slice(&new_hubs);
1187    }
1188
1189    // Convert to HashMap
1190    let authority_map = nodes
1191        .iter()
1192        .enumerate()
1193        .map(|(i, n)| (n.clone(), authorities[i]))
1194        .collect();
1195    let hub_map = nodes
1196        .iter()
1197        .enumerate()
1198        .map(|(i, n)| (n.clone(), hubs[i]))
1199        .collect();
1200
1201    Ok(HitsScores {
1202        authorities: authority_map,
1203        hubs: hub_map,
1204    })
1205}
1206
1207/// Calculates PageRank centrality for nodes in a directed graph
1208///
1209/// # Arguments
1210/// * `graph` - The directed graph to analyze
1211/// * `damping` - Damping parameter (typically 0.85)
1212/// * `tolerance` - Convergence tolerance
1213///
1214/// # Returns
1215/// * `Result<HashMap<N, f64>>` - PageRank values
1216#[allow(dead_code)]
1217pub fn pagerank_centrality_digraph<N, E, Ix>(
1218    graph: &DiGraph<N, E, Ix>,
1219    damping: f64,
1220    tolerance: f64,
1221) -> Result<HashMap<N, f64>>
1222where
1223    N: Node + std::fmt::Debug,
1224    E: EdgeWeight,
1225    Ix: petgraph::graph::IndexType,
1226{
1227    let nodes = graph.nodes();
1228    let n = nodes.len();
1229
1230    if n == 0 {
1231        return Err(GraphError::InvalidGraph("Empty graph".to_string()));
1232    }
1233
1234    // Initialize PageRank values
1235    let mut pagerank = Array1::<f64>::from_elem(n, 1.0 / n as f64);
1236    let max_iter = 100;
1237
1238    // Get out-degree of each node for normalization
1239    let out_degrees = graph.out_degree_vector();
1240
1241    for _ in 0..max_iter {
1242        let mut new_pagerank = Array1::<f64>::from_elem(n, (1.0 - damping) / n as f64);
1243
1244        // Calculate PageRank contribution from each node
1245        for (i, node_idx) in graph.inner().node_indices().enumerate() {
1246            let node_out_degree = out_degrees[i] as f64;
1247            if node_out_degree > 0.0 {
1248                let contribution = damping * pagerank[i] / node_out_degree;
1249
1250                // Distribute to all outgoing neighbors
1251                for neighbor_idx in graph
1252                    .inner()
1253                    .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
1254                {
1255                    let neighbor_i = neighbor_idx.index();
1256                    new_pagerank[neighbor_i] += contribution;
1257                }
1258            } else {
1259                // Handle dangling nodes by distributing equally to all nodes
1260                let contribution = damping * pagerank[i] / n as f64;
1261                for j in 0..n {
1262                    new_pagerank[j] += contribution;
1263                }
1264            }
1265        }
1266
1267        // Check for convergence
1268        let diff = (&new_pagerank - &pagerank)
1269            .iter()
1270            .map(|v| v.abs())
1271            .sum::<f64>();
1272        if diff < tolerance {
1273            pagerank = new_pagerank;
1274            break;
1275        }
1276
1277        pagerank = new_pagerank;
1278    }
1279
1280    // Convert to HashMap
1281    let mut result = HashMap::new();
1282    for (i, &node) in nodes.iter().enumerate() {
1283        result.insert(node.clone(), pagerank[i]);
1284    }
1285
1286    Ok(result)
1287}
1288
1289/// Calculates weighted degree centrality for undirected graphs
1290///
1291/// Weighted degree centrality is the sum of the weights of all edges incident to a node.
1292#[allow(dead_code)]
1293fn weighted_degree_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
1294where
1295    N: Node + std::fmt::Debug,
1296    E: EdgeWeight + Into<f64> + Clone,
1297    Ix: IndexType,
1298{
1299    let mut centrality = HashMap::new();
1300
1301    for node in graph.nodes() {
1302        let mut weight_sum = 0.0;
1303
1304        if let Ok(neighbors) = graph.neighbors(node) {
1305            for neighbor in neighbors {
1306                if let Ok(weight) = graph.edge_weight(node, &neighbor) {
1307                    weight_sum += weight.into();
1308                }
1309            }
1310        }
1311
1312        centrality.insert(node.clone(), weight_sum);
1313    }
1314
1315    Ok(centrality)
1316}
1317
1318/// Calculates weighted degree centrality for directed graphs
1319#[allow(dead_code)]
1320fn weighted_degree_centrality_digraph<N, E, Ix>(
1321    graph: &DiGraph<N, E, Ix>,
1322) -> Result<HashMap<N, f64>>
1323where
1324    N: Node + std::fmt::Debug,
1325    E: EdgeWeight + Into<f64> + Clone,
1326    Ix: IndexType,
1327{
1328    let mut centrality = HashMap::new();
1329
1330    for node in graph.nodes() {
1331        let mut in_weight = 0.0;
1332        let mut out_weight = 0.0;
1333
1334        // Sum incoming edge weights
1335        if let Ok(predecessors) = graph.predecessors(node) {
1336            for pred in predecessors {
1337                if let Ok(weight) = graph.edge_weight(&pred, node) {
1338                    in_weight += weight.into();
1339                }
1340            }
1341        }
1342
1343        // Sum outgoing edge weights
1344        if let Ok(successors) = graph.successors(node) {
1345            for succ in successors {
1346                if let Ok(weight) = graph.edge_weight(node, &succ) {
1347                    out_weight += weight.into();
1348                }
1349            }
1350        }
1351
1352        centrality.insert(node.clone(), in_weight + out_weight);
1353    }
1354
1355    Ok(centrality)
1356}
1357
1358/// Calculates weighted betweenness centrality for undirected graphs
1359///
1360/// Uses Dijkstra's algorithm to find shortest weighted paths between all pairs of nodes.
1361#[allow(dead_code)]
1362fn weighted_betweenness_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
1363where
1364    N: Node + std::fmt::Debug,
1365    E: EdgeWeight
1366        + Into<f64>
1367        + scirs2_core::numeric::Zero
1368        + scirs2_core::numeric::One
1369        + std::ops::Add<Output = E>
1370        + PartialOrd
1371        + Copy
1372        + std::fmt::Debug
1373        + Default,
1374    Ix: IndexType,
1375{
1376    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1377    let n = nodes.len();
1378    let mut centrality: HashMap<N, f64> = nodes.iter().map(|n| (n.clone(), 0.0)).collect();
1379
1380    // For each pair of nodes, find shortest weighted paths
1381    for source in &nodes {
1382        for target in &nodes {
1383            if source != target {
1384                // Find shortest weighted path
1385                if let Ok(Some(path)) = dijkstra_path(graph, source, target) {
1386                    // Count how many times each intermediate node appears
1387                    for intermediate in &path.nodes[1..path.nodes.len() - 1] {
1388                        *centrality
1389                            .get_mut(intermediate)
1390                            .expect("Failed to get mutable reference") += 1.0;
1391                    }
1392                }
1393            }
1394        }
1395    }
1396
1397    // Normalize by (n-1)(n-2) for undirected graphs
1398    if n > 2 {
1399        let normalization = ((n - 1) * (n - 2)) as f64;
1400        for value in centrality.values_mut() {
1401            *value /= normalization;
1402        }
1403    }
1404
1405    Ok(centrality)
1406}
1407
1408/// Calculates weighted betweenness centrality for directed graphs
1409#[allow(dead_code)]
1410fn weighted_betweenness_centrality_digraph<N, E, Ix>(
1411    graph: &DiGraph<N, E, Ix>,
1412) -> Result<HashMap<N, f64>>
1413where
1414    N: Node + std::fmt::Debug,
1415    E: EdgeWeight
1416        + Into<f64>
1417        + scirs2_core::numeric::Zero
1418        + scirs2_core::numeric::One
1419        + std::ops::Add<Output = E>
1420        + PartialOrd
1421        + Copy
1422        + std::fmt::Debug
1423        + Default,
1424    Ix: IndexType,
1425{
1426    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1427    let n = nodes.len();
1428    let mut centrality: HashMap<N, f64> = nodes.iter().map(|n| (n.clone(), 0.0)).collect();
1429
1430    // For each pair of nodes, find shortest weighted paths
1431    for source in &nodes {
1432        for target in &nodes {
1433            if source != target {
1434                // Find shortest weighted path in directed graph
1435                if let Ok(Some(path)) = dijkstra_path_digraph(graph, source, target) {
1436                    // Count how many times each intermediate node appears
1437                    for intermediate in &path.nodes[1..path.nodes.len() - 1] {
1438                        *centrality
1439                            .get_mut(intermediate)
1440                            .expect("Failed to get mutable reference") += 1.0;
1441                    }
1442                }
1443            }
1444        }
1445    }
1446
1447    // Normalize by (n-1)(n-2) for directed graphs
1448    if n > 2 {
1449        let normalization = ((n - 1) * (n - 2)) as f64;
1450        for value in centrality.values_mut() {
1451            *value /= normalization;
1452        }
1453    }
1454
1455    Ok(centrality)
1456}
1457
1458/// Calculates weighted closeness centrality for undirected graphs
1459///
1460/// Weighted closeness centrality uses the shortest weighted path distances.
1461#[allow(dead_code)]
1462fn weighted_closeness_centrality<N, E, Ix>(graph: &Graph<N, E, Ix>) -> Result<HashMap<N, f64>>
1463where
1464    N: Node + std::fmt::Debug,
1465    E: EdgeWeight
1466        + Into<f64>
1467        + scirs2_core::numeric::Zero
1468        + scirs2_core::numeric::One
1469        + std::ops::Add<Output = E>
1470        + PartialOrd
1471        + Copy
1472        + std::fmt::Debug
1473        + Default,
1474    Ix: IndexType,
1475{
1476    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1477    let n = nodes.len();
1478    let mut centrality = HashMap::new();
1479
1480    for node in &nodes {
1481        let mut total_distance = 0.0;
1482        let mut reachable_count = 0;
1483
1484        // Calculate shortest weighted paths to all other nodes
1485        for other in &nodes {
1486            if node != other {
1487                if let Ok(Some(path)) = dijkstra_path(graph, node, other) {
1488                    let distance: f64 = path.total_weight.into();
1489                    total_distance += distance;
1490                    reachable_count += 1;
1491                }
1492            }
1493        }
1494
1495        if reachable_count > 0 && total_distance > 0.0 {
1496            let closeness = reachable_count as f64 / total_distance;
1497            // Normalize by (n-1) to get values between 0 and 1
1498            let normalized_closeness = if n > 1 {
1499                closeness * (reachable_count as f64 / (n - 1) as f64)
1500            } else {
1501                closeness
1502            };
1503            centrality.insert(node.clone(), normalized_closeness);
1504        } else {
1505            centrality.insert(node.clone(), 0.0);
1506        }
1507    }
1508
1509    Ok(centrality)
1510}
1511
1512/// Calculates weighted closeness centrality for directed graphs
1513#[allow(dead_code)]
1514fn weighted_closeness_centrality_digraph<N, E, Ix>(
1515    graph: &DiGraph<N, E, Ix>,
1516) -> Result<HashMap<N, f64>>
1517where
1518    N: Node + std::fmt::Debug,
1519    E: EdgeWeight
1520        + Into<f64>
1521        + scirs2_core::numeric::Zero
1522        + scirs2_core::numeric::One
1523        + std::ops::Add<Output = E>
1524        + PartialOrd
1525        + Copy
1526        + std::fmt::Debug
1527        + Default,
1528    Ix: IndexType,
1529{
1530    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
1531    let n = nodes.len();
1532    let mut centrality = HashMap::new();
1533
1534    for node in &nodes {
1535        let mut total_distance = 0.0;
1536        let mut reachable_count = 0;
1537
1538        // Calculate shortest weighted paths to all other nodes
1539        for other in &nodes {
1540            if node != other {
1541                if let Ok(Some(path)) = dijkstra_path_digraph(graph, node, other) {
1542                    let distance: f64 = path.total_weight.into();
1543                    total_distance += distance;
1544                    reachable_count += 1;
1545                }
1546            }
1547        }
1548
1549        if reachable_count > 0 && total_distance > 0.0 {
1550            let closeness = reachable_count as f64 / total_distance;
1551            // Normalize by (n-1) to get values between 0 and 1
1552            let normalized_closeness = if n > 1 {
1553                closeness * (reachable_count as f64 / (n - 1) as f64)
1554            } else {
1555                closeness
1556            };
1557            centrality.insert(node.clone(), normalized_closeness);
1558        } else {
1559            centrality.insert(node.clone(), 0.0);
1560        }
1561    }
1562
1563    Ok(centrality)
1564}
1565
1566#[cfg(test)]
1567mod tests {
1568    use super::*;
1569
1570    #[test]
1571    fn test_degree_centrality() {
1572        let mut graph: Graph<char, f64> = Graph::new();
1573
1574        // Create a star graph with A in the center
1575        // A -- B
1576        // |
1577        // |
1578        // C -- D
1579
1580        graph.add_edge('A', 'B', 1.0).expect("Test failed");
1581        graph.add_edge('A', 'C', 1.0).expect("Test failed");
1582        graph.add_edge('C', 'D', 1.0).expect("Test failed");
1583
1584        let centrality = centrality(&graph, CentralityType::Degree).expect("Test failed");
1585
1586        // A has 2 connections out of 3 possible, so centrality = 2/3
1587        // B has 1 connection out of 3 possible, so centrality = 1/3
1588        // C has 2 connections out of 3 possible, so centrality = 2/3
1589        // D has 1 connection out of 3 possible, so centrality = 1/3
1590
1591        assert_eq!(centrality[&'A'], 2.0 / 3.0);
1592        assert_eq!(centrality[&'B'], 1.0 / 3.0);
1593        assert_eq!(centrality[&'C'], 2.0 / 3.0);
1594        assert_eq!(centrality[&'D'], 1.0 / 3.0);
1595    }
1596
1597    #[test]
1598    fn test_clustering_coefficient() {
1599        let mut graph: Graph<i32, f64> = Graph::new();
1600
1601        // Create a graph:
1602        // 1 -- 2 -- 3
1603        // |         |
1604        // +----4----+
1605        //      |
1606        //      5
1607
1608        graph.add_edge(1, 2, 1.0).expect("Test failed");
1609        graph.add_edge(2, 3, 1.0).expect("Test failed");
1610        graph.add_edge(3, 4, 1.0).expect("Test failed");
1611        graph.add_edge(4, 1, 1.0).expect("Test failed");
1612        graph.add_edge(4, 5, 1.0).expect("Test failed");
1613
1614        let coefficients = clustering_coefficient(&graph).expect("Test failed");
1615
1616        // Node 1 has neighbors 2 and 4, and they're not connected, so coefficient = 0/1 = 0
1617        assert_eq!(coefficients[&1], 0.0);
1618
1619        // Node 2 has neighbors 1 and 3, and they're not connected, so coefficient = 0/1 = 0
1620        assert_eq!(coefficients[&2], 0.0);
1621
1622        // Node 3 has neighbors 2 and 4, and they're not connected, so coefficient = 0/1 = 0
1623        assert_eq!(coefficients[&3], 0.0);
1624
1625        // Node 4 has neighbors 1, 3, and 5.
1626        // Neighbors 1 and 3 are not directly connected, and 5 is not connected to either 1 or 3
1627        // So coefficient = 0/3 = 0
1628        assert_eq!(coefficients[&4], 0.0);
1629
1630        // Node 5 has only one neighbor (4), so coefficient = 0
1631        assert_eq!(coefficients[&5], 0.0);
1632
1633        // Now let's add an edge to create a triangle
1634        graph.add_edge(1, 3, 1.0).expect("Test failed");
1635
1636        let coefficients = clustering_coefficient(&graph).expect("Test failed");
1637
1638        // Now nodes 1, 3, and 4 form a triangle
1639        // Node 4 has 3 neighbors (1, 3, 5) with 1 edge between them (1-3)
1640        // Possible edges: 3 choose 2 = 3
1641        // So coefficient = 1/3
1642        assert!((coefficients[&4] - 1.0 / 3.0).abs() < 1e-10);
1643    }
1644
1645    #[test]
1646    fn test_graph_density() {
1647        let mut graph: Graph<i32, f64> = Graph::new();
1648
1649        // Empty graph should error
1650        assert!(graph_density(&graph).is_err());
1651
1652        // Add one node
1653        graph.add_node(1);
1654
1655        // Graph with one node should error
1656        assert!(graph_density(&graph).is_err());
1657
1658        // Create a graph with 4 nodes and 3 edges
1659        graph.add_node(2);
1660        graph.add_node(3);
1661        graph.add_node(4);
1662
1663        graph.add_edge(1, 2, 1.0).expect("Test failed");
1664        graph.add_edge(2, 3, 1.0).expect("Test failed");
1665        graph.add_edge(3, 4, 1.0).expect("Test failed");
1666
1667        // 3 edges out of 6 possible edges (4 choose 2 = 6)
1668        let density = graph_density(&graph).expect("Test failed");
1669        assert_eq!(density, 0.5);
1670
1671        // Add 3 more edges to make a complete graph
1672        graph.add_edge(1, 3, 1.0).expect("Test failed");
1673        graph.add_edge(1, 4, 1.0).expect("Test failed");
1674        graph.add_edge(2, 4, 1.0).expect("Test failed");
1675
1676        // 6 edges out of 6 possible edges
1677        let density = graph_density(&graph).expect("Test failed");
1678        assert_eq!(density, 1.0);
1679    }
1680
1681    #[test]
1682    fn test_katz_centrality() {
1683        let mut graph: Graph<char, f64> = Graph::new();
1684
1685        // Create a simple star graph with A in the center
1686        graph.add_edge('A', 'B', 1.0).expect("Test failed");
1687        graph.add_edge('A', 'C', 1.0).expect("Test failed");
1688        graph.add_edge('A', 'D', 1.0).expect("Test failed");
1689
1690        let centrality = katz_centrality(&graph, 0.1, 1.0).expect("Test failed");
1691
1692        // The center node should have higher Katz centrality
1693        assert!(centrality[&'A'] > centrality[&'B']);
1694        assert!(centrality[&'A'] > centrality[&'C']);
1695        assert!(centrality[&'A'] > centrality[&'D']);
1696
1697        // All leaf nodes should have similar centrality
1698        assert!((centrality[&'B'] - centrality[&'C']).abs() < 0.1);
1699        assert!((centrality[&'B'] - centrality[&'D']).abs() < 0.1);
1700    }
1701
1702    #[test]
1703    fn test_pagerank_centrality() {
1704        let mut graph: Graph<char, f64> = Graph::new();
1705
1706        // Create a simple triangle
1707        graph.add_edge('A', 'B', 1.0).expect("Test failed");
1708        graph.add_edge('B', 'C', 1.0).expect("Test failed");
1709        graph.add_edge('C', 'A', 1.0).expect("Test failed");
1710
1711        let centrality = pagerank_centrality(&graph, 0.85, 1e-6).expect("Test failed");
1712
1713        // All nodes should have equal PageRank in a symmetric triangle
1714        let values: Vec<f64> = centrality.values().cloned().collect();
1715        let expected = 1.0 / 3.0; // Should sum to 1, so each gets 1/3
1716
1717        for &value in &values {
1718            assert!((value - expected).abs() < 0.1);
1719        }
1720
1721        // Check that PageRank values sum to approximately 1
1722        let sum: f64 = values.iter().sum();
1723        assert!((sum - 1.0).abs() < 0.01);
1724    }
1725
1726    #[test]
1727    fn test_pagerank_centrality_digraph() {
1728        let mut graph: DiGraph<char, f64> = DiGraph::new();
1729
1730        // Create a directed path: A -> B -> C
1731        graph.add_edge('A', 'B', 1.0).expect("Test failed");
1732        graph.add_edge('B', 'C', 1.0).expect("Test failed");
1733
1734        let centrality = pagerank_centrality_digraph(&graph, 0.85, 1e-6).expect("Test failed");
1735
1736        // C should have the highest PageRank (receives links but doesn't give any)
1737        // A should have the lowest (gives links but doesn't receive any except random jumps)
1738        assert!(centrality[&'C'] > centrality[&'B']);
1739        assert!(centrality[&'B'] > centrality[&'A']);
1740    }
1741
1742    #[test]
1743    fn test_centrality_enum_katz_pagerank() {
1744        let mut graph: Graph<char, f64> = Graph::new();
1745
1746        graph.add_edge('A', 'B', 1.0).expect("Test failed");
1747        graph.add_edge('A', 'C', 1.0).expect("Test failed");
1748
1749        // Test that the enum-based centrality function works for new types
1750        let katz_result = centrality(&graph, CentralityType::Katz).expect("Test failed");
1751        let pagerank_result = centrality(&graph, CentralityType::PageRank).expect("Test failed");
1752
1753        // Both should return valid results
1754        assert_eq!(katz_result.len(), 3);
1755        assert_eq!(pagerank_result.len(), 3);
1756
1757        // All values should be positive
1758        for value in katz_result.values() {
1759            assert!(*value > 0.0);
1760        }
1761        for value in pagerank_result.values() {
1762            assert!(*value > 0.0);
1763        }
1764    }
1765
1766    #[test]
1767    fn test_hits_algorithm() {
1768        let mut graph: DiGraph<char, f64> = DiGraph::new();
1769
1770        // Create a small web graph
1771        // A and B are hubs (point to many pages)
1772        // C and D are authorities (pointed to by many pages)
1773        graph.add_edge('A', 'C', 1.0).expect("Test failed");
1774        graph.add_edge('A', 'D', 1.0).expect("Test failed");
1775        graph.add_edge('B', 'C', 1.0).expect("Test failed");
1776        graph.add_edge('B', 'D', 1.0).expect("Test failed");
1777        // E is both a hub and authority
1778        graph.add_edge('E', 'C', 1.0).expect("Test failed");
1779        graph.add_edge('B', 'E', 1.0).expect("Test failed");
1780
1781        let hits = hits_algorithm(&graph, 100, 1e-6).expect("Test failed");
1782
1783        // Check that we have scores for all nodes
1784        assert_eq!(hits.authorities.len(), 5);
1785        assert_eq!(hits.hubs.len(), 5);
1786
1787        // C and D should have high authority scores
1788        assert!(hits.authorities[&'C'] > hits.authorities[&'A']);
1789        assert!(hits.authorities[&'D'] > hits.authorities[&'A']);
1790
1791        // A and B should have high hub scores
1792        assert!(hits.hubs[&'A'] > hits.hubs[&'C']);
1793        assert!(hits.hubs[&'B'] > hits.hubs[&'C']);
1794
1795        // Check that scores are normalized (sum of squares = 1)
1796        let auth_norm: f64 = hits.authorities.values().map(|&x| x * x).sum::<f64>();
1797        let hub_norm: f64 = hits.hubs.values().map(|&x| x * x).sum::<f64>();
1798        assert!((auth_norm - 1.0).abs() < 0.01);
1799        assert!((hub_norm - 1.0).abs() < 0.01);
1800    }
1801
1802    #[test]
1803    fn test_weighted_degree_centrality() {
1804        let mut graph = crate::generators::create_graph::<&str, f64>();
1805
1806        // Create a simple weighted graph
1807        graph.add_edge("A", "B", 2.0).expect("Test failed");
1808        graph.add_edge("A", "C", 3.0).expect("Test failed");
1809        graph.add_edge("B", "C", 1.0).expect("Test failed");
1810
1811        let centrality = centrality(&graph, CentralityType::WeightedDegree).expect("Test failed");
1812
1813        // A has edges with weights 2.0 + 3.0 = 5.0
1814        assert_eq!(centrality[&"A"], 5.0);
1815
1816        // B has edges with weights 2.0 + 1.0 = 3.0
1817        assert_eq!(centrality[&"B"], 3.0);
1818
1819        // C has edges with weights 3.0 + 1.0 = 4.0
1820        assert_eq!(centrality[&"C"], 4.0);
1821    }
1822
1823    #[test]
1824    fn test_weighted_closeness_centrality() {
1825        let mut graph = crate::generators::create_graph::<&str, f64>();
1826
1827        // Create a simple weighted graph
1828        graph.add_edge("A", "B", 1.0).expect("Test failed");
1829        graph.add_edge("B", "C", 2.0).expect("Test failed");
1830
1831        let centrality =
1832            centrality(&graph, CentralityType::WeightedCloseness).expect("Test failed");
1833
1834        // All centrality values should be positive
1835        for value in centrality.values() {
1836            assert!(*value > 0.0);
1837        }
1838
1839        // Node B should have highest closeness (shortest paths to others)
1840        assert!(centrality[&"B"] > centrality[&"A"]);
1841        assert!(centrality[&"B"] > centrality[&"C"]);
1842    }
1843
1844    #[test]
1845    fn test_weighted_betweenness_centrality() {
1846        let mut graph = crate::generators::create_graph::<&str, f64>();
1847
1848        // Create a path graph A-B-C
1849        graph.add_edge("A", "B", 1.0).expect("Test failed");
1850        graph.add_edge("B", "C", 1.0).expect("Test failed");
1851
1852        let centrality =
1853            centrality(&graph, CentralityType::WeightedBetweenness).expect("Test failed");
1854
1855        // B should have positive betweenness (lies on path from A to C)
1856        assert!(centrality[&"B"] > 0.0);
1857
1858        // A and C should have zero betweenness (no paths pass through them)
1859        assert_eq!(centrality[&"A"], 0.0);
1860        assert_eq!(centrality[&"C"], 0.0);
1861    }
1862
1863    #[test]
1864    fn test_weighted_centrality_digraph() {
1865        let mut graph = crate::generators::create_digraph::<&str, f64>();
1866
1867        // Create a simple directed weighted graph
1868        graph.add_edge("A", "B", 2.0).expect("Test failed");
1869        graph.add_edge("B", "C", 3.0).expect("Test failed");
1870        graph.add_edge("A", "C", 1.0).expect("Test failed");
1871
1872        let degree_centrality =
1873            centrality_digraph(&graph, CentralityType::WeightedDegree).expect("Test failed");
1874        let closeness_centrality =
1875            centrality_digraph(&graph, CentralityType::WeightedCloseness).expect("Test failed");
1876
1877        // All centrality values should be non-negative
1878        for value in degree_centrality.values() {
1879            assert!(*value >= 0.0);
1880        }
1881        for value in closeness_centrality.values() {
1882            assert!(*value >= 0.0);
1883        }
1884
1885        // A has weighted degree 2.0 + 1.0 = 3.0 (outgoing only)
1886        // B has weighted degree 2.0 (incoming) + 3.0 (outgoing) = 5.0 total
1887        // C has weighted degree 3.0 + 1.0 = 4.0 (incoming only)
1888        // So B should have the highest total weighted degree
1889        assert!(degree_centrality[&"B"] > degree_centrality[&"A"]);
1890        assert!(degree_centrality[&"B"] > degree_centrality[&"C"]);
1891    }
1892}