Skip to main content

hypergraph_rs/generators/
lattice.rs

1//! Lattice hypergraph generators (XGI `generators/lattice.py`).
2
3use serde_json::Value;
4
5use super::classic::GeneratorError;
6use crate::Hypergraph;
7
8/// The edges of `ring_lattice(n, d, k, l, ..)` in id order: node i, then the d-1 nodes
9/// (start + l + j) % n for j in 0..d-1, for start in i+1 ..= i + k/2. XGI's `_ring_lattice_edges`.
10///
11/// The result has `n * (k / 2)` edges of `d` entries; it is empty for `n == 0` (the loop over the nodes never
12/// runs, so the `% n` is never reached). `ring_lattice` itself refuses `n == 0`.
13#[must_use]
14pub fn ring_lattice_edges(n: usize, d: usize, k: usize, l: usize) -> Vec<Vec<usize>> {
15    let mut edges: Vec<Vec<usize>> = Vec::with_capacity(n * (k / 2));
16    for node in 0..n {
17        for start in (node + 1)..=(node + k / 2) {
18            let mut members: Vec<usize> = Vec::with_capacity(d);
19            members.push(node);
20            for j in 0..d.saturating_sub(1) {
21                members.push((start + l + j) % n);
22            }
23            edges.push(members);
24        }
25    }
26    edges
27}
28
29/// A d-uniform ring-lattice hypergraph on `n` nodes: each node is in `k` edges,
30/// consecutive edges overlap by `d - l`. XGI `ring_lattice(n, d, k, l, with_positions)`.
31///
32/// With `with_positions`, node `i` gets the attribute `"pos"` = `[cos(2 pi i / n), sin(2 pi i / n)]`
33/// (a JSON list: attribute values are JSON, so XGI's tuple comes back as a list).
34///
35/// `k` is `usize` here (negative k is unrepresentable); XGI's `k < 2` /
36/// odd-`k` warnings are elided; the structural output is unchanged.
37///
38/// # Errors
39///
40/// `GeneratorError::InvalidParameter` when `n == 0` or `d == 0`.
41pub fn ring_lattice(
42    n: usize,
43    d: usize,
44    k: usize,
45    l: usize,
46    with_positions: bool,
47) -> Result<Hypergraph, GeneratorError> {
48    if n == 0 {
49        return Err(GeneratorError::InvalidParameter("n must be > 0".into()));
50    }
51    if d == 0 {
52        return Err(GeneratorError::InvalidParameter("d must be >= 1".into()));
53    }
54    let mut h = Hypergraph::new();
55    for members in ring_lattice_edges(n, d, k, l) {
56        let members: Vec<String> = members.iter().map(ToString::to_string).collect();
57        let _ = h.add_edge(members, None, Value::Null);
58    }
59    h.add_nodes_from((0..n).map(|i| {
60        let attrs = if with_positions {
61            let angle = 2.0 * std::f64::consts::PI * (i as f64) / (n as f64);
62            serde_json::json!({ "pos": [angle.cos(), angle.sin()] })
63        } else {
64            Value::Null
65        };
66        (i.to_string(), attrs)
67    }));
68    Ok(h)
69}