Release 0.2.4 #7

Merged
warrence merged 19 commits from release-0.2.4 into main 2026-07-31 09:38:27 +02:00
9 changed files with 624 additions and 20 deletions
Showing only changes of commit dd4e959554 - Show all commits
+1 -1
View File
@@ -15,7 +15,7 @@ For more information, see the [documentation](https://docs.rs/grapherity/latest/
## Example ## Example
``` ```rust
// Brings commonly used traits into scope. // Brings commonly used traits into scope.
use grapherity::prelude::*; use grapherity::prelude::*;
use grapherity::models::Graph; use grapherity::models::Graph;
+446 -7
View File
@@ -1,3 +1,33 @@
//! Algorithms for graph topologies.
//!
//! # Dijkstra's algorithm
//!
//! [Dijkstra's algorithm] finds the shortest distances from a source vertex to all other vertices
//! in the graph. Note that for unweighted graphs it has worse time and space complexity than
//! [Breadth-first search](#breadth-first-search).
//!
//! Variants: [`dijkstra`], [`dijkstra_distances`], [`dijkstra_unweighted`],
//! [`dijkstra_distances_unweighted`].
//!
//! # Breadth-first search
//!
//! [Breadth-first search] traverses a graph topology, exploring all neighboring vertices first
//! before descending further into their neighborhoods.
//!
//! Variants: [`bfs`], [`bfs_distances`], [`bfs_find`], [`bfs_find_where`].
//!
//! # Depth-first search
//!
//! [Depth-first search] traverses a graph topology, exploring each branch path as far as possible
//! first before backtracking and exploring other branches.
//!
//! Variants: [`dfs`], [`dfs_visited`], [`dfs_find`], [`dfs_find_where`], [`dfs_find_path`],
//! [`dfs_find_path_where`].
//!
//! [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search
//! [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
//! [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::{BinaryHeap, VecDeque}; use std::collections::{BinaryHeap, VecDeque};
@@ -22,12 +52,45 @@ impl<V: Eq> Ord for DistanceOrderedVertex<V> {
} }
} }
/// Return data type for [`dijkstra`] and [`dijkstra_unweighted`].
pub struct DijkstraResult<V: Copy> { pub struct DijkstraResult<V: Copy> {
/// Vertex map of minimum distances from a given `source` vertex.
pub distances: VertexMap<V, Option<u32>>, pub distances: VertexMap<V, Option<u32>>,
/// Vertex map of predecessors on some shortest path from a given `source` vertex.
pub predecessors: VertexMap<V, Option<V>>, pub predecessors: VertexMap<V, Option<V>>,
} }
// TODO: Generalize the return type of the weight function. // TODO: Generalize the return type of the weight function.
/// [Dijkstra's algorithm] with custom edge weights, returns minimum distances and predecessors.
///
/// Calculates the shortest paths from `source` to all vertices in `graph` with edge weights given
/// by `weight` function. Returns the distances from `source` to each vertex, and the predecessors
/// of each vertex on some shortest path from `source` to that vertex. Returns `None` for any vertex
/// not connected to `source`.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dijkstra;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// let e = graph.add_edge(source, target);
/// let mut weights = graph.edge_map(1);
/// weights[e] = 5;
///
/// let result = dijkstra(&graph, source, |e| weights[e]);
/// assert_eq!(result.distances[target], Some(5));
/// assert_eq!(result.predecessors[target], Some(source));
/// ```
///
/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
pub fn dijkstra<G, W>(graph: &G, source: G::Vertex, weight: W) -> DijkstraResult<G::Vertex> pub fn dijkstra<G, W>(graph: &G, source: G::Vertex, weight: W) -> DijkstraResult<G::Vertex>
where where
G: GraphTopology, G: GraphTopology,
@@ -43,13 +106,34 @@ where
} }
} }
pub fn dijkstra_unweighted<G>(graph: &G, source: G::Vertex) -> DijkstraResult<G::Vertex> /// [Dijkstra's algorithm] with custom edge weights, returns minimum distances.
where ///
G: GraphTopology, /// Calculates the shortest paths from `source` to all vertices in `graph` with edge weights given
{ /// by `weight` function. Returns the distances from `source` to each vertex. Returns `None` for any
dijkstra(graph, source, |_| 1) /// vertex not connected to `source`.
} ///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dijkstra_distances;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// let e = graph.add_edge(source, target);
/// let mut weights = graph.edge_map(1);
/// weights[e] = 5;
///
/// let distances = dijkstra_distances(&graph, source, |e| weights[e]);
/// assert_eq!(distances[target], Some(5));
/// ```
///
/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
pub fn dijkstra_distances<G, W>( pub fn dijkstra_distances<G, W>(
graph: &G, graph: &G,
source: G::Vertex, source: G::Vertex,
@@ -62,6 +146,70 @@ where
dijkstra_impl(graph, source, weight, |_, _| {}) dijkstra_impl(graph, source, weight, |_, _| {})
} }
/// [Dijkstra's algorithm] with unit edge weights, returns minimum distances and predecessors.
///
/// Calculates the shortest paths from `source` to all vertices in an unweighted `graph`. Returns
/// the distances from `source` to each vertex, and the predecessors of each vertex on some shortest
/// path from `source` to that vertex. Returns `None` for any vertex not connected to `source`.
///
/// Prefer [`bfs`] for unweighted graphs, it has better time and space complexity.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dijkstra_unweighted;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// let result = dijkstra_unweighted(&graph, source);
/// assert_eq!(result.distances[target], Some(1));
/// assert_eq!(result.predecessors[target], Some(source));
/// ```
///
/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
pub fn dijkstra_unweighted<G>(graph: &G, source: G::Vertex) -> DijkstraResult<G::Vertex>
where
G: GraphTopology,
{
dijkstra(graph, source, |_| 1)
}
/// [Dijkstra's algorithm] with unit edge weights, returns minimum distances.
///
/// Calculates the shortest paths from `source` to all vertices in an unweighted `graph`. Returns
/// the distances from `source` to each vertex. Returns `None` for any vertex not connected to
/// `source`.
///
/// Prefer [`bfs_distances`] for unweighted graphs, it has better time and space complexity.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dijkstra_distances_unweighted;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// let distances = dijkstra_distances_unweighted(&graph, source);
/// assert_eq!(distances[target], Some(1));
/// ```
///
/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
pub fn dijkstra_distances_unweighted<G>( pub fn dijkstra_distances_unweighted<G>(
graph: &G, graph: &G,
source: G::Vertex, source: G::Vertex,
@@ -112,11 +260,44 @@ where
distances distances
} }
/// Return data type for [`bfs`].
pub struct BfsResult<V: Copy> { pub struct BfsResult<V: Copy> {
/// Vertex map of minimum distances from a given `source` vertex.
pub distances: VertexMap<V, Option<u32>>, pub distances: VertexMap<V, Option<u32>>,
/// Vertex map of predecessors on some shortest path from a given `source` vertex.
pub predecessors: VertexMap<V, Option<V>>, pub predecessors: VertexMap<V, Option<V>>,
} }
/// [Breadth-first search] traversal from `source`, returns distances and predecessors.
///
/// Traverses vertices in `graph` starting from `source`, exploring all neighbors before descending
/// further. Returns the distances from `source` to each vertex, and the predecessors of each vertex
/// on some shortest path from `source` to that vertex. Returns `None` for any vertex not connected
/// to `source`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::bfs;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// let result = bfs(&graph, source);
/// assert_eq!(result.distances[target], Some(1));
/// assert_eq!(result.predecessors[target], Some(source));
/// ```
///
/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search
pub fn bfs<G>(graph: &G, source: G::Vertex) -> BfsResult<G::Vertex> pub fn bfs<G>(graph: &G, source: G::Vertex) -> BfsResult<G::Vertex>
where where
G: GraphTopology, G: GraphTopology,
@@ -132,6 +313,34 @@ where
} }
} }
/// [Breadth-first search] traversal from `source`, returns distances.
///
/// Traverses vertices in `graph` starting from `source`, exploring all neighbors before descending
/// further. Returns the distances from `source` to each vertex. Returns `None` for any vertex not
/// connected to `source`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::bfs_distances;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// let distances = bfs_distances(&graph, source);
/// assert_eq!(distances[target], Some(1));
/// ```
///
/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search
pub fn bfs_distances<G>(graph: &G, source: G::Vertex) -> VertexMap<G::Vertex, Option<u32>> pub fn bfs_distances<G>(graph: &G, source: G::Vertex) -> VertexMap<G::Vertex, Option<u32>>
where where
G: GraphTopology, G: GraphTopology,
@@ -139,6 +348,33 @@ where
bfs_impl(graph, source, |_, _| true).distances bfs_impl(graph, source, |_, _| true).distances
} }
/// [Breadth-first search] from `source` for `target`, returns the distance.
///
/// Traverses vertices in `graph` starting from `source` until `target` is found, exploring all
/// neighbors before descending further. Returns the minimum distance from `source` to `target` if
/// `target` is a valid vertex of `graph` connected to `source`, or `None` otherwise.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::bfs_find;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// assert_eq!(bfs_find(&graph, source, target), Some(1));
/// ```
///
/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search
pub fn bfs_find<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> Option<u32> pub fn bfs_find<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> Option<u32>
where where
G: GraphTopology, G: GraphTopology,
@@ -146,6 +382,35 @@ where
bfs_find_where(graph, source, |v| v == target).map(|(_, distance)| distance) bfs_find_where(graph, source, |v| v == target).map(|(_, distance)| distance)
} }
/// [Breadth-first search] from `source` for a vertex matching `predicate`, returns the vertex and
/// its distance.
///
/// Traverses vertices in `graph` starting from `source` until a vertex satisfying `predicate` is
/// found, exploring all neighbors before descending further. Returns the first vertex satisfying
/// `predicate` and its minimum distance from `source`, or `None` if no such vertex is connected to
/// `source`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::bfs_find_where;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// assert_eq!(bfs_find_where(&graph, source, |v| v == target), Some((target, 1)));
/// ```
///
/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search
pub fn bfs_find_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<(G::Vertex, u32)> pub fn bfs_find_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<(G::Vertex, u32)>
where where
G: GraphTopology, G: GraphTopology,
@@ -194,11 +459,44 @@ where
} }
} }
/// Return data type for [`dfs`].
pub struct DfsResult<V: Copy> { pub struct DfsResult<V: Copy> {
/// Vertex map indicating which vertices were visited during the search.
pub visited: VertexMap<V, bool>, pub visited: VertexMap<V, bool>,
/// Vertex map of predecessors on the DFS tree path from a given `source` vertex.
pub predecessors: VertexMap<V, Option<V>>, pub predecessors: VertexMap<V, Option<V>>,
} }
/// [Depth-first search] traversal from `source`, returns visited vertices and predecessors.
///
/// Traverses vertices in `graph` starting from `source`, exploring each branch as far as possible
/// before backtracking. Returns for each vertex whether it was visited, and the predecessors of
/// each vertex on the DFS tree path from `source` to that vertex. Any vertex not connected to
/// `source` is marked unvisited and has no predecessor.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dfs;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// let result = dfs(&graph, source);
/// assert!(result.visited[target]);
/// assert_eq!(result.predecessors[target], Some(source));
/// ```
///
/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
pub fn dfs<G>(graph: &G, source: G::Vertex) -> DfsResult<G::Vertex> pub fn dfs<G>(graph: &G, source: G::Vertex) -> DfsResult<G::Vertex>
where where
G: GraphTopology, G: GraphTopology,
@@ -214,6 +512,34 @@ where
} }
} }
/// [Depth-first search] traversal from `source`, returns visited vertices.
///
/// Traverses vertices in `graph` starting from `source`, exploring each branch as far as possible
/// before backtracking. Returns a map indicating which vertices were visited, i.e. which vertices
/// are connected to `source`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dfs_visited;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// let visited = dfs_visited(&graph, source);
/// assert!(visited[target]);
/// ```
///
/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
pub fn dfs_visited<G>(graph: &G, source: G::Vertex) -> VertexMap<G::Vertex, bool> pub fn dfs_visited<G>(graph: &G, source: G::Vertex) -> VertexMap<G::Vertex, bool>
where where
G: GraphTopology, G: GraphTopology,
@@ -221,6 +547,33 @@ where
dfs_impl(graph, source, |_, _| true).visited dfs_impl(graph, source, |_, _| true).visited
} }
/// [Depth-first search] from `source` for `target`, returns whether it was found.
///
/// Traverses vertices in `graph` starting from `source` until `target` is found, exploring each
/// branch as far as possible before backtracking. Returns `true` if `target` is a valid vertex of
/// `graph` connected to `source`, or `false` otherwise.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dfs_find;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// assert!(dfs_find(&graph, source, target));
/// ```
///
/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
pub fn dfs_find<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> bool pub fn dfs_find<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> bool
where where
G: GraphTopology, G: GraphTopology,
@@ -228,6 +581,33 @@ where
dfs_find_where(graph, source, |v| v == target).is_some() dfs_find_where(graph, source, |v| v == target).is_some()
} }
/// [Depth-first search] from `source` for a vertex matching `predicate`, returns the vertex.
///
/// Traverses vertices in `graph` starting from `source` until a vertex satisfying `predicate` is
/// found, exploring each branch as far as possible before backtracking. Returns the first vertex
/// satisfying `predicate`, or `None` if no such vertex is connected to `source`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dfs_find_where;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// graph.add_edge(source, target);
///
/// assert_eq!(dfs_find_where(&graph, source, |v| v == target), Some(target));
/// ```
///
/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
pub fn dfs_find_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<G::Vertex> pub fn dfs_find_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<G::Vertex>
where where
G: GraphTopology, G: GraphTopology,
@@ -275,6 +655,35 @@ where
} }
} }
/// [Depth-first search] from `source` for `target`, returns the path as a sequence of edges.
///
/// Traverses vertices in `graph` starting from `source` until `target` is found, exploring each
/// branch as far as possible before backtracking. Returns some path from `source` to `target` as a
/// sequence of edges in traversal order if `target` is a valid vertex of `graph` connected to
/// `source`, or `None` otherwise. The returned path is empty if and only if `source` equals
/// `target`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dfs_find_path;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// let e = graph.add_edge(source, target);
///
/// assert_eq!(dfs_find_path(&graph, source, target), Some(vec![e]));
/// ```
///
/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
pub fn dfs_find_path<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> Option<Vec<G::Edge>> pub fn dfs_find_path<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> Option<Vec<G::Edge>>
where where
G: GraphTopology, G: GraphTopology,
@@ -282,6 +691,36 @@ where
dfs_find_path_where(graph, source, |v| v == target) dfs_find_path_where(graph, source, |v| v == target)
} }
/// [Depth-first search] from `source` for a vertex matching `predicate`, returns the path as a
/// sequence of edges.
///
/// Traverses vertices in `graph` starting from `source` until a vertex satisfying `predicate` is
/// found, exploring each branch as far as possible before backtracking. Returns some path from
/// `source` to the first vertex satisfying `predicate` as a sequence of edges in traversal order,
/// or `None` if no such vertex is connected to `source`. The returned path is empty if and only if
/// `source` satisfies `predicate`.
///
/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*.
///
/// # Panics
///
/// Panics if `source` is not a valid vertex of `graph`.
///
/// # Examples
///
/// ```
/// # use grapherity::prelude::*;
/// # use grapherity::algorithms::dfs_find_path_where;
/// # use grapherity::models::Graph;
/// let mut graph = Graph::new();
/// let source = graph.add_vertex();
/// let target = graph.add_vertex();
/// let e = graph.add_edge(source, target);
///
/// assert_eq!(dfs_find_path_where(&graph, source, |v| v == target), Some(vec![e]));
/// ```
///
/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
pub fn dfs_find_path_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<Vec<G::Edge>> pub fn dfs_find_path_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<Vec<G::Edge>>
where where
G: GraphTopology, G: GraphTopology,
+1
View File
@@ -132,6 +132,7 @@ pub mod maps;
pub mod models; pub mod models;
pub mod traits; pub mod traits;
/// Convenience re-exports of graph topology traits for common use.
pub mod prelude { pub mod prelude {
pub use crate::traits::{GraphTopology, GraphTopologyDeletion}; pub use crate::traits::{GraphTopology, GraphTopologyDeletion};
} }
+41 -2
View File
@@ -1,24 +1,45 @@
//! Provides maps to associate custom data to graph vertices and edges.
//!
//! [`VertexMap`] and [`EdgeMap`] provide copy-on-write, [`Vec`]-backed maps to associate data to
//! all vertices or all edges in a graph, respectively.
use std::ops::{Index, IndexMut}; use std::ops::{Index, IndexMut};
use crate::traits::GraphTopology; use crate::traits::GraphTopology;
/// A map to associate custom data to graph vertices.
///
/// This map uses raw entity indices to associate homogenous custom data of type `T` to graph
/// vertices. The implementation uses a [`Vec`], allocating contiguous slots for the data, which
/// means that the provided index conversion function should map vertices to contiguous indices, or
/// indices with relatively few gaps.
///
/// Data allocation happens as copy-on-write, i.e. the backing [`Vec`] is only resized if a value
/// beyond current capacity is written, but the `default` value can transparently be read. No bound
/// or validity checks are performed by the map on the provided vertex handles.
///
/// Use [`GraphTopology::vertex_map`] to obtain a `VertexMap`.
pub struct VertexMap<V: Copy, T: Clone> { pub struct VertexMap<V: Copy, T: Clone> {
inner: EntityMap<V, T>, inner: EntityMap<V, T>,
} }
impl<V: Copy, T: Clone> VertexMap<V, T> { impl<V: Copy, T: Clone> VertexMap<V, T> {
/// Creates a new map with the given `default` value, an index conversion function `to_index`,
/// and an initial `capacity`.
pub fn new(default: T, to_index: fn(V) -> usize, capacity: usize) -> Self { pub fn new(default: T, to_index: fn(V) -> usize, capacity: usize) -> Self {
Self { Self {
inner: EntityMap::new(default, to_index, capacity), inner: EntityMap::new(default, to_index, capacity),
} }
} }
// Reads beyond 'capacity' are valid and return the default value. /// Returns the total number of data entries the map can write without reallocating. Reads
/// beyond `capacity` are valid and return the default value.
pub fn capacity(&self) -> usize { pub fn capacity(&self) -> usize {
self.inner.capacity() self.inner.capacity()
} }
#[deprecated(since = "0.2.2", note = "use 'capacity' instead")] #[deprecated(since = "0.2.2", note = "use 'capacity' instead")]
#[allow(missing_docs)]
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.capacity() self.capacity()
} }
@@ -33,6 +54,7 @@ impl<V: Copy, T: Clone> VertexMap<V, T> {
} }
#[deprecated(since = "0.2.4", note = "use 'extend(graph.vertex_capacity())' instead")] #[deprecated(since = "0.2.4", note = "use 'extend(graph.vertex_capacity())' instead")]
#[allow(missing_docs)]
pub fn sync<G: GraphTopology<Vertex = V>>(&mut self, graph: &G) { pub fn sync<G: GraphTopology<Vertex = V>>(&mut self, graph: &G) {
self.inner.extend(graph.vertex_capacity()); self.inner.extend(graph.vertex_capacity());
} }
@@ -52,23 +74,39 @@ impl<V: Copy, T: Clone> IndexMut<V> for VertexMap<V, T> {
} }
} }
/// A map to associate custom data to graph edges.
///
/// This map uses raw entity indices to associate homogenous custom data of type `T` to graph edges.
/// The implementation uses a [`Vec`], allocating contiguous slots for the data, which means that
/// the provided index conversion function should map edges to contiguous indices, or indices with
/// relatively few gaps.
///
/// Data allocation happens as copy-on-write, i.e. the backing [`Vec`] is only resized if a value
/// beyond current capacity is written, but the `default` value can transparently be read. No bound
/// or validity checks are performed by the map on the provided edge handles.
///
/// Use [`GraphTopology::edge_map`] to obtain an `EdgeMap`.
pub struct EdgeMap<E: Copy, T: Clone> { pub struct EdgeMap<E: Copy, T: Clone> {
inner: EntityMap<E, T>, inner: EntityMap<E, T>,
} }
impl<E: Copy, T: Clone> EdgeMap<E, T> { impl<E: Copy, T: Clone> EdgeMap<E, T> {
/// Creates a new map with the given `default` value, an index conversion function `to_index`,
/// and an initial `capacity`.
pub fn new(default: T, to_index: fn(E) -> usize, capacity: usize) -> Self { pub fn new(default: T, to_index: fn(E) -> usize, capacity: usize) -> Self {
Self { Self {
inner: EntityMap::new(default, to_index, capacity), inner: EntityMap::new(default, to_index, capacity),
} }
} }
// Reads beyond 'capacity' are valid and return the default value. /// Returns the total number of data entries the map can write without reallocating. Reads
/// beyond `capacity` are valid and return the default value.
pub fn capacity(&self) -> usize { pub fn capacity(&self) -> usize {
self.inner.capacity() self.inner.capacity()
} }
#[deprecated(since = "0.2.2", note = "use 'capacity' instead")] #[deprecated(since = "0.2.2", note = "use 'capacity' instead")]
#[allow(missing_docs)]
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.capacity() self.capacity()
} }
@@ -83,6 +121,7 @@ impl<E: Copy, T: Clone> EdgeMap<E, T> {
} }
#[deprecated(since = "0.2.4", note = "use 'extend(graph.edge_capacity())' instead")] #[deprecated(since = "0.2.4", note = "use 'extend(graph.edge_capacity())' instead")]
#[allow(missing_docs)]
pub fn sync<G: GraphTopology<Edge = E>>(&mut self, graph: &G) { pub fn sync<G: GraphTopology<Edge = E>>(&mut self, graph: &G) {
self.inner.extend(graph.edge_capacity()); self.inner.extend(graph.edge_capacity());
} }
+2
View File
@@ -1,3 +1,5 @@
//! Concrete graph topology models.
pub mod append_graph; pub mod append_graph;
pub mod graph; pub mod graph;
+51 -2
View File
@@ -1,13 +1,26 @@
//! [`AppendGraph`], an undirected graph topology supporting addition only.
use crate::maps::{EdgeMap, VertexMap}; use crate::maps::{EdgeMap, VertexMap};
use crate::traits::{GraphTopology, IncidenceCursor}; use crate::traits::{GraphTopology, IncidenceCursor};
/// An opaque handle identifying a vertex in an [`AppendGraph`].
///
/// Handles are stable for the lifetime of the graph. Obtain via graph methods like
/// [`AppendGraph::add_vertex`] and [`AppendGraph::vertices`].
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Vertex(usize); pub struct Vertex(usize);
/// An opaque handle identifying an edge in an [`AppendGraph`].
///
/// Handles are stable for the lifetime of the graph. Obtain via graph methods like
/// [`AppendGraph::add_edge`] and [`AppendGraph::edges`].
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Edge(usize); pub struct Edge(usize);
/// A [`VertexMap`] for [`AppendGraph`] vertices.
pub type AppendGraphVertexMap<T> = VertexMap<Vertex, T>; pub type AppendGraphVertexMap<T> = VertexMap<Vertex, T>;
/// An [`EdgeMap`] for [`AppendGraph`] edges.
pub type AppendGraphEdgeMap<T> = EdgeMap<Edge, T>; pub type AppendGraphEdgeMap<T> = EdgeMap<Edge, T>;
impl Edge { impl Edge {
@@ -16,6 +29,7 @@ impl Edge {
} }
} }
// TODO: Check if VertexIncidenceHeader and IncidenceEntry can be made smaller. Currently they both take 24 bytes (on 64bit), see https://stackoverflow.com/a/79653173
struct VertexIncidenceHeader { struct VertexIncidenceHeader {
incidence_count: usize, incidence_count: usize,
first_incidence: Option<Edge>, first_incidence: Option<Edge>,
@@ -27,6 +41,9 @@ struct IncidenceEntry {
adjacent: Vertex, adjacent: Vertex,
} }
/// A resumable cursor over the incidences of a single vertex in an [`AppendGraph`].
///
/// Obtain via [`AppendGraph::incidence_cursor`]. See [`IncidenceCursor`] on usage guidance.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct AppendGraphIncidenceCursor { pub struct AppendGraphIncidenceCursor {
incidence: Option<Edge>, incidence: Option<Edge>,
@@ -40,12 +57,44 @@ impl IncidenceCursor<AppendGraph> for AppendGraphIncidenceCursor {
} }
} }
/// An undirected graph that supports adding vertices and edges, but not deleting them.
///
/// `AppendGraph` is optimised for workloads that incrementally build a graph and query it
/// repeatedly. [`Vertex`] and [`Edge`] handles are never invalidated. Use [`Graph`] instead if you
/// need to remove vertices or edges.
///
/// Incidences are stored as interleaved adjacency lists in a single flat [`Vec`]. In general,
/// vertex neighborhood traversals result in scattered index jumps.
///
/// # Examples
///
/// ```
/// use grapherity::prelude::*;
/// use grapherity::models::AppendGraph;
///
/// let mut graph = AppendGraph::new();
/// let v1 = graph.add_vertex();
/// let v2 = graph.add_vertex();
/// let e = graph.add_edge(v1, v2);
/// assert!(graph.are_adjacent(v1, v2));
/// ```
///
/// # Time and space complexity
///
/// Both [`add_vertex`] and [`add_edge`] run in amortised *O(1)* time. [`degree`] runs in *O(1)*
/// time since vertex degrees are stored. Space complexity is *O(|V| + |E|)*.
///
/// [`add_vertex`]: Self::add_vertex
/// [`add_edge`]: Self::add_edge
/// [`degree`]: Self::degree
/// [`Graph`]: crate::models::Graph
pub struct AppendGraph { pub struct AppendGraph {
vertices: Vec<VertexIncidenceHeader>, vertices: Vec<VertexIncidenceHeader>,
incidences: Vec<IncidenceEntry>, incidences: Vec<IncidenceEntry>,
} }
impl AppendGraph { impl AppendGraph {
/// Creates an empty graph instance with no vertices or edges.
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
vertices: vec![], vertices: vec![],
@@ -53,8 +102,8 @@ impl AppendGraph {
} }
} }
// Adds a single incidence of an edge, which is composed by two such incidences, to the /// Adds a single incidence of an edge, which is composed by two such incidences, to the
// incidences vector. /// incidences vector.
fn add_incidence(&mut self, v1: Vertex, v2: Vertex) { fn add_incidence(&mut self, v1: Vertex, v2: Vertex) {
self.incidences.push(IncidenceEntry { self.incidences.push(IncidenceEntry {
next: self.vertices[v1.0].first_incidence.take(), next: self.vertices[v1.0].first_incidence.take(),
+76 -7
View File
@@ -1,12 +1,26 @@
//! [`Graph`], an undirected graph topology supporting addition and deletion.
use typed_generational_arena::{Arena, Index}; use typed_generational_arena::{Arena, Index};
use crate::maps::{EdgeMap, VertexMap}; use crate::maps::{EdgeMap, VertexMap};
use crate::traits::{GraphTopology, GraphTopologyDeletion, IncidenceCursor}; use crate::traits::{GraphTopology, GraphTopologyDeletion, IncidenceCursor};
/// An opaque handle identifying a vertex in a [`Graph`].
///
/// Handles remain valid until the vertex is explicitly deleted. Obtain via graph methods like
/// [`Graph::add_vertex`] and [`Graph::vertices`].
pub type Vertex = Index<VertexIncidenceHeader, usize, usize>; pub type Vertex = Index<VertexIncidenceHeader, usize, usize>;
/// An opaque handle identifying an edge in a [`Graph`].
///
/// Handles remain valid until the edge is explicitly deleted, or one of its endpoint vertices is
/// deleted. Obtain via graph methods like [`Graph::add_edge`] and [`Graph::edges`].
pub type Edge = Index<IncidenceEntry, usize, usize>; pub type Edge = Index<IncidenceEntry, usize, usize>;
/// A [`VertexMap`] for [`Graph`] vertices.
pub type GraphVertexMap<T> = VertexMap<Vertex, T>; pub type GraphVertexMap<T> = VertexMap<Vertex, T>;
/// An [`EdgeMap`] for [`Graph`] edges.
pub type GraphEdgeMap<T> = EdgeMap<Edge, T>; pub type GraphEdgeMap<T> = EdgeMap<Edge, T>;
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
@@ -15,11 +29,18 @@ struct VertexSlot(usize);
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
struct IncidenceSlot(usize); struct IncidenceSlot(usize);
// TODO: Check if VertexIncidenceHeader and IncidenceEntry can be made smaller. Currently they both take 24 bytes (on 64bit), see https://stackoverflow.com/a/79653173
/// `pub` because [`Vertex`] references it as a type parameter of the underlying arena. Not
/// intended for direct external use.
#[doc(hidden)]
pub struct VertexIncidenceHeader { pub struct VertexIncidenceHeader {
incidence_count: usize, incidence_count: usize,
first_incidence: Option<IncidenceSlot>, first_incidence: Option<IncidenceSlot>,
} }
/// `pub` because [`Edge`] references it as a type parameter of the underlying arena. Not intended
/// for direct external use.
#[doc(hidden)]
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct IncidenceEntry { pub struct IncidenceEntry {
next: Option<IncidenceSlot>, next: Option<IncidenceSlot>,
@@ -36,6 +57,9 @@ impl IncidentEdgeCursor {
} }
} }
/// A resumable cursor over the incidences of a single vertex in a [`Graph`].
///
/// Obtain via [`Graph::incidence_cursor`]. See [`IncidenceCursor`] on usage guidance.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct GraphIncidenceCursor { pub struct GraphIncidenceCursor {
incidence: Option<IncidenceSlot>, incidence: Option<IncidenceSlot>,
@@ -52,6 +76,49 @@ impl IncidenceCursor<Graph> for GraphIncidenceCursor {
} }
} }
/// An undirected graph that supports adding vertices and edges, and deleting them.
///
/// `Graph` is suited for workloads that need to modify the graph structure over time, i.e. adding
/// amd removing vertices and edges. [`Vertex`] and [`Edge`] handles remain valid until the vertex
/// or edge they identify is explicitly deleted. Use [`AppendGraph`] instead if you only need to
/// append vertices and edges.
///
/// Incidences are stored as interleaved adjacency lists in a generational [`Arena`]. In general,
/// vertex neighborhood traversals result in scattered memory accesses.
///
/// # Examples
///
/// ```
/// use grapherity::prelude::*;
/// use grapherity::models::Graph;
///
/// let mut graph = Graph::new();
/// let v1 = graph.add_vertex();
/// let v2 = graph.add_vertex();
/// let _e = graph.add_edge(v1, v2);
/// assert!(graph.are_adjacent(v1, v2));
/// graph.delete_vertex(v1);
/// assert_eq!(graph.degree(v2), 0);
/// ```
///
/// # Time and space complexity
///
/// Both [`add_vertex`] and [`add_edge`] run in amortised *O(1)* time. [`degree`] runs in *O(1)*
/// time since vertex degrees are stored. [`delete_vertex`] runs in *O(degree(v))* time.
/// [`delete_edge`] runs in *O(degree(u) + degree(v))* time, where *u* and *v* are the edge's
/// endpoints.
///
/// Space complexity is *O(|V| + |E|)*, but freed slots for vertices and edges are not compacted and
/// their allocation is never reclaimed. Capacity only grows. If additions and deletions are both
/// planned, performing deletions first allows freed slots to be reused by subsequent additions,
/// potentially avoiding reallocation.
///
/// [`add_vertex`]: Self::add_vertex
/// [`add_edge`]: Self::add_edge
/// [`degree`]: Self::degree
/// [`delete_vertex`]: Self::delete_vertex
/// [`delete_edge`]: Self::delete_edge
/// [`AppendGraph`]: crate::models::AppendGraph
pub struct Graph { pub struct Graph {
// TODO: Arena index and generation types could be externalized to Graph. // TODO: Arena index and generation types could be externalized to Graph.
vertices: Arena<VertexIncidenceHeader, usize, usize>, vertices: Arena<VertexIncidenceHeader, usize, usize>,
@@ -59,6 +126,7 @@ pub struct Graph {
} }
impl Graph { impl Graph {
/// Creates an empty graph instance with no vertices or edges.
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
vertices: Arena::new(), vertices: Arena::new(),
@@ -66,8 +134,8 @@ impl Graph {
} }
} }
// Adds a single incidence of an edge, which is composed by two such incidences, to the /// Adds a single incidence of an edge, which is composed by two such incidences, to the
// incidences arena, and returns its index. /// incidences arena, and returns its index.
fn add_incidence(&mut self, v1: Vertex, v2: Vertex) -> Edge { fn add_incidence(&mut self, v1: Vertex, v2: Vertex) -> Edge {
let edge = self.incidences.insert(IncidenceEntry { let edge = self.incidences.insert(IncidenceEntry {
next: self.vertices[v1].first_incidence.take(), next: self.vertices[v1].first_incidence.take(),
@@ -94,8 +162,9 @@ impl Graph {
(f, e_entry, f_entry) (f, e_entry, f_entry)
} }
// Updates the source vertex incidence list after the incidence "e" was deleted from the /// Updates the `source` vertex incidence list after the incidence `e` was deleted from the
// incidence arena. "next" is the next incidence after "e" in the source vertex incidence list. /// incidence arena. `next` is the next incidence after `e` in the `source` vertex incidence
/// list.
fn update_incidence_list( fn update_incidence_list(
&mut self, &mut self,
e: Edge, e: Edge,
@@ -275,10 +344,10 @@ impl GraphTopologyDeletion for Graph {
} }
} }
// The incidence entries are removed before patching the linked lists. This is safe because
// update_incidence_list() searches by raw slot index (IncidenceSlot.0) and only dereferences
// the predecessor, never the removed entries themselves.
fn delete_edge(&mut self, e: Self::Edge) { fn delete_edge(&mut self, e: Self::Edge) {
// The incidence entries are removed before patching the linked lists. This is safe because
// `update_incidence_list` searches by raw slot index (IncidenceSlot.0) and only
// dereferences the predecessor, never the removed entries themselves.
let (f, e_entry, f_entry) = self.remove_incidence_pair(e); let (f, e_entry, f_entry) = self.remove_incidence_pair(e);
if e_entry.adjacent != f_entry.adjacent { if e_entry.adjacent != f_entry.adjacent {
self.update_incidence_list(e, f_entry.adjacent, e_entry.next, false); self.update_incidence_list(e, f_entry.adjacent, e_entry.next, false);
+2
View File
@@ -1,3 +1,5 @@
//! Test fixture and test macros for graph topology and algorithm implementations.
pub(crate) mod bfs_testing; pub(crate) mod bfs_testing;
pub(crate) mod dfs_testing; pub(crate) mod dfs_testing;
pub(crate) mod dijkstra_testing; pub(crate) mod dijkstra_testing;
+4 -1
View File
@@ -1,14 +1,17 @@
//! Core traits for undirected graph topologies.
use crate::maps::{EdgeMap, VertexMap}; use crate::maps::{EdgeMap, VertexMap};
// TODO: Add functions to reserve memory for vertices and edges. // TODO: Add functions to reserve memory for vertices and edges.
// TODO: Split out GraphTopologyAddition trait. // TODO: Split out GraphTopologyAddition trait.
// TODO: Introduce an Incidence struct.
/// A trait representing an undirected graph topology. /// A trait representing an undirected graph topology.
/// ///
/// An undirected graph is a set of vertices and undirected edges, where each edge connects either /// An undirected graph is a set of vertices and undirected edges, where each edge connects either
/// exactly two vertices or one vertex with itself (loop edge). This trait provides methods for /// exactly two vertices or one vertex with itself (loop edge). This trait provides methods for
/// querying a graph topology, iterating over vertices and edges, and adding new vertices and edges. /// querying a graph topology, iterating over vertices and edges, and adding new vertices and edges.
/// ///
/// # Vertices and Edges /// # Vertices and edges
/// ///
/// Vertices and edges are identified by opaque handles ([`Vertex`] and [`Edge`]) that implement /// Vertices and edges are identified by opaque handles ([`Vertex`] and [`Edge`]) that implement
/// [`Copy`] and [`Eq`]. Handles remain valid for the lifetime of the graph unless the graph also /// [`Copy`] and [`Eq`]. Handles remain valid for the lifetime of the graph unless the graph also