Skip to main content

hypergraph_rs/generators/
growth.rs

1//! Growing simplicial complexes (XGI 1.1 `generators/growth.py`).
2//!
3//! The pseudofractal and Apollonian complexes are deterministic. XGI adds the missing faces of each step by
4//! iterating a Python `set`, so its simplex ids, and from `n_iter = 2` on its node labels, follow CPython's set
5//! order. These functions visit faces in the complex's own id order instead: the counts and the structure are
6//! XGI's, the labels from `n_iter = 2` on are not. The Python bindings port XGI's code to get XGI's labels.
7
8use std::collections::HashSet;
9
10use indexmap::IndexMap;
11use serde_json::Value;
12
13use super::classic::GeneratorError;
14use super::rng::{seeded_rng, uniform_f64};
15use crate::SimplicialComplex;
16
17/// The simplices of a complex under construction, in id order, each a sorted list of node numbers.
18#[derive(Default)]
19struct Growth {
20    simplices: Vec<Vec<usize>>,
21    present: HashSet<Vec<usize>>,
22    num_nodes: usize,
23}
24
25impl Growth {
26    /// Adds the simplex itself; returns whether it was new.
27    fn add_top(&mut self, mut members: Vec<usize>) -> bool {
28        members.sort_unstable();
29        members.dedup();
30        if let Some(&last) = members.last() {
31            self.num_nodes = self.num_nodes.max(last + 1);
32        }
33        if self.present.contains(&members) {
34            return false;
35        }
36        self.present.insert(members.clone());
37        self.simplices.push(members);
38        true
39    }
40
41    /// Adds every missing face of size >= 2 of each simplex, largest first, in lexicographic order.
42    fn add_faces(&mut self, tops: &[Vec<usize>]) {
43        for top in tops {
44            let mut top = top.clone();
45            top.sort_unstable();
46            top.dedup();
47            for size in (2..top.len()).rev() {
48                for face in combinations(&top, size) {
49                    if self.present.insert(face.clone()) {
50                        self.simplices.push(face);
51                    }
52                }
53            }
54        }
55    }
56
57    /// XGI's `add_simplices_from`: the new simplices first, in order, then their missing faces.
58    fn add_simplices_from(&mut self, tops: Vec<Vec<usize>>) {
59        let added: Vec<Vec<usize>> = tops
60            .into_iter()
61            .filter(|t| self.add_top(t.clone()))
62            .collect();
63        self.add_faces(&added);
64    }
65
66    /// XGI's `add_simplex`: the simplex, then its missing faces.
67    fn add_simplex(&mut self, top: Vec<usize>) {
68        if self.add_top(top.clone()) {
69            self.add_faces(&[top]);
70        }
71    }
72
73    /// The simplices of `size` members, in id order.
74    fn of_size(&self, size: usize) -> Vec<Vec<usize>> {
75        self.simplices
76            .iter()
77            .filter(|s| s.len() == size)
78            .cloned()
79            .collect()
80    }
81
82    fn finish(self) -> SimplicialComplex {
83        let nodes = (0..self.num_nodes)
84            .map(|i| (i.to_string(), Value::Null))
85            .collect();
86        let simplices = self
87            .simplices
88            .into_iter()
89            .enumerate()
90            .map(|(id, members)| {
91                let members = members.iter().map(ToString::to_string).collect();
92                (id.to_string(), members, Value::Null)
93            })
94            .collect();
95        let mut complex = SimplicialComplex::from_closed_simplices(nodes, simplices)
96            .expect("every face of every simplex was added");
97        complex.update_uid_counter(complex.num_edges().saturating_sub(1) as u64);
98        complex
99    }
100}
101
102/// Every `size`-combination of `items`, in lexicographic order of positions. Bounded by C(len, size).
103fn combinations(items: &[usize], size: usize) -> Vec<Vec<usize>> {
104    let n = items.len();
105    let mut out = Vec::new();
106    if size == 0 || size > n {
107        return out;
108    }
109    let mut idx: Vec<usize> = (0..size).collect();
110    loop {
111        out.push(idx.iter().map(|&i| items[i]).collect());
112        let Some(i) = (0..size).rev().find(|&i| idx[i] != i + n - size) else {
113            return out;
114        };
115        idx[i] += 1;
116        for j in (i + 1)..size {
117            idx[j] = idx[j - 1] + 1;
118        }
119    }
120}
121
122fn check_order(order: usize) -> Result<(), GeneratorError> {
123    if order < 2 {
124        return Err(GeneratorError::InvalidParameter(
125            "order must be at least 2.".into(),
126        ));
127    }
128    Ok(())
129}
130
131/// The pseudofractal simplicial complex of `order` (Nurisso et al. 2024). XGI 1.1
132/// `pseudofractal_simplicial_complex(order, n_iter)`.
133///
134/// Starting from one `order`-simplex, each step attaches a new node to every (order-1)-simplex. The
135/// (order-1)-faces of each step are visited in the complex's own `edge_ids()` order, so node labels from
136/// `n_iter = 2` on differ from XGI's. Counts and structure are XGI's.
137///
138/// # Errors
139///
140/// `GeneratorError::InvalidParameter("order must be at least 2.")` when `order < 2`.
141pub fn pseudofractal_simplicial_complex(
142    order: usize,
143    n_iter: usize,
144) -> Result<SimplicialComplex, GeneratorError> {
145    check_order(order)?;
146    let mut growth = Growth::default();
147    growth.add_simplex((0..=order).collect());
148    for _ in 0..n_iter {
149        let mut next = growth.num_nodes;
150        let new: Vec<Vec<usize>> = growth
151            .of_size(order)
152            .into_iter()
153            .map(|mut face| {
154                face.push(next);
155                next += 1;
156                face
157            })
158            .collect();
159        growth.add_simplices_from(new);
160    }
161    Ok(growth.finish())
162}
163
164/// The Apollonian simplicial complex of `order` (Nurisso et al. 2024). XGI 1.1 `apollonian_complex(order, n_iter)`.
165///
166/// Starting from one `order`-simplex, each step attaches a new node to every (order-1)-simplex that contains
167/// a node added in the step before. Faces are visited as in [`pseudofractal_simplicial_complex`].
168///
169/// # Errors
170///
171/// `GeneratorError::InvalidParameter("order must be at least 2.")` when `order < 2`.
172pub fn apollonian_complex(
173    order: usize,
174    n_iter: usize,
175) -> Result<SimplicialComplex, GeneratorError> {
176    check_order(order)?;
177    let mut growth = Growth::default();
178    growth.add_simplex((0..=order).collect());
179    let mut newest: HashSet<usize> = (0..=order).collect();
180    for _ in 0..n_iter {
181        let mut next = growth.num_nodes;
182        let mut added = HashSet::new();
183        let new: Vec<Vec<usize>> = growth
184            .of_size(order)
185            .into_iter()
186            .filter(|face| face.iter().any(|v| newest.contains(v)))
187            .map(|mut face| {
188                face.push(next);
189                added.insert(next);
190                next += 1;
191                face
192            })
193            .collect();
194        growth.add_simplices_from(new);
195        newest = added;
196    }
197    Ok(growth.finish())
198}
199
200/// Network geometry with flavor (Bianconi and Rahmede 2016). XGI 1.1
201/// `network_geometry_flavor(order, s, beta, n_iter, energy_distribution, seed)`.
202///
203/// `order >= 1`, `s` in {-1, 0, 1}. `energies`, when given, holds one energy per node in node order
204/// (`order + 1 + n_iter` values); when `None`, energies are drawn uniformly in [0, 10) from the seeded
205/// generator, before the growth. Each step attaches a new node to an (order-1)-face chosen with weight
206/// `exp(-beta * energy(face)) * (1 + s * (count - 1))`, computed in log space, where `count` is the number of
207/// `order`-simplices holding the face; faces with weight 0 are skipped, and faces are visited in the order
208/// they were first counted. The same seed gives the same complex; the draws are not XGI's.
209///
210/// # Errors
211///
212/// `GeneratorError::InvalidParameter` when `order < 1`, `s` is not -1, 0 or 1, `energies` has the wrong
213/// length, or an attachment weight is not a number.
214pub fn network_geometry_flavor(
215    order: usize,
216    s: i8,
217    beta: f64,
218    n_iter: usize,
219    energies: Option<&[f64]>,
220    seed: Option<u64>,
221) -> Result<SimplicialComplex, GeneratorError> {
222    if order < 1 {
223        return Err(GeneratorError::InvalidParameter(
224            "order must be at least 1.".into(),
225        ));
226    }
227    if !(-1..=1).contains(&s) {
228        return Err(GeneratorError::InvalidParameter(
229            "s must be -1, 0, or 1.".into(),
230        ));
231    }
232    let num_nodes = order + 1 + n_iter;
233    let mut rng = seeded_rng(seed);
234    let energy: Vec<f64> = match energies {
235        Some(given) if given.len() != num_nodes => {
236            return Err(GeneratorError::InvalidParameter(format!(
237                "energies must hold one value per node ({num_nodes}), not {}",
238                given.len()
239            )))
240        }
241        Some(given) => given.to_vec(),
242        None => (0..num_nodes)
243            .map(|_| 10.0 * uniform_f64(&mut rng))
244            .collect(),
245    };
246
247    let mut growth = Growth::default();
248    // The number of `order`-simplices holding each (order-1)-face, in the order the faces were first counted.
249    let mut face_counts: IndexMap<Vec<usize>, i64> = IndexMap::new();
250    let count_faces = |simplex: &[usize], counts: &mut IndexMap<Vec<usize>, i64>| {
251        for face in combinations(simplex, order) {
252            *counts.entry(face).or_insert(0) += 1;
253        }
254    };
255    let first: Vec<usize> = (0..=order).collect();
256    growth.add_simplex(first.clone());
257    count_faces(&first, &mut face_counts);
258
259    for new_node in (order + 1)..num_nodes {
260        let mut faces: Vec<&Vec<usize>> = Vec::with_capacity(face_counts.len());
261        let mut log_weights: Vec<f64> = Vec::with_capacity(face_counts.len());
262        for (face, &count) in &face_counts {
263            let multiplicity = 1 + i64::from(s) * (count - 1);
264            if multiplicity <= 0 {
265                continue;
266            }
267            let face_energy: f64 = face.iter().map(|&v| energy[v]).sum();
268            faces.push(face);
269            log_weights.push(-beta * face_energy + (multiplicity as f64).ln());
270        }
271        let max = log_weights
272            .iter()
273            .copied()
274            .fold(f64::NEG_INFINITY, f64::max);
275        let weights: Vec<f64> = log_weights.iter().map(|w| (w - max).exp()).collect();
276        let total: f64 = weights.iter().sum();
277        if !total.is_finite() || total <= 0.0 {
278            return Err(GeneratorError::InvalidParameter(
279                "the attachment weights are not numbers; check beta and the energies".into(),
280            ));
281        }
282        let target = uniform_f64(&mut rng) * total;
283        let mut chosen = faces.len() - 1;
284        let mut running = 0.0;
285        for (i, w) in weights.iter().enumerate() {
286            running += w;
287            if target < running {
288                chosen = i;
289                break;
290            }
291        }
292        let mut simplex = faces[chosen].clone();
293        simplex.push(new_node);
294        growth.add_simplex(simplex.clone());
295        simplex.sort_unstable();
296        count_faces(&simplex, &mut face_counts);
297    }
298    Ok(growth.finish())
299}