Skip to main content

hypergraph_rs/dynamics/
mod.rs

1//! Kuramoto synchronization dynamics, first ported from `xgi/dynamics/synchronization.py`.
2//!
3//! XGI 1.0 dropped its `dynamics` package. This module stays as an extra of this crate, behind the
4//! `dynamics` feature; it is no longer checked against XGI and the Python bindings no longer
5//! expose it.
6//!
7//! NOTE: XGI's `dynamics/` slice is Kuramoto synchronization, NOT epidemic (SIR/SIS)
8//! models — the spec's "epidemic" summary is wrong (see the Phase-6 plan header). This
9//! module ports the pieces whose dependencies exist by Phase 6: `simulate_kuramoto`
10//! (pairwise + triangle coupling) and `compute_kuramoto_order_parameter`. The simplicial
11//! Kuramoto pair needs the Phase-3 Hodge boundary matrix + `SimplicialComplex` and is
12//! deferred.
13//!
14//! Complex arithmetic is done manually with `(re, im)` f64 pairs (no `num-complex`
15//! dependency). Randomness (default `omega`/`theta`) uses seeded `rand_pcg::Pcg64Mcg`;
16//! sequence-level parity with numpy is NOT claimed (spec §9.4).
17
18use indexmap::IndexMap;
19use rand::RngExt;
20use rand_core::SeedableRng;
21use rand_pcg::Pcg64Mcg;
22
23use crate::Hypergraph;
24
25/// The Kuramoto order parameter timeseries.
26///
27/// XGI parity: `xgi.compute_kuramoto_order_parameter`
28/// (`dynamics/synchronization.py:121-141`). For each timestep `t`,
29/// `r_t = |(1/N) Σ_n exp(i·theta[t][n])|` — a synchrony measure in `[0, 1]`.
30pub fn compute_kuramoto_order_parameter(theta_time: &[Vec<f64>]) -> Vec<f64> {
31    theta_time
32        .iter()
33        .map(|row| {
34            let n = row.len();
35            if n == 0 {
36                return 0.0;
37            }
38            let (mut re, mut im) = (0.0_f64, 0.0_f64);
39            for &theta in row {
40                re += theta.cos();
41                im += theta.sin();
42            }
43            re /= n as f64;
44            im /= n as f64;
45            (re * re + im * im).sqrt()
46        })
47        .collect()
48}
49
50/// Accumulate `exp(i·phi)` into a `(re, im)` complex accumulator.
51#[inline]
52fn add_exp(acc: &mut (f64, f64), phi: f64) {
53    acc.0 += phi.cos();
54    acc.1 += phi.sin();
55}
56
57/// Imaginary part of `r · exp(-i·theta)` for `r = (re, im)`:
58/// `Im((re + i·im)(cos θ − i·sin θ)) = im·cos θ − re·sin θ`.
59#[inline]
60fn imag_times_conj(r: (f64, f64), theta: f64) -> f64 {
61    r.1 * theta.cos() - r.0 * theta.sin()
62}
63
64/// Simulate the Kuramoto model on a hypergraph (pairwise + triangle coupling).
65///
66/// XGI parity: `xgi.simulate_kuramoto` (`dynamics/synchronization.py:18-118`). Integrates
67/// the phase ODE via the explicit Euler method over `timesteps` steps of size `dt`.
68/// Returns `(theta_time, times)` where `theta_time[t][n]` is node `n`'s phase at step `t`.
69///
70/// Node indices follow `h.node_ids()` insertion order. `links` are size-2 edges and
71/// `triangles` are size-3 edges (other sizes do not contribute — matching XGI's
72/// `filterby("size", 2 | 3)`). Defaulted `omega` ~ N(0,1) (Box–Muller) and
73/// `theta` ~ U[0,2π) are drawn from a seeded `Pcg64Mcg`; supply both for exact
74/// determinism independent of the RNG.
75#[allow(clippy::too_many_arguments)]
76pub fn simulate_kuramoto(
77    h: &Hypergraph,
78    k2: f64,
79    k3: f64,
80    omega: Option<Vec<f64>>,
81    theta: Option<Vec<f64>>,
82    timesteps: usize,
83    dt: f64,
84    seed: Option<u64>,
85) -> (Vec<Vec<f64>>, Vec<f64>) {
86    let n = h.num_nodes();
87    let node_index: IndexMap<String, usize> = h
88        .node_ids()
89        .into_iter()
90        .enumerate()
91        .map(|(i, id)| (id, i))
92        .collect();
93
94    // Extract links (size 2) and triangles (size 3) as index tuples.
95    let mut links: Vec<(usize, usize)> = Vec::new();
96    let mut triangles: Vec<(usize, usize, usize)> = Vec::new();
97    for e in h.edge_ids() {
98        let members = h.members(&e).unwrap_or_default();
99        match members.len() {
100            2 => links.push((node_index[&members[0]], node_index[&members[1]])),
101            3 => triangles.push((
102                node_index[&members[0]],
103                node_index[&members[1]],
104                node_index[&members[2]],
105            )),
106            _ => {}
107        }
108    }
109
110    let mut rng = Pcg64Mcg::seed_from_u64(seed.unwrap_or(0));
111
112    let omega: Vec<f64> = omega.unwrap_or_else(|| {
113        // N(0, 1) via Box–Muller from the seeded PCG.
114        (0..n)
115            .map(|_| {
116                let u1: f64 = 1.0 - rng.random_range(0.0..1.0); // in (0, 1]
117                let u2: f64 = rng.random_range(0.0..1.0);
118                (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos()
119            })
120            .collect()
121    });
122    let mut theta: Vec<f64> = theta.unwrap_or_else(|| {
123        (0..n)
124            .map(|_| rng.random_range(0.0..1.0) * 2.0 * std::f64::consts::PI)
125            .collect()
126    });
127
128    let mut theta_time: Vec<Vec<f64>> = vec![vec![0.0; n]; timesteps];
129    let times: Vec<f64> = (0..timesteps).map(|t| t as f64 * dt).collect();
130
131    // `t` indexes `theta_time` only, but the loop body below also needs the plain
132    // integer count (dt-scaled elsewhere); the index form reads clearer than an
133    // iterator adapter here.
134    #[allow(clippy::needless_range_loop)]
135    for t in 0..timesteps {
136        theta_time[t] = theta.clone();
137
138        let mut r1 = vec![(0.0_f64, 0.0_f64); n];
139        let mut r2 = vec![(0.0_f64, 0.0_f64); n];
140
141        for &(i, j) in &links {
142            add_exp(&mut r1[i], theta[j]);
143            add_exp(&mut r1[j], theta[i]);
144        }
145        for &(i, j, k) in &triangles {
146            add_exp(&mut r2[i], 2.0 * theta[j] - theta[k]);
147            add_exp(&mut r2[i], 2.0 * theta[k] - theta[j]);
148            add_exp(&mut r2[j], 2.0 * theta[i] - theta[k]);
149            add_exp(&mut r2[j], 2.0 * theta[k] - theta[i]);
150            add_exp(&mut r2[k], 2.0 * theta[i] - theta[j]);
151            add_exp(&mut r2[k], 2.0 * theta[j] - theta[i]);
152        }
153
154        let mut next = vec![0.0_f64; n];
155        for idx in 0..n {
156            let d_theta = omega[idx]
157                + k2 * imag_times_conj(r1[idx], theta[idx])
158                + k3 * imag_times_conj(r2[idx], theta[idx]);
159            next[idx] = theta[idx] + d_theta * dt;
160        }
161        theta = next;
162    }
163
164    (theta_time, times)
165}