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