Skip to main content

hypergraph_rs/core/
hypergraph.rs

1//! The core `Hypergraph` data structure.
2
3#[cfg(feature = "generators")]
4use rand::RngExt;
5#[cfg(feature = "generators")]
6use rand_core::SeedableRng;
7#[cfg(feature = "generators")]
8use rand_pcg::Pcg64Mcg;
9use rustworkx_core::petgraph::graph::{NodeIndex as GraphNodeIndex, UnGraph};
10use rustworkx_core::petgraph::stable_graph::{NodeIndex, StableDiGraph};
11use rustworkx_core::petgraph::visit::NodeIndexable;
12use serde_json::Value;
13
14use super::error::{EdgeError, MembershipError, NodeError, SwapError};
15use super::idmap::IdMap;
16use super::kinds::{MembershipEdge, NodeKind};
17
18/// A hypergraph, represented as a bipartite graph.
19///
20/// The bipartite graph has two node kinds: `Agent` (the hypergraph's nodes)
21/// and `Hyperedge` (the hypergraph's edges). Membership edges connect agents
22/// to their hyperedges. This representation makes the hypergraph a genuine
23/// rustworkx-core plugin — all petgraph/rustworkx-core algorithms work on
24/// the bipartite graph directly.
25///
26/// # Type Parameters
27///
28/// - `N` — agent node attribute type (defaults to `serde_json::Value`)
29/// - `E` — hyperedge attribute type (defaults to `serde_json::Value`)
30/// - `M` — per-membership attribute type (defaults to `serde_json::Value`)
31pub struct Hypergraph<N = serde_json::Value, E = serde_json::Value, M = serde_json::Value> {
32    /// The bipartite graph: Agent nodes + Hyperedge nodes + membership edges.
33    /// StableDiGraph preserves insertion order under removal (leaves holes,
34    /// doesn't compact) — required for III.7 determinism parity.
35    inner: StableDiGraph<NodeKind<N, E>, MembershipEdge<M>>,
36
37    /// Insertion-ordered bimap: agent_id -> NodeIndex in `inner`.
38    agent_ids: IdMap,
39
40    /// Insertion-ordered bimap: edge_id -> NodeIndex in `inner`.
41    hyperedge_ids: IdMap,
42
43    /// Auto-incrementing counter for edges added without an explicit `idx`.
44    edge_uid_counter: u64,
45
46    /// Graph-level attributes (XGI's `H.graph` dict).
47    graph_attrs: serde_json::Map<String, serde_json::Value>,
48
49    /// Whether this hypergraph is frozen (mutation methods panic when true).
50    frozen: bool,
51}
52
53/// How to name a merged edge (subset of XGI's `rename`; `"tuple"` deferred).
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum MergeRename {
56    /// Reuse the smallest (sorted) duplicate id.
57    First,
58    /// Assign a fresh auto-generated id.
59    New,
60}
61
62/// How to combine attrs of merged edges (XGI's `merge_rule`).
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum MergeRule {
65    /// Take the smallest-id duplicate's attrs.
66    First,
67    /// For each key, a JSON array of the distinct values (missing -> null).
68    Union,
69    /// For each key, the shared value or null if the duplicates disagree.
70    Intersection,
71}
72
73/// What `cleanup` keeps. `true` keeps that kind; the default (all false) removes all of them, as XGI's defaults do.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75pub struct CleanupOptions {
76    /// Keep isolated nodes.
77    pub isolates: bool,
78    /// Keep edges of size one.
79    pub singletons: bool,
80    /// Keep edges of size zero.
81    pub empties: bool,
82    /// Keep duplicate edges.
83    pub multiedges: bool,
84}
85
86impl<N, E, M> Default for Hypergraph<N, E, M> {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92impl<N, E, M> Hypergraph<N, E, M> {
93    /// Create an empty hypergraph.
94    pub fn new() -> Self {
95        Self {
96            inner: StableDiGraph::new(),
97            agent_ids: IdMap::new(),
98            hyperedge_ids: IdMap::new(),
99            edge_uid_counter: 0,
100            graph_attrs: serde_json::Map::new(),
101            frozen: false,
102        }
103    }
104
105    /// Panic if the hypergraph is frozen. Called at the top of every
106    /// mutation method. XGI parity: frozen-method guard (hypergraph.py:1550).
107    fn assert_not_frozen(&self) {
108        if self.frozen {
109            panic!("Frozen hypergraph can't be modified");
110        }
111    }
112
113    /// The number of agent nodes in the hypergraph.
114    pub fn num_nodes(&self) -> usize {
115        self.agent_ids.len()
116    }
117
118    /// The number of hyperedges in the hypergraph.
119    pub fn num_edges(&self) -> usize {
120        self.hyperedge_ids.len()
121    }
122
123    /// Add a node with attributes. Returns `true` if a new node was created,
124    /// `false` if it already existed.
125    ///
126    /// XGI parity: `H.add_node(node, **attr)`. If `node_id` already exists,
127    /// its stored attrs are REPLACED (XGI's binding merges the incoming
128    /// dict into the existing one before calling; a generic `N` can't
129    /// merge, so the core replaces and the PyO3 layer composes the merge
130    /// on top — divergence D6).
131    pub fn add_node(&mut self, node_id: &str, attrs: N) -> bool {
132        self.assert_not_frozen();
133        if let Some(idx) = self.agent_ids.get(node_id) {
134            if let Some(NodeKind::Agent(existing)) = self.inner.node_weight_mut(*idx) {
135                *existing = attrs;
136            }
137            return false;
138        }
139        let idx = self.inner.add_node(NodeKind::Agent(attrs));
140        self.agent_ids.insert(node_id.to_string(), idx);
141        true
142    }
143
144    /// Check if a node exists in the hypergraph.
145    ///
146    /// XGI parity: `n in H` / `H.has_node(n)`.
147    pub fn has_node(&self, node_id: &str) -> bool {
148        self.agent_ids.contains_key(node_id)
149    }
150
151    /// Add a hyperedge connecting the given members.
152    ///
153    /// XGI parity: `H.add_edge(members, idx=id, **attr)`.
154    pub fn add_edge(
155        &mut self,
156        members: Vec<String>,
157        idx: Option<String>,
158        attrs: E,
159    ) -> Result<String, EdgeError>
160    where
161        N: Default,
162        M: Default + Clone,
163    {
164        self.assert_not_frozen();
165
166        let edge_id = match &idx {
167            Some(id) => {
168                if self.hyperedge_ids.contains_key(id) {
169                    return Err(EdgeError::AlreadyExists {
170                        edge_id: id.clone(),
171                    });
172                }
173                id.clone()
174            }
175            None => self.edge_uid_counter.to_string(),
176        };
177
178        // XGI 1.x `update_uid_counter` advances the counter for every explicit id that parses as an
179        // integer, `0` included (XGI 0.10.2 skipped `0` as falsy: issue 720, fixed in 1.0).
180        if let Some(id) = &idx {
181            if let Ok(n) = id.parse::<u64>() {
182                if n >= self.edge_uid_counter {
183                    self.edge_uid_counter = n.saturating_add(1);
184                }
185            }
186        } else {
187            self.edge_uid_counter = self.edge_uid_counter.saturating_add(1);
188        }
189
190        let mut seen = std::collections::HashSet::new();
191        let unique_members: Vec<String> = members
192            .into_iter()
193            .filter(|m| seen.insert(m.clone()))
194            .collect();
195
196        for member in &unique_members {
197            if !self.agent_ids.contains_key(member) {
198                let nidx = self.inner.add_node(NodeKind::Agent(N::default()));
199                self.agent_ids.insert(member.clone(), nidx);
200            }
201        }
202
203        let he_idx = self.inner.add_node(NodeKind::Hyperedge(attrs));
204        self.hyperedge_ids.insert(edge_id.clone(), he_idx);
205
206        for member in &unique_members {
207            let agent_idx = self.agent_ids[member];
208            let membership = MembershipEdge {
209                member_data: M::default(),
210            };
211            self.inner.add_edge(agent_idx, he_idx, membership.clone());
212            self.inner.add_edge(he_idx, agent_idx, membership);
213        }
214
215        Ok(edge_id)
216    }
217
218    /// Add a hyperedge with NO members (an empty edge). Returns the assigned edge id.
219    ///
220    /// **Documentation-defect fix (this comment previously claimed the opposite of what the code
221    /// does — see the register entry below).** XGI 0.10.2's own docstring claims `add_edge([])`
222    /// raises `XGIError`; its RUNTIME does not — it silently creates an empty edge, and XGI's own
223    /// test suite asserts that (D1 register, `conform_add_edge_empty_creates_edge`). `add_edge`
224    /// above matches the runtime, not the docstring: an empty member list is ACCEPTED, not
225    /// rejected, and no `EdgeError::EmptyMembers` variant exists anywhere in this crate. This
226    /// method is not a workaround for a rejection that does not happen — it is the explicit,
227    /// self-documenting spelling for the empty-edge case (Phase 7 OQ-1), duplicating only
228    /// `add_edge`'s id-assignment/counter policy, adding a lone `Hyperedge` node with no
229    /// membership edges, and returning the id (so callers need no separate auto-id peek).
230    pub fn add_empty_edge(&mut self, idx: Option<String>, attrs: E) -> String {
231        self.assert_not_frozen();
232        let edge_id = match &idx {
233            Some(id) => id.clone(),
234            None => self.edge_uid_counter.to_string(),
235        };
236        if let Some(id) = &idx {
237            if let Ok(n) = id.parse::<u64>() {
238                if n >= self.edge_uid_counter {
239                    self.edge_uid_counter = n.saturating_add(1);
240                }
241            }
242        } else {
243            self.edge_uid_counter = self.edge_uid_counter.saturating_add(1);
244        }
245        let he_idx = self.inner.add_node(NodeKind::Hyperedge(attrs));
246        self.hyperedge_ids.insert(edge_id.clone(), he_idx);
247        edge_id
248    }
249
250    /// Check if a hyperedge exists.
251    /// XGI parity: `id in H.edges`.
252    pub fn has_edge(&self, edge_id: &str) -> bool {
253        self.hyperedge_ids.contains_key(edge_id)
254    }
255
256    /// Get the edge IDs of which a node is a member, in insertion (membership-add)
257    /// order. petgraph's `neighbors` walks a node's adjacency list in REVERSE
258    /// insertion order, so we collect + reverse before mapping back to ids
259    /// (same correction as DiHypergraph's D5 owner upgrade).
260    /// XGI parity: `H.nodes.memberships(n)`.
261    pub fn memberships(&self, node_id: &str) -> Option<Vec<String>> {
262        let agent_idx = *self.agent_ids.get(node_id)?;
263        let mut neighbor_idxs: Vec<_> = self.inner.neighbors(agent_idx).collect();
264        neighbor_idxs.reverse();
265        let mut result: Vec<String> = Vec::new();
266        for neighbor_idx in neighbor_idxs {
267            if let Some(NodeKind::Hyperedge(_)) = self.inner.node_weight(neighbor_idx) {
268                if let Some(eid) = self.hyperedge_ids.id_of(neighbor_idx) {
269                    result.push(eid.to_string());
270                }
271            }
272        }
273        Some(result)
274    }
275
276    /// Get the node IDs that are members of an edge, in insertion order (see
277    /// [`Self::memberships`] for the reverse-adjacency correction).
278    /// XGI parity: `H.edges.members(e)`.
279    pub fn members(&self, edge_id: &str) -> Option<Vec<String>> {
280        let he_idx = *self.hyperedge_ids.get(edge_id)?;
281        let mut neighbor_idxs: Vec<_> = self.inner.neighbors(he_idx).collect();
282        neighbor_idxs.reverse();
283        let mut result: Vec<String> = Vec::new();
284        for neighbor_idx in neighbor_idxs {
285            if let Some(NodeKind::Agent(_)) = self.inner.node_weight(neighbor_idx) {
286                if let Some(nid) = self.agent_ids.id_of(neighbor_idx) {
287                    result.push(nid.to_string());
288                }
289            }
290        }
291        Some(result)
292    }
293
294    /// All node IDs in insertion order (III.7 determinism parity).
295    /// XGI parity: `list(H.nodes)`.
296    pub fn node_ids(&self) -> Vec<String> {
297        self.agent_ids.keys().cloned().collect()
298    }
299
300    /// All edge IDs in insertion order (III.7 determinism parity).
301    /// XGI parity: `list(H.edges)`.
302    pub fn edge_ids(&self) -> Vec<String> {
303        self.hyperedge_ids.keys().cloned().collect()
304    }
305
306    /// Remove a node from the hypergraph. Weak removal (`strong=false`)
307    /// detaches the node from its edges and, when `remove_empty` is true,
308    /// drops edges that become empty as a result; strong removal drops all
309    /// containing edges regardless of `remove_empty` (D9).
310    /// XGI parity: `H.remove_node(n, strong=False, remove_empty=True)`.
311    pub fn remove_node(
312        &mut self,
313        node_id: &str,
314        strong: bool,
315        remove_empty: bool,
316    ) -> Result<(), NodeError> {
317        self.assert_not_frozen();
318        let agent_idx = *self.agent_ids.get(node_id).ok_or(NodeError::NotFound {
319            node_id: node_id.to_string(),
320        })?;
321
322        let edge_ids: Vec<String> = self.memberships(node_id).unwrap_or_default();
323
324        if strong {
325            for eid in &edge_ids {
326                let he_idx = self.hyperedge_ids[eid];
327                self.inner.remove_node(he_idx);
328                self.hyperedge_ids.shift_remove(eid);
329            }
330        } else {
331            for eid in &edge_ids {
332                let he_idx = self.hyperedge_ids[eid];
333                if let Some(e) = self.inner.find_edge(agent_idx, he_idx) {
334                    self.inner.remove_edge(e);
335                }
336                if let Some(e) = self.inner.find_edge(he_idx, agent_idx) {
337                    self.inner.remove_edge(e);
338                }
339                if remove_empty {
340                    let has_members = self
341                        .inner
342                        .neighbors(he_idx)
343                        .any(|n| matches!(self.inner.node_weight(n), Some(NodeKind::Agent(_))));
344                    if !has_members {
345                        self.inner.remove_node(he_idx);
346                        self.hyperedge_ids.shift_remove(eid);
347                    }
348                }
349            }
350        }
351
352        self.inner.remove_node(agent_idx);
353        self.agent_ids.shift_remove(node_id);
354        Ok(())
355    }
356
357    /// Remove a hyperedge from the hypergraph.
358    /// XGI parity: `H.remove_edge(e)`.
359    pub fn remove_edge(&mut self, edge_id: &str) -> Result<(), EdgeError> {
360        self.assert_not_frozen();
361        let he_idx = *self.hyperedge_ids.get(edge_id).ok_or(EdgeError::NotFound {
362            edge_id: edge_id.to_string(),
363        })?;
364        self.inner.remove_node(he_idx);
365        self.hyperedge_ids.shift_remove(edge_id);
366        Ok(())
367    }
368
369    /// Read a node's attributes. XGI parity: `H.nodes[n]`.
370    pub fn node_attrs(&self, node_id: &str) -> Option<&N> {
371        let idx = self.agent_ids.get(node_id)?;
372        match self.inner.node_weight(*idx)? {
373            NodeKind::Agent(attrs) => Some(attrs),
374            _ => None,
375        }
376    }
377
378    /// Mutably access a node's attributes.
379    pub fn node_attrs_mut(&mut self, node_id: &str) -> Option<&mut N> {
380        let idx = *self.agent_ids.get(node_id)?;
381        match self.inner.node_weight_mut(idx)? {
382            NodeKind::Agent(attrs) => Some(attrs),
383            _ => None,
384        }
385    }
386
387    /// Read a hyperedge's attributes. XGI parity: `H.edges[e]`.
388    pub fn edge_attrs(&self, edge_id: &str) -> Option<&E> {
389        let idx = self.hyperedge_ids.get(edge_id)?;
390        match self.inner.node_weight(*idx)? {
391            NodeKind::Hyperedge(attrs) => Some(attrs),
392            _ => None,
393        }
394    }
395
396    /// Mutably access a hyperedge's attributes.
397    pub fn edge_attrs_mut(&mut self, edge_id: &str) -> Option<&mut E> {
398        let idx = *self.hyperedge_ids.get(edge_id)?;
399        match self.inner.node_weight_mut(idx)? {
400            NodeKind::Hyperedge(attrs) => Some(attrs),
401            _ => None,
402        }
403    }
404
405    /// Read a graph-level attribute. XGI parity: `H["name"]`.
406    pub fn graph_attr(&self, key: &str) -> Option<&serde_json::Value> {
407        self.graph_attrs.get(key)
408    }
409
410    /// Set a graph-level attribute. XGI parity: `H["name"] = value`.
411    pub fn set_graph_attr(&mut self, key: &str, value: serde_json::Value) {
412        self.graph_attrs.insert(key.to_string(), value);
413    }
414
415    /// Remove all nodes and edges. XGI parity: `H.clear()`.
416    ///
417    /// The edge-uid counter is deliberately NOT reset — XGI's `clear()`
418    /// never touches `_edge_uid` (verified 0.10.2: auto-ids continue the
419    /// pre-clear sequence).
420    pub fn clear(&mut self) {
421        self.assert_not_frozen();
422        self.inner = StableDiGraph::new();
423        self.agent_ids.clear();
424        self.hyperedge_ids.clear();
425        self.graph_attrs.clear();
426    }
427
428    /// Remove all edges, keeping nodes.
429    ///
430    /// XGI parity: `H.clear_edges()` — the edge-uid counter is NOT reset
431    /// (XGI's `clear_edges` never touches `_edge_uid`, verified 0.10.2).
432    pub fn clear_edges(&mut self) {
433        self.assert_not_frozen();
434        let hyperedge_indices: Vec<NodeIndex> = self.hyperedge_ids.values().copied().collect();
435        for he_idx in hyperedge_indices {
436            self.inner.remove_node(he_idx);
437        }
438        self.hyperedge_ids.clear();
439    }
440
441    /// The id the next edge added without an explicit id will get.
442    /// XGI parity: `H._edge_uid`.
443    pub fn next_edge_id(&self) -> u64 {
444        self.edge_uid_counter
445    }
446
447    /// Raise the counter past `idx`: if `next_edge_id() <= idx`, it becomes
448    /// `idx + 1`. XGI parity: `update_uid_counter`. Not a structural change,
449    /// so it is allowed on a frozen hypergraph. At `idx == u64::MAX` the
450    /// counter saturates there instead of overflowing.
451    pub fn update_uid_counter(&mut self, idx: u64) {
452        if self.edge_uid_counter <= idx {
453            self.edge_uid_counter = idx.saturating_add(1);
454        }
455    }
456
457    /// Freeze the hypergraph, preventing modification.
458    /// XGI parity: `H.freeze()`.
459    pub fn freeze(&mut self) {
460        self.frozen = true;
461    }
462
463    /// Check if the hypergraph is frozen.
464    /// XGI parity: `H.is_frozen`.
465    pub fn is_frozen(&self) -> bool {
466        self.frozen
467    }
468
469    /// Return an independent deep copy. XGI parity: `H.copy()`.
470    /// D13: the copy carries `frozen`, unlike XGI's `copy()` — XGI's
471    /// freeze is per-instance method-swizzling that a fresh instance
472    /// never inherits, but the core's `frozen` is data, so the safety
473    /// property must propagate.
474    pub fn copy(&self) -> Self
475    where
476        N: Clone,
477        E: Clone,
478        M: Clone,
479    {
480        Self {
481            inner: self.inner.clone(),
482            agent_ids: self.agent_ids.clone(),
483            hyperedge_ids: self.hyperedge_ids.clone(),
484            edge_uid_counter: self.edge_uid_counter,
485            graph_attrs: self.graph_attrs.clone(),
486            frozen: self.frozen,
487        }
488    }
489
490    /// Add multiple nodes. XGI parity: `H.add_nodes_from(nodes_for_adding)`.
491    pub fn add_nodes_from(&mut self, nodes: impl IntoIterator<Item = (String, N)>) {
492        for (node_id, attrs) in nodes {
493            self.add_node(&node_id, attrs);
494        }
495    }
496
497    /// Add multiple edges. Returns a result per edge.
498    pub fn add_edges_from(
499        &mut self,
500        edges: impl IntoIterator<Item = (Vec<String>, Option<String>, E)>,
501    ) -> Vec<Result<String, EdgeError>>
502    where
503        N: Default,
504        M: Default + Clone,
505    {
506        edges
507            .into_iter()
508            .map(|(m, i, a)| self.add_edge(m, i, a))
509            .collect()
510    }
511
512    /// Add a node to an existing edge. Auto-creates both if missing.
513    /// XGI parity: `H.add_node_to_edge(edge, node)`.
514    pub fn add_node_to_edge(&mut self, edge_id: &str, node_id: &str) -> Result<(), EdgeError>
515    where
516        N: Default,
517        E: Default,
518        M: Default + Clone,
519    {
520        self.assert_not_frozen();
521        self.ensure_edge_and_node(edge_id, node_id);
522        // Add the membership edges (both directions for undirected)
523        let agent_idx = self.agent_ids[node_id];
524        let he_idx = self.hyperedge_ids[edge_id];
525        // Check if membership already exists
526        if self.inner.find_edge(agent_idx, he_idx).is_none() {
527            let membership = MembershipEdge {
528                member_data: M::default(),
529            };
530            self.inner.add_edge(agent_idx, he_idx, membership.clone());
531            self.inner.add_edge(he_idx, agent_idx, membership);
532        }
533        Ok(())
534    }
535
536    /// Look up both ends of a membership, naming what is missing.
537    fn resolve_membership(
538        &self,
539        edge_id: &str,
540        node_id: &str,
541    ) -> Result<(NodeIndex, NodeIndex), MembershipError> {
542        let he_idx =
543            *self
544                .hyperedge_ids
545                .get(edge_id)
546                .ok_or_else(|| MembershipError::EdgeNotFound {
547                    edge_id: edge_id.to_string(),
548                })?;
549        let agent_idx =
550            *self
551                .agent_ids
552                .get(node_id)
553                .ok_or_else(|| MembershipError::NodeNotFound {
554                    node_id: node_id.to_string(),
555                })?;
556        if self.inner.find_edge(agent_idx, he_idx).is_none() {
557            return Err(MembershipError::NotAMember {
558                node_id: node_id.to_string(),
559                edge_id: edge_id.to_string(),
560            });
561        }
562        Ok((agent_idx, he_idx))
563    }
564
565    /// The value the membership of `node_id` in `edge_id` carries. `None` when
566    /// the edge or the node does not exist, or the node is not a member of the
567    /// edge.
568    ///
569    /// A membership made by any constructor carries `M::default()` until a
570    /// value is written with [`Self::set_member_data`] or
571    /// [`Self::add_node_to_edge_with_data`]. XGI has no value on a membership,
572    /// so the XGI-compatible formats do not carry it.
573    ///
574    /// ```
575    /// use hypergraph_rs::Hypergraph;
576    ///
577    /// let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
578    /// h.add_edge(vec!["a".into(), "b".into()], Some("e".into()), ()).unwrap();
579    /// assert_eq!(h.member_data("e", "a"), Some(&0));
580    /// assert_eq!(h.member_data("e", "nobody"), None);
581    /// ```
582    pub fn member_data(&self, edge_id: &str, node_id: &str) -> Option<&M> {
583        let (agent_idx, he_idx) = self.resolve_membership(edge_id, node_id).ok()?;
584        let edge = self.inner.find_edge(agent_idx, he_idx)?;
585        self.inner.edge_weight(edge).map(|m| &m.member_data)
586    }
587
588    /// Replace that value. Refuses an unknown edge, an unknown node, and a
589    /// node that is not a member. Both stored directions of the membership
590    /// receive the value. Panics on a frozen hypergraph, like every mutator.
591    ///
592    /// ```
593    /// use hypergraph_rs::{Hypergraph, MembershipError};
594    ///
595    /// let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
596    /// h.add_edge(vec!["a".into(), "b".into()], Some("e".into()), ()).unwrap();
597    /// h.set_member_data("e", "a", 7).unwrap();
598    /// assert_eq!(h.member_data("e", "a"), Some(&7));
599    /// assert_eq!(h.member_data("e", "b"), Some(&0));
600    /// assert!(matches!(
601    ///     h.set_member_data("e", "zed", 1),
602    ///     Err(MembershipError::NodeNotFound { .. })
603    /// ));
604    /// ```
605    pub fn set_member_data(
606        &mut self,
607        edge_id: &str,
608        node_id: &str,
609        data: M,
610    ) -> Result<(), MembershipError>
611    where
612        M: Clone,
613    {
614        self.assert_not_frozen();
615        let (agent_idx, he_idx) = self.resolve_membership(edge_id, node_id)?;
616        self.write_member_data(agent_idx, he_idx, data);
617        Ok(())
618    }
619
620    /// Write `data` to both stored directions of an existing membership.
621    fn write_member_data(&mut self, agent_idx: NodeIndex, he_idx: NodeIndex, data: M)
622    where
623        M: Clone,
624    {
625        if let Some(e) = self.inner.find_edge(he_idx, agent_idx) {
626            if let Some(w) = self.inner.edge_weight_mut(e) {
627                w.member_data = data.clone();
628            }
629        }
630        if let Some(e) = self.inner.find_edge(agent_idx, he_idx) {
631            if let Some(w) = self.inner.edge_weight_mut(e) {
632                w.member_data = data;
633            }
634        }
635    }
636
637    /// The members of an edge with their values, in the order of
638    /// [`Self::members`]. `None` when the edge does not exist.
639    ///
640    /// ```
641    /// use hypergraph_rs::Hypergraph;
642    ///
643    /// let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
644    /// h.add_edge(vec!["a".into(), "b".into()], Some("e".into()), ()).unwrap();
645    /// h.set_member_data("e", "b", 2).unwrap();
646    /// assert_eq!(
647    ///     h.members_with_data("e"),
648    ///     Some(vec![("a".to_string(), &0), ("b".to_string(), &2)])
649    /// );
650    /// ```
651    pub fn members_with_data(&self, edge_id: &str) -> Option<Vec<(String, &M)>> {
652        let he_idx = *self.hyperedge_ids.get(edge_id)?;
653        let mut neighbor_idxs: Vec<_> = self.inner.neighbors(he_idx).collect();
654        neighbor_idxs.reverse();
655        let mut result = Vec::new();
656        for neighbor_idx in neighbor_idxs {
657            if let Some(NodeKind::Agent(_)) = self.inner.node_weight(neighbor_idx) {
658                // A neighbour that cannot be resolved is skipped, exactly as
659                // `members()` skips it, so the two listings never disagree.
660                let Some(id) = self.agent_ids.id_of(neighbor_idx) else {
661                    continue;
662                };
663                let Some(edge) = self.inner.find_edge(neighbor_idx, he_idx) else {
664                    continue;
665                };
666                let Some(weight) = self.inner.edge_weight(edge) else {
667                    continue;
668                };
669                result.push((id.to_string(), &weight.member_data));
670            }
671        }
672        Some(result)
673    }
674
675    /// [`Self::add_node_to_edge`], with the value the new membership carries.
676    /// Auto-creates the edge and the node if missing. If the node is already a
677    /// member, its value is replaced.
678    ///
679    /// ```
680    /// use hypergraph_rs::Hypergraph;
681    ///
682    /// let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
683    /// h.add_node_to_edge_with_data("e", "a", 5).unwrap();
684    /// assert_eq!(h.member_data("e", "a"), Some(&5));
685    /// h.add_node_to_edge_with_data("e", "a", 9).unwrap();
686    /// assert_eq!(h.member_data("e", "a"), Some(&9));
687    /// ```
688    pub fn add_node_to_edge_with_data(
689        &mut self,
690        edge_id: &str,
691        node_id: &str,
692        data: M,
693    ) -> Result<(), EdgeError>
694    where
695        N: Default,
696        E: Default,
697        M: Clone,
698    {
699        self.assert_not_frozen();
700        self.ensure_edge_and_node(edge_id, node_id);
701        let agent_idx = self.agent_ids[node_id];
702        let he_idx = self.hyperedge_ids[edge_id];
703        if self.inner.find_edge(agent_idx, he_idx).is_none() {
704            let membership = MembershipEdge {
705                member_data: data.clone(),
706            };
707            self.inner.add_edge(agent_idx, he_idx, membership.clone());
708            self.inner.add_edge(he_idx, agent_idx, membership);
709        } else {
710            self.write_member_data(agent_idx, he_idx, data);
711        }
712        Ok(())
713    }
714
715    /// Create the edge and the node when missing (default attributes), and
716    /// keep the auto-id counter ahead of a numeric edge id.
717    fn ensure_edge_and_node(&mut self, edge_id: &str, node_id: &str)
718    where
719        N: Default,
720        E: Default,
721    {
722        if !self.hyperedge_ids.contains_key(edge_id) {
723            let he_idx = self.inner.add_node(NodeKind::Hyperedge(E::default()));
724            self.hyperedge_ids.insert(edge_id.to_string(), he_idx);
725            if let Ok(n) = edge_id.parse::<u64>() {
726                if n >= self.edge_uid_counter {
727                    self.edge_uid_counter = n.saturating_add(1);
728                }
729            }
730        }
731        if !self.agent_ids.contains_key(node_id) {
732            let nidx = self.inner.add_node(NodeKind::Agent(N::default()));
733            self.agent_ids.insert(node_id.to_string(), nidx);
734        }
735    }
736
737    /// Remove a node from an existing edge.
738    ///
739    /// XGI parity: `H.remove_node_from_edge(edge, node, remove_empty=True)`.
740    /// XGI raises `XGIError` for a missing edge, a missing node, or a node
741    /// that exists but is not a member of the named edge — the core returns
742    /// the matching [`MembershipError`] variant so callers discriminate
743    /// without string-matching; the PyO3 binding translates `Err` -> raise,
744    /// reproducing XGI's exact per-branch messages (D2 error channel).
745    pub fn remove_node_from_edge(
746        &mut self,
747        edge_id: &str,
748        node_id: &str,
749        remove_empty: bool,
750    ) -> Result<(), MembershipError> {
751        self.assert_not_frozen();
752        let he_idx = *self
753            .hyperedge_ids
754            .get(edge_id)
755            .ok_or(MembershipError::EdgeNotFound {
756                edge_id: edge_id.to_string(),
757            })?;
758        let agent_idx = *self
759            .agent_ids
760            .get(node_id)
761            .ok_or(MembershipError::NodeNotFound {
762                node_id: node_id.to_string(),
763            })?;
764
765        // Check if the node is actually in the edge
766        let edge_to_he = self.inner.find_edge(agent_idx, he_idx);
767        let edge_from_he = self.inner.find_edge(he_idx, agent_idx);
768        if edge_to_he.is_none() {
769            return Err(MembershipError::NotAMember {
770                node_id: node_id.to_string(),
771                edge_id: edge_id.to_string(),
772            });
773        }
774
775        // Remove the bipartite membership edges
776        if let Some(e) = edge_to_he {
777            self.inner.remove_edge(e);
778        }
779        if let Some(e) = edge_from_he {
780            self.inner.remove_edge(e);
781        }
782
783        // Check if edge is now empty
784        if remove_empty {
785            let has_members = self
786                .inner
787                .neighbors(he_idx)
788                .any(|n| matches!(self.inner.node_weight(n), Some(NodeKind::Agent(_))));
789            if !has_members {
790                self.inner.remove_node(he_idx);
791                self.hyperedge_ids.shift_remove(edge_id);
792            }
793        }
794        Ok(())
795    }
796
797    /// Remove multiple edges, returning a result per ATTEMPTED edge.
798    ///
799    /// XGI parity: `H.remove_edges_from(ebunch)` — XGI iterates in order
800    /// and RAISES on the first missing id, so ids after it are never
801    /// attempted (partial effects: ids before the failure are already
802    /// removed). The core mirrors this: stop on the first `Err`.
803    pub fn remove_edges_from(&mut self, edge_ids: &[String]) -> Vec<Result<(), EdgeError>> {
804        let mut results = Vec::new();
805        for eid in edge_ids {
806            let result = self.remove_edge(eid);
807            let stop = result.is_err();
808            results.push(result);
809            if stop {
810                break;
811            }
812        }
813        results
814    }
815
816    /// Remove multiple nodes, returning a result per item.
817    ///
818    /// XGI parity: `H.remove_nodes_from(nodes)` — XGI warns and skips a
819    /// missing id, then CONTINUES; the core records a per-item `Err` and
820    /// continues (D2-class channel translation — the binding warns per
821    /// `Err` item).
822    pub fn remove_nodes_from(
823        &mut self,
824        node_ids: &[String],
825        strong: bool,
826        remove_empty: bool,
827    ) -> Vec<Result<(), NodeError>> {
828        node_ids
829            .iter()
830            .map(|nid| self.remove_node(nid, strong, remove_empty))
831            .collect()
832    }
833
834    /// Add nodes then edges. XGI parity: `H.update(edges=, nodes=)`
835    /// (hypergraph.py:1210-1229).
836    pub fn update(&mut self, nodes: Vec<(String, N)>, edges: Vec<(Vec<String>, Option<String>, E)>)
837    where
838        N: Default,
839        M: Default + Clone,
840    {
841        self.add_nodes_from(nodes);
842        let _ = self.add_edges_from(edges);
843    }
844
845    /// Node ids with zero memberships, in insertion order.
846    /// XGI parity: `H.nodes.isolates()` (views.py:632-667, default).
847    pub fn isolate_node_ids(&self) -> Vec<String> {
848        self.node_ids()
849            .into_iter()
850            .filter(|n| self.memberships(n).is_some_and(|m| m.is_empty()))
851            .collect()
852    }
853
854    /// Edge ids with exactly one member, in insertion order.
855    /// XGI parity: `H.edges.singletons()` (views.py:749-761).
856    pub fn singleton_edge_ids(&self) -> Vec<String> {
857        self.edge_ids()
858            .into_iter()
859            .filter(|e| self.members(e).is_some_and(|m| m.len() == 1))
860            .collect()
861    }
862
863    /// Read-only view of the graph-level attribute dict (XGI's `H.graph`).
864    pub fn graph_attrs(&self) -> &serde_json::Map<String, serde_json::Value> {
865        &self.graph_attrs
866    }
867
868    /// Attach `node_id` to `edge_id` (both bipartite directions). No-op if the
869    /// membership already exists. Both ids must already exist.
870    fn attach_member(&mut self, edge_id: &str, node_id: &str)
871    where
872        M: Default + Clone,
873    {
874        let a = self.agent_ids[node_id];
875        let he = self.hyperedge_ids[edge_id];
876        if self.inner.find_edge(a, he).is_none() {
877            let m = MembershipEdge {
878                member_data: M::default(),
879            };
880            self.inner.add_edge(a, he, m.clone());
881            self.inner.add_edge(he, a, m);
882        }
883    }
884
885    /// Detach `node_id` from `edge_id` (both bipartite directions). No-op if
886    /// the membership is absent.
887    fn detach_member(&mut self, edge_id: &str, node_id: &str) {
888        let a = self.agent_ids[node_id];
889        let he = self.hyperedge_ids[edge_id];
890        if let Some(e) = self.inner.find_edge(a, he) {
891            self.inner.remove_edge(e);
892        }
893        if let Some(e) = self.inner.find_edge(he, a) {
894            self.inner.remove_edge(e);
895        }
896    }
897
898    /// Swap the edge memberships of two nodes between two edges.
899    /// XGI parity: `H.double_edge_swap(n1, n2, e1, e2)` (hypergraph.py:918-992).
900    pub fn double_edge_swap(
901        &mut self,
902        n_id1: &str,
903        n_id2: &str,
904        e_id1: &str,
905        e_id2: &str,
906    ) -> Result<(), SwapError>
907    where
908        M: Default + Clone,
909    {
910        self.assert_not_frozen();
911
912        let members1 = self.members(e_id1).ok_or(SwapError::IdNotFound {
913            id: e_id1.to_string(),
914        })?;
915        let members2 = self.members(e_id2).ok_or(SwapError::IdNotFound {
916            id: e_id2.to_string(),
917        })?;
918        if !members1.iter().any(|m| m == n_id1) {
919            return Err(SwapError::IdNotFound {
920                id: n_id1.to_string(),
921            });
922        }
923        if !members2.iter().any(|m| m == n_id2) {
924            return Err(SwapError::IdNotFound {
925                id: n_id2.to_string(),
926            });
927        }
928
929        // Compute the post-swap member sets and verify size preservation BEFORE
930        // mutating (XGI hypergraph.py:980-986).
931        use std::collections::BTreeSet;
932        let new1: BTreeSet<String> = members1
933            .iter()
934            .filter(|m| *m != n_id1)
935            .cloned()
936            .chain(std::iter::once(n_id2.to_string()))
937            .collect();
938        let new2: BTreeSet<String> = members2
939            .iter()
940            .filter(|m| *m != n_id2)
941            .cloned()
942            .chain(std::iter::once(n_id1.to_string()))
943            .collect();
944        if new1.len() != members1.len() || new2.len() != members2.len() {
945            return Err(SwapError::SizeNotPreserved);
946        }
947
948        // Commit: e1 loses n1 gains n2; e2 loses n2 gains n1.
949        self.detach_member(e_id1, n_id1);
950        self.attach_member(e_id1, n_id2);
951        self.detach_member(e_id2, n_id2);
952        self.attach_member(e_id2, n_id1);
953        Ok(())
954    }
955
956    /// Randomly redistribute nodes between two hyperedges, preserving both
957    /// sizes. XGI parity: `H.random_edge_shuffle(e1, e2, seed)`
958    /// (hypergraph.py:994-1078). Requires an explicit seed (deviation #3);
959    /// the rand_pcg sequence does not match numpy, so only structural
960    /// invariants are guaranteed across implementations.
961    ///
962    /// Gated on `generators` (the feature that owns the `rand_pcg`/`rand_core`
963    /// optional deps this method needs) so the core module stays buildable
964    /// under `--no-default-features` (Phase 4 Task 19 feature-matrix check).
965    #[cfg(feature = "generators")]
966    pub fn random_edge_shuffle(
967        &mut self,
968        e_id1: Option<&str>,
969        e_id2: Option<&str>,
970        seed: u64,
971    ) -> Result<(), EdgeError>
972    where
973        M: Default + Clone,
974    {
975        self.assert_not_frozen();
976        if self.hyperedge_ids.len() < 2 {
977            return Err(EdgeError::TooFewEdges);
978        }
979        let mut rng = Pcg64Mcg::seed_from_u64(seed);
980
981        // Resolve the two edge ids (given, or two distinct random).
982        let (id1, id2) = match (e_id1, e_id2) {
983            (Some(a), Some(b)) => (a.to_string(), b.to_string()),
984            _ => {
985                let ids = self.edge_ids();
986                let i = rng.random_range(0..ids.len());
987                let mut j = rng.random_range(0..ids.len() - 1);
988                if j >= i {
989                    j += 1;
990                }
991                (ids[i].clone(), ids[j].clone())
992            }
993        };
994
995        use std::collections::BTreeSet;
996        let s1: BTreeSet<String> = self
997            .members(&id1)
998            .ok_or(EdgeError::NotFound {
999                edge_id: id1.clone(),
1000            })?
1001            .into_iter()
1002            .collect();
1003        let s2: BTreeSet<String> = self
1004            .members(&id2)
1005            .ok_or(EdgeError::NotFound {
1006                edge_id: id2.clone(),
1007            })?
1008            .into_iter()
1009            .collect();
1010
1011        let both: BTreeSet<String> = s1.intersection(&s2).cloned().collect();
1012        let only1: BTreeSet<String> = s1.difference(&both).cloned().collect();
1013        let only2: BTreeSet<String> = s2.difference(&both).cloned().collect();
1014
1015        // Bucket in a deterministic base order (BTreeSet -> sorted).
1016        let mut bucket: Vec<String> = only1.union(&only2).cloned().collect();
1017        let k = only1.len();
1018        let n = bucket.len();
1019        // Partial Fisher-Yates: bounded by k (computed above), never exceeds n.
1020        for i in 0..k {
1021            let j = i + rng.random_range(0..(n - i));
1022            bucket.swap(i, j);
1023        }
1024        let new_only1: BTreeSet<String> = bucket[..k].iter().cloned().collect();
1025        let new_e1: BTreeSet<String> = new_only1.union(&both).cloned().collect();
1026        let new_only2: BTreeSet<String> = bucket[k..].iter().cloned().collect();
1027        let new_e2: BTreeSet<String> = new_only2.union(&both).cloned().collect();
1028
1029        // Rewire: detach all old members, attach the new ones (ids/attrs kept).
1030        for node in &s1 {
1031            self.detach_member(&id1, node);
1032        }
1033        for node in &s2 {
1034            self.detach_member(&id2, node);
1035        }
1036        for node in &new_e1 {
1037            self.attach_member(&id1, node);
1038        }
1039        for node in &new_e2 {
1040            self.attach_member(&id2, node);
1041        }
1042        Ok(())
1043    }
1044
1045    /// The undirected 1-skeleton (pairwise projection): a node for every agent
1046    /// (weight = its id, added in `node_ids()` order so `NodeIndex::new(i)`
1047    /// corresponds to `node_ids()[i]`), and an edge (weight `1.0`) between two
1048    /// agents that co-occur in at least one hyperedge.
1049    ///
1050    /// Undirected (deviation from spec §4.1's `Graph`): the connectivity,
1051    /// shortest-path, and clustering algorithms operate on this graph.
1052    pub fn skeleton(&self) -> UnGraph<String, f64> {
1053        let mut g = UnGraph::<String, f64>::new_undirected();
1054        let node_ids = self.node_ids();
1055        let mut idx_of: indexmap::IndexMap<String, GraphNodeIndex> = indexmap::IndexMap::new();
1056        for n in &node_ids {
1057            let ix = g.add_node(n.clone());
1058            idx_of.insert(n.clone(), ix);
1059        }
1060        let mut seen: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new();
1061        for e in self.edge_ids() {
1062            let members = self.members(&e).unwrap_or_default();
1063            // Bounded: |members| choose 2.
1064            for a in 0..members.len() {
1065                for b in (a + 1)..members.len() {
1066                    let ia = idx_of[&members[a]];
1067                    let ib = idx_of[&members[b]];
1068                    let key = if g.to_index(ia) < g.to_index(ib) {
1069                        (g.to_index(ia), g.to_index(ib))
1070                    } else {
1071                        (g.to_index(ib), g.to_index(ia))
1072                    };
1073                    if seen.insert(key) {
1074                        g.add_edge(ia, ib, 1.0);
1075                    }
1076                }
1077            }
1078        }
1079        g
1080    }
1081
1082    /// The neighbours of a node: all nodes that share at least one hyperedge
1083    /// with it, excluding itself, in insertion order (deduped). `None` if the
1084    /// node is absent. XGI parity: `H.nodes.neighbors(n)`.
1085    pub fn node_neighbors(&self, node_id: &str) -> Option<Vec<String>> {
1086        let edges = self.memberships(node_id)?;
1087        let mut result: Vec<String> = Vec::new();
1088        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1089        for e in edges {
1090            for m in self.members(&e).unwrap_or_default() {
1091                if m != node_id && seen.insert(m.clone()) {
1092                    result.push(m);
1093                }
1094            }
1095        }
1096        Some(result)
1097    }
1098
1099    /// The degree of a node = number of edges it belongs to. With
1100    /// `order = Some(d)`, counts only edges of that order (size `d+1`).
1101    /// `None` if the node is absent. XGI parity: `H.degree(n, order)`.
1102    pub fn node_degree(&self, node_id: &str, order: Option<usize>) -> Option<usize> {
1103        let edges = self.memberships(node_id)?;
1104        Some(match order {
1105            None => edges.len(),
1106            Some(d) => edges
1107                .iter()
1108                .filter(|e| self.edge_size(e) == Some(d + 1))
1109                .count(),
1110        })
1111    }
1112
1113    /// The size (number of members) of an edge. `None` if the edge is absent.
1114    pub fn edge_size(&self, edge_id: &str) -> Option<usize> {
1115        self.members(edge_id).map(|m| m.len())
1116    }
1117}
1118
1119impl<M> Hypergraph<serde_json::Value, serde_json::Value, M> {
1120    /// Set node attributes from (id, attr_map) pairs.
1121    /// XGI parity: `H.set_node_attributes(values, name=None)`.
1122    /// Silently skips missing node IDs (XGI warns).
1123    pub fn set_node_attributes(
1124        &mut self,
1125        values: impl IntoIterator<Item = (String, serde_json::Map<String, serde_json::Value>)>,
1126    ) {
1127        for (node_id, attrs) in values {
1128            if let Some(node_attrs) = self.node_attrs_mut(&node_id) {
1129                if !node_attrs.is_object() {
1130                    *node_attrs = serde_json::Value::Object(serde_json::Map::new());
1131                }
1132                if let Some(obj) = node_attrs.as_object_mut() {
1133                    for (k, v) in attrs {
1134                        obj.insert(k, v);
1135                    }
1136                }
1137            }
1138            // Silently skip missing nodes (XGI warns)
1139        }
1140    }
1141
1142    /// Set edge attributes from (id, attr_map) pairs.
1143    /// XGI parity: `H.set_edge_attributes(values, name=None)`.
1144    /// Silently skips missing edge IDs (XGI warns).
1145    pub fn set_edge_attributes(
1146        &mut self,
1147        values: impl IntoIterator<Item = (String, serde_json::Map<String, serde_json::Value>)>,
1148    ) {
1149        for (edge_id, attrs) in values {
1150            if let Some(edge_attrs) = self.edge_attrs_mut(&edge_id) {
1151                if !edge_attrs.is_object() {
1152                    *edge_attrs = serde_json::Value::Object(serde_json::Map::new());
1153                }
1154                if let Some(obj) = edge_attrs.as_object_mut() {
1155                    for (k, v) in attrs {
1156                        obj.insert(k, v);
1157                    }
1158                }
1159            }
1160        }
1161    }
1162}
1163
1164impl Hypergraph<Value, Value, Value> {
1165    /// The dual: nodes become edges and edges become nodes.
1166    /// XGI parity: `H.dual()` (hypergraph.py:1446-1466). Isolate nodes are
1167    /// dropped (they would map to empty dual-edges, which our strict add_edge
1168    /// cannot represent — deviation #8).
1169    pub fn dual(&self) -> Self {
1170        let mut d = Self::new();
1171
1172        // Original edges -> dual nodes (id = edge id, attrs = edge attrs).
1173        // Done FIRST so their attrs survive the auto-node-creation in add_edge.
1174        for eid in self.edge_ids() {
1175            let attrs = self.edge_attrs(&eid).cloned().unwrap_or(Value::Null);
1176            d.add_node(&eid, attrs);
1177        }
1178
1179        // Original nodes -> dual edges (id = node id, members = memberships).
1180        for nid in self.node_ids() {
1181            let memberships = self.memberships(&nid).unwrap_or_default();
1182            if memberships.is_empty() {
1183                continue; // isolate node -> empty dual-edge -> skipped
1184            }
1185            let attrs = self.node_attrs(&nid).cloned().unwrap_or(Value::Null);
1186            let _ = d.add_edge(memberships, Some(nid.clone()), attrs);
1187        }
1188
1189        // Graph attrs.
1190        for (k, val) in self.graph_attrs().clone() {
1191            d.set_graph_attr(&k, val);
1192        }
1193        d
1194    }
1195}
1196
1197impl Hypergraph<Value, Value, Value> {
1198    /// Merge edges that have identical member-sets.
1199    /// XGI parity: `H.merge_duplicate_edges(rename, merge_rule, multiplicity)`
1200    /// (hypergraph.py:1257-1419). `rename="tuple"` is deferred (deviation #6);
1201    /// union produces a JSON array, not a Python set.
1202    pub fn merge_duplicate_edges(
1203        &mut self,
1204        rename: MergeRename,
1205        merge_rule: MergeRule,
1206        multiplicity: Option<&str>,
1207    ) {
1208        self.assert_not_frozen();
1209        use std::collections::BTreeMap;
1210
1211        // Group edge ids by their sorted member-set (deterministic).
1212        let mut groups: BTreeMap<Vec<String>, Vec<String>> = BTreeMap::new();
1213        for eid in self.edge_ids() {
1214            let mut mem = self.members(&eid).unwrap_or_default();
1215            mem.sort();
1216            groups.entry(mem).or_default().push(eid);
1217        }
1218
1219        let mut to_remove: Vec<String> = Vec::new();
1220        let mut to_add: Vec<(Vec<String>, String, Value)> = Vec::new();
1221        for (members, dup_ids) in &groups {
1222            if dup_ids.len() <= 1 {
1223                continue;
1224            }
1225            to_remove.extend(dup_ids.iter().cloned());
1226            let new_id = match rename {
1227                MergeRename::First => {
1228                    let mut sorted = dup_ids.clone();
1229                    sorted.sort();
1230                    sorted[0].clone()
1231                }
1232                MergeRename::New => {
1233                    let id = self.edge_uid_counter.to_string();
1234                    self.edge_uid_counter = self.edge_uid_counter.saturating_add(1);
1235                    id
1236                }
1237            };
1238            let mut new_attrs = self.merged_edge_attrs(dup_ids, merge_rule);
1239            if let Some(mkey) = multiplicity {
1240                // merged_edge_attrs(MergeRule::First) can yield a non-object
1241                // (e.g. Value::Null, our default empty attrs) — coerce before
1242                // inserting the multiplicity key (2026-07-19 preflight defect
1243                // P2-D1: Null.as_object_mut() silently dropped the insert).
1244                if !new_attrs.is_object() {
1245                    new_attrs = serde_json::json!({});
1246                }
1247                new_attrs
1248                    .as_object_mut()
1249                    .unwrap()
1250                    .insert(mkey.to_string(), serde_json::json!(dup_ids.len()));
1251            }
1252            to_add.push((members.clone(), new_id, new_attrs));
1253        }
1254
1255        for eid in &to_remove {
1256            let _ = self.remove_edge(eid);
1257        }
1258        for (members, id, attrs) in to_add {
1259            let _ = self.add_edge(members, Some(id), attrs);
1260        }
1261    }
1262
1263    /// Combine the attrs of a group of duplicate edges per `merge_rule`.
1264    fn merged_edge_attrs(&self, dup_ids: &[String], rule: MergeRule) -> Value {
1265        match rule {
1266            MergeRule::First => {
1267                let min_id = dup_ids.iter().min().cloned().unwrap_or_default();
1268                self.edge_attrs(&min_id)
1269                    .cloned()
1270                    .unwrap_or_else(|| serde_json::json!({}))
1271            }
1272            MergeRule::Union | MergeRule::Intersection => {
1273                use std::collections::BTreeSet;
1274                let mut keys: BTreeSet<String> = BTreeSet::new();
1275                for id in dup_ids {
1276                    if let Some(obj) = self.edge_attrs(id).and_then(|a| a.as_object()) {
1277                        keys.extend(obj.keys().cloned());
1278                    }
1279                }
1280                let mut out = serde_json::Map::new();
1281                for k in keys {
1282                    let mut distinct: Vec<Value> = Vec::new();
1283                    for id in dup_ids {
1284                        let val = self
1285                            .edge_attrs(id)
1286                            .and_then(|a| a.get(&k))
1287                            .cloned()
1288                            .unwrap_or(Value::Null);
1289                        if !distinct.contains(&val) {
1290                            distinct.push(val);
1291                        }
1292                    }
1293                    let merged = match rule {
1294                        MergeRule::Union => Value::Array(distinct),
1295                        _ => {
1296                            if distinct.len() == 1 {
1297                                distinct.into_iter().next().unwrap()
1298                            } else {
1299                                Value::Null
1300                            }
1301                        }
1302                    };
1303                    out.insert(k, merged);
1304                }
1305                Value::Object(out)
1306            }
1307        }
1308    }
1309
1310    /// Remove undesirable artifacts in place. XGI parity: `H.cleanup(...)`
1311    /// (hypergraph.py). `connected` and `relabel` are not part of the core
1312    /// (the Python binding does them). In order: merge duplicate edges,
1313    /// remove singleton edges, remove empty edges, remove isolated nodes.
1314    /// Each flag in [`CleanupOptions`] keeps that kind; the default removes
1315    /// all of them.
1316    pub fn cleanup(&mut self, options: CleanupOptions) {
1317        self.assert_not_frozen();
1318        if !options.multiedges {
1319            self.merge_duplicate_edges(MergeRename::First, MergeRule::First, None);
1320        }
1321        if !options.singletons {
1322            let s = self.singleton_edge_ids();
1323            let _ = self.remove_edges_from(&s);
1324        }
1325        if !options.empties {
1326            let e: Vec<String> = self
1327                .edge_ids()
1328                .into_iter()
1329                .filter(|id| self.members(id).is_some_and(|m| m.is_empty()))
1330                .collect();
1331            let _ = self.remove_edges_from(&e);
1332        }
1333        if !options.isolates {
1334            let i = self.isolate_node_ids();
1335            let _ = self.remove_nodes_from(&i, false, true);
1336        }
1337    }
1338
1339    /// Return a cleaned copy, leaving `self` untouched.
1340    pub fn cleaned(&self, options: CleanupOptions) -> Self {
1341        let mut c = self.copy();
1342        c.cleanup(options);
1343        c
1344    }
1345}
1346
1347impl<N: PartialEq, E: PartialEq, M: PartialEq> PartialEq for Hypergraph<N, E, M> {
1348    /// Two hypergraphs are equal if they have the same nodes, edges,
1349    /// memberships, and attributes. XGI parity: `H1 == H2`.
1350    fn eq(&self, other: &Self) -> bool {
1351        if self.agent_ids.len() != other.agent_ids.len() {
1352            return false;
1353        }
1354        for (nid, _) in &self.agent_ids {
1355            match (self.node_attrs(nid), other.node_attrs(nid)) {
1356                (Some(a), Some(b)) if a == b => {}
1357                _ => return false,
1358            }
1359        }
1360        if self.hyperedge_ids.len() != other.hyperedge_ids.len() {
1361            return false;
1362        }
1363        for (eid, _) in &self.hyperedge_ids {
1364            match (self.edge_attrs(eid), other.edge_attrs(eid)) {
1365                (Some(a), Some(b)) if a == b => {}
1366                _ => return false,
1367            }
1368            let mut m1 = self.members(eid).unwrap_or_default();
1369            let mut m2 = other.members(eid).unwrap_or_default();
1370            m1.sort();
1371            m2.sort();
1372            if m1 != m2 {
1373                return false;
1374            }
1375        }
1376        self.graph_attrs == other.graph_attrs
1377    }
1378}
1379
1380impl<N, E, M> std::fmt::Debug for Hypergraph<N, E, M>
1381where
1382    N: std::fmt::Debug,
1383    E: std::fmt::Debug,
1384    M: std::fmt::Debug,
1385{
1386    /// XGI parity: `__repr__` returns `Hypergraph([{members}, ...])`.
1387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1388        write!(f, "Hypergraph(")?;
1389        let edges: Vec<String> = self
1390            .hyperedge_ids
1391            .keys()
1392            .map(|eid| {
1393                let members = self.members(eid).unwrap_or_default();
1394                format!("{{{}}}", members.join(", "))
1395            })
1396            .collect();
1397        write!(f, "[{}])", edges.join(", "))
1398    }
1399}