erpc_analysis/algorithms/
centrality.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use log::info;
use std::sync::Arc;

use crate::db_trait::{AnalysisDatabase, AnalysisError};
use crate::models::metrics::CentralityAnalysisResult;

pub struct CentralityAnalyzer {
    db_client: Arc<dyn AnalysisDatabase>,
}

impl CentralityAnalyzer {
    pub fn new(db_client: Arc<dyn AnalysisDatabase>) -> Self {
        Self { db_client }
    }

    /// Analyze betweenness centrality for a given projection
    ///
    /// Betweenness centrality measures how often a node lies on the shortest path
    /// between two other nodes. High betweenness centrality indicates nodes
    /// that serve as bridges or bottlenecks in the network.
    pub async fn analyze_betweenness_centrality(
        &self,
        projection_name: &str,
        sampling_size: Option<usize>,
        sampling_seed: Option<u64>,
    ) -> Result<CentralityAnalysisResult, AnalysisError> {
        info!("=== Starting Betweenness Centrality Analysis ===");

        if let Some(sample_size) = sampling_size {
            info!("Using sampling size: {} nodes", sample_size);
        }

        let result = self
            .db_client
            .calculate_betweenness_centrality(
                projection_name,
                sampling_size,
                sampling_seed,
            )
            .await?;

        info!("=== Betweenness Centrality Analysis Complete ===");

        Ok(result)
    }

    /// Analyze closeness centrality for a given projection
    ///
    /// Closeness centrality measures how close a node is to all other nodes in the
    /// network. High closeness centrality indicates nodes that can quickly reach
    /// all other nodes.
    pub async fn analyze_closeness_centrality(
        &self,
        projection_name: &str,
        use_wasserman_faust: Option<bool>,
    ) -> Result<CentralityAnalysisResult, AnalysisError> {
        info!("=== Starting Closeness Centrality Analysis ===");

        if let Some(use_wf) = use_wasserman_faust {
            info!("Using Wasserman-Faust formula: {}", use_wf);
        }

        let result = self
            .db_client
            .calculate_closeness_centrality(
                projection_name,
                use_wasserman_faust,
            )
            .await?;

        info!("=== Closeness Centrality Analysis Complete ===");

        Ok(result)
    }

    /// Analyze both betweenness and closeness centrality in a single operation
    pub async fn analyze_combined_centrality(
        &self,
        projection_name: &str,
        betweenness_sampling_size: Option<usize>,
        betweenness_sampling_seed: Option<u64>,
        use_wasserman_faust: Option<bool>,
    ) -> Result<CentralityAnalysisResult, AnalysisError> {
        info!("=== Starting Combined Centrality Analysis ===");

        let result = self
            .db_client
            .calculate_combined_centrality(
                projection_name,
                betweenness_sampling_size,
                betweenness_sampling_seed,
                use_wasserman_faust,
            )
            .await?;

        info!("=== Combined Centrality Analysis Complete ===");

        Ok(result)
    }

    /// Display detailed centrality analysis results
    pub fn display_centrality_results(
        &self,
        result: &CentralityAnalysisResult,
        centrality_type: &str,
        config: &crate::config::AnalysisSettings,
    ) {
        info!("=== {} Centrality Analysis Results ===", centrality_type);
        info!(
            "Total nodes analyzed: {}",
            result.total_nodes_analyzed.unwrap_or(0)
        );

        // Display distribution statistics
        if let Some(betweenness_dist) = &result.betweenness_distribution {
            info!("Betweenness Centrality Distribution:");
            info!("  Min: {:.6}", betweenness_dist.min);
            info!("  Max: {:.6}", betweenness_dist.max);
            info!("  Mean: {:.6}", betweenness_dist.mean);
            info!("  Median (p50): {:.6}", betweenness_dist.p50);
            info!("  p75: {:.6}", betweenness_dist.p75);
            info!("  p90: {:.6}", betweenness_dist.p90);
            info!("  p95: {:.6}", betweenness_dist.p95);
            info!("  p99: {:.6}", betweenness_dist.p99);
            info!("  p999: {:.6}", betweenness_dist.p999);
        }

        if let Some(closeness_dist) = &result.closeness_distribution {
            info!("Closeness Centrality Distribution:");
            info!("  Min: {:.6}", closeness_dist.min);
            info!("  Max: {:.6}", closeness_dist.max);
            info!("  Mean: {:.6}", closeness_dist.mean);
            info!("  Median (p50): {:.6}", closeness_dist.p50);
            info!("  p75: {:.6}", closeness_dist.p75);
            info!("  p90: {:.6}", closeness_dist.p90);
            info!("  p95: {:.6}", closeness_dist.p95);
            info!("  p99: {:.6}", closeness_dist.p99);
            info!("  p999: {:.6}", closeness_dist.p999);
        }

        // Display top nodes
        let display_count = config.max_display_components;
        info!("=== Top {} Nodes by Centrality ===", display_count);
        self.display_top_nodes(&result.centrality_metrics, display_count);
    }

    /// Display top nodes by centrality scores
    fn display_top_nodes(
        &self,
        metrics: &[crate::models::metrics::CentralityMetrics],
        top_count: usize,
    ) {
        // Sort by betweenness centrality if available
        if metrics.iter().any(|m| m.betweenness_centrality.is_some()) {
            let mut sorted_by_betweenness = metrics.to_vec();
            sorted_by_betweenness.sort_by(|a, b| {
                b.betweenness_centrality
                    .unwrap_or(0.0)
                    .partial_cmp(&a.betweenness_centrality.unwrap_or(0.0))
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            info!("Top {} nodes by Betweenness Centrality:", top_count);
            for (i, metric) in
                sorted_by_betweenness.iter().take(top_count).enumerate()
            {
                let betweenness = metric.betweenness_centrality.unwrap_or(0.0);
                info!(
                    "  {}. {} - {:.6}",
                    i + 1,
                    metric.fingerprint,
                    betweenness
                );
            }
        }

        // Sort by closeness centrality if available
        if metrics.iter().any(|m| m.closeness_centrality.is_some()) {
            let mut sorted_by_closeness = metrics.to_vec();
            sorted_by_closeness.sort_by(|a, b| {
                b.closeness_centrality
                    .unwrap_or(0.0)
                    .partial_cmp(&a.closeness_centrality.unwrap_or(0.0))
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            info!("Top {} nodes by Closeness Centrality:", top_count);
            for (i, metric) in
                sorted_by_closeness.iter().take(top_count).enumerate()
            {
                let closeness = metric.closeness_centrality.unwrap_or(0.0);
                info!(
                    "  {}. {} - {:.6}",
                    i + 1,
                    metric.fingerprint,
                    closeness
                );
            }
        }
    }
}