Expand description
Graphity is a graph library which keeps graphs in a compact, immutable form and provides algorithms on top of it, such as strongly and weakly connected components, bridges and articulation points, topological order and levels, cycle detection and edge classification, breadth-first distances and reachability, lowest common ancestors, dominators, loop nesting and condensed graphs.
This is its Rust implementation, which follows the Java library of the same version type by type and function by function.
Every algorithm returns a typed, immutable result with follow-up queries, and runs without recursion, so deep graphs do not overflow the call stack. Data on nodes and edges stays in your own arrays, indexed by node ID or edge index, and every transformation tells you how to carry them along. The graph itself stores only structure: 4 bytes per node and per edge, in a compressed sparse row (CSR) layout, which is where speed and footprint come from.
§Where to start
The nodes of a [Graph] are the u32 IDs 0..node_count(), and its edges are numbered by edge
index 0..edge_count(), ordered by source and then by target. [GraphBuilder] builds a graph
from edges in any order. The algorithms are not methods of the graph but functions and types of
their own: of on a type named after the algorithm, such as [Dominators::of]; the functions
of the modules [components] for the components, [top_order] and [back_edges]; and those of
[graphs] for the rest, such as [graphs::find_cycle].
A [Graph] holds the out-nodes of every node. [BiAdjacentGraph::of] adds the in-nodes. The
algorithms that need them, such as [Dominators] and [components::biconnectivity_of], take a
[BiAdjacentGraph]: build it once and pass it to all of them.
The following example builds a graph of the dependencies between the packages of a small Rust program. These dependencies contain a cycle:
// The packages are the nodes 0 to 7, and uses[p] lists the packages that package p
// uses.
let names = [
"app", "cli", "ui", "service", "model", "storage", "json", "util",
];
let uses: [&[u32]; 8] = [
&[1, 2, 3],
&[7],
&[3, 4, 7],
&[4, 5],
&[5],
&[4, 6, 7],
&[7],
&[],
];
// Build the graph: an edge p -> q for every package q that p uses.
let mut builder = GraphBuilder::new();
builder.add_nodes(uses.len() as u32);
for (pkg, used) in uses.iter().enumerate() {
builder.add_out_edges(pkg as u32, used);
}
let dependencies = builder.build();
// Find a cycle.
let cycle = graphs::find_cycle(&dependencies);
// cycle: [4, 5] - model and storage use each other§Where to find what
| Question | Entry points |
|---|---|
| How do I build a graph? | [GraphBuilder] from edges in any order, or [Graph::of] from the two arrays of a CSR layout. |
| Which parts belong together? | [components]: strongly and weakly connected components, and the connected components of the graph read as undirected; bridges, articulation points and biconnected components; strong bridges and strong articulation points. |
| In which order, and where are the cycles? | A topological order ([top_order]), and one with a level per node ([TopOrderAndLevels]); whether a graph has a cycle, and one of its cycles ([graphs::is_dag], [graphs::find_cycle]); the tree, back, forward and cross edges of a depth-first search ([EdgeTypes], [back_edges]). |
| What is reachable, and how far? | The nodes reachable from one or several nodes ([graphs::reachable_from], [graphs::reachable_from_sources]); distances and shortest paths by breadth-first search ([BfsDistances]); transitive closure and, for a DAG (directed acyclic graph), transitive reduction ([graphs::transitive_closure], [graphs::transitive_reduction]). |
| Who is the ancestor of whom in a tree? | Parent, depth and LCA (lowest common ancestor) in a forest ([Ancestry]); the ancestor test in O(1) and the nodes of each subtree ([PreorderAncestry]); shape checks such as [graphs::is_tree], [graphs::is_path] and [graphs::is_bipartite]. |
| Which node dominates which? | Dominators from one or several entries, and post-dominators on the transposed graph ([Dominators]); the dominator tree ([graphs::dominator_tree]). |
Where are the loops, where do phi-nodes go, what controls what? (graphity-controlflow) | The loop nesting forest, irreducible loops included ([controlflow::Loops]); the blocks where SSA (static single assignment) form places phi-nodes ([controlflow::IteratedDominanceFrontier]); dominance frontiers and control dependence ([controlflow::control_flow]). |
| How do I condense, filter or renumber a graph? | The condensed graph of a partition of your choosing ([NodePartition::condense]); subgraphs and renumbered graphs ([graphs::remapped] with a [NodeMapping]); the transposed graph, without copying ([BiAdjacentGraph::transposed]). |
| How does my data follow a transformation? | [NodeMapping] for data on nodes; [graphs::edge_mapping], [graphs::transposed_edge_mapping] and [graphs::edge_partition] for data on edges. |
| How do I store, load and compare graphs? | [Graph::write_to] and [Graph::read_from], as the two arrays of the CSR layout; a 64-bit hash of the nodes and edges ([graphs::topology_hash]); the edges added and removed between two versions of a graph ([graphs::diff]). |
How do I look at a graph? (graphity-dot, graphity-mermaid) | [dot::DotWriter] and [mermaid::MermaidWriter], with labels, attributes, shapes and clusters from your own arrays; [graphs::adjacency_list_of] for a whole graph as text. |
| How do I write a search of my own? | The base types of depth-first and breadth-first searches, without recursion ([DfsTraverser], [DfsEdgeTraverser], [FrontierTraverser]); [csr] hands the arrays of a graph to loops of your own. |
The documentation of each crate, listed below, groups its entry points by topic, and the documentation of each type names the algorithm it uses.
§Contracts
Every function states its contract: what it returns, and when it panics or returns an error, whether a result is a view or a copy, in which order the results come where that matters, and its cost in time and memory. Three rules hold across the whole API:
- Where there is no result, a function returns
None; an array of the caller marks an entry for none with [NONE]. - Graphs, mappings, partitions and the results of the algorithms are immutable and safe to share
between threads. The builder and the traversers are mutable, and a change needs a
&mutborrow; the writers hold arbitrary closures and are neitherSendnorSync. - A node ID, an edge index or any other ID or position outside its range panics with an
index out of boundsmessage, or is an [ErrorKind::IndexOutOfBounds] error where a whole input is checked; any other invalid argument panics with aninvalid argumentmessage, or is an [ErrorKind::InvalidArgument] error. The module [error] describes which operations return errors.
§Further references
- Guide: kaufco.github.io/graphity-doc - one page per problem, from building a graph to control-flow analysis: the problem, the graph before and after, and tested code, with an index by API and a glossary.
- README: kaufco/graphity-rust - how to add Graphity to a project, and a first complete program.
- Repository: kaufco/graphity-rust - the source code and the changelog. It follows Graphity for Java, where development happens.
§Crates
This crate is all of Graphity in one dependency. It has no code of its own: it has the items of
graphity-core at its root and the other crates at [controlflow], [dot] and [mermaid].
| Crate | Path here | What it adds |
|---|---|---|
graphity-core | graphity_all | The graph, the builder, and every algorithm that applies to any directed graph, dominators included |
graphity-controlflow | graphity_all::controlflow | The analyses of control flow: loops, dominance frontiers, control dependence and the placement of phi-nodes |
graphity-dot | graphity_all::dot | A writer for DOT (the language of Graphviz) |
graphity-mermaid | graphity_all::mermaid | A writer for Mermaid flowcharts, which render in Markdown |
graphity-all | - | All of the above |
Re-exports§
pub use graphity_controlflow as controlflow;pub use graphity_dot as dot;pub use graphity_mermaid as mermaid;pub use graphity_core::*;