erpc_analysis/algorithms/
communities.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// Community detection algorithms (Louvain, LPA)

use log::info;
use std::sync::Arc;

use crate::db_trait::{AnalysisDatabase, AnalysisError};
use crate::models::partitions::ComponentAnalysisResult;

/// Analyzer for community detection in the Tor network graph
pub struct CommunityAnalyzer {
    db_client: Arc<dyn AnalysisDatabase>,
}

impl CommunityAnalyzer {
    /// Create a new CommunityAnalyzer with the given database client
    pub fn new(db_client: Arc<dyn AnalysisDatabase>) -> Self {
        Self { db_client }
    }

    /// Analyze communities using Louvain algorithm for a given projection
    pub async fn analyze_louvain_communities(
        &self,
        projection_name: &str,
        params: &crate::config::LouvainConfig,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!("=== Starting Louvain Community Detection Analysis ===");

        let result = self
            .db_client
            .calculate_louvain_communities(projection_name, params)
            .await?;

        info!("=== Louvain Community Detection Analysis Complete ===");

        info!(
            "Network has {} communities detected by Louvain algorithm",
            result.components.len()
        );

        Ok(result)
    }

    /// Analyze communities using Label Propagation algorithm for a given
    /// projection
    pub async fn analyze_label_propagation_communities(
        &self,
        projection_name: &str,
        params: &crate::config::LabelPropagationConfig,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!(
            "=== Starting Label Propagation Community Detection Analysis ==="
        );

        let result = self
            .db_client
            .calculate_label_propagation_communities(projection_name, params)
            .await?;

        info!(
            "=== Label Propagation Community Detection Analysis Complete ==="
        );
        info!(
            "Network has {} communities detected by Label Propagation \
             algorithm",
            result.total_components.unwrap_or(0)
        );

        Ok(result)
    }

    /// Display detailed Louvain community analysis results
    pub fn display_louvain_community_analysis(
        &self,
        result: &ComponentAnalysisResult,
        config: &crate::config::AnalysisSettings,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Louvain Community Detection Analysis:");
        info!(
            "Total Communities: {}",
            result.total_components.unwrap_or(0)
        );
        info!(
            "Largest Community Size: {}",
            result.largest_component_size.unwrap_or(0)
        );
        info!(
            "Smallest Community Size: {}",
            result.smallest_component_size.unwrap_or(0)
        );

        let isolation_ratio = result.isolation_ratio.unwrap_or(0.0);
        info!("Isolation Ratio: {:.2}%", isolation_ratio);

        // Display modularity information
        if let Some(modularity) = result.modularity {
            info!("Modularity Score: {:.4}", modularity);
            if modularity >= 0.3 {
                info!(
                    "✅ Strong community structure detected (modularity >= 0.3)"
                );
            } else if modularity >= 0.1 {
                info!(
                    "⚠️  Moderate community structure detected \
                     (modularity >= 0.1)"
                );
            } else {
                info!(
                    "❌ Weak community structure detected (modularity < 0.1)"
                );
            }
        } else {
            info!("Modularity Score: Not calculated");
        }

        // Check against threshold
        if isolation_ratio < config.isolation_ratio_threshold {
            info!(
                "⚠️  Network fragmentation detected: Isolation ratio \
                 {:.2}% is below threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        } else {
            info!(
                "✅ Network connectivity is healthy: Isolation ratio \
                 {:.2}% is above threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        }

        if config.calculate_distribution {
            if let Some(distribution) = &result.component_size_distribution {
                info!("Community Size Distribution:");
                let mut sizes: Vec<_> = distribution.iter().collect();
                sizes.sort_by(|a, b| b.0.cmp(a.0)); // Sort by size descending

                for (size, count) in
                    sizes.iter().take(config.max_display_components.min(5))
                {
                    info!(
                        "{} community/communities with {} relays each",
                        count, size
                    );
                }
            }
        }

        // Show top communities by size
        if result.components.len() > 1 {
            info!(
                "Top {} Largest Communities:",
                config.max_display_components.min(result.components.len())
            );
            for (i, community) in result
                .components
                .iter()
                .take(config.max_display_components)
                .enumerate()
            {
                info!(
                    "{}. Community {}: {} relays",
                    i + 1,
                    community.component_id,
                    community.size
                );
            }
        }

        Ok(())
    }

    /// Display detailed Label Propagation community analysis results
    pub fn display_label_propagation_community_analysis(
        &self,
        result: &ComponentAnalysisResult,
        config: &crate::config::AnalysisSettings,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Label Propagation Community Detection Analysis:");
        info!(
            "Total Communities: {}",
            result.total_components.unwrap_or(0)
        );
        info!(
            "Largest Community Size: {}",
            result.largest_component_size.unwrap_or(0)
        );
        info!(
            "Smallest Community Size: {}",
            result.smallest_component_size.unwrap_or(0)
        );

        let isolation_ratio = result.isolation_ratio.unwrap_or(0.0);
        info!("Isolation Ratio: {:.2}%", isolation_ratio);

        // Display modularity information
        if let Some(modularity) = result.modularity {
            info!("Modularity Score: {:.4}", modularity);
            if modularity >= 0.3 {
                info!(
                    "✅ Strong community structure detected (modularity >= 0.3)"
                );
            } else if modularity >= 0.1 {
                info!(
                    "⚠️  Moderate community structure detected \
                     (modularity >= 0.1)"
                );
            } else {
                info!(
                    "❌ Weak community structure detected (modularity < 0.1)"
                );
            }
        } else {
            info!("Modularity Score: Not calculated");
        }

        // Check against threshold
        if isolation_ratio < config.isolation_ratio_threshold {
            info!(
                "⚠️  Network fragmentation detected: Isolation ratio \
                 {:.2}% is below threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        } else {
            info!(
                "✅ Network connectivity is healthy: Isolation ratio \
                 {:.2}% is above threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        }

        if config.calculate_distribution {
            if let Some(distribution) = &result.component_size_distribution {
                info!("Community Size Distribution:");
                let mut sizes: Vec<_> = distribution.iter().collect();
                sizes.sort_by(|a, b| b.0.cmp(a.0)); // Sort by size descending

                for (size, count) in
                    sizes.iter().take(config.max_display_components.min(5))
                {
                    info!(
                        "{} community/communities with {} relays each",
                        count, size
                    );
                }
            }
        }

        // Show top communities by size
        if result.components.len() > 1 {
            info!(
                "Top {} Largest Communities:",
                config.max_display_components.min(result.components.len())
            );
            for (i, community) in result
                .components
                .iter()
                .take(config.max_display_components)
                .enumerate()
            {
                info!(
                    "{}. Community {}: {} relays",
                    i + 1,
                    community.component_id,
                    community.size
                );
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db_trait::mock::MockDatabase;
    use crate::models::metrics::NodeMetrics;

    /// Test Louvain algorithm correctness with known graph topology
    #[tokio::test]
    async fn test_louvain_algorithm_correctness() {
        // Create a graph with 6 nodes for community detection
        let nodes = vec![
            NodeMetrics {
                fingerprint: "RELAY_A".to_string(),
                in_degree: 0,
                out_degree: 2,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_B".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_C".to_string(),
                in_degree: 1,
                out_degree: 0,
                total_degree: 1,
            },
            NodeMetrics {
                fingerprint: "RELAY_D".to_string(),
                in_degree: 0,
                out_degree: 2,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_E".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_F".to_string(),
                in_degree: 1,
                out_degree: 0,
                total_degree: 1,
            },
        ];

        let db = Arc::new(
            MockDatabase::new().with_projection("test_louvain", nodes),
        );

        let analyzer = CommunityAnalyzer::new(db);
        let result = analyzer
            .analyze_louvain_communities(
                "test_louvain",
                &crate::config::LouvainConfig::default(),
            )
            .await
            .expect("Louvain analysis should succeed");

        // MockDatabase creates 2 communities when > 2 nodes (6 nodes here)
        assert_eq!(result.total_components, Some(2));
        assert_eq!(result.components.len(), 2); // actual communities = 2

        // Verify basic structure
        assert!(result.largest_component_size.is_some());
        assert!(result.smallest_component_size.is_some());
        assert!(result.isolation_ratio.is_some());

        // Check that modularity is populated for community detection
        assert!(result.modularity.is_some());
        let modularity = result.modularity.unwrap();
        // Valid modularity range
        assert!((0.0..=1.0).contains(&modularity));

        // Check that all fingerprints are accounted for
        let total_fingerprints: usize =
            result.components.iter().map(|c| c.size).sum();
        assert_eq!(total_fingerprints, 6);
    }

    /// Test Label Propagation algorithm with modularity calculation
    #[tokio::test]
    async fn test_label_propagation_algorithm_with_modularity() {
        // Create a graph with 9 nodes for community detection
        let nodes = vec![
            NodeMetrics {
                fingerprint: "RELAY_1".to_string(),
                in_degree: 2,
                out_degree: 2,
                total_degree: 4,
            },
            NodeMetrics {
                fingerprint: "RELAY_2".to_string(),
                in_degree: 2,
                out_degree: 2,
                total_degree: 4,
            },
            NodeMetrics {
                fingerprint: "RELAY_3".to_string(),
                in_degree: 2,
                out_degree: 2,
                total_degree: 4,
            },
            NodeMetrics {
                fingerprint: "RELAY_4".to_string(),
                in_degree: 2,
                out_degree: 2,
                total_degree: 4,
            },
            NodeMetrics {
                fingerprint: "RELAY_5".to_string(),
                in_degree: 2,
                out_degree: 2,
                total_degree: 4,
            },
            NodeMetrics {
                fingerprint: "RELAY_6".to_string(),
                in_degree: 2,
                out_degree: 2,
                total_degree: 4,
            },
            NodeMetrics {
                fingerprint: "RELAY_7".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_8".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_9".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
        ];

        let db =
            Arc::new(MockDatabase::new().with_projection("test_lpa", nodes));

        let analyzer = CommunityAnalyzer::new(db);
        let result = analyzer
            .analyze_label_propagation_communities(
                "test_lpa",
                &crate::config::LabelPropagationConfig::default(),
            )
            .await
            .expect("LPA analysis should succeed");

        // MockDatabase creates 3 communities when nodes > 3 (9 nodes here)
        assert_eq!(result.total_components, Some(3));
        assert_eq!(result.components.len(), 3); // actual communities = 3

        // Verify modularity is calculated for LPA
        assert!(result.modularity.is_some());
        let modularity = result.modularity.unwrap();
        // Valid modularity range
        assert!((0.0..=1.0).contains(&modularity));
        assert_eq!(modularity, 0.42); // Mock returns 0.42

        // Check that all fingerprints are accounted for
        let total_fingerprints: usize =
            result.components.iter().map(|c| c.size).sum();
        assert_eq!(total_fingerprints, 9);
    }

    /// Test modularity integration in community detection results
    #[tokio::test]
    async fn test_modularity_integration() {
        let db = MockDatabase::new().with_projection(
            "test_graph",
            vec![
                NodeMetrics {
                    fingerprint: "RELAY_A".to_string(),
                    in_degree: 2,
                    out_degree: 2,
                    total_degree: 4,
                },
                NodeMetrics {
                    fingerprint: "RELAY_B".to_string(),
                    in_degree: 2,
                    out_degree: 2,
                    total_degree: 4,
                },
            ],
        );

        let analyzer = CommunityAnalyzer::new(Arc::new(db));
        let result = analyzer
            .analyze_louvain_communities(
                "test_graph",
                &crate::config::LouvainConfig::default(),
            )
            .await
            .unwrap();

        // Verify modularity is populated in results
        assert!(result.modularity.is_some());
        assert_eq!(result.modularity.unwrap(), 0.42);
    }

    /// Test error handling for modularity calculation failures
    #[tokio::test]
    async fn test_modularity_error_handling() {
        let db = MockDatabase::new()
            .with_projection(
                "test_fail",
                vec![NodeMetrics {
                    fingerprint: "RELAY_X".to_string(),
                    in_degree: 1,
                    out_degree: 1,
                    total_degree: 2,
                }],
            )
            .fail_on("calculate_modularity");

        // Test that modularity calculation fails as expected
        let result = db.calculate_modularity("test_fail", "community").await;
        assert!(result.is_err());

        // Verify the call was tracked
        assert_eq!(db.get_call_count("calculate_modularity"), 1);
    }
}