graph_types/graphs/
mod.rs

1use crate::{Edge, EdgeID, EdgeInsertID, EdgeQuery, GraphKind, NodeID};
2
3pub mod weighted;
4use crate::{edges::typed_edges::IndeterminateEdge, errors::GraphError, vertexes::NodeDegree};
5use std::{
6    mem::size_of,
7    ops::{Deref, DerefMut},
8};
9
10pub mod named;
11
12/// Represent a graph storage, with a set of nodes and edges.
13///
14/// # Examples
15///
16/// ```
17/// use graph_theory::GraphEngine;
18/// ```
19#[allow(unused_variables)]
20pub trait GraphEngine
21where
22    Self: Sized,
23{
24    /// According to a given vertex, find all neighbor nodes.
25    /// See more in [Self::all_neighbors], [Self::all_incoming], [Self::all_outgoing].
26    type NeighborIterator<'a>: DoubleEndedIterator<Item = NodeID>
27    where
28        Self: 'a;
29    /// An iterator over the edges.
30    type BridgeIterator<'a>: DoubleEndedIterator<Item = IndeterminateEdge>
31    where
32        Self: 'a;
33    /// Traverse all nodes in the graph,
34    /// note that this traversal is neither BFS nor DFS, but the most friendly traversal to the data structure.
35    /// See more in [Self::all_nodes].
36    type NodeTraverser<'a>: DoubleEndedIterator<Item = NodeID>
37    where
38        Self: 'a;
39    /// An iterator over the edges.
40    type EdgeTraverser<'a>: DoubleEndedIterator<Item = EdgeID>
41    where
42        Self: 'a;
43    /// An iterator over the edges.
44    type BridgeTraverser<'a>: DoubleEndedIterator<Item = IndeterminateEdge>
45    where
46        Self: 'a;
47
48    /// Check the graph kind, it can be directed or undirected.
49    ///
50    /// # Examples
51    ///
52    /// ```
53    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
54    /// assert_eq!(CompleteGraph::one_way(5).get_node(5), true);
55    /// assert_eq!(CompleteGraph::one_way(5).get_node(6), false);
56    /// ```
57    fn graph_kind(&self) -> GraphKind;
58    /// Check if the node exists, return the node id if exists.
59    ///
60    /// # Examples
61    ///
62    /// ```
63    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
64    /// assert_eq!(CompleteGraph::one_way(5).get_node(5), true);
65    /// assert_eq!(CompleteGraph::one_way(5).get_node(6), false);
66    /// ```
67    fn get_node(&self, node: NodeID) -> Result<NodeID, GraphError>;
68    /// Traverse all nodes in the entire graph in the most friendly way to the data structure, and the order of this traversal is arbitrary.
69    ///
70    ///
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
76    /// let mut graph = CompleteGraph::one_way(5);
77    /// assert_eq!(graph.all_nodes().count(), 20)
78    /// ```
79    fn all_nodes<'a>(&'a self) -> Self::NodeTraverser<'a>;
80    /// Count the number of nodes in the graph.
81    ///
82    /// # Examples
83    ///
84    /// ```
85    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
86    /// assert_eq!(CompleteGraph::one_way(5).count_nodes(), 5);
87    /// ```
88    fn count_nodes<'a>(&'a self) -> usize {
89        self.all_nodes().count()
90    }
91    /// Given a vertex, return all adjacent nodes.
92    ///
93    ///
94    /// Return [None] if the node does not exist.
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// use graph_theory::{graph_engines::UnGraphAND, GraphEngine};
100    /// let graph = UnGraphAND::default();
101    /// assert_eq!(graph.all_neighbors(5).count(), 5);
102    /// ```
103    fn all_neighbors<'a>(&'a self, node: NodeID) -> Self::NeighborIterator<'a>;
104    /// Given a vertex as the starting point, return the ids corresponding to all ending points.
105    ///
106    /// In an undirected graph, it is equivalent to calling [Self::all_neighbors].
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// use graph_theory::{graph_engines::UnGraphAND, GraphEngine};
112    /// let graph = UnGraphAND::default();
113    /// assert_eq!(graph.all_outgoing(5).count(), 5);
114    /// ```
115    fn all_outgoing<'a>(&'a self, node: NodeID) -> Self::NeighborIterator<'a> {
116        debug_assert!(self.graph_kind() == GraphKind::Undirected);
117        self.all_neighbors(node)
118    }
119    /// Given a vertex as the ending point, return the ids corresponding to all starting points.
120    ///
121    /// In an undirected graph, it is equivalent to calling [Self::all_neighbors].
122    ///
123    /// # Examples
124    ///
125    /// ```
126    /// use graph_theory::{graph_engines::UnGraphAND, GraphEngine};
127    /// let graph = UnGraphAND::default();
128    /// assert_eq!(graph.all_incoming(5).count(), 5);
129    /// ```
130    fn all_incoming<'a>(&'a self, node: NodeID) -> Self::NeighborIterator<'a> {
131        debug_assert!(self.graph_kind() == GraphKind::Undirected);
132        self.all_neighbors(node)
133    }
134    /// Check if the node exists, return the node id if exists.
135    ///
136    /// Return [None] if the node does not exist.
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
142    /// assert_eq!(CompleteGraph::one_way(5).count_nodes(), 5);
143    /// ```
144    fn count_degree<'a>(&'a self, node: NodeID) -> NodeDegree {
145        match self.graph_kind() {
146            GraphKind::Directed => {
147                NodeDegree::Directed { in_coming: self.all_incoming(node).count(), out_going: self.all_outgoing(node).count() }
148            }
149            GraphKind::Undirected => NodeDegree::Undirected { total: self.all_neighbors(node).count() },
150        }
151    }
152
153    /// Check if the edge exists, return the node id if exists.
154    ///
155    /// At most one element will be returned, even if there are multiple edges with the same starting point and ending point.
156    ///
157    /// If you need to return all eligible edges, use [Self::get_bridges].
158    ///
159    /// # Examples
160    ///
161    /// ```
162    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
163    /// assert_eq!(CompleteGraph::one_way(5).get_node(5), true);
164    /// assert_eq!(CompleteGraph::one_way(5).get_node(6), false);
165    /// ```
166    fn get_edge(&self, edge: EdgeID) -> Result<EdgeID, GraphError>;
167    /// Traverse all edges in the entire graph in the most friendly way to the data structure, the order of traversal is arbitrary.
168    ///
169    ///
170    /// ```
171    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
172    /// let mut graph = CompleteGraph::one_way(5);
173    /// assert_eq!(graph.all_nodes().count(), 20)
174    /// ```
175    fn all_edges<'a>(&'a self) -> Self::EdgeTraverser<'a>;
176    /// Count the number of edges in the graph.
177    ///
178    /// # Examples
179    ///
180    /// ```
181    /// # use graph_theory::{GraphEngine};
182    /// # use graph_theory::graph_engines::{CycleGraph, StarGraph, CompleteGraph};
183    /// assert_eq!(CycleGraph::one_way(5).count_edges(), 5);
184    /// assert_eq!(CycleGraph::two_way(5).count_edges(), 10);
185    /// assert_eq!(StarGraph::one_way(5).count_edges(), 5);
186    /// assert_eq!(StarGraph::two_way(5).count_edges(), 10);
187    /// assert_eq!(CompleteGraph::one_way(5).count_edges(), 5);
188    /// assert_eq!(CompleteGraph::one_way(5).count_edges(), 10);
189    /// ```
190    fn count_edges<'a>(&'a self) -> usize {
191        self.all_edges().count()
192    }
193    fn get_bridge(&self, edge: EdgeID) -> Result<IndeterminateEdge, GraphError>;
194    /// Give all edges matching the start and end points
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
200    /// assert_eq!(CompleteGraph::one_way(5).get_node(5), true);
201    /// assert_eq!(CompleteGraph::one_way(5).get_node(6), false);
202    /// ```
203    fn get_bridges<'a>(&'a self, from: NodeID, goto: NodeID) -> Self::BridgeIterator<'a>;
204    /// Get the edges of the graph.
205    ///
206    ///
207    /// ```
208    /// use graph_theory::{graph_engines::CompleteGraph, GraphEngine};
209    /// let mut graph = CompleteGraph::one_way(5);
210    /// assert_eq!(graph.all_nodes().count(), 20)
211    /// ```
212    fn all_bridges<'a>(&'a self) -> Self::BridgeTraverser<'a>;
213    /// Query the total space occupied by the structure, return 0 if failed to query
214    ///
215    /// Note that this volume contains garbage data, call [GraphEngine::shrink] at the right time to perform garbage collection.
216    fn size_hint(&self) -> usize {
217        size_of::<Self>()
218    }
219}
220
221/// Mark a graph engine that can add and delete edges or points
222pub trait MutableGraph: GraphEngine {
223    /// Insert a node without any neighbors (edges).
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use graph_theory::{graph_engines::AdjacencyNodeDict, GraphEngine};
229    /// let mut graph = AdjacencyNodeDict::default();
230    /// assert_eq!(graph.count_nodes(), 0);
231    /// graph.insert_node(5);
232    /// assert_eq!(graph.count_nodes(), 1);
233    /// ```
234    fn insert_node(&mut self, node_id: usize) -> bool;
235    /// Insert a node without any neighbors (edges).
236    ///
237    /// # Examples
238    ///
239    /// ```
240    /// use graph_theory::{graph_engines::AdjacencyNodeDict, GraphEngine};
241    /// let mut graph = AdjacencyNodeDict::default();
242    /// assert_eq!(graph.count_nodes(), 0);
243    /// graph.insert_node(5);
244    /// assert_eq!(graph.count_nodes(), 1);
245    /// ```
246    fn create_node(&mut self) -> usize;
247
248    /// Remove the given node.
249    ///
250    /// # Undefined Behavior
251    ///
252    /// - If the node has any edges, the behavior is undefined.
253    ///
254    /// It is recommended to remove all edges before removing the node, see [`GraphEngine::remove_node_with_edges`].
255    ///
256    ///
257    /// # Examples
258    ///
259    /// ```
260    /// use graph_theory::{graph_engines::AdjacencyNodeDict, GraphEngine};
261    /// let mut graph = AdjacencyNodeDict::default();
262    /// assert_eq!(graph.count_nodes(), 0);
263    /// graph.insert_node(5);
264    /// assert_eq!(graph.count_nodes(), 1);
265    /// ```
266    fn remove_node(&mut self, node_id: usize) {
267        self.remove_node_with_edges(node_id)
268    }
269    /// Remove the given node and all edges connected to it.
270    ///
271    /// # Examples
272    ///
273    /// ```
274    /// use graph_theory::{graph_engines::AdjacencyNodeDict, GraphEngine};
275    /// let mut graph = AdjacencyNodeDict::default();
276    /// assert_eq!(graph.count_nodes(), 0);
277    /// graph.insert_node(5);
278    /// assert_eq!(graph.count_nodes(), 1);
279    /// ```
280    fn remove_node_with_edges(&mut self, node_id: usize);
281    /// Insert a edge between two nodes.
282    ///
283    /// # Undefined Behaviors
284    ///
285    /// - If the nodes does not exist, the behavior is undefined.
286    ///
287    /// It is recommended to check the existence of the nodes before inserting the edge, see [`GraphEngine::insert_edge_with_nodes`].
288    ///
289    /// - Insert undirected edge to directed graph.
290    ///
291    /// Two edges will be inserted, but only return last edge's id.
292    ///
293    /// # Panics
294    ///
295    /// - No such ability
296    ///
297    /// Not all graph engine supports insert edge.
298    ///
299    /// - Insert disconnected edge
300    ///
301    /// Meaningless, don't do that.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use graph_theory::GraphEngine;
307    /// ```
308    fn insert_edge<E: Edge>(&mut self, edge: E) -> EdgeInsertID {
309        self.insert_edge_with_nodes(edge)
310    }
311    /// Insert edge to graph, if the nodes does not exist, also insert them.
312    ///
313    /// # Panics
314    ///
315    /// - No such ability
316    ///
317    /// Not all graph engine supports insert edge.
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// use graph_theory::GraphEngine;
323    /// ```
324    fn insert_edge_with_nodes<E: Edge>(&mut self, edge: E) -> EdgeInsertID;
325    /// Remove edge by given edge-id or start and end node-id.
326    ///
327    /// # Panics
328    ///
329    /// - No such ability
330    ///
331    /// Not all graph engine supports insert edge.
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// use graph_theory::GraphEngine;
337    /// ```
338    fn remove_edge<E>(&mut self, edge: E)
339    where
340        E: Into<EdgeQuery>;
341
342    /// Remove invalid edges and nodes to improve the efficiency of subsequent queries.
343    fn shrink(&mut self) {}
344}