scirs2-graph 0.4.2

Graph processing module for SciRS2 (scirs2-graph)
Documentation
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
//! Modularity calculation and optimization algorithms

use super::types::{CommunityResult, CommunityStructure};
use crate::base::{EdgeWeight, Graph, IndexType, Node};
use std::collections::{HashMap, HashSet};
use std::hash::Hash;

/// Computes the modularity of a given community partition
///
/// Modularity measures the quality of a partition by comparing the number
/// of edges within communities to what would be expected in a random graph.
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `communities` - Map from nodes to community IDs
///
/// # Returns
/// * The modularity score (typically between -1 and 1, higher is better)
///
/// # Time Complexity
/// O(m + n) where m is the number of edges and n is the number of nodes.
/// This is the optimized implementation that avoids the O(n²) naive approach.
///
/// # Space Complexity
/// O(n) for storing degree information and community assignments.
#[allow(dead_code)]
pub fn modularity<N, E, Ix>(graph: &Graph<N, E, Ix>, communities: &HashMap<N, usize>) -> f64
where
    N: Node + std::fmt::Debug,
    E: EdgeWeight + Into<f64> + Copy,
    Ix: IndexType,
{
    let n = graph.node_count();
    if n == 0 || communities.is_empty() {
        return 0.0;
    }

    // Calculate total edge weight
    let mut m = 0.0;
    for edge in graph.inner().edge_references() {
        m += (*edge.weight()).into();
    }

    if m == 0.0 {
        return 0.0;
    }

    // Calculate node degrees
    let mut node_degrees: HashMap<N, f64> = HashMap::new();
    for node in graph.nodes() {
        let mut degree = 0.0;
        if let Ok(neighbors) = graph.neighbors(node) {
            for neighbor in neighbors {
                if let Ok(weight) = graph.edge_weight(node, &neighbor) {
                    degree += weight.into();
                }
            }
        }
        node_degrees.insert(node.clone(), degree);
    }

    // Calculate modularity
    let mut q = 0.0;
    for node_i in graph.nodes() {
        for node_j in graph.nodes() {
            if communities.get(node_i) == communities.get(node_j) {
                // Check if edge exists
                let a_ij = if let Ok(weight) = graph.edge_weight(node_i, node_j) {
                    weight.into()
                } else {
                    0.0
                };

                let k_i = node_degrees.get(node_i).unwrap_or(&0.0);
                let k_j = node_degrees.get(node_j).unwrap_or(&0.0);

                q += a_ij - (k_i * k_j) / (2.0 * m);
            }
        }
    }

    q / (2.0 * m)
}

/// Optimizes modularity using simulated annealing
///
/// This algorithm tries to maximize modularity by iteratively moving nodes
/// between communities using simulated annealing to escape local optima.
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `initial_temp` - Initial temperature for simulated annealing
/// * `cooling_rate` - Rate at which temperature decreases (0 < rate < 1)
/// * `max_iterations` - Maximum number of iterations
///
/// # Returns
/// * A community structure with optimized modularity
///
/// # Time Complexity
/// O(k * n * m) where k is the number of iterations, n is the number of nodes,
/// and m is the number of edges. Each iteration involves evaluating modularity
/// changes for potential node moves.
///
/// # Space Complexity
/// O(n) for storing community assignments and modularity calculations.
#[deprecated(
    note = "Use `modularity_optimization_result` instead for standardized community detection API"
)]
#[allow(dead_code)]
pub fn modularity_optimization<N, E, Ix>(
    graph: &Graph<N, E, Ix>,
    initial_temp: f64,
    cooling_rate: f64,
    max_iterations: usize,
) -> CommunityStructure<N>
where
    N: Node + Clone + Hash + Eq + std::fmt::Debug,
    E: EdgeWeight + Into<f64> + Copy,
    Ix: IndexType,
{
    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
    let n = nodes.len();

    if n == 0 {
        return CommunityStructure {
            node_communities: HashMap::new(),
            modularity: 0.0,
        };
    }

    // Initialize with each node in its own community
    let mut current_communities: HashMap<N, usize> = nodes
        .iter()
        .enumerate()
        .map(|(i, node)| (node.clone(), i))
        .collect();

    let mut current_modularity = modularity(graph, &current_communities);
    let mut best_communities = current_communities.clone();
    let mut best_modularity = current_modularity;

    let mut temp = initial_temp;
    let mut rng = scirs2_core::random::rng();

    for _iteration in 0..max_iterations {
        // Choose a random node to move
        use scirs2_core::random::{Rng, RngExt};
        let node_idx = rng.random_range(0..n);
        let node = &nodes[node_idx];
        let current_community = current_communities[node];

        // Find possible communities to move to (neighboring communities + new community)
        let mut candidate_communities = HashSet::new();
        candidate_communities.insert(n); // New community

        if let Ok(neighbors) = graph.neighbors(node) {
            for neighbor in neighbors {
                if let Some(&comm) = current_communities.get(&neighbor) {
                    candidate_communities.insert(comm);
                }
            }
        }

        // Try moving to a random candidate community
        let candidates: Vec<usize> = candidate_communities.into_iter().collect();
        if candidates.is_empty() {
            continue;
        }

        let new_community = candidates[rng.random_range(0..candidates.len())];

        if new_community == current_community {
            continue;
        }

        // Make the move temporarily
        current_communities.insert(node.clone(), new_community);
        let new_modularity = modularity(graph, &current_communities);
        let delta = new_modularity - current_modularity;

        // Accept or reject the move
        let accept = if delta > 0.0 {
            true
        } else {
            // Accept with probability exp(delta / temp)
            let prob = (delta / temp).exp();
            rng.random::<f64>() < prob
        };

        if accept {
            current_modularity = new_modularity;
            if current_modularity > best_modularity {
                best_modularity = current_modularity;
                best_communities = current_communities.clone();
            }
        } else {
            // Revert the move
            current_communities.insert(node.clone(), current_community);
        }

        // Cool down
        temp *= cooling_rate;

        // Early stopping if temperature is too low
        if temp < 1e-8 {
            break;
        }
    }

    // Renumber communities to be consecutive
    let mut community_map: HashMap<usize, usize> = HashMap::new();
    let mut next_id = 0;
    for &comm in best_communities.values() {
        if let std::collections::hash_map::Entry::Vacant(e) = community_map.entry(comm) {
            e.insert(next_id);
            next_id += 1;
        }
    }

    // Apply renumbering
    for (_, comm) in best_communities.iter_mut() {
        *comm = community_map[comm];
    }

    CommunityStructure {
        node_communities: best_communities,
        modularity: best_modularity,
    }
}

/// Greedy modularity optimization algorithm
///
/// This is a simplified version of modularity optimization that uses a greedy
/// approach without simulated annealing. It's faster but may get stuck in local optima.
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `max_iterations` - Maximum number of iterations
///
/// # Returns
/// * A community structure with optimized modularity
///
/// # Time Complexity
/// O(k * n * d) where k is the number of iterations, n is the number of nodes,
/// and d is the average degree. Each iteration involves finding the best community
/// for each node based on local modularity improvements.
///
/// # Space Complexity
/// O(n) for storing community assignments and tracking modularity gains.
#[deprecated(
    note = "Use `greedy_modularity_optimization_result` instead for standardized community detection API"
)]
#[allow(dead_code)]
pub fn greedy_modularity_optimization<N, E, Ix>(
    graph: &Graph<N, E, Ix>,
    max_iterations: usize,
) -> CommunityStructure<N>
where
    N: Node + Clone + Hash + Eq + std::fmt::Debug,
    E: EdgeWeight + Into<f64> + Copy,
    Ix: IndexType,
{
    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
    let n = nodes.len();

    if n == 0 {
        return CommunityStructure {
            node_communities: HashMap::new(),
            modularity: 0.0,
        };
    }

    // Initialize with each node in its own community
    let mut communities: HashMap<N, usize> = nodes
        .iter()
        .enumerate()
        .map(|(i, node)| (node.clone(), i))
        .collect();

    let mut improved = true;
    let mut _iterations = 0;

    while improved && _iterations < max_iterations {
        improved = false;
        _iterations += 1;

        let current_modularity = modularity(graph, &communities);

        // Try moving each node to each neighboring community
        for node in &nodes {
            let original_community = communities[node];
            let mut best_modularity = current_modularity;
            let mut best_community = original_community;

            // Get neighboring communities
            let mut neighboring_communities = HashSet::new();
            if let Ok(neighbors) = graph.neighbors(node) {
                for neighbor in neighbors {
                    if let Some(&comm) = communities.get(&neighbor) {
                        neighboring_communities.insert(comm);
                    }
                }
            }

            // Try each neighboring community
            for &candidate_community in &neighboring_communities {
                if candidate_community != original_community {
                    communities.insert(node.clone(), candidate_community);
                    let new_modularity = modularity(graph, &communities);

                    if new_modularity > best_modularity {
                        best_modularity = new_modularity;
                        best_community = candidate_community;
                    }
                }
            }

            // Move to best community if it's better
            if best_community != original_community {
                communities.insert(node.clone(), best_community);
                improved = true;
            } else {
                // Restore original community
                communities.insert(node.clone(), original_community);
            }
        }
    }

    // Renumber communities to be consecutive
    let mut community_map: HashMap<usize, usize> = HashMap::new();
    let mut next_id = 0;
    for &comm in communities.values() {
        if let std::collections::hash_map::Entry::Vacant(e) = community_map.entry(comm) {
            e.insert(next_id);
            next_id += 1;
        }
    }

    // Apply renumbering
    for (_, comm) in communities.iter_mut() {
        *comm = community_map[comm];
    }

    let final_modularity = modularity(graph, &communities);

    CommunityStructure {
        node_communities: communities,
        modularity: final_modularity,
    }
}

/// Optimizes modularity using simulated annealing (modern API)
///
/// Returns a standardized `CommunityResult` type that provides multiple ways
/// to access the community structure.
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `initial_temp` - Initial temperature for simulated annealing
/// * `cooling_rate` - Rate at which temperature decreases (0 < rate < 1)
/// * `max_iterations` - Maximum number of iterations
///
/// # Returns
/// * A `CommunityResult` with comprehensive community information
#[allow(dead_code)]
pub fn modularity_optimization_result<N, E, Ix>(
    graph: &Graph<N, E, Ix>,
    initial_temp: f64,
    cooling_rate: f64,
    max_iterations: usize,
) -> CommunityResult<N>
where
    N: Node + Clone + Hash + Eq + std::fmt::Debug,
    E: EdgeWeight + Into<f64> + Copy,
    Ix: IndexType,
{
    #[allow(deprecated)]
    let structure = modularity_optimization(graph, initial_temp, cooling_rate, max_iterations);
    CommunityResult::from_community_structure(structure)
}

/// Greedy modularity optimization algorithm (modern API)
///
/// Returns a standardized `CommunityResult` type that provides multiple ways
/// to access the community structure.
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `max_iterations` - Maximum number of iterations
///
/// # Returns
/// * A `CommunityResult` with comprehensive community information
#[allow(dead_code)]
pub fn greedy_modularity_optimization_result<N, E, Ix>(
    graph: &Graph<N, E, Ix>,
    max_iterations: usize,
) -> CommunityResult<N>
where
    N: Node + Clone + Hash + Eq + std::fmt::Debug,
    E: EdgeWeight + Into<f64> + Copy,
    Ix: IndexType,
{
    #[allow(deprecated)]
    let structure = greedy_modularity_optimization(graph, max_iterations);
    CommunityResult::from_community_structure(structure)
}