Skip to main content

Hypergraph

Struct Hypergraph 

Source
pub struct Hypergraph<N = Value, E = Value, M = Value> { /* private fields */ }
Expand description

A hypergraph, represented as a bipartite graph.

The bipartite graph has two node kinds: Agent (the hypergraph’s nodes) and Hyperedge (the hypergraph’s edges). Membership edges connect agents to their hyperedges. This representation makes the hypergraph a genuine rustworkx-core plugin — all petgraph/rustworkx-core algorithms work on the bipartite graph directly.

§Type Parameters

  • N — agent node attribute type (defaults to serde_json::Value)
  • E — hyperedge attribute type (defaults to serde_json::Value)
  • M — per-membership attribute type (defaults to serde_json::Value)

Implementations§

Source§

impl<N, E, M> Hypergraph<N, E, M>

Source

pub fn new() -> Self

Create an empty hypergraph.

Examples found in repository?
examples/quickstart.rs (line 10)
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}
More examples
Hide additional examples
examples/membership_data.rs (line 10)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn num_nodes(&self) -> usize

The number of agent nodes in the hypergraph.

Source

pub fn num_edges(&self) -> usize

The number of hyperedges in the hypergraph.

Source

pub fn add_node(&mut self, node_id: &str, attrs: N) -> bool

Add a node with attributes. Returns true if a new node was created, false if it already existed.

XGI parity: H.add_node(node, **attr). If node_id already exists, its stored attrs are REPLACED (XGI’s binding merges the incoming dict into the existing one before calling; a generic N can’t merge, so the core replaces and the PyO3 layer composes the merge on top — divergence D6).

Source

pub fn has_node(&self, node_id: &str) -> bool

Check if a node exists in the hypergraph.

XGI parity: n in H / H.has_node(n).

Source

pub fn add_edge( &mut self, members: Vec<String>, idx: Option<String>, attrs: E, ) -> Result<String, EdgeError>
where N: Default, M: Default + Clone,

Add a hyperedge connecting the given members.

XGI parity: H.add_edge(members, idx=id, **attr).

Examples found in repository?
examples/quickstart.rs (lines 13-17)
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}
Source

pub fn add_empty_edge(&mut self, idx: Option<String>, attrs: E) -> String

Add a hyperedge with NO members (an empty edge). Returns the assigned edge id.

Documentation-defect fix (this comment previously claimed the opposite of what the code does — see the register entry below). XGI 0.10.2’s own docstring claims add_edge([]) raises XGIError; its RUNTIME does not — it silently creates an empty edge, and XGI’s own test suite asserts that (D1 register, conform_add_edge_empty_creates_edge). add_edge above matches the runtime, not the docstring: an empty member list is ACCEPTED, not rejected, and no EdgeError::EmptyMembers variant exists anywhere in this crate. This method is not a workaround for a rejection that does not happen — it is the explicit, self-documenting spelling for the empty-edge case (Phase 7 OQ-1), duplicating only add_edge’s id-assignment/counter policy, adding a lone Hyperedge node with no membership edges, and returning the id (so callers need no separate auto-id peek).

Source

pub fn has_edge(&self, edge_id: &str) -> bool

Check if a hyperedge exists. XGI parity: id in H.edges.

Source

pub fn memberships(&self, node_id: &str) -> Option<Vec<String>>

Get the edge IDs of which a node is a member, in insertion (membership-add) order. petgraph’s neighbors walks a node’s adjacency list in REVERSE insertion order, so we collect + reverse before mapping back to ids (same correction as DiHypergraph’s D5 owner upgrade). XGI parity: H.nodes.memberships(n).

Examples found in repository?
examples/quickstart.rs (line 32)
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}
Source

pub fn members(&self, edge_id: &str) -> Option<Vec<String>>

Get the node IDs that are members of an edge, in insertion order (see Self::memberships for the reverse-adjacency correction). XGI parity: H.edges.members(e).

Examples found in repository?
examples/quickstart.rs (line 31)
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}
Source

pub fn node_ids(&self) -> Vec<String>

All node IDs in insertion order (III.7 determinism parity). XGI parity: list(H.nodes).

Examples found in repository?
examples/quickstart.rs (line 29)
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}
Source

pub fn edge_ids(&self) -> Vec<String>

All edge IDs in insertion order (III.7 determinism parity). XGI parity: list(H.edges).

Examples found in repository?
examples/quickstart.rs (line 30)
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}
More examples
Hide additional examples
examples/membership_data.rs (line 28)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn remove_node( &mut self, node_id: &str, strong: bool, remove_empty: bool, ) -> Result<(), NodeError>

Remove a node from the hypergraph. Weak removal (strong=false) detaches the node from its edges and, when remove_empty is true, drops edges that become empty as a result; strong removal drops all containing edges regardless of remove_empty (D9). XGI parity: H.remove_node(n, strong=False, remove_empty=True).

Source

pub fn remove_edge(&mut self, edge_id: &str) -> Result<(), EdgeError>

Remove a hyperedge from the hypergraph. XGI parity: H.remove_edge(e).

Source

pub fn node_attrs(&self, node_id: &str) -> Option<&N>

Read a node’s attributes. XGI parity: H.nodes[n].

Source

pub fn node_attrs_mut(&mut self, node_id: &str) -> Option<&mut N>

Mutably access a node’s attributes.

Source

pub fn edge_attrs(&self, edge_id: &str) -> Option<&E>

Read a hyperedge’s attributes. XGI parity: H.edges[e].

Source

pub fn edge_attrs_mut(&mut self, edge_id: &str) -> Option<&mut E>

Mutably access a hyperedge’s attributes.

Source

pub fn graph_attr(&self, key: &str) -> Option<&Value>

Read a graph-level attribute. XGI parity: H["name"].

Source

pub fn set_graph_attr(&mut self, key: &str, value: Value)

Set a graph-level attribute. XGI parity: H["name"] = value.

Source

pub fn clear(&mut self)

Remove all nodes and edges. XGI parity: H.clear().

The edge-uid counter is deliberately NOT reset — XGI’s clear() never touches _edge_uid (verified 0.10.2: auto-ids continue the pre-clear sequence).

Source

pub fn clear_edges(&mut self)

Remove all edges, keeping nodes.

XGI parity: H.clear_edges() — the edge-uid counter is NOT reset (XGI’s clear_edges never touches _edge_uid, verified 0.10.2).

Source

pub fn next_edge_id(&self) -> u64

The id the next edge added without an explicit id will get. XGI parity: H._edge_uid.

Source

pub fn update_uid_counter(&mut self, idx: u64)

Raise the counter past idx: if next_edge_id() <= idx, it becomes idx + 1. XGI parity: update_uid_counter. Not a structural change, so it is allowed on a frozen hypergraph. At idx == u64::MAX the counter saturates there instead of overflowing.

Source

pub fn freeze(&mut self)

Freeze the hypergraph, preventing modification. XGI parity: H.freeze().

Source

pub fn is_frozen(&self) -> bool

Check if the hypergraph is frozen. XGI parity: H.is_frozen.

Source

pub fn copy(&self) -> Self
where N: Clone, E: Clone, M: Clone,

Return an independent deep copy. XGI parity: H.copy(). D13: the copy carries frozen, unlike XGI’s copy() — XGI’s freeze is per-instance method-swizzling that a fresh instance never inherits, but the core’s frozen is data, so the safety property must propagate.

Source

pub fn add_nodes_from(&mut self, nodes: impl IntoIterator<Item = (String, N)>)

Add multiple nodes. XGI parity: H.add_nodes_from(nodes_for_adding).

Source

pub fn add_edges_from( &mut self, edges: impl IntoIterator<Item = (Vec<String>, Option<String>, E)>, ) -> Vec<Result<String, EdgeError>>
where N: Default, M: Default + Clone,

Add multiple edges. Returns a result per edge.

Source

pub fn add_node_to_edge( &mut self, edge_id: &str, node_id: &str, ) -> Result<(), EdgeError>
where N: Default, E: Default, M: Default + Clone,

Add a node to an existing edge. Auto-creates both if missing. XGI parity: H.add_node_to_edge(edge, node).

Examples found in repository?
examples/membership_data.rs (line 25)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn member_data(&self, edge_id: &str, node_id: &str) -> Option<&M>

The value the membership of node_id in edge_id carries. None when the edge or the node does not exist, or the node is not a member of the edge.

A membership made by any constructor carries M::default() until a value is written with Self::set_member_data or Self::add_node_to_edge_with_data. XGI has no value on a membership, so the XGI-compatible formats do not carry it.

use hypergraph_rs::Hypergraph;

let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
h.add_edge(vec!["a".into(), "b".into()], Some("e".into()), ()).unwrap();
assert_eq!(h.member_data("e", "a"), Some(&0));
assert_eq!(h.member_data("e", "nobody"), None);
Examples found in repository?
examples/membership_data.rs (line 26)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn set_member_data( &mut self, edge_id: &str, node_id: &str, data: M, ) -> Result<(), MembershipError>
where M: Clone,

Replace that value. Refuses an unknown edge, an unknown node, and a node that is not a member. Both stored directions of the membership receive the value. Panics on a frozen hypergraph, like every mutator.

use hypergraph_rs::{Hypergraph, MembershipError};

let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
h.add_edge(vec!["a".into(), "b".into()], Some("e".into()), ()).unwrap();
h.set_member_data("e", "a", 7).unwrap();
assert_eq!(h.member_data("e", "a"), Some(&7));
assert_eq!(h.member_data("e", "b"), Some(&0));
assert!(matches!(
    h.set_member_data("e", "zed", 1),
    Err(MembershipError::NodeNotFound { .. })
));
Examples found in repository?
examples/membership_data.rs (line 24)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn members_with_data(&self, edge_id: &str) -> Option<Vec<(String, &M)>>

The members of an edge with their values, in the order of Self::members. None when the edge does not exist.

use hypergraph_rs::Hypergraph;

let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
h.add_edge(vec!["a".into(), "b".into()], Some("e".into()), ()).unwrap();
h.set_member_data("e", "b", 2).unwrap();
assert_eq!(
    h.members_with_data("e"),
    Some(vec![("a".to_string(), &0), ("b".to_string(), &2)])
);
Examples found in repository?
examples/membership_data.rs (line 29)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn add_node_to_edge_with_data( &mut self, edge_id: &str, node_id: &str, data: M, ) -> Result<(), EdgeError>
where N: Default, E: Default, M: Clone,

Self::add_node_to_edge, with the value the new membership carries. Auto-creates the edge and the node if missing. If the node is already a member, its value is replaced.

use hypergraph_rs::Hypergraph;

let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
h.add_node_to_edge_with_data("e", "a", 5).unwrap();
assert_eq!(h.member_data("e", "a"), Some(&5));
h.add_node_to_edge_with_data("e", "a", 9).unwrap();
assert_eq!(h.member_data("e", "a"), Some(&9));
Examples found in repository?
examples/membership_data.rs (line 14)
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}
Source

pub fn remove_node_from_edge( &mut self, edge_id: &str, node_id: &str, remove_empty: bool, ) -> Result<(), MembershipError>

Remove a node from an existing edge.

XGI parity: H.remove_node_from_edge(edge, node, remove_empty=True). XGI raises XGIError for a missing edge, a missing node, or a node that exists but is not a member of the named edge — the core returns the matching MembershipError variant so callers discriminate without string-matching; the PyO3 binding translates Err -> raise, reproducing XGI’s exact per-branch messages (D2 error channel).

Source

pub fn remove_edges_from( &mut self, edge_ids: &[String], ) -> Vec<Result<(), EdgeError>>

Remove multiple edges, returning a result per ATTEMPTED edge.

XGI parity: H.remove_edges_from(ebunch) — XGI iterates in order and RAISES on the first missing id, so ids after it are never attempted (partial effects: ids before the failure are already removed). The core mirrors this: stop on the first Err.

Source

pub fn remove_nodes_from( &mut self, node_ids: &[String], strong: bool, remove_empty: bool, ) -> Vec<Result<(), NodeError>>

Remove multiple nodes, returning a result per item.

XGI parity: H.remove_nodes_from(nodes) — XGI warns and skips a missing id, then CONTINUES; the core records a per-item Err and continues (D2-class channel translation — the binding warns per Err item).

Source

pub fn update( &mut self, nodes: Vec<(String, N)>, edges: Vec<(Vec<String>, Option<String>, E)>, )
where N: Default, M: Default + Clone,

Add nodes then edges. XGI parity: H.update(edges=, nodes=) (hypergraph.py:1210-1229).

Source

pub fn isolate_node_ids(&self) -> Vec<String>

Node ids with zero memberships, in insertion order. XGI parity: H.nodes.isolates() (views.py:632-667, default).

Source

pub fn singleton_edge_ids(&self) -> Vec<String>

Edge ids with exactly one member, in insertion order. XGI parity: H.edges.singletons() (views.py:749-761).

Source

pub fn graph_attrs(&self) -> &Map<String, Value>

Read-only view of the graph-level attribute dict (XGI’s H.graph).

Source

pub fn double_edge_swap( &mut self, n_id1: &str, n_id2: &str, e_id1: &str, e_id2: &str, ) -> Result<(), SwapError>
where M: Default + Clone,

Swap the edge memberships of two nodes between two edges. XGI parity: H.double_edge_swap(n1, n2, e1, e2) (hypergraph.py:918-992).

Source

pub fn random_edge_shuffle( &mut self, e_id1: Option<&str>, e_id2: Option<&str>, seed: u64, ) -> Result<(), EdgeError>
where M: Default + Clone,

Available on crate feature generators only.

Randomly redistribute nodes between two hyperedges, preserving both sizes. XGI parity: H.random_edge_shuffle(e1, e2, seed) (hypergraph.py:994-1078). Requires an explicit seed (deviation #3); the rand_pcg sequence does not match numpy, so only structural invariants are guaranteed across implementations.

Gated on generators (the feature that owns the rand_pcg/rand_core optional deps this method needs) so the core module stays buildable under --no-default-features (Phase 4 Task 19 feature-matrix check).

Source

pub fn skeleton(&self) -> UnGraph<String, f64>

The undirected 1-skeleton (pairwise projection): a node for every agent (weight = its id, added in node_ids() order so NodeIndex::new(i) corresponds to node_ids()[i]), and an edge (weight 1.0) between two agents that co-occur in at least one hyperedge.

Undirected (deviation from spec §4.1’s Graph): the connectivity, shortest-path, and clustering algorithms operate on this graph.

Source

pub fn node_neighbors(&self, node_id: &str) -> Option<Vec<String>>

The neighbours of a node: all nodes that share at least one hyperedge with it, excluding itself, in insertion order (deduped). None if the node is absent. XGI parity: H.nodes.neighbors(n).

Source

pub fn node_degree(&self, node_id: &str, order: Option<usize>) -> Option<usize>

The degree of a node = number of edges it belongs to. With order = Some(d), counts only edges of that order (size d+1). None if the node is absent. XGI parity: H.degree(n, order).

Source

pub fn edge_size(&self, edge_id: &str) -> Option<usize>

The size (number of members) of an edge. None if the edge is absent.

Source§

impl<M> Hypergraph<Value, Value, M>

Source

pub fn set_node_attributes( &mut self, values: impl IntoIterator<Item = (String, Map<String, Value>)>, )

Set node attributes from (id, attr_map) pairs. XGI parity: H.set_node_attributes(values, name=None). Silently skips missing node IDs (XGI warns).

Source

pub fn set_edge_attributes( &mut self, values: impl IntoIterator<Item = (String, Map<String, Value>)>, )

Set edge attributes from (id, attr_map) pairs. XGI parity: H.set_edge_attributes(values, name=None). Silently skips missing edge IDs (XGI warns).

Source§

impl Hypergraph<Value, Value, Value>

Source

pub fn dual(&self) -> Self

The dual: nodes become edges and edges become nodes. XGI parity: H.dual() (hypergraph.py:1446-1466). Isolate nodes are dropped (they would map to empty dual-edges, which our strict add_edge cannot represent — deviation #8).

Source§

impl Hypergraph<Value, Value, Value>

Source

pub fn merge_duplicate_edges( &mut self, rename: MergeRename, merge_rule: MergeRule, multiplicity: Option<&str>, )

Merge edges that have identical member-sets. XGI parity: H.merge_duplicate_edges(rename, merge_rule, multiplicity) (hypergraph.py:1257-1419). rename="tuple" is deferred (deviation #6); union produces a JSON array, not a Python set.

Source

pub fn cleanup(&mut self, options: CleanupOptions)

Remove undesirable artifacts in place. XGI parity: H.cleanup(...) (hypergraph.py). connected and relabel are not part of the core (the Python binding does them). In order: merge duplicate edges, remove singleton edges, remove empty edges, remove isolated nodes. Each flag in CleanupOptions keeps that kind; the default removes all of them.

Source

pub fn cleaned(&self, options: CleanupOptions) -> Self

Return a cleaned copy, leaving self untouched.

Source§

impl<N, E, M> Hypergraph<N, E, M>

Source

pub fn nodes(&self) -> NodeView<'_, N, E, M>

A view over all nodes (insertion order). XGI parity: H.nodes.

Source§

impl<N, E, M> Hypergraph<N, E, M>

Source

pub fn edges(&self) -> EdgeView<'_, N, E, M>

A view over all edges (insertion order). XGI parity: H.edges.

Source§

impl<M> Hypergraph<Value, Value, M>

Source

pub fn render(&self, strategy: LayoutStrategy) -> SceneGraph

Available on crate feature viz only.

Build a SceneGraph from a layout strategy (spec §5.3). Concrete impl: clones serde_json::Value node/edge attrs into the glyphs.

Source

pub fn render_to_json(&self, strategy: LayoutStrategy) -> String

Available on crate feature viz only.

Serialize the rendered scene-graph to JSON (spec §5.3).

Source

pub fn render_to_svg(&self, strategy: LayoutStrategy) -> String

Available on crate feature viz only.

Render the scene-graph to a self-contained SVG string (spec §5.3).

Trait Implementations§

Source§

impl<N, E, M> Debug for Hypergraph<N, E, M>
where N: Debug, E: Debug, M: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

XGI parity: __repr__ returns Hypergraph([{members}, ...]).

Source§

impl<N, E, M> Default for Hypergraph<N, E, M>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<N: PartialEq, E: PartialEq, M: PartialEq> PartialEq for Hypergraph<N, E, M>

Source§

fn eq(&self, other: &Self) -> bool

Two hypergraphs are equal if they have the same nodes, edges, memberships, and attributes. XGI parity: H1 == H2.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl<N, E, M> Forget for Hypergraph<N, E, M>

§

impl<N, E, M> Freeze for Hypergraph<N, E, M>

§

impl<N, E, M> Move for Hypergraph<N, E, M>

§

impl<N, E, M> RefUnwindSafe for Hypergraph<N, E, M>

§

impl<N, E, M> Send for Hypergraph<N, E, M>
where M: Send, E: Send, N: Send, RawVecInner: Send, RawTable<usize>: Send, RawTable<(NodeIndex, String)>: Send, NodeRef<Owned, String, Value, LeafOrInternal>: Send, BoxRaw<(String, Value)>: Send,

§

impl<N, E, M> Sync for Hypergraph<N, E, M>
where M: Sync, E: Sync, N: Sync, RawVecInner: Sync, RawTable<usize>: Sync, RawTable<(NodeIndex, String)>: Sync, NodeRef<Owned, String, Value, LeafOrInternal>: Sync, BoxRaw<(String, Value)>: Sync,

§

impl<N, E, M> Unpin for Hypergraph<N, E, M>
where M: Unpin, E: Unpin, N: Unpin, *const u8 is !null: Unpin, *const LeafNode<String, Value> is !null: Unpin, Box<(String, Value)>: Unpin,

§

impl<N, E, M> UnsafeUnpin for Hypergraph<N, E, M>

§

impl<N, E, M> UnwindSafe for Hypergraph<N, E, M>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

unsafe fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.