erpc_analysis/models/
partitions.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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Represents a single connected component in the graph (works for
/// both WCC and SCC)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectedComponent {
    pub component_id: i64,
    pub relay_fingerprints: Vec<String>,
    pub size: usize,
}

/// Represents the results of connected components analysis (works for
/// both WCC and SCC)
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComponentAnalysisResult {
    pub components: Vec<ConnectedComponent>,
    pub total_components: Option<usize>,
    pub largest_component_size: Option<usize>,
    pub smallest_component_size: Option<usize>,
    pub component_size_distribution: Option<HashMap<usize, usize>>,
    // Percentage of nodes in largest component
    pub isolation_ratio: Option<f64>,
    /// Modularity score for community detection
    /// (None for connectivity analysis)
    pub modularity: Option<f64>,
}

/// Classification types for partition analysis
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub enum ClassificationType {
    #[default]
    Geographic,
    ASN,
    Family,
    Flags,
}

/// Represents a group of relays with shared classification attributes
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClassificationGroup {
    pub identifier: String,
    pub relay_fingerprints: Vec<String>,
    pub component_mapping: HashMap<i64, usize>, // component_id -> relay_count
    // percentage of group relays NOT in the largest component (fragmentation)
    pub isolation_score: f64,
}

/// Comprehensive classification metrics for a specific classification type
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ClassificationMetrics {
    pub total_groups: usize,
    pub groups_with_partitions: usize,
    // percentage of relays with classification data
    pub classification_coverage: f64,
    pub largest_group_size: usize,
    pub average_group_size: f64,
    pub diversity_score: f64, // measures distribution across groups
    // correlation between groups and partitions
    pub partition_correlation: f64,
}

/// Results of partition classification analysis
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PartitionClassificationResult {
    pub classification_type: ClassificationType,
    pub groups: Vec<ClassificationGroup>,
    pub metrics: ClassificationMetrics,
    pub unclassified_relays: Vec<String>, // relays without classification data
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_component_analysis_result_comprehensive() {
        let component1 = ConnectedComponent {
            component_id: 1,
            relay_fingerprints: vec![
                "RELAY001".to_string(),
                "RELAY002".to_string(),
                "RELAY003".to_string(),
            ],
            size: 3,
        };
        let component2 = ConnectedComponent {
            component_id: 2,
            relay_fingerprints: vec!["RELAY004".to_string()],
            size: 1,
        };

        let mut size_distribution = HashMap::new();
        size_distribution.insert(1, 1); // 1 component with size 1
        size_distribution.insert(3, 1); // 1 component with size 3

        let result = ComponentAnalysisResult {
            components: vec![component1, component2],
            total_components: Some(2),
            largest_component_size: Some(3),
            smallest_component_size: Some(1),
            component_size_distribution: Some(size_distribution.clone()),
            // 3 out of 4 nodes in largest component = 75%
            isolation_ratio: Some(75.0),
            modularity: None,
        };

        // Verify basic structure
        assert_eq!(result.components.len(), 2);
        assert_eq!(result.total_components.unwrap(), 2);
        assert_eq!(result.largest_component_size.unwrap(), 3);
        assert_eq!(result.smallest_component_size.unwrap(), 1);
        assert_eq!(result.isolation_ratio.unwrap(), 75.0);
        assert_eq!(
            result.component_size_distribution.unwrap(),
            size_distribution
        );

        // Verify component details
        assert_eq!(result.components[0].size, 3);
        assert_eq!(result.components[1].size, 1);
        assert_eq!(result.components[0].relay_fingerprints.len(), 3);
    }

    #[test]
    fn test_isolation_ratio_edge_cases() {
        // Test perfect isolation (all nodes in one component)
        let perfect_isolation = ComponentAnalysisResult {
            components: vec![],
            total_components: Some(1),
            largest_component_size: Some(100),
            smallest_component_size: Some(100),
            component_size_distribution: None,
            isolation_ratio: Some(100.0),
            modularity: None,
        };
        assert_eq!(perfect_isolation.isolation_ratio.unwrap(), 100.0);

        // Test complete fragmentation (all components size 1)
        let complete_fragmentation = ComponentAnalysisResult {
            components: vec![],
            total_components: Some(50),
            largest_component_size: Some(1),
            smallest_component_size: Some(1),
            component_size_distribution: None,
            isolation_ratio: Some(2.0), // (1/50)*100 = 2%
            modularity: None,
        };
        assert_eq!(complete_fragmentation.isolation_ratio.unwrap(), 2.0);
    }

    // Tests for new classification structures
    #[test]
    fn test_classification_group_structure() {
        let mut component_mapping = HashMap::new();
        component_mapping.insert(1, 5); // 5 relays in component 1
        component_mapping.insert(2, 2); // 2 relays in component 2

        let group = ClassificationGroup {
            identifier: "US".to_string(),
            relay_fingerprints: vec![
                "RELAY001".to_string(),
                "RELAY002".to_string(),
                "RELAY003".to_string(),
                "RELAY004".to_string(),
                "RELAY005".to_string(),
                "RELAY006".to_string(),
                "RELAY007".to_string(),
            ],
            component_mapping: component_mapping.clone(),
            isolation_score: 28.6, // 2/7 relays NOT in largest component
        };

        assert_eq!(group.identifier, "US");
        assert_eq!(group.relay_fingerprints.len(), 7);
        assert_eq!(group.component_mapping, component_mapping);
        assert!((group.isolation_score - 28.6).abs() < 0.1);
    }

    #[test]
    fn test_isolation_score_calculation_logic() {
        // Test perfect cohesion (0% isolation)
        let mut component_mapping = HashMap::new();
        component_mapping.insert(1, 10);

        let total_relays = 10;
        let largest_component_size =
            component_mapping.values().max().unwrap_or(&0);
        let non_largest_component_relays =
            total_relays - largest_component_size;
        let isolation_score = (non_largest_component_relays as f64
            / total_relays as f64)
            * 100.0;

        assert_eq!(isolation_score, 0.0);

        // Test high fragmentation (75% isolation)
        let mut fragmented_mapping = HashMap::new();
        fragmented_mapping.insert(1, 2); // 2 relays in largest component
        fragmented_mapping.insert(2, 1); // 1 relay in smaller component
        fragmented_mapping.insert(3, 1); // 1 relay in smaller component
        fragmented_mapping.insert(4, 1); // 1 relay in smaller component
        fragmented_mapping.insert(5, 1); // 1 relay in smaller component
        fragmented_mapping.insert(6, 1); // 1 relay in smaller component
        fragmented_mapping.insert(7, 1); // 1 relay in smaller component

        let total_relays = 8;
        let largest_component_size =
            fragmented_mapping.values().max().unwrap_or(&0);
        let non_largest_component_relays =
            total_relays - largest_component_size;
        let isolation_score = (non_largest_component_relays as f64
            / total_relays as f64)
            * 100.0;

        assert_eq!(isolation_score, 75.0);

        // Test moderate fragmentation (60% isolation)
        let mut moderate_mapping = HashMap::new();
        moderate_mapping.insert(1, 4); // 4 relays in largest component
        moderate_mapping.insert(2, 3); // 3 relays in smaller component
        moderate_mapping.insert(3, 2); // 2 relays in smaller component
        moderate_mapping.insert(4, 1); // 1 relay in smallest component

        let total_relays = 10;
        let largest_component_size =
            moderate_mapping.values().max().unwrap_or(&0);
        let non_largest_component_relays =
            total_relays - largest_component_size;
        let isolation_score = (non_largest_component_relays as f64
            / total_relays as f64)
            * 100.0;

        assert_eq!(isolation_score, 60.0);
    }

    #[test]
    fn test_classification_metrics() {
        let metrics = ClassificationMetrics {
            total_groups: 10,
            groups_with_partitions: 3,
            classification_coverage: 95.5,
            largest_group_size: 150,
            average_group_size: 45.7,
            diversity_score: 0.85,
            partition_correlation: 0.72,
        };

        assert_eq!(metrics.total_groups, 10);
        assert_eq!(metrics.groups_with_partitions, 3);
        assert!((metrics.classification_coverage - 95.5).abs() < 0.1);
        assert_eq!(metrics.largest_group_size, 150);
        assert!((metrics.average_group_size - 45.7).abs() < 0.1);
        assert!((metrics.diversity_score - 0.85).abs() < 0.1);
        assert!((metrics.partition_correlation - 0.72).abs() < 0.1);
    }

    #[test]
    fn test_partition_classification_result() {
        let group = ClassificationGroup {
            identifier: "DE".to_string(),
            relay_fingerprints: vec!["RELAY001".to_string()],
            component_mapping: HashMap::new(),
            isolation_score: 100.0,
        };

        let metrics = ClassificationMetrics {
            total_groups: 1,
            groups_with_partitions: 0,
            classification_coverage: 90.0,
            largest_group_size: 1,
            average_group_size: 1.0,
            diversity_score: 1.0,
            partition_correlation: 0.0,
        };

        let result = PartitionClassificationResult {
            classification_type: ClassificationType::Geographic,
            groups: vec![group],
            metrics,
            unclassified_relays: vec!["RELAY_UNKNOWN".to_string()],
        };

        assert_eq!(result.classification_type, ClassificationType::Geographic);
        assert_eq!(result.groups.len(), 1);
        assert_eq!(result.unclassified_relays.len(), 1);
        assert_eq!(result.metrics.total_groups, 1);
    }
}