open_hypergraphs/lax/
hypergraph.rs

1use crate::array::vec::{VecArray, VecKind};
2use crate::finite_function::*;
3
4use core::fmt::Debug;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub struct NodeId(pub usize);
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct EdgeId(pub usize);
13
14#[derive(Debug, Clone, PartialEq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct Hyperedge {
17    pub sources: Vec<NodeId>,
18    pub targets: Vec<NodeId>,
19}
20
21/// Create a [`Hyperedge`] from a tuple of `(sources, targets)`.
22///
23/// This allows convenient creation of hyperedges from various collection types:
24/// ```
25/// # use open_hypergraphs::lax::{Hyperedge, NodeId};
26/// let edge: Hyperedge = (vec![NodeId(0), NodeId(1)], vec![NodeId(2)]).into();
27/// let edge: Hyperedge = ([NodeId(0), NodeId(1)], [NodeId(2)]).into();
28/// ```
29impl<S, T> From<(S, T)> for Hyperedge
30where
31    S: Into<Vec<NodeId>>,
32    T: Into<Vec<NodeId>>,
33{
34    fn from((sources, targets): (S, T)) -> Self {
35        Hyperedge {
36            sources: sources.into(),
37            targets: targets.into(),
38        }
39    }
40}
41
42pub type Interface = (Vec<NodeId>, Vec<NodeId>);
43
44/// A [`crate::lax::Hypergraph`] represents an "un-quotiented" hypergraph.
45///
46/// It can be thought of as a collection of disconnected operations and wires along with a
47/// *quotient map* which can be used with connected components to produce a `Hypergraph`.
48#[derive(Debug, Clone, PartialEq)]
49#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
50#[cfg_attr(
51    feature = "serde",
52    serde(
53        bound = "O: serde::Serialize + serde::de::DeserializeOwned, A: serde::Serialize + serde::de::DeserializeOwned"
54    )
55)]
56pub struct Hypergraph<O, A> {
57    /// Node labels. Defines a finite map from [`NodeId`] to node label
58    pub nodes: Vec<O>,
59
60    /// Edge labels. Defines a finite map from [`EdgeId`] to edge label
61    pub edges: Vec<A>,
62
63    /// Hyperedges map an *ordered list* of source nodes to an ordered list of target nodes.
64    pub adjacency: Vec<Hyperedge>,
65
66    // A finite endofunction on the set of nodes, identifying nodes to be quotiented.
67    // NOTE: this is a *graph* on the set of nodes.
68    pub quotient: (Vec<NodeId>, Vec<NodeId>),
69}
70
71impl<O, A> Hypergraph<O, A> {
72    /// The empty Hypergraph with no nodes or edges.
73    pub fn empty() -> Self {
74        Hypergraph {
75            nodes: vec![],
76            edges: vec![],
77            adjacency: vec![],
78            quotient: (vec![], vec![]),
79        }
80    }
81
82    /// Check if the quotient map is empty: if so, then this is already a strict OpenHypergraph
83    pub fn is_strict(&self) -> bool {
84        self.quotient.0.is_empty()
85    }
86
87    pub fn from_strict(h: crate::strict::hypergraph::Hypergraph<VecKind, O, A>) -> Self {
88        let mut adjacency = Vec::with_capacity(h.x.0.len());
89        for (sources, targets) in h.s.into_iter().zip(h.t.into_iter()) {
90            adjacency.push(Hyperedge {
91                sources: sources.table.iter().map(|i| NodeId(*i)).collect(),
92                targets: targets.table.iter().map(|i| NodeId(*i)).collect(),
93            })
94        }
95
96        Hypergraph {
97            nodes: h.w.0 .0,
98            edges: h.x.0 .0,
99            adjacency,
100            quotient: (vec![], vec![]),
101        }
102    }
103
104    pub fn discrete(nodes: Vec<O>) -> Self {
105        let mut h = Self::empty();
106        h.nodes = nodes;
107        h
108    }
109
110    /// Add a single node labeled `w` to the [`Hypergraph`]
111    pub fn new_node(&mut self, w: O) -> NodeId {
112        let index = self.nodes.len();
113        self.nodes.push(w);
114        NodeId(index)
115    }
116
117    /// Add a single hyperedge labeled `a` to the [`Hypergraph`]
118    /// it has sources and targets specified by `interface`
119    /// return which `EdgeId` corresponds to that new hyperedge
120    pub fn new_edge(&mut self, x: A, interface: impl Into<Hyperedge>) -> EdgeId {
121        let edge_idx = self.edges.len();
122        self.edges.push(x);
123        self.adjacency.push(interface.into());
124        EdgeId(edge_idx)
125    }
126
127    /// Append a "singleton" operation to the Hypergraph.
128    ///
129    /// 1. For each element t of `source_type` (resp. `target_type`), creates a node labeled t
130    /// 2. creates An edge labeled `x`, and sets its source/target nodes to those from step (1)
131    ///
132    /// Returns the index [`EdgeId`] of the operation in the [`Hypergraph`], and its source and
133    /// target nodes.
134    pub fn new_operation(
135        &mut self,
136        x: A,
137        source_type: Vec<O>,
138        target_type: Vec<O>,
139    ) -> (EdgeId, Interface) {
140        let sources: Vec<NodeId> = source_type.into_iter().map(|t| self.new_node(t)).collect();
141        let targets: Vec<NodeId> = target_type.into_iter().map(|t| self.new_node(t)).collect();
142        let interface = (sources.clone(), targets.clone());
143        let edge_id = self.new_edge(x, Hyperedge { sources, targets });
144        (edge_id, interface)
145    }
146
147    /// Identify a pair of nodes `(v, w)` by adding them to the quotient map.
148    ///
149    /// Note that if the labels of `v` and `w` are not equal, then this will not represent a valid
150    /// `Hypergraph`.
151    /// This is intentional so that typechecking and type inference can be deferred until after
152    /// construction of the `Hypergraph`.
153    pub fn unify(&mut self, v: NodeId, w: NodeId) {
154        // add nodes to the quotient graph
155        self.quotient.0.push(v);
156        self.quotient.1.push(w);
157    }
158
159    /// Add a new *source* node labeled `w` to edge `edge_id`.
160    pub fn add_edge_source(&mut self, edge_id: EdgeId, w: O) -> NodeId {
161        let node_id = self.new_node(w);
162        self.adjacency[edge_id.0].sources.push(node_id);
163        node_id
164    }
165
166    /// Add a new *target* node labeled `w` to edge `edge_id`
167    pub fn add_edge_target(&mut self, edge_id: EdgeId, w: O) -> NodeId {
168        let node_id = self.new_node(w);
169        self.adjacency[edge_id.0].targets.push(node_id);
170        node_id
171    }
172
173    /// Set the nodes of a Hypergraph, possibly changing types.
174    /// Returns None if new nodes array had different length.
175    pub fn with_nodes<T, F: FnOnce(Vec<O>) -> Vec<T>>(self, f: F) -> Option<Hypergraph<T, A>> {
176        let n = self.nodes.len();
177        let nodes = f(self.nodes);
178        if nodes.len() != n {
179            return None;
180        }
181
182        Some(Hypergraph {
183            nodes,
184            edges: self.edges,
185            adjacency: self.adjacency,
186            quotient: self.quotient,
187        })
188    }
189
190    /// Map the node labels of this Hypergraph, possibly changing their type
191    pub fn map_nodes<F: Fn(O) -> T, T>(self, f: F) -> Hypergraph<T, A> {
192        // note: unwrap is safe because length is preserved
193        self.with_nodes(|nodes| nodes.into_iter().map(f).collect())
194            .unwrap()
195    }
196
197    /// Set the edges of a Hypergraph, possibly changing types.
198    /// Returns None if new edges array had different length.
199    pub fn with_edges<T, F: FnOnce(Vec<A>) -> Vec<T>>(self, f: F) -> Option<Hypergraph<O, T>> {
200        let n = self.edges.len();
201        let edges = f(self.edges);
202        if edges.len() != n {
203            return None;
204        }
205
206        Some(Hypergraph {
207            nodes: self.nodes,
208            edges,
209            adjacency: self.adjacency,
210            quotient: self.quotient,
211        })
212    }
213
214    /// Map the edge labels of this Hypergraph, possibly changing their type
215    pub fn map_edges<F: Fn(A) -> T, T>(self, f: F) -> Hypergraph<O, T> {
216        // note: unwrap is safe because length is preserved
217        self.with_edges(|edges| edges.into_iter().map(f).collect())
218            .unwrap()
219    }
220}
221
222impl<O: Clone + PartialEq, A: Clone> Hypergraph<O, A> {
223    /// Construct a [`Hypergraph`] by identifying nodes in the quotient map.
224    /// Mutably quotient this [`Hypergraph`], returning the coequalizer calculated from `self.quotient`.
225    ///
226    /// NOTE: this operation is unchecked; you should verify quotiented nodes have the exact same
227    /// type first, or this operation is undefined.
228    pub fn quotient(&mut self) -> FiniteFunction<VecKind> {
229        use std::mem::take;
230        let q = self.coequalizer();
231
232        self.nodes = coequalizer_universal(&q, &VecArray(take(&mut self.nodes)))
233            .unwrap()
234            .0;
235
236        // map hyperedges
237        for e in &mut self.adjacency {
238            e.sources.iter_mut().for_each(|x| *x = NodeId(q.table[x.0]));
239            e.targets.iter_mut().for_each(|x| *x = NodeId(q.table[x.0]));
240        }
241
242        // clear the quotient map (we just used it)
243        self.quotient = (vec![], vec![]); // empty
244
245        q // return the coequalizer used to quotient the hypergraph
246    }
247}
248
249impl<O: Clone, A: Clone> Hypergraph<O, A> {
250    pub fn to_hypergraph(&self) -> crate::strict::Hypergraph<VecKind, O, A> {
251        make_hypergraph(self)
252    }
253
254    pub fn coequalizer(&self) -> FiniteFunction<VecKind> {
255        // Compute the coequalizer (connected components) of the quotient graph
256        let s: FiniteFunction<VecKind> = FiniteFunction {
257            table: VecArray(self.quotient.0.iter().map(|x| x.0).collect()),
258            target: self.nodes.len(),
259        };
260
261        let t: FiniteFunction<VecKind> = FiniteFunction {
262            table: VecArray(self.quotient.1.iter().map(|x| x.0).collect()),
263            target: self.nodes.len(),
264        };
265
266        s.coequalizer(&t)
267            .expect("coequalizer must exist for any graph")
268    }
269}
270
271pub(crate) fn finite_function_coproduct(
272    v1: &[NodeId],
273    v2: &[NodeId],
274    target: usize,
275) -> Vec<NodeId> {
276    v1.iter()
277        .cloned()
278        .chain(v2.iter().map(|&s| NodeId(s.0 + target)))
279        .collect()
280}
281
282pub(crate) fn concat<T: Clone>(v1: &[T], v2: &[T]) -> Vec<T> {
283    v1.iter().cloned().chain(v2.iter().cloned()).collect()
284}
285
286impl<O: Clone, A: Clone> Hypergraph<O, A> {
287    pub(crate) fn coproduct(&self, other: &Hypergraph<O, A>) -> Hypergraph<O, A> {
288        let n = self.nodes.len();
289
290        let adjacency = self
291            .adjacency
292            .iter()
293            .cloned()
294            .chain(other.adjacency.iter().map(|edge| Hyperedge {
295                sources: edge.sources.iter().map(|&s| NodeId(s.0 + n)).collect(),
296                targets: edge.targets.iter().map(|&t| NodeId(t.0 + n)).collect(),
297            }))
298            .collect();
299
300        let quotient = (
301            finite_function_coproduct(&self.quotient.0, &other.quotient.0, n),
302            finite_function_coproduct(&self.quotient.1, &other.quotient.1, n),
303        );
304
305        Hypergraph {
306            nodes: concat(&self.nodes, &other.nodes),
307            edges: concat(&self.edges, &other.edges),
308            adjacency,
309            quotient,
310        }
311    }
312}
313
314/// Create a [`crate::strict::hypergraph::Hypergraph`] by forgetting about the quotient map.
315fn make_hypergraph<O: Clone, A: Clone>(
316    h: &Hypergraph<O, A>,
317) -> crate::strict::hypergraph::Hypergraph<VecKind, O, A> {
318    use crate::finite_function::*;
319    use crate::indexed_coproduct::*;
320    use crate::semifinite::*;
321
322    let s = {
323        let mut lengths = Vec::<usize>::with_capacity(h.edges.len());
324        let mut values = Vec::<usize>::new();
325        for e in h.adjacency.iter() {
326            lengths.push(e.sources.len());
327            values.extend(e.sources.iter().map(|x| x.0));
328        }
329
330        let sources = SemifiniteFunction(VecArray(lengths));
331        let values =
332            FiniteFunction::new(VecArray(values), h.nodes.len()).expect("invalid lax::Hypergraph!");
333        IndexedCoproduct::from_semifinite(sources, values).expect("valid IndexedCoproduct")
334    };
335
336    let t = {
337        let mut lengths = Vec::<usize>::with_capacity(h.edges.len());
338        let mut values = Vec::<usize>::new();
339        for e in h.adjacency.iter() {
340            lengths.push(e.targets.len());
341            values.extend(e.targets.iter().map(|x| x.0));
342        }
343
344        let sources = SemifiniteFunction(VecArray(lengths));
345        let values =
346            FiniteFunction::new(VecArray(values), h.nodes.len()).expect("invalid lax::Hypergraph!");
347        IndexedCoproduct::from_semifinite(sources, values).expect("valid IndexedCoproduct")
348    };
349
350    let w = SemifiniteFunction(VecArray(h.nodes.clone()));
351    let x = SemifiniteFunction(VecArray(h.edges.clone()));
352
353    crate::strict::hypergraph::Hypergraph { s, t, w, x }
354}