hypergraph-rs 0.3.0

Hypergraphs for Rust: a port of XGI built on rustworkx-core, with a value on every membership
Documentation
//! Growing simplicial complexes (XGI 1.1 `generators/growth.py`).
//!
//! The pseudofractal and Apollonian complexes are deterministic. XGI adds the missing faces of each step by
//! iterating a Python `set`, so its simplex ids, and from `n_iter = 2` on its node labels, follow CPython's set
//! order. These functions visit faces in the complex's own id order instead: the counts and the structure are
//! XGI's, the labels from `n_iter = 2` on are not. The Python bindings port XGI's code to get XGI's labels.

use std::collections::HashSet;

use indexmap::IndexMap;
use serde_json::Value;

use super::classic::GeneratorError;
use super::rng::{seeded_rng, uniform_f64};
use crate::SimplicialComplex;

/// The simplices of a complex under construction, in id order, each a sorted list of node numbers.
#[derive(Default)]
struct Growth {
    simplices: Vec<Vec<usize>>,
    present: HashSet<Vec<usize>>,
    num_nodes: usize,
}

impl Growth {
    /// Adds the simplex itself; returns whether it was new.
    fn add_top(&mut self, mut members: Vec<usize>) -> bool {
        members.sort_unstable();
        members.dedup();
        if let Some(&last) = members.last() {
            self.num_nodes = self.num_nodes.max(last + 1);
        }
        if self.present.contains(&members) {
            return false;
        }
        self.present.insert(members.clone());
        self.simplices.push(members);
        true
    }

    /// Adds every missing face of size >= 2 of each simplex, largest first, in lexicographic order.
    fn add_faces(&mut self, tops: &[Vec<usize>]) {
        for top in tops {
            let mut top = top.clone();
            top.sort_unstable();
            top.dedup();
            for size in (2..top.len()).rev() {
                for face in combinations(&top, size) {
                    if self.present.insert(face.clone()) {
                        self.simplices.push(face);
                    }
                }
            }
        }
    }

    /// XGI's `add_simplices_from`: the new simplices first, in order, then their missing faces.
    fn add_simplices_from(&mut self, tops: Vec<Vec<usize>>) {
        let added: Vec<Vec<usize>> = tops
            .into_iter()
            .filter(|t| self.add_top(t.clone()))
            .collect();
        self.add_faces(&added);
    }

    /// XGI's `add_simplex`: the simplex, then its missing faces.
    fn add_simplex(&mut self, top: Vec<usize>) {
        if self.add_top(top.clone()) {
            self.add_faces(&[top]);
        }
    }

    /// The simplices of `size` members, in id order.
    fn of_size(&self, size: usize) -> Vec<Vec<usize>> {
        self.simplices
            .iter()
            .filter(|s| s.len() == size)
            .cloned()
            .collect()
    }

    fn finish(self) -> SimplicialComplex {
        let nodes = (0..self.num_nodes)
            .map(|i| (i.to_string(), Value::Null))
            .collect();
        let simplices = self
            .simplices
            .into_iter()
            .enumerate()
            .map(|(id, members)| {
                let members = members.iter().map(ToString::to_string).collect();
                (id.to_string(), members, Value::Null)
            })
            .collect();
        let mut complex = SimplicialComplex::from_closed_simplices(nodes, simplices)
            .expect("every face of every simplex was added");
        complex.update_uid_counter(complex.num_edges().saturating_sub(1) as u64);
        complex
    }
}

/// Every `size`-combination of `items`, in lexicographic order of positions. Bounded by C(len, size).
fn combinations(items: &[usize], size: usize) -> Vec<Vec<usize>> {
    let n = items.len();
    let mut out = Vec::new();
    if size == 0 || size > n {
        return out;
    }
    let mut idx: Vec<usize> = (0..size).collect();
    loop {
        out.push(idx.iter().map(|&i| items[i]).collect());
        let Some(i) = (0..size).rev().find(|&i| idx[i] != i + n - size) else {
            return out;
        };
        idx[i] += 1;
        for j in (i + 1)..size {
            idx[j] = idx[j - 1] + 1;
        }
    }
}

fn check_order(order: usize) -> Result<(), GeneratorError> {
    if order < 2 {
        return Err(GeneratorError::InvalidParameter(
            "order must be at least 2.".into(),
        ));
    }
    Ok(())
}

/// The pseudofractal simplicial complex of `order` (Nurisso et al. 2024). XGI 1.1
/// `pseudofractal_simplicial_complex(order, n_iter)`.
///
/// Starting from one `order`-simplex, each step attaches a new node to every (order-1)-simplex. The
/// (order-1)-faces of each step are visited in the complex's own `edge_ids()` order, so node labels from
/// `n_iter = 2` on differ from XGI's. Counts and structure are XGI's.
///
/// # Errors
///
/// `GeneratorError::InvalidParameter("order must be at least 2.")` when `order < 2`.
pub fn pseudofractal_simplicial_complex(
    order: usize,
    n_iter: usize,
) -> Result<SimplicialComplex, GeneratorError> {
    check_order(order)?;
    let mut growth = Growth::default();
    growth.add_simplex((0..=order).collect());
    for _ in 0..n_iter {
        let mut next = growth.num_nodes;
        let new: Vec<Vec<usize>> = growth
            .of_size(order)
            .into_iter()
            .map(|mut face| {
                face.push(next);
                next += 1;
                face
            })
            .collect();
        growth.add_simplices_from(new);
    }
    Ok(growth.finish())
}

/// The Apollonian simplicial complex of `order` (Nurisso et al. 2024). XGI 1.1 `apollonian_complex(order, n_iter)`.
///
/// Starting from one `order`-simplex, each step attaches a new node to every (order-1)-simplex that contains
/// a node added in the step before. Faces are visited as in [`pseudofractal_simplicial_complex`].
///
/// # Errors
///
/// `GeneratorError::InvalidParameter("order must be at least 2.")` when `order < 2`.
pub fn apollonian_complex(
    order: usize,
    n_iter: usize,
) -> Result<SimplicialComplex, GeneratorError> {
    check_order(order)?;
    let mut growth = Growth::default();
    growth.add_simplex((0..=order).collect());
    let mut newest: HashSet<usize> = (0..=order).collect();
    for _ in 0..n_iter {
        let mut next = growth.num_nodes;
        let mut added = HashSet::new();
        let new: Vec<Vec<usize>> = growth
            .of_size(order)
            .into_iter()
            .filter(|face| face.iter().any(|v| newest.contains(v)))
            .map(|mut face| {
                face.push(next);
                added.insert(next);
                next += 1;
                face
            })
            .collect();
        growth.add_simplices_from(new);
        newest = added;
    }
    Ok(growth.finish())
}

/// Network geometry with flavor (Bianconi and Rahmede 2016). XGI 1.1
/// `network_geometry_flavor(order, s, beta, n_iter, energy_distribution, seed)`.
///
/// `order >= 1`, `s` in {-1, 0, 1}. `energies`, when given, holds one energy per node in node order
/// (`order + 1 + n_iter` values); when `None`, energies are drawn uniformly in [0, 10) from the seeded
/// generator, before the growth. Each step attaches a new node to an (order-1)-face chosen with weight
/// `exp(-beta * energy(face)) * (1 + s * (count - 1))`, computed in log space, where `count` is the number of
/// `order`-simplices holding the face; faces with weight 0 are skipped, and faces are visited in the order
/// they were first counted. The same seed gives the same complex; the draws are not XGI's.
///
/// # Errors
///
/// `GeneratorError::InvalidParameter` when `order < 1`, `s` is not -1, 0 or 1, `energies` has the wrong
/// length, or an attachment weight is not a number.
pub fn network_geometry_flavor(
    order: usize,
    s: i8,
    beta: f64,
    n_iter: usize,
    energies: Option<&[f64]>,
    seed: Option<u64>,
) -> Result<SimplicialComplex, GeneratorError> {
    if order < 1 {
        return Err(GeneratorError::InvalidParameter(
            "order must be at least 1.".into(),
        ));
    }
    if !(-1..=1).contains(&s) {
        return Err(GeneratorError::InvalidParameter(
            "s must be -1, 0, or 1.".into(),
        ));
    }
    let num_nodes = order + 1 + n_iter;
    let mut rng = seeded_rng(seed);
    let energy: Vec<f64> = match energies {
        Some(given) if given.len() != num_nodes => {
            return Err(GeneratorError::InvalidParameter(format!(
                "energies must hold one value per node ({num_nodes}), not {}",
                given.len()
            )))
        }
        Some(given) => given.to_vec(),
        None => (0..num_nodes)
            .map(|_| 10.0 * uniform_f64(&mut rng))
            .collect(),
    };

    let mut growth = Growth::default();
    // The number of `order`-simplices holding each (order-1)-face, in the order the faces were first counted.
    let mut face_counts: IndexMap<Vec<usize>, i64> = IndexMap::new();
    let count_faces = |simplex: &[usize], counts: &mut IndexMap<Vec<usize>, i64>| {
        for face in combinations(simplex, order) {
            *counts.entry(face).or_insert(0) += 1;
        }
    };
    let first: Vec<usize> = (0..=order).collect();
    growth.add_simplex(first.clone());
    count_faces(&first, &mut face_counts);

    for new_node in (order + 1)..num_nodes {
        let mut faces: Vec<&Vec<usize>> = Vec::with_capacity(face_counts.len());
        let mut log_weights: Vec<f64> = Vec::with_capacity(face_counts.len());
        for (face, &count) in &face_counts {
            let multiplicity = 1 + i64::from(s) * (count - 1);
            if multiplicity <= 0 {
                continue;
            }
            let face_energy: f64 = face.iter().map(|&v| energy[v]).sum();
            faces.push(face);
            log_weights.push(-beta * face_energy + (multiplicity as f64).ln());
        }
        let max = log_weights
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max);
        let weights: Vec<f64> = log_weights.iter().map(|w| (w - max).exp()).collect();
        let total: f64 = weights.iter().sum();
        if !total.is_finite() || total <= 0.0 {
            return Err(GeneratorError::InvalidParameter(
                "the attachment weights are not numbers; check beta and the energies".into(),
            ));
        }
        let target = uniform_f64(&mut rng) * total;
        let mut chosen = faces.len() - 1;
        let mut running = 0.0;
        for (i, w) in weights.iter().enumerate() {
            running += w;
            if target < running {
                chosen = i;
                break;
            }
        }
        let mut simplex = faces[chosen].clone();
        simplex.push(new_node);
        growth.add_simplex(simplex.clone());
        simplex.sort_unstable();
        count_faces(&simplex, &mut face_counts);
    }
    Ok(growth.finish())
}