Table of Contents

Class Graphs

Namespace
Graphity
Assembly
Graphity.Core.dll

Operations on graphs, in five families: derived graphs, edge mappings, node sets, shape checks, and a graph as text, hash or diff.

public static class Graphs
Inheritance
Graphs
Inherited Members

Remarks

Data on nodes and edges follows a renumbered, transposed or condensed graph through the mappings. Like the node mappings that the factories of NodeMapping make, the edge mappings point from new to old: from the derived graph to the original one. Their Gather methods carry an array of data over to the derived graph. An EdgePartition groups the edges of the original by the condensed edge they became, and its Reduce methods combine their data.

A shape check without a prefix reads the graph as directed. One prefixed Undirected reads it as undirected, as CcsOf(Graph) does: each edge connects its source and target both ways, and the edges a -> b and b -> a count as one. IsBipartite(Graph) and IsWeaklyConnected(Graph) read it so too, without the prefix, because neither property has a directed reading. The checks of the undirected reading use union-find, whose cost grows with alpha(NodeCount). The inverse Ackermann function alpha is below 5 for any graph. No shape check needs memory in proportion to the edge count.

Every result is computed anew on every call, not cached, and shares no array with the arguments: keep a result to use it more than once. No method recurses, so deep graphs do not overflow the call stack.

Methods

AdjacencyListOf(Graph)

Returns the whole graph as text: one line per node with its out-nodes, in ascending order.

public static string AdjacencyListOf(Graph graph)

Parameters

graph Graph

The graph to list.

Returns

string

The adjacency list, one line per node.

Examples

For the control flow of a method with a loop:

string text = Graphs.AdjacencyListOf(cfg);
// 0 -> [1]
// 1 -> [2, 5]
// 2 -> [3, 4]
// 3 -> [4]
// 4 -> [1]
// 5 -> []

Remarks

Each line ends with a line feed. Unlike ToString(), which is cut short for large graphs, this lists every node and edge; a BiAdjacentGraph lists its out-nodes. The text of a graph with more than about 100 million edges is longer than a string can be (2^30 - 33 characters) and ends in an OutOfMemoryException.

Time: O(NodeCount + EdgeCount).
Memory: 2 bytes per character for the result; while it runs, about as much again.

Diff(Graph, Graph)

Returns the edges added and removed between before and after. Both are graphs over the same nodes.

public static GraphDiff Diff(Graph before, Graph after)

Parameters

before Graph

The older graph.

after Graph

The newer graph, with the same node count.

Returns

GraphDiff

The added and removed edges.

Remarks

Added edges come with their edge indices in after, removed edges with theirs in before. With these edge indices, the caller can look up data on the edges of either graph in arrays indexed by edge index. Both lists are in edge index order. An empty diff means that the graphs are equal.

Time: O(NodeCount + EdgeCount), with the edges of both graphs.
Memory: 12 bytes per added or removed edge for the result; while it runs, up to 18 bytes more per such edge.

Exceptions

ArgumentException

The node counts differ.

DominatorTree(Dominators)

Returns the dominator tree of dominators as a graph, with an edge d -> n for every node n whose immediate dominator is d.

public static Graph DominatorTree(Dominators dominators)

Parameters

dominators Dominators

The dominators of a graph.

Returns

Graph

The dominator tree.

Remarks

The result has the node IDs of the analyzed graph, and its edges point away from the roots of the tree, for a walk down the tree such as with a DfsTraverser. Its root nodes are the entries, the nodes that only the virtual root above several entries dominates, and the unreachable nodes. To ask whether one node dominates another, use Of(Dominators), which shares the immediate dominators instead of building this graph.

Time: O(NodeCount).
Memory: 4 bytes per node and per edge for the result.

EdgeMapping(Graph, Graph, NodeMapping)

Returns the edge mapping from newGraph to oldGraph that goes with the node mapping newToOld.

public static EdgeMapping EdgeMapping(Graph newGraph, Graph oldGraph, NodeMapping newToOld)

Parameters

newGraph Graph

The graph whose edges are mapped.

oldGraph Graph

The graph they are mapped to.

newToOld NodeMapping

The node of oldGraph for each node of newGraph, or -1.

Returns

EdgeMapping

The edge mapping.

Examples

Here, siteCount holds the number of call sites of each call by edge index of calls, and the subgraph loading from the example at Remapped(Graph, NodeMapping) takes these counts along:

int[] loadingSiteCount =
    Graphs.EdgeMapping(loading, calls, newToOld).Gather(siteCount);
// 1 for load -> parse and for load -> read, 2 for parse -> parse

Remarks

Edge s -> t of newGraph maps to the edge newToOld.Get(s) -> newToOld.Get(t) of oldGraph, or to -1 if oldGraph has no such edge or s or t maps to -1. For a graph from Remapped(oldGraph, newToOld), every edge has its counterpart, and the Gather methods of the result carry data on the edges over to the new graph. For the opposite direction, from the edges of oldGraph to those of newGraph, invert the result with Inverted(int). The transposed graph needs TransposedEdgeMapping(Graph) instead, as its edges run the other way.

Time: O(NodeCount + EdgeCount log maxOutDegree), with the node and edge count of newGraph and the out-degrees of oldGraph.
Memory: 4 bytes per edge of newGraph for the result.

Exceptions

ArgumentException

newToOld.IndexCount != newGraph.NodeCount.

ArgumentOutOfRangeException

A node of newGraph maps to an ID that is not a node of oldGraph.

EdgePartition(Graph, NodePartition)

Returns the edge partition that goes with the node partition partition, from the edges of the partitioned graph to the edges of condensedGraph.

public static EdgePartition EdgePartition(Graph condensedGraph, NodePartition partition)

Parameters

condensedGraph Graph

The graph that partition.Condense() returned.

partition NodePartition

The partition of the nodes.

Returns

EdgePartition

The edge partition, with a group per edge of condensedGraph.

Examples

Here, byPackage groups the methods of a program by package. Its condensed graph packageCalls holds the calls between packages (see Of(Graph, ReadOnlySpan<int>, int)). byPackageCall tells which calls between methods are behind the call from service to model:

EdgePartition byPackageCall = Graphs.EdgePartition(packageCalls, byPackage);
int serviceToModel = packageCalls.EdgeIndexOf(service, model);
SortedIntView behind = byPackageCall.EdgesOf(serviceToModel);
// behind: [5, 7] - the calls load -> parse and save -> format

Remarks

The edges from group g to group h all map to the condensed edge g -> h, which is edge condensedGraph.EdgeIndexOf(g, h). EdgesOf(int) lists them, and the Reduce methods of the result combine their data. An edge inside a group, or from or to a node in no group, maps to -1. condensedGraph must be partition.Condense(); only its node count is checked.

Time: O(NodeCount + EdgeCount log maxOutDegree), with the node and edge count of the partitioned graph and the out-degrees of condensedGraph.
Memory: up to 12 bytes per edge of the partitioned graph for the result.

Exceptions

ArgumentException

condensedGraph.NodeCount is not partition.GroupCount.

FindCycle(Graph)

Returns the nodes of a cycle of graph in the order of its edges, or an empty list if graph is a DAG.

public static ImmutableArray<int> FindCycle(Graph graph)

Parameters

graph Graph

The graph to search.

Returns

ImmutableArray<int>

The nodes of the cycle, each once, or an empty list.

Examples

Here, the cycle in the dependencies between the packages of a program:

ImmutableArray<int> cycle = Graphs.FindCycle(dependencies);
// cycle: [4, 5] - model and storage, closed by the edge storage -> model

Remarks

The last node has an edge to the first, and a self-loop is a cycle of one node. The search goes depth-first, from each unvisited node in ascending order and through the out-nodes in ascending order, and returns the first cycle it closes: always the same one, but not necessarily the shortest. For a cycle inside a given SCC, search the subgraph of its nodes from Remapped(Graph, NodeMapping); the node mapping of the subgraph translates the result back.

Time: O(NodeCount + EdgeCount), stopping at the first cycle.
Memory: 4 bytes per node of the cycle for the result; while it runs, 2 bits per node and up to 8 x NodeCount bytes for the stack, which grows with the deepest path.

Exceptions

ArgumentException

A depth-first path is longer than 2^30 - 29 nodes.

IsBipartite(Graph)

Returns whether graph is bipartite: its nodes split into two sets such that every edge runs from one set to the other.

public static bool IsBipartite(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is bipartite.

Remarks

Reads the graph as undirected, so the direction of the edges does not matter. A self-loop makes the graph not bipartite, unlike the other checks of the undirected reading, which ignore self-loops. The empty graph is bipartite.

Time: O(NodeCount + EdgeCount x alpha(NodeCount)), stopping at the first cycle of odd length.
Memory: 10 x NodeCount bytes while it runs.

Exceptions

ArgumentException

graph has more than 2^30 - 29 nodes.

IsDag(Graph)

Returns whether graph is a DAG: a graph without cycles. A self-loop is a cycle.

public static bool IsDag(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph has no cycle.

Remarks

FindCycle(Graph) returns a cycle where this method finds one.

Time: O(NodeCount + EdgeCount), stopping at the first cycle.
Memory: 2 bits per node while it runs, and up to 8 x NodeCount bytes for the stack, which grows with the deepest path.

Exceptions

ArgumentException

A depth-first path is longer than 2^30 - 29 nodes.

IsForest(Graph)

Returns whether graph is a forest: a DAG in which every node has in-degree at most 1, so that the edges point away from the root nodes.

public static bool IsForest(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is a forest.

Remarks

The empty graph is a forest. For the undirected reading, see IsUndirectedForest(Graph).

Time: O(NodeCount + EdgeCount).
Memory: 8 x NodeCount bytes while it runs.

IsPath(Graph)

Returns whether graph is a path: a tree in which every node has out-degree at most 1.

public static bool IsPath(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is a path.

Remarks

The empty graph is a path.

Time: O(NodeCount + EdgeCount).
Memory: 8 x NodeCount bytes while it runs.

IsStronglyConnected(Graph)

Returns whether graph is strongly connected: every node reaches every other along the edges.

public static bool IsStronglyConnected(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if every node reaches every other.

Remarks

Answers without the partition of SccsOf(Graph). Uses Tarjan's algorithm, without recursion. It starts from node 0 and stops as soon as an SCC without node 0 is complete. Where the SCCs are already computed, IsStronglyConnected answers in O(1). The empty graph is strongly connected, and so is a single node. For the undirected reading, see IsWeaklyConnected(Graph).

Time: O(NodeCount + EdgeCount), stopping at the first SCC without node 0.
Memory: 8 x NodeCount bytes while it runs, and up to 8 x NodeCount bytes for the stack, which grows with the deepest path.

Exceptions

ArgumentException

A depth-first path is longer than 2^30 - 29 nodes.

IsTree(Graph)

Returns whether graph is a tree: a forest with at most one root node.

public static bool IsTree(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is a tree.

Remarks

The edges of a tree point away from its root. For a tree whose edges point toward the root, check the transposed graph, which is BiAdjacentGraph.Of(graph).Transposed(). For the undirected reading, see IsUndirectedTree(Graph). The empty graph is a tree.

Time: O(NodeCount + EdgeCount).
Memory: 8 x NodeCount bytes while it runs.

IsUndirectedForest(Graph)

Returns whether graph is a forest when read as undirected: without cycles.

public static bool IsUndirectedForest(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is a forest when read as undirected.

Remarks

Unlike for IsForest(Graph), the direction of the edges does not matter. The edges a -> b and b -> a count as one, so they make no cycle, and self-loops are ignored. The empty graph is a forest.

Time: O(NodeCount + EdgeCount x alpha(NodeCount)), plus O(log maxOutDegree) for each pair a -> b, b -> a; O(1) for more than 3 x NodeCount - 2 edges, too many for any forest.
Memory: 5 x NodeCount bytes while it runs.

IsUndirectedTree(Graph)

Returns whether graph is a tree when read as undirected: connected and without cycles.

public static bool IsUndirectedTree(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is a tree when read as undirected.

Remarks

Unlike for IsTree(Graph), the direction of the edges does not matter: edges toward the root, or in mixed directions, make a tree as well. The edges a -> b and b -> a count as one, so a tree may store its edges in both directions, and self-loops are ignored. The empty graph is a tree.

Time: O(NodeCount + EdgeCount x alpha(NodeCount)), plus O(log maxOutDegree) for each pair a -> b, b -> a; O(1) for more than 3 x NodeCount - 2 edges, too many for any tree.
Memory: 5 x NodeCount bytes while it runs.

IsWeaklyConnected(Graph)

Returns whether graph is weakly connected: connected when the direction of the edges is ignored.

public static bool IsWeaklyConnected(Graph graph)

Parameters

graph Graph

The graph to check.

Returns

bool

true if graph is weakly connected.

Remarks

Answers without the partition of WccsOf(Graph), and stops as soon as all nodes are connected. The empty graph is weakly connected, and so is a single node. For the directed reading, see IsStronglyConnected(Graph).

Time: O(NodeCount + EdgeCount x alpha(NodeCount)), stopping once all nodes are connected.
Memory: 5 x NodeCount bytes while it runs.

ReachableFrom(Graph, int)

Returns the nodes reachable from source, in ascending order and with source included. Equivalent to ReachableFrom(graph, [source]).

public static SortedIntView ReachableFrom(Graph graph, int source)

Parameters

graph Graph

The graph to search.

source int

Node ID in 0..NodeCount-1.

Returns

SortedIntView

The reachable nodes.

Remarks

Time: O(NodeCount + EdgeCount).
Memory: as for ReachableFrom(Graph, ReadOnlySpan<int>).

Exceptions

ArgumentOutOfRangeException

source is out of range.

ReachableFrom(Graph, ReadOnlySpan<int>)

Returns the nodes reachable from at least one of sources, in ascending order and with the sources included.

public static SortedIntView ReachableFrom(Graph graph, ReadOnlySpan<int> sources)

Parameters

graph Graph

The graph to search.

sources ReadOnlySpan<int>

Node IDs, each in 0..NodeCount-1.

Returns

SortedIntView

The reachable nodes.

Remarks

The search follows the edges in their direction; for the nodes from which a source is reachable, search the transposed graph, as shown at Transposed(). A source given twice counts once, and with no sources, no node is reachable. Being sorted, the result goes straight into ForSubgraph(SortedIntView) for the subgraph of the reachable nodes, as shown at Remapped(Graph, NodeMapping). For distances and shortest paths, use BfsDistances.

Time: O(sources.Length + NodeCount + EdgeCount).
Memory: 4 bytes per reachable node for the result; while it runs, 1 bit per node and briefly up to 12 bytes per reachable node.

Exceptions

ArgumentOutOfRangeException

A source is out of range.

Remapped(Graph, NodeMapping)

Returns graph with its nodes renumbered by newToOld: node i of the result is node newToOld.Get(i) of graph.

public static Graph Remapped(Graph graph, NodeMapping newToOld)

Parameters

graph Graph

The graph to renumber.

newToOld NodeMapping

The node of graph for each node of the result.

Returns

Graph

The renumbered graph.

Examples

Here, calls holds the calls between the methods of a program, and the methods that load reaches become a graph of their own, with their names from names:

NodeMapping newToOld = NodeMapping.ForSubgraph(Graphs.ReachableFrom(calls, load));
Graph loading = Graphs.Remapped(calls, newToOld);
string[] loadingNames = new string[loading.NodeCount];
newToOld.Gather(names, loadingNames);
// loadingNames: [load, parse, read]
// loading: load -> parse, load -> read, parse -> parse

Remarks

The result has the edges of graph between the nodes that newToOld maps to; the other nodes are left out, with their edges. The factories of NodeMapping make the mapping: ForSubgraph selects nodes, ForPermutation(ReadOnlySpan<int>) and Reindex(Graph) reorder all of them. Data on the nodes follows with the Gather methods of the mapping, data on the edges with EdgeMapping(Graph, Graph, NodeMapping). To merge nodes into groups instead, use Condense().

Time: O(NodeCount + EdgeCount log maxOutDegree).
Memory: 4 bytes per node and per edge for the result; while it runs, 4 x NodeCount bytes more.

Exceptions

ArgumentException

A node of the result maps to -1, or two map to the same node.

ArgumentOutOfRangeException

A node of the result maps to an ID that is not a node of graph.

RootNodes(BiAdjacentGraph)

Returns the root nodes of graph in ascending order. A root node has in-degree 0.

public static SortedIntView RootNodes(BiAdjacentGraph graph)

Parameters

graph BiAdjacentGraph

The graph to search.

Returns

SortedIntView

The root nodes.

Remarks

A traversal of a DAG or a forest starts from them, as in traverser.Run(Graphs.RootNodes(graph)) with a DfsTraverser. IsRootNode(int) checks a single node in O(1).

Time: O(NodeCount).
Memory: 4 bytes per root node for the result.

TopologyHash(Graph)

Returns a 64-bit hash of the nodes and edges of graph, consistent with Equals(Graph?).

public static long TopologyHash(Graph graph)

Parameters

graph Graph

The graph to hash.

Returns

long

The hash.

Remarks

Equal graphs have equal hashes, and different graphs rarely do. A BiAdjacentGraph and a Graph with the same nodes and edges count as equal. Like GetHashCode(), the hash is computed on every call: compute it once and keep it, for instance as the key of a cache of results per graph, or to see when a transformation stops changing a graph. It depends on nothing but the nodes and edges, so it is the same in every run and on every platform; a release of Graphity that changes it says so in its changelog. Every implementation of Graphity computes the same hash. Equal hashes do not prove equal graphs, and graphs can be made to collide on purpose: compare with Equals(Graph?) where it matters.

Time: O(NodeCount + EdgeCount).

TransitiveClosure(Graph)

Returns the transitive closure of graph: the same nodes, with an edge u -> v wherever a path of one or more edges leads from u to v.

public static Graph TransitiveClosure(Graph graph)

Parameters

graph Graph

The graph to close.

Returns

Graph

The transitive closure.

Remarks

A node has a self-loop in the result if and only if it lies on a cycle. The result can have up to NodeCount^2 edges; for the nodes reachable from a few nodes, ReachableFrom(Graph, ReadOnlySpan<int>) costs far less.

The closure is computed on the SCCs (strongly connected components) of graph, with a row of bits per SCC for the SCCs it reaches. The rows take sccCount^2 / 8 bytes, about 1.25 GB for 100 000 SCCs.

Time: O(NodeCount + EdgeCount + sccCount x (sccCount + EdgeCount) / 64 + resultEdgeCount log NodeCount), with sccCount the number of SCCs.
Memory: 4 bytes per node and per edge for the result; while it runs, sccCount^2 / 8 bytes for the rows, which are held together with the result at the peak, and O(NodeCount + EdgeCount) more.

Exceptions

ArgumentException

The closure has more edges than a graph can have, or graph has more than 2^30 - 29 nodes.

TransitiveReduction(Graph)

Returns the transitive reduction of dag: the same nodes, keeping each edge u -> v unless another path leads from u to v.

public static Graph TransitiveReduction(Graph dag)

Parameters

dag Graph

The DAG to reduce.

Returns

Graph

The transitive reduction.

Remarks

From each node, the result reaches the same nodes as dag, with as few edges as possible; on a DAG, this result is unique. For a graph with cycles, reduce the DAG of its SCCs, which is Components.SccsOf(graph).Condense().

The reduction is computed with a row of bits per node for the nodes it reaches. The rows take NodeCount^2 / 8 bytes, about 1.25 GB for 100 000 nodes.

Time: O(NodeCount + EdgeCount log maxOutDegree + (NodeCount + EdgeCount) x NodeCount / 64).
Memory: 4 bytes per node and per edge for the result; while it runs, NodeCount^2 / 8 bytes for the rows and O(NodeCount + EdgeCount) more.

Exceptions

ArgumentException

dag has a cycle, a self-loop included, or a depth-first path is longer than 2^30 - 29 nodes.

TransposedEdgeMapping(Graph)

Returns the edge mapping from the transposed graph of graph to graph.

public static EdgeMapping TransposedEdgeMapping(Graph graph)

Parameters

graph Graph

The graph whose transposed graph is mapped to it.

Returns

EdgeMapping

The edge mapping from the transposed graph to graph.

Examples

Here, siteCount holds the number of call sites of each call by edge index of calls, and the counts follow the calls to the transposed graph, which lists the callers of parse:

BiAdjacentGraph calledBy = BiAdjacentGraph.Of(calls).Transposed();
int[] calledBySiteCount = Graphs.TransposedEdgeMapping(calls).Gather(siteCount);
for (int edge = calledBy.OutEdgeStart(parse);
     edge < calledBy.OutEdgeEnd(parse);
     edge++)
{
    output.WriteLine(
        $"{names[calledBy.EdgeTarget(edge)]}: {calledBySiteCount[edge]}");
}
// load: 1
// parse: 2

Remarks

Edge e of BiAdjacentGraph.Of(graph).Transposed() maps to the edge of graph it reverses: the transposed graph keeps the node IDs, but not the edge indices. The mapping is total, and its Gather methods carry data on the edges over to the transposed graph. TransposedEdgeIndex(int) translates a single edge, in the opposite direction.

Time: O(NodeCount + EdgeCount).
Memory: 4 x EdgeCount bytes for the result; while it runs, 4 x NodeCount bytes more.