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
21impl<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#[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 pub nodes: Vec<O>,
59
60 pub edges: Vec<A>,
62
63 pub adjacency: Vec<Hyperedge>,
65
66 pub quotient: (Vec<NodeId>, Vec<NodeId>),
69}
70
71impl<O, A> Hypergraph<O, A> {
72 pub fn empty() -> Self {
74 Hypergraph {
75 nodes: vec![],
76 edges: vec![],
77 adjacency: vec![],
78 quotient: (vec![], vec![]),
79 }
80 }
81
82 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 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 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 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 pub fn unify(&mut self, v: NodeId, w: NodeId) {
154 self.quotient.0.push(v);
156 self.quotient.1.push(w);
157 }
158
159 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 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 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 pub fn map_nodes<F: Fn(O) -> T, T>(self, f: F) -> Hypergraph<T, A> {
192 self.with_nodes(|nodes| nodes.into_iter().map(f).collect())
194 .unwrap()
195 }
196
197 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 pub fn map_edges<F: Fn(A) -> T, T>(self, f: F) -> Hypergraph<O, T> {
216 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 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 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 self.quotient = (vec![], vec![]); q }
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 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
314fn 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}