Skip to main content

hypergraph_rs/stats/
mod.rs

1//! Node/edge statistics (XGI `xgi/stats/*.py` port).
2//!
3//! XGI wraps stats in lazy proxy objects (`IDStat`) with `.asdict()`/`.aslist()`/
4//! `.filterby()`. We compute eagerly into an insertion-ordered [`Stat`] value that
5//! offers the same terminal operations as pure data.
6
7pub mod diedgestats;
8pub mod dinodestats;
9pub mod edgestats;
10pub mod nodestats;
11
12pub use diedgestats::{di_edge_order, di_edge_size, di_head_size, di_tail_size};
13pub use dinodestats::{di_degree, di_in_degree, di_out_degree};
14pub use edgestats::{edge_attrs, edge_order, edge_size};
15pub use nodestats::{node_attrs, node_degree, node_degree_weighted};
16
17use indexmap::IndexMap;
18
19/// An id → quantity mapping, insertion-ordered (mirrors XGI's `IDStat` result dict).
20///
21/// `T` is the stat's value type (`usize` for degree/order/size, `serde_json::Value`
22/// for attribute stats). Terminal ops mirror XGI's `as*` / `filterby` surface.
23#[derive(Clone, Debug, PartialEq)]
24pub struct Stat<T> {
25    inner: IndexMap<String, T>,
26}
27
28impl<T> Stat<T> {
29    /// Construct from an insertion-ordered map (internal to the stat functions).
30    pub fn new(inner: IndexMap<String, T>) -> Self {
31        Self { inner }
32    }
33
34    /// XGI `.asdict()` — borrow the id → value map.
35    pub fn asdict(&self) -> &IndexMap<String, T> {
36        &self.inner
37    }
38
39    /// XGI `.aslist()` — values in id insertion order.
40    pub fn aslist(&self) -> Vec<T>
41    where
42        T: Clone,
43    {
44        self.inner.values().cloned().collect()
45    }
46
47    /// Number of ids in the mapping (XGI `len(stat)`).
48    pub fn len(&self) -> usize {
49        self.inner.len()
50    }
51
52    /// Whether the mapping is empty.
53    pub fn is_empty(&self) -> bool {
54        self.inner.is_empty()
55    }
56
57    /// Value for one id (XGI `stat[idx]`), if present.
58    pub fn get(&self, id: &str) -> Option<&T> {
59        self.inner.get(id)
60    }
61}
62
63impl<T: PartialEq> Stat<T> {
64    /// XGI `.filterby('stat', value)` — ids whose value equals `value`, in order.
65    pub fn filterby(&self, value: &T) -> Vec<String> {
66        self.inner
67            .iter()
68            .filter(|(_, v)| *v == value)
69            .map(|(k, _)| k.clone())
70            .collect()
71    }
72}
73
74impl<T: PartialOrd> Stat<T> {
75    /// Ids whose value is strictly greater than `value` (XGI `filterby(..., mode="gt")`).
76    pub fn filterby_gt(&self, value: &T) -> Vec<String> {
77        self.inner
78            .iter()
79            .filter(|(_, v)| *v > value)
80            .map(|(k, _)| k.clone())
81            .collect()
82    }
83}