leiden-rs 0.7.0

High-performance Leiden community detection algorithm for graphs in Rust
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
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
503
504
505
506
507
508
509
//! Builder for constructing [`GraphData`] from edges and node weights.
//!
//! [`GraphDataBuilder`] is the single entry-point for creating a [`GraphData`]
//! instance. It accumulates edges and optional node weights, then builds the
//! internal CSR structure on [`build`](GraphDataBuilder::build).
//!
//! # Example
//!
//! ```
//! use leiden_rs::graph::GraphDataBuilder;
//!
//! let mut b = GraphDataBuilder::new(4);
//! b.add_edge(0, 1, 1.0).unwrap();
//! b.add_edge(1, 2, 2.0).unwrap();
//! b.add_edge(2, 3, 1.5).unwrap();
//! let graph = b.build().unwrap();
//!
//! assert_eq!(graph.node_count(), 4);
//! ```

use crate::error::{LeidenError, Result};
use crate::graph::data::GraphData;

/// Builder that accumulates edges and node weights, then produces a [`GraphData`].
///
/// This is the **only** way to construct a [`GraphData`] from raw edges. The
/// builder validates inputs incrementally (on each [`add_edge`] call) and then
/// builds the CSR layout in [`build`].
///
/// [`add_edge`]: GraphDataBuilder::add_edge
/// [`build`]: GraphDataBuilder::build
pub struct GraphDataBuilder {
    node_count: usize,
    directed: bool,
    edges: Vec<(usize, usize, f64)>,
    node_weights: Vec<f64>,
}

impl GraphDataBuilder {
    /// Create a new builder for a graph with `node_count` nodes.
    ///
    /// All node weights default to `1.0`, `directed` defaults to `false`,
    /// and the edge list starts empty.
    pub fn new(node_count: usize) -> Self {
        Self {
            node_count,
            directed: false,
            edges: Vec::new(),
            node_weights: vec![1.0; node_count],
        }
    }

    /// Set the graph to directed mode.
    ///
    /// **Note:** directed CSR construction is not yet implemented (Phase 2).
    /// Calling [`build`] after this will return an error.
    ///
    /// [`build`]: GraphDataBuilder::build
    pub fn directed(mut self) -> Self {
        self.directed = true;
        self
    }

    /// Add a weighted edge `(src, dst, weight)`.
    ///
    /// Returns `Err(LeidenError::InconsistentStructure)` if `src` or `dst` is
    /// out of range, or `Err(LeidenError::InvalidEdgeWeight)` if the weight is
    /// not finite and non-negative.
    pub fn add_edge(&mut self, src: usize, dst: usize, weight: f64) -> Result<&mut Self> {
        if !(weight.is_finite() && weight >= 0.0) {
            return Err(LeidenError::InvalidEdgeWeight { weight });
        }
        if src >= self.node_count || dst >= self.node_count {
            return Err(LeidenError::InconsistentStructure {
                message: format!(
                    "node ID {} exceeds node_count {}",
                    src.max(dst),
                    self.node_count
                ),
            });
        }
        self.edges.push((src, dst, weight));
        Ok(self)
    }

    /// Override the weight for a single node.
    ///
    /// Returns `Err(LeidenError::InconsistentStructure)` if `node` is out of
    /// range.
    pub fn set_node_weight(&mut self, node: usize, weight: f64) -> Result<&mut Self> {
        if node >= self.node_count {
            return Err(LeidenError::InconsistentStructure {
                message: format!("node ID {} exceeds node_count {}", node, self.node_count),
            });
        }
        self.node_weights[node] = weight;
        Ok(self)
    }

    /// Consume the builder and produce a [`GraphData`].
    ///
    /// Delegates to the appropriate CSR constructor based on the `directed`
    /// flag. In Phase 1 only undirected construction is supported.
    pub fn build(self) -> Result<GraphData> {
        if self.directed {
            build_directed_csr(self.node_count, self.edges, self.node_weights)
        } else {
            build_undirected_csr(self.node_count, self.edges, self.node_weights)
        }
    }
}

/// Build an undirected [`GraphData`] from an edge list.
///
/// Produces exactly the same CSR as the original `GraphData::from_edgelist`:
///
/// * Each edge `(u, v, w)` with `u != v` is stored twice — once in the
///   adjacency of `u` and once in `v`. Self-loops `(u, u, w)` are stored
///   once but contribute `2·w` to the degree.
/// * `total_weight = degree.sum() / 2`
/// * `in_*` fields are empty, `directed` is `false`.
fn build_undirected_csr(
    n: usize,
    edges: Vec<(usize, usize, f64)>,
    node_weights: Vec<f64>,
) -> Result<GraphData> {
    let mut degree: Vec<f64> = vec![0.0; n];
    for &(u, v, w) in &edges {
        if u == v {
            degree[u] += 2.0 * w;
        } else {
            degree[u] += w;
            degree[v] += w;
        }
    }

    let mut neighbor_count: Vec<usize> = vec![0; n];
    for &(u, v, _) in &edges {
        neighbor_count[u] += 1;
        if u != v {
            neighbor_count[v] += 1;
        }
    }

    let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
    out_offsets.push(0);
    let mut total = 0;
    for &count in &neighbor_count {
        total += count;
        out_offsets.push(total);
    }

    let mut out_targets: Vec<usize> = vec![0; total];
    let mut out_weights: Vec<f64> = vec![0.0; total];
    let mut cursor: Vec<usize> = out_offsets[..n].to_vec();

    for &(u, v, w) in &edges {
        out_targets[cursor[u]] = v;
        out_weights[cursor[u]] = w;
        cursor[u] += 1;
        if u != v {
            out_targets[cursor[v]] = u;
            out_weights[cursor[v]] = w;
            cursor[v] += 1;
        }
    }

    validate_csr(
        n,
        &out_offsets,
        &out_targets,
        &out_weights,
        &degree,
        &node_weights,
    )?;

    let total_weight = degree.iter().sum::<f64>() / 2.0;

    Ok(GraphData {
        n,
        out_offsets,
        out_targets,
        out_weights,
        total_weight,
        out_degree: degree,
        node_weight: node_weights,
        directed: false,
        in_offsets: Vec::new(),
        in_targets: Vec::new(),
        in_weights: Vec::new(),
        in_degree: Vec::new(),
    })
}

/// Build a directed [`GraphData`] from an edge list.
///
/// Each edge `(u, v, w)` is stored once in the out-edge CSR of `u` and once
/// in the in-edge CSR of `v`. Self-loops `(u, u, w)` are stored once in each CSR
/// and contribute `w` to both out-degree and in-degree.
///
/// `total_weight = sum of all edge weights` (each edge counted once).
fn build_directed_csr(
    n: usize,
    edges: Vec<(usize, usize, f64)>,
    node_weights: Vec<f64>,
) -> Result<GraphData> {
    // ── Out-edge CSR ──
    let mut out_degree: Vec<f64> = vec![0.0; n];
    let mut out_neighbor_count: Vec<usize> = vec![0; n];
    for &(u, _v, w) in &edges {
        out_degree[u] += w;
        out_neighbor_count[u] += 1;
    }

    let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
    out_offsets.push(0);
    let mut total = 0;
    for &count in &out_neighbor_count {
        total += count;
        out_offsets.push(total);
    }

    let mut out_targets: Vec<usize> = vec![0; total];
    let mut out_weights: Vec<f64> = vec![0.0; total];
    let mut out_cursor: Vec<usize> = out_offsets[..n].to_vec();

    for &(u, v, w) in &edges {
        let idx = out_cursor[u];
        out_targets[idx] = v;
        out_weights[idx] = w;
        out_cursor[u] += 1;
    }

    // ── In-edge CSR ──
    let mut in_degree: Vec<f64> = vec![0.0; n];
    let mut in_neighbor_count: Vec<usize> = vec![0; n];
    for &(_u, v, w) in &edges {
        in_degree[v] += w;
        in_neighbor_count[v] += 1;
    }

    let mut in_offsets: Vec<usize> = Vec::with_capacity(n + 1);
    in_offsets.push(0);
    total = 0;
    for &count in &in_neighbor_count {
        total += count;
        in_offsets.push(total);
    }

    let mut in_targets: Vec<usize> = vec![0; total];
    let mut in_weights: Vec<f64> = vec![0.0; total];
    let mut in_cursor: Vec<usize> = in_offsets[..n].to_vec();

    for &(u, v, w) in &edges {
        let idx = in_cursor[v];
        in_targets[idx] = u;
        in_weights[idx] = w;
        in_cursor[v] += 1;
    }

    validate_csr(
        n,
        &out_offsets,
        &out_targets,
        &out_weights,
        &out_degree,
        &node_weights,
    )?;
    validate_csr(
        n,
        &in_offsets,
        &in_targets,
        &in_weights,
        &in_degree,
        &node_weights,
    )?;

    let total_weight: f64 = edges.iter().map(|&(_, _, w)| w).sum();

    Ok(GraphData {
        n,
        out_offsets,
        out_targets,
        out_weights,
        total_weight,
        out_degree,
        node_weight: node_weights,
        directed: true,
        in_offsets,
        in_targets,
        in_weights,
        in_degree,
    })
}

/// Validate the structural invariants of a CSR representation.
///
/// Checks (mirroring the original `from_parts` logic):
///
/// * `offsets.len() == n + 1`
/// * `targets.len() == weights.len()`
/// * `degree.len() == n`
/// * `node_weight.len() == n`
/// * `offsets[0] == 0`
/// * `offsets[n] == targets.len()`
///
/// All failures produce [`LeidenError::InconsistentStructure`].
fn validate_csr(
    n: usize,
    offsets: &[usize],
    targets: &[usize],
    weights: &[f64],
    degree: &[f64],
    node_weight: &[f64],
) -> Result<()> {
    if offsets.len() != n + 1 {
        return Err(LeidenError::InconsistentStructure {
            message: format!("offsets length {} != n + 1 ({})", offsets.len(), n + 1),
        });
    }
    if targets.len() != weights.len() {
        return Err(LeidenError::InconsistentStructure {
            message: format!(
                "targets length {} != weights length {}",
                targets.len(),
                weights.len()
            ),
        });
    }
    if degree.len() != n {
        return Err(LeidenError::InconsistentStructure {
            message: format!("degree length {} != n ({})", degree.len(), n),
        });
    }
    if node_weight.len() != n {
        return Err(LeidenError::InconsistentStructure {
            message: format!("node_weight length {} != n ({})", node_weight.len(), n),
        });
    }
    if offsets[0] != 0 {
        return Err(LeidenError::InconsistentStructure {
            message: format!("offsets[0] must be 0, got {}", offsets[0]),
        });
    }
    if offsets[n] != targets.len() {
        return Err(LeidenError::InconsistentStructure {
            message: format!(
                "offsets[n] ({}) != targets.len() ({})",
                offsets[n],
                targets.len()
            ),
        });
    }
    Ok(())
}

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

    #[test]
    fn test_builder_triangle() {
        let mut b = GraphDataBuilder::new(3);
        b.add_edge(0, 1, 1.0).unwrap();
        b.add_edge(1, 2, 2.0).unwrap();
        b.add_edge(0, 2, 3.0).unwrap();
        let gd = b.build().unwrap();

        assert_eq!(gd.node_count(), 3);
        // total_weight = (degree[0] + degree[1] + degree[2]) / 2
        // degree[0] = 1 + 3 = 4, degree[1] = 1 + 2 = 3, degree[2] = 2 + 3 = 5
        // total_weight = 12 / 2 = 6
        assert!((gd.total_weight() - 6.0).abs() < 1e-10);
        assert!((gd.degree_of(0) - 4.0).abs() < 1e-10);
        assert!((gd.degree_of(1) - 3.0).abs() < 1e-10);
        assert!((gd.degree_of(2) - 5.0).abs() < 1e-10);
    }

    #[test]
    fn test_builder_self_loop() {
        let mut b = GraphDataBuilder::new(2);
        b.add_edge(0, 0, 5.0).unwrap();
        b.add_edge(0, 1, 1.0).unwrap();
        let gd = b.build().unwrap();

        // degree[0] = 2*5 + 1 = 11, degree[1] = 1, total_weight = 12 / 2 = 6
        assert_eq!(gd.node_count(), 2);
        assert!((gd.degree_of(0) - 11.0).abs() < 1e-10);
        assert!((gd.degree_of(1) - 1.0).abs() < 1e-10);
        assert!((gd.total_weight() - 6.0).abs() < 1e-10);
    }

    #[test]
    fn test_builder_invalid_weight() {
        let mut b = GraphDataBuilder::new(3);
        assert!(b.add_edge(0, 1, f64::NAN).is_err());
        assert!(b.add_edge(0, 1, f64::INFINITY).is_err());
        assert!(b.add_edge(0, 1, -1.0).is_err());
    }

    #[test]
    fn test_builder_node_out_of_range() {
        let mut b = GraphDataBuilder::new(3);
        assert!(b.add_edge(0, 5, 1.0).is_err());
        assert!(b.add_edge(5, 0, 1.0).is_err());
    }

    #[test]
    fn test_builder_set_node_weight() {
        let mut b = GraphDataBuilder::new(3);
        b.set_node_weight(1, 5.0).unwrap();
        let gd = b.build().unwrap();
        assert!((gd.node_weight(0) - 1.0).abs() < 1e-10);
        assert!((gd.node_weight(1) - 5.0).abs() < 1e-10);
        assert!((gd.node_weight(2) - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_builder_directed_basic() {
        let mut b = GraphDataBuilder::new(4).directed();
        b.add_edge(0, 1, 1.0).unwrap();
        b.add_edge(1, 2, 2.0).unwrap();
        b.add_edge(2, 0, 3.0).unwrap();
        b.add_edge(0, 3, 0.5).unwrap();
        let gd = b.build().unwrap();

        assert_eq!(gd.node_count(), 4);
        assert!(gd.is_directed());
        // total_weight = 1.0 + 2.0 + 3.0 + 0.5 = 6.5
        assert!((gd.total_weight() - 6.5).abs() < 1e-10);

        // out_degree: 0→1+0.5=1.5, 1→2=2, 2→3=3, 3→0=0
        assert!((gd.out_degree_of(0) - 1.5).abs() < 1e-10);
        assert!((gd.out_degree_of(1) - 2.0).abs() < 1e-10);
        assert!((gd.out_degree_of(2) - 3.0).abs() < 1e-10);
        assert!((gd.out_degree_of(3) - 0.0).abs() < 1e-10);

        // in_degree: 0→3=3, 1→1=1, 2→2=2, 3→0.5=0.5
        assert!((gd.in_degree_of(0) - 3.0).abs() < 1e-10);
        assert!((gd.in_degree_of(1) - 1.0).abs() < 1e-10);
        assert!((gd.in_degree_of(2) - 2.0).abs() < 1e-10);
        assert!((gd.in_degree_of(3) - 0.5).abs() < 1e-10);

        // degree_of for directed = out + in
        assert!((gd.degree_of(0) - 4.5).abs() < 1e-10);
        assert!((gd.degree_of(1) - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_builder_directed_self_loop() {
        let mut b = GraphDataBuilder::new(3).directed();
        b.add_edge(0, 0, 5.0).unwrap();
        b.add_edge(0, 1, 1.0).unwrap();
        let gd = b.build().unwrap();

        // out_degree: 0→5+1=6, 1→0, 2→0
        assert!((gd.out_degree_of(0) - 6.0).abs() < 1e-10);
        // in_degree: 0→5, 1→1, 2→0
        assert!((gd.in_degree_of(0) - 5.0).abs() < 1e-10);
        assert!((gd.in_degree_of(1) - 1.0).abs() < 1e-10);
        // total_weight = 5.0 + 1.0 = 6.0
        assert!((gd.total_weight() - 6.0).abs() < 1e-10);
    }

    #[test]
    fn test_builder_empty_graph() {
        let gd = GraphDataBuilder::new(5).build().unwrap();
        assert_eq!(gd.node_count(), 5);
        assert!((gd.total_weight() - 0.0).abs() < 1e-10);
        for i in 0..5 {
            assert!((gd.degree_of(i) - 0.0).abs() < 1e-10);
            assert_eq!(gd.neighbors(i).count(), 0);
        }
    }

    #[test]
    fn test_builder_matches_from_edgelist() {
        let edges: Vec<(usize, usize, f64)> =
            vec![(0, 1, 1.0), (1, 2, 2.0), (0, 2, 3.0), (2, 2, 0.5)];

        let mut b = GraphDataBuilder::new(3);
        for &(u, v, w) in &edges {
            b.add_edge(u, v, w).unwrap();
        }
        let gd = b.build().unwrap();

        let mut expected_degree = [0.0f64; 3];
        for &(u, v, w) in &edges {
            if u == v {
                expected_degree[u] += 2.0 * w;
            } else {
                expected_degree[u] += w;
                expected_degree[v] += w;
            }
        }
        let expected_total: f64 = expected_degree.iter().sum::<f64>() / 2.0;

        for i in 0..3 {
            assert!(
                (gd.degree_of(i) - expected_degree[i]).abs() < 1e-10,
                "degree mismatch at node {i}"
            );
        }
        assert!(
            (gd.total_weight() - expected_total).abs() < 1e-10,
            "total_weight mismatch"
        );
    }
}