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 toserde_json::Value)E— hyperedge attribute type (defaults toserde_json::Value)M— per-membership attribute type (defaults toserde_json::Value)
Implementations§
Source§impl<N, E, M> Hypergraph<N, E, M>
impl<N, E, M> Hypergraph<N, E, M>
Sourcepub fn new() -> Self
pub fn new() -> Self
Create an empty hypergraph.
Examples found in repository?
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
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}Sourcepub fn add_node(&mut self, node_id: &str, attrs: N) -> bool
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).
Sourcepub fn has_node(&self, node_id: &str) -> bool
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).
Sourcepub fn add_edge(
&mut self,
members: Vec<String>,
idx: Option<String>,
attrs: E,
) -> Result<String, EdgeError>
pub fn add_edge( &mut self, members: Vec<String>, idx: Option<String>, attrs: E, ) -> Result<String, EdgeError>
Add a hyperedge connecting the given members.
XGI parity: H.add_edge(members, idx=id, **attr).
Examples found in repository?
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}Sourcepub fn add_empty_edge(&mut self, idx: Option<String>, attrs: E) -> String
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).
Sourcepub fn has_edge(&self, edge_id: &str) -> bool
pub fn has_edge(&self, edge_id: &str) -> bool
Check if a hyperedge exists.
XGI parity: id in H.edges.
Sourcepub fn memberships(&self, node_id: &str) -> Option<Vec<String>>
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?
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}Sourcepub fn members(&self, edge_id: &str) -> Option<Vec<String>>
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?
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}Sourcepub fn node_ids(&self) -> Vec<String>
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?
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}Sourcepub fn edge_ids(&self) -> Vec<String>
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?
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
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}Sourcepub fn remove_node(
&mut self,
node_id: &str,
strong: bool,
remove_empty: bool,
) -> Result<(), NodeError>
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).
Sourcepub fn remove_edge(&mut self, edge_id: &str) -> Result<(), EdgeError>
pub fn remove_edge(&mut self, edge_id: &str) -> Result<(), EdgeError>
Remove a hyperedge from the hypergraph.
XGI parity: H.remove_edge(e).
Sourcepub fn node_attrs(&self, node_id: &str) -> Option<&N>
pub fn node_attrs(&self, node_id: &str) -> Option<&N>
Read a node’s attributes. XGI parity: H.nodes[n].
Sourcepub fn node_attrs_mut(&mut self, node_id: &str) -> Option<&mut N>
pub fn node_attrs_mut(&mut self, node_id: &str) -> Option<&mut N>
Mutably access a node’s attributes.
Sourcepub fn edge_attrs(&self, edge_id: &str) -> Option<&E>
pub fn edge_attrs(&self, edge_id: &str) -> Option<&E>
Read a hyperedge’s attributes. XGI parity: H.edges[e].
Sourcepub fn edge_attrs_mut(&mut self, edge_id: &str) -> Option<&mut E>
pub fn edge_attrs_mut(&mut self, edge_id: &str) -> Option<&mut E>
Mutably access a hyperedge’s attributes.
Sourcepub fn graph_attr(&self, key: &str) -> Option<&Value>
pub fn graph_attr(&self, key: &str) -> Option<&Value>
Read a graph-level attribute. XGI parity: H["name"].
Sourcepub fn set_graph_attr(&mut self, key: &str, value: Value)
pub fn set_graph_attr(&mut self, key: &str, value: Value)
Set a graph-level attribute. XGI parity: H["name"] = value.
Sourcepub fn clear(&mut self)
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).
Sourcepub fn clear_edges(&mut self)
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).
Sourcepub fn next_edge_id(&self) -> u64
pub fn next_edge_id(&self) -> u64
The id the next edge added without an explicit id will get.
XGI parity: H._edge_uid.
Sourcepub fn update_uid_counter(&mut self, idx: u64)
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.
Sourcepub fn freeze(&mut self)
pub fn freeze(&mut self)
Freeze the hypergraph, preventing modification.
XGI parity: H.freeze().
Sourcepub fn copy(&self) -> Self
pub fn copy(&self) -> Self
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.
Sourcepub fn add_nodes_from(&mut self, nodes: impl IntoIterator<Item = (String, N)>)
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).
Sourcepub fn add_edges_from(
&mut self,
edges: impl IntoIterator<Item = (Vec<String>, Option<String>, E)>,
) -> Vec<Result<String, EdgeError>>
pub fn add_edges_from( &mut self, edges: impl IntoIterator<Item = (Vec<String>, Option<String>, E)>, ) -> Vec<Result<String, EdgeError>>
Add multiple edges. Returns a result per edge.
Sourcepub fn add_node_to_edge(
&mut self,
edge_id: &str,
node_id: &str,
) -> Result<(), EdgeError>
pub fn add_node_to_edge( &mut self, edge_id: &str, node_id: &str, ) -> Result<(), EdgeError>
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?
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}Sourcepub fn member_data(&self, edge_id: &str, node_id: &str) -> Option<&M>
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?
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}Sourcepub fn set_member_data(
&mut self,
edge_id: &str,
node_id: &str,
data: M,
) -> Result<(), MembershipError>where
M: Clone,
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?
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}Sourcepub fn members_with_data(&self, edge_id: &str) -> Option<Vec<(String, &M)>>
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?
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}Sourcepub fn add_node_to_edge_with_data(
&mut self,
edge_id: &str,
node_id: &str,
data: M,
) -> Result<(), EdgeError>
pub fn add_node_to_edge_with_data( &mut self, edge_id: &str, node_id: &str, data: M, ) -> Result<(), EdgeError>
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?
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}Sourcepub fn remove_node_from_edge(
&mut self,
edge_id: &str,
node_id: &str,
remove_empty: bool,
) -> Result<(), MembershipError>
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).
Sourcepub fn remove_edges_from(
&mut self,
edge_ids: &[String],
) -> Vec<Result<(), EdgeError>>
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.
Sourcepub fn remove_nodes_from(
&mut self,
node_ids: &[String],
strong: bool,
remove_empty: bool,
) -> Vec<Result<(), NodeError>>
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).
Sourcepub fn update(
&mut self,
nodes: Vec<(String, N)>,
edges: Vec<(Vec<String>, Option<String>, E)>,
)
pub fn update( &mut self, nodes: Vec<(String, N)>, edges: Vec<(Vec<String>, Option<String>, E)>, )
Add nodes then edges. XGI parity: H.update(edges=, nodes=)
(hypergraph.py:1210-1229).
Sourcepub fn isolate_node_ids(&self) -> Vec<String>
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).
Sourcepub fn singleton_edge_ids(&self) -> Vec<String>
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).
Sourcepub fn graph_attrs(&self) -> &Map<String, Value>
pub fn graph_attrs(&self) -> &Map<String, Value>
Read-only view of the graph-level attribute dict (XGI’s H.graph).
Sourcepub fn double_edge_swap(
&mut self,
n_id1: &str,
n_id2: &str,
e_id1: &str,
e_id2: &str,
) -> Result<(), SwapError>
pub fn double_edge_swap( &mut self, n_id1: &str, n_id2: &str, e_id1: &str, e_id2: &str, ) -> Result<(), SwapError>
Swap the edge memberships of two nodes between two edges.
XGI parity: H.double_edge_swap(n1, n2, e1, e2) (hypergraph.py:918-992).
Sourcepub fn random_edge_shuffle(
&mut self,
e_id1: Option<&str>,
e_id2: Option<&str>,
seed: u64,
) -> Result<(), EdgeError>
Available on crate feature generators only.
pub fn random_edge_shuffle( &mut self, e_id1: Option<&str>, e_id2: Option<&str>, seed: u64, ) -> Result<(), EdgeError>
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).
Sourcepub fn skeleton(&self) -> UnGraph<String, f64>
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.
Sourcepub fn node_neighbors(&self, node_id: &str) -> Option<Vec<String>>
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§impl<M> Hypergraph<Value, Value, M>
impl<M> Hypergraph<Value, Value, M>
Sourcepub fn set_node_attributes(
&mut self,
values: impl IntoIterator<Item = (String, Map<String, Value>)>,
)
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).
Sourcepub fn set_edge_attributes(
&mut self,
values: impl IntoIterator<Item = (String, Map<String, Value>)>,
)
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>
impl Hypergraph<Value, Value, Value>
Sourcepub fn merge_duplicate_edges(
&mut self,
rename: MergeRename,
merge_rule: MergeRule,
multiplicity: Option<&str>,
)
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.
Sourcepub fn cleanup(&mut self, options: CleanupOptions)
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.
Sourcepub fn cleaned(&self, options: CleanupOptions) -> Self
pub fn cleaned(&self, options: CleanupOptions) -> Self
Return a cleaned copy, leaving self untouched.
Source§impl<N, E, M> Hypergraph<N, E, M>
impl<N, E, M> Hypergraph<N, E, M>
Source§impl<N, E, M> Hypergraph<N, E, M>
impl<N, E, M> Hypergraph<N, E, M>
Source§impl<M> Hypergraph<Value, Value, M>
impl<M> Hypergraph<Value, Value, M>
Sourcepub fn render(&self, strategy: LayoutStrategy) -> SceneGraph
Available on crate feature viz only.
pub fn render(&self, strategy: LayoutStrategy) -> SceneGraph
viz only.Build a SceneGraph from a layout strategy (spec §5.3). Concrete impl:
clones serde_json::Value node/edge attrs into the glyphs.
Sourcepub fn render_to_json(&self, strategy: LayoutStrategy) -> String
Available on crate feature viz only.
pub fn render_to_json(&self, strategy: LayoutStrategy) -> String
viz only.Serialize the rendered scene-graph to JSON (spec §5.3).
Sourcepub fn render_to_svg(&self, strategy: LayoutStrategy) -> String
Available on crate feature viz only.
pub fn render_to_svg(&self, strategy: LayoutStrategy) -> String
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>
impl<N, E, M> Debug for Hypergraph<N, E, M>
Source§impl<N, E, M> Default for Hypergraph<N, E, M>
impl<N, E, M> Default for Hypergraph<N, E, M>
Auto Trait Implementations§
impl<N, E, M> Forget for Hypergraph<N, E, M>
impl<N, E, M> Freeze for Hypergraph<N, E, M>where
*const u8 is !null: Freeze,
PhantomData<Node<Option<NodeKind<N, E>>>>: Freeze,
PhantomData<Edge<Option<MembershipEdge<M>>>>: Freeze,
PhantomData<Directed>: Freeze,
PhantomData<usize>: Freeze,
PhantomData<Bucket<String, NodeIndex>>: Freeze,
PhantomData<(NodeIndex, String)>: Freeze,
*const LeafNode<String, Value> is !null: Freeze,
PhantomData<(Owned, LeafOrInternal)>: Freeze,
PhantomData<Box<(String, Value)>>: Freeze,
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>
impl<N, E, M> Sync for Hypergraph<N, E, M>
impl<N, E, M> Unpin for Hypergraph<N, E, M>
impl<N, E, M> UnsafeUnpin for Hypergraph<N, E, M>where
*const u8 is !null: UnsafeUnpin,
PhantomData<Node<Option<NodeKind<N, E>>>>: UnsafeUnpin,
PhantomData<Edge<Option<MembershipEdge<M>>>>: UnsafeUnpin,
PhantomData<Directed>: UnsafeUnpin,
PhantomData<usize>: UnsafeUnpin,
PhantomData<Bucket<String, NodeIndex>>: UnsafeUnpin,
PhantomData<(NodeIndex, String)>: UnsafeUnpin,
*const LeafNode<String, Value> is !null: UnsafeUnpin,
PhantomData<(Owned, LeafOrInternal)>: UnsafeUnpin,
PhantomData<Box<(String, Value)>>: UnsafeUnpin,
impl<N, E, M> UnwindSafe for Hypergraph<N, E, M>where
RawVecInner: UnwindSafe,
N: UnwindSafe,
E: UnwindSafe,
M: UnwindSafe,
NonNull<u8>: UnwindSafe,
HashMap<NodeIndex, String>: UnwindSafe,
BTreeMap<String, Value>: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§unsafe fn to_subset_unchecked(&self) -> SS
unsafe fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.