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