hypergraph-rs 0.3.0

Hypergraphs for Rust: a port of XGI built on rustworkx-core, with a value on every membership
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Read-only proxy views over a [`Hypergraph`]: `NodeView` and `EdgeView`.
//!
//! Each view borrows the hypergraph and holds an insertion-ordered subset of
//! ids. Filtering methods (`isolates`, `singletons`, `filterby_*`) return a new
//! sub-view over the same hypergraph. XGI parity: `H.nodes` / `H.edges`.

use super::hypergraph::Hypergraph;
use std::collections::{BTreeSet, HashMap};

/// Group `(id, key)` pairs by key; keep groups of two or more, in order of first occurrence.
fn group_by_key(items: impl Iterator<Item = (String, BTreeSet<String>)>) -> Vec<Vec<String>> {
    let mut index: HashMap<BTreeSet<String>, usize> = HashMap::new();
    let mut groups: Vec<Vec<String>> = Vec::new();
    for (id, key) in items {
        match index.get(&key) {
            Some(&i) => groups[i].push(id),
            None => {
                index.insert(key, groups.len());
                groups.push(vec![id]);
            }
        }
    }
    groups.retain(|g| g.len() > 1);
    groups
}

/// Comparison mode for `filterby_*`. XGI parity: the `mode` argument of
/// `IDView.filterby` (views.py:197-287). `between` is a dedicated method.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterMode {
    Eq,
    Neq,
    Lt,
    Gt,
    Leq,
    Geq,
}

impl FilterMode {
    /// Whether `actual <mode> val` holds.
    pub fn matches(self, actual: usize, val: usize) -> bool {
        match self {
            FilterMode::Eq => actual == val,
            FilterMode::Neq => actual != val,
            FilterMode::Lt => actual < val,
            FilterMode::Gt => actual > val,
            FilterMode::Leq => actual <= val,
            FilterMode::Geq => actual >= val,
        }
    }
}

/// A read-only view over the nodes of a hypergraph.
pub struct NodeView<'a, N, E, M> {
    graph: &'a Hypergraph<N, E, M>,
    ids: Vec<String>,
}

impl<N, E, M> Hypergraph<N, E, M> {
    /// A view over all nodes (insertion order). XGI parity: `H.nodes`.
    pub fn nodes(&self) -> NodeView<'_, N, E, M> {
        NodeView {
            graph: self,
            ids: self.node_ids(),
        }
    }
}

impl<'a, N, E, M> NodeView<'a, N, E, M> {
    /// The tracked node ids, in insertion order.
    pub fn ids(&self) -> &[String] {
        &self.ids
    }

    /// The number of nodes tracked.
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    /// Whether the view is empty.
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    /// Whether `node_id` is tracked by this view.
    pub fn contains(&self, node_id: &str) -> bool {
        self.ids.iter().any(|n| n == node_id)
    }

    /// The node's attributes. XGI parity: `H.nodes[n]`.
    pub fn attrs(&self, node_id: &str) -> Option<&'a N> {
        self.graph.node_attrs(node_id)
    }

    /// The number of edges the node belongs to. XGI parity: `H.nodes.degree`.
    pub fn degree(&self, node_id: &str) -> usize {
        self.graph.memberships(node_id).map_or(0, |m| m.len())
    }

    /// The edge ids the node is a member of. XGI parity:
    /// `H.nodes.memberships(n)` (views.py:604-630).
    pub fn memberships(&self, node_id: &str) -> Option<Vec<String>> {
        self.graph.memberships(node_id)
    }

    /// Node ids with the same edge-membership set, grouped. Only groups of two or more; groups in
    /// order of first occurrence in this view; ids in a group in insertion order. XGI parity:
    /// `H.nodes.duplicate_groups()`.
    pub fn duplicate_groups(&self) -> Vec<Vec<String>> {
        group_by_key(self.ids.iter().map(|n| {
            let key: BTreeSet<String> = self
                .graph
                .memberships(n)
                .unwrap_or_default()
                .into_iter()
                .collect();
            (n.clone(), key)
        }))
    }

    /// Sub-view of degree-0 nodes. XGI parity: `H.nodes.isolates()`.
    pub fn isolates(&self) -> NodeView<'a, N, E, M> {
        let ids = self
            .ids
            .iter()
            .filter(|n| self.degree(n) == 0)
            .cloned()
            .collect();
        NodeView {
            graph: self.graph,
            ids,
        }
    }

    /// Sub-view of nodes in no edge of size >= 2. XGI parity:
    /// `H.nodes.isolates(ignore_singletons=True)` (views.py:632-667).
    pub fn isolates_ignoring_singletons(&self) -> NodeView<'a, N, E, M> {
        use std::collections::BTreeSet;
        let mut in_big_edges: BTreeSet<String> = BTreeSet::new();
        for eid in self.graph.edge_ids() {
            let members = self.graph.members(&eid).unwrap_or_default();
            if members.len() >= 2 {
                in_big_edges.extend(members);
            }
        }
        let ids = self
            .ids
            .iter()
            .filter(|n| !in_big_edges.contains(*n))
            .cloned()
            .collect();
        NodeView {
            graph: self.graph,
            ids,
        }
    }

    /// Sub-view of nodes whose degree satisfies `mode` vs `val`.
    /// XGI parity: `H.nodes.filterby('degree', val, mode)`.
    pub fn filterby_degree(&self, val: usize, mode: FilterMode) -> NodeView<'a, N, E, M> {
        let ids = self
            .ids
            .iter()
            .filter(|n| mode.matches(self.degree(n), val))
            .cloned()
            .collect();
        NodeView {
            graph: self.graph,
            ids,
        }
    }

    /// Sub-view of nodes with `lo <= degree <= hi`.
    /// XGI parity: `filterby('degree', (lo, hi), 'between')`.
    pub fn filterby_degree_between(&self, lo: usize, hi: usize) -> NodeView<'a, N, E, M> {
        let ids = self
            .ids
            .iter()
            .filter(|n| {
                let d = self.degree(n);
                lo <= d && d <= hi
            })
            .cloned()
            .collect();
        NodeView {
            graph: self.graph,
            ids,
        }
    }
}

/// A read-only view over the edges of a hypergraph.
pub struct EdgeView<'a, N, E, M> {
    graph: &'a Hypergraph<N, E, M>,
    ids: Vec<String>,
}

impl<N, E, M> Hypergraph<N, E, M> {
    /// A view over all edges (insertion order). XGI parity: `H.edges`.
    pub fn edges(&self) -> EdgeView<'_, N, E, M> {
        EdgeView {
            graph: self,
            ids: self.edge_ids(),
        }
    }
}

impl<'a, N, E, M> EdgeView<'a, N, E, M> {
    /// The tracked edge ids, in insertion order.
    pub fn ids(&self) -> &[String] {
        &self.ids
    }

    /// The number of edges tracked.
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    /// Whether the view is empty.
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    /// Whether `edge_id` is tracked by this view.
    pub fn contains(&self, edge_id: &str) -> bool {
        self.ids.iter().any(|e| e == edge_id)
    }

    /// The edge's attributes. XGI parity: `H.edges[e]`.
    pub fn attrs(&self, edge_id: &str) -> Option<&'a E> {
        self.graph.edge_attrs(edge_id)
    }

    /// The number of members. XGI parity: `H.edges.size` (edgestats.py:148).
    pub fn size(&self, edge_id: &str) -> usize {
        self.graph.members(edge_id).map_or(0, |m| m.len())
    }

    /// The order (size − 1). XGI parity: `H.edges.order` (edgestats.py:108).
    /// Saturates at 0 (our edges are never empty in normal use).
    pub fn order(&self, edge_id: &str) -> usize {
        self.size(edge_id).saturating_sub(1)
    }

    /// The member node ids. XGI parity: `H.edges.members(e)` (views.py:706-747).
    pub fn members(&self, edge_id: &str) -> Option<Vec<String>> {
        self.graph.members(edge_id)
    }

    /// Sub-view of size-1 edges. XGI parity: `H.edges.singletons()`.
    pub fn singletons(&self) -> EdgeView<'a, N, E, M> {
        self.filterby_size(1, FilterMode::Eq)
    }

    /// Sub-view of size-0 edges. XGI parity: `H.edges.empty()`.
    pub fn empty(&self) -> EdgeView<'a, N, E, M> {
        self.filterby_size(0, FilterMode::Eq)
    }

    /// Sub-view of edges whose size satisfies `mode` vs `val`.
    pub fn filterby_size(&self, val: usize, mode: FilterMode) -> EdgeView<'a, N, E, M> {
        let ids = self
            .ids
            .iter()
            .filter(|e| mode.matches(self.size(e), val))
            .cloned()
            .collect();
        EdgeView {
            graph: self.graph,
            ids,
        }
    }

    /// Sub-view of edges whose order satisfies `mode` vs `val`.
    pub fn filterby_order(&self, val: usize, mode: FilterMode) -> EdgeView<'a, N, E, M> {
        let ids = self
            .ids
            .iter()
            .filter(|e| mode.matches(self.order(e), val))
            .cloned()
            .collect();
        EdgeView {
            graph: self.graph,
            ids,
        }
    }

    /// Edge ids with the same member set, grouped. Only groups of two or more; groups in order of
    /// first occurrence in this view; ids in a group in insertion order. XGI parity:
    /// `H.edges.duplicate_groups()`.
    pub fn duplicate_groups(&self) -> Vec<Vec<String>> {
        group_by_key(self.ids.iter().map(|e| {
            let key: BTreeSet<String> = self
                .graph
                .members(e)
                .unwrap_or_default()
                .into_iter()
                .collect();
            (e.clone(), key)
        }))
    }

    /// Sub-view of edges that duplicate an earlier one (same member-set).
    /// The first (sorted) id of each group is kept; the rest are duplicates.
    /// XGI parity: `H.edges.duplicates()` (views.py:409-465).
    pub fn duplicates(&self) -> EdgeView<'a, N, E, M> {
        use std::collections::BTreeMap;
        let mut groups: BTreeMap<Vec<String>, Vec<String>> = BTreeMap::new();
        for eid in &self.ids {
            let mut mem = self.graph.members(eid).unwrap_or_default();
            mem.sort();
            groups.entry(mem).or_default().push(eid.clone());
        }
        let mut dups: Vec<String> = Vec::new();
        for members_ids in groups.values() {
            if members_ids.len() > 1 {
                let mut sorted = members_ids.clone();
                sorted.sort();
                dups.extend(sorted.into_iter().skip(1));
            }
        }
        // Preserve insertion order among the flagged ids.
        let ids = self
            .ids
            .iter()
            .filter(|e| dups.contains(e))
            .cloned()
            .collect();
        EdgeView {
            graph: self.graph,
            ids,
        }
    }

    /// Sub-view of edges whose member-set equals `members`.
    /// XGI parity: `H.edges.lookup(members)` (views.py:467-509).
    pub fn lookup(&self, members: &[String]) -> EdgeView<'a, N, E, M> {
        use std::collections::BTreeSet;
        let want: BTreeSet<String> = members.iter().cloned().collect();
        let ids = self
            .ids
            .iter()
            .filter(|e| {
                let got: BTreeSet<String> = self
                    .graph
                    .members(e)
                    .unwrap_or_default()
                    .into_iter()
                    .collect();
                got == want
            })
            .cloned()
            .collect();
        EdgeView {
            graph: self.graph,
            ids,
        }
    }

    /// Sub-view of maximal edges (not a subset of any other edge).
    /// `strict=false` keeps maximal multiedges; `strict=true` excludes any edge
    /// that is a subset of or equal to another. XGI parity: `H.edges.maximal()`
    /// (views.py:777-847).
    pub fn maximal(&self, strict: bool) -> EdgeView<'a, N, E, M> {
        use std::collections::BTreeSet;
        let sets: Vec<(String, BTreeSet<String>)> = self
            .ids
            .iter()
            .map(|e| {
                let s: BTreeSet<String> = self
                    .graph
                    .members(e)
                    .unwrap_or_default()
                    .into_iter()
                    .collect();
                (e.clone(), s)
            })
            .collect();

        let ids = self
            .ids
            .iter()
            .filter(|e| {
                let me = &sets.iter().find(|(id, _)| id == *e).unwrap().1;
                // Keep e unless some OTHER edge f makes it non-maximal.
                !sets.iter().any(|(fid, mf)| {
                    if fid == *e {
                        return false;
                    }
                    if strict {
                        me.is_subset(mf) // subset OR equal disqualifies (strict)
                    } else {
                        me.is_subset(mf) && me.len() < mf.len() // strict subset only
                    }
                })
            })
            .cloned()
            .collect();
        EdgeView {
            graph: self.graph,
            ids,
        }
    }
}