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#[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 pub nodes: Vec<O>,
38
39 pub edges: Vec<A>,
41
42 pub adjacency: Vec<Hyperedge>,
44
45 pub quotient: (Vec<NodeId>, Vec<NodeId>),
48}
49
50impl<O, A> Hypergraph<O, A> {
51 pub fn empty() -> Self {
53 Hypergraph {
54 nodes: vec![],
55 edges: vec![],
56 adjacency: vec![],
57 quotient: (vec![], vec![]),
58 }
59 }
60
61 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 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 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 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 pub fn unify(&mut self, v: NodeId, w: NodeId) {
133 self.quotient.0.push(v);
135 self.quotient.1.push(w);
136 }
137
138 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 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 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 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 self.quotient = (vec![], vec![]); q }
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 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
245fn 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}