Graphity for Java 3.0.0
Graphity is a Java 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.
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 int IDs
0..nodeCount()-1, and its edges are numbered by edge index 0..edgeCount()-1,
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 static methods: of on a class named after the
algorithm, such as TopOrder.of and
Dominators.of; the methods of Components for the components; and
those of Graphs for the rest, such as
Graphs.findCycle.
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.biconnectivityOf, 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 Java program. These dependencies contain a cycle:
// The packages are the nodes 0..7, and uses[p] lists the packages that package p
// uses.
String[] names = {"app", "cli", "ui", "service", "model", "storage", "json", "util"};
int[][] uses = {{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.
var builder = new GraphBuilder();
builder.addNodes(uses.length);
for (int pkg = 0; pkg < uses.length; pkg++) {
builder.addOutEdges(pkg, uses[pkg]);
}
Graph dependencies = builder.build();
// Find a cycle.
IntList cycle = Graphs.findCycle(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 (TopOrder), and one with a level per node
(TopOrderAndLevels); whether a graph has a cycle, and one of its
cycles (Graphs.isDag,
Graphs.findCycle);
the tree, back, forward and cross edges of a depth-first search
(EdgeTypes, BackEdges). |
| What is reachable, and how far? | The nodes reachable from one or several nodes
(Graphs.reachableFrom); distances and shortest paths by breadth-first search
(BfsDistances); transitive closure and, for a DAG (directed acyclic
graph), transitive reduction
(Graphs.transitiveClosure,
Graphs.transitiveReduction). |
| 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.isTree,
Graphs.isPath and
Graphs.isBipartite. |
| Which node dominates which? | Dominators from one or several entries, and post-dominators on the transposed graph
(Dominators); the dominator tree
(Graphs.dominatorTree). |
Where are the loops, where do phi-nodes go, what controls what?
(graphity-controlflow) |
The loop nesting forest, irreducible loops included
(Loops); the blocks where SSA (static single
assignment) form places phi-nodes
(IteratedDominanceFrontier); dominance frontiers and
control dependence (ControlFlow). |
| 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.edgeMapping,
Graphs.transposedEdgeMapping and
Graphs.edgePartition for data on edges. |
| How do I store, load and compare graphs? | Graph.writeTo and
Graph.readFrom, as the two
arrays of the CSR layout; a 64-bit hash of the nodes and edges
(Graphs.topologyHash); the edges added and removed between two versions of a graph
(Graphs.diff). |
How do I look at a graph? (graphity-dot, graphity-mermaid) |
DotWriter and
MermaidWriter, with labels, attributes, shapes and
clusters from your own arrays;
Graphs.adjacencyListOf for a whole graph as text. |
| How do I write a search of my own? | The base classes 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 package, listed below, groups its entry points by topic, and the documentation of each class names the algorithm it uses.
Contracts
Every method states its contract: what it returns and throws, 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:
- No parameter, return value or element in the API is
nullunless its type is annotated@Nullable. - Graphs, mappings, partitions and the results of the algorithms are immutable and safe to share between threads. The builder, the traversers and the writers are mutable and not safe to share between threads.
- A node ID, an edge index or any other ID or position outside its range throws
IndexOutOfBoundsException; any other invalid argument throwsIllegalArgumentException.
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 - how to add Graphity to a project, a first complete program, and how it compares with other libraries.
- Repository: kaufco/graphity - the source code, the changelog and the issues.