Table of Contents

Class Graph

Namespace
Graphity
Assembly
Graphity.Core.dll

A directed graph, which is the input of the algorithms in this library.

public class Graph : IEquatable<Graph>
Inheritance
Graph
Implements
Derived
Inherited Members

Remarks

Nodes are the int IDs 0..NodeCount-1. Edges are numbered by edge index 0..EdgeCount-1, ordered by source and then by target. No two edges have the same source and target; self-loops are allowed. The graph holds nothing but this structure: names, weights and any other data live in arrays of the caller, indexed by node ID or by edge index.

GraphBuilder builds a graph from edges in any order. Of(ReadOnlySpan<int>, ReadOnlySpan<int>) takes the two arrays of a CSR (compressed sparse row) layout. A graph keeps its edges in this form, and Csr hands the arrays to algorithm code. WriteTo(Stream) and ReadFrom(Stream) store a graph in a stream and load it again.

A Graph holds the out-nodes of every node, called its out-adjacency. Algorithms that also need the in-nodes take a BiAdjacentGraph, which Of(Graph) builds and which also gives the transposed graph. Algorithms are not methods of the graph but classes of their own, such as Components, TopOrder and Dominators; the README lists them by topic.

Instances are immutable and safe to share between threads. No other assembly can derive from this class; BiAdjacentGraph is its only subclass.

Memory: 4 x (NodeCount + EdgeCount) bytes.

A graph has at most Array.MaxLength - 1 nodes and Array.MaxLength edges (2,147,483,590 and 2,147,483,591).

Properties

EdgeCount

Gets the number of edges.

public int EdgeCount { get; }

Property Value

int

Remarks

Time: O(1).

IsEmpty

Gets whether this graph has no nodes. Equivalent to NodeCount == 0.

public bool IsEmpty { get; }

Property Value

bool

Remarks

Time: O(1).

NodeCount

Gets the number of nodes.

public int NodeCount { get; }

Property Value

int

Remarks

Time: O(1).

Methods

ContainsSelfLoop(int)

Returns whether node has an edge to itself, called a self-loop. Equivalent to HasOutNode(node, node).

public bool ContainsSelfLoop(int node)

Parameters

node int

Node ID in 0..NodeCount-1.

Returns

bool

true if the edge node -> node exists.

Remarks

Time: O(log OutDegree(node)).

Exceptions

ArgumentOutOfRangeException

node is out of range.

EdgeIndexOf(int, int)

Returns the edge index of the edge source -> target, or -1 if there is none.

public int EdgeIndexOf(int source, int target)

Parameters

source int

Node ID in 0..NodeCount-1.

target int

Node ID; a value out of range yields -1.

Returns

int

The edge index in 0..EdgeCount-1, or -1.

Examples

Here, calls was built with one edge per call site, and the call sites of each call are counted:

int[] siteCount = new int[calls.EdgeCount];
foreach (CallSite site in callSites)
{
    siteCount[calls.EdgeIndexOf(site.Caller, site.Callee)]++;
}
// 2 for run -> show and for parse -> parse, 1 for every other edge

Remarks

GraphBuilder sorts the edges and merges duplicates, so an edge does not keep the position at which it was added; this method finds where it went.

Time: O(log OutDegree(source)).

Exceptions

ArgumentOutOfRangeException

source is out of range.

EdgeSource(int)

Returns the source of edge edgeIndex.

public int EdgeSource(int edgeIndex)

Parameters

edgeIndex int

Edge index in 0..EdgeCount-1.

Returns

int

The source node ID.

Remarks

Unlike the target, the source is searched for; ForEachEdge(EdgeConsumer) gives every edge with its source without a search.

Time: O(log NodeCount).

Exceptions

ArgumentOutOfRangeException

edgeIndex is out of range.

EdgeTarget(int)

Returns the target of edge edgeIndex.

public int EdgeTarget(int edgeIndex)

Parameters

edgeIndex int

Edge index in 0..EdgeCount-1.

Returns

int

The target node ID.

Remarks

Time: O(1).

Exceptions

ArgumentOutOfRangeException

edgeIndex is out of range.

Equals(Graph?)

Returns whether other is a graph with the same nodes and edges.

public bool Equals(Graph? other)

Parameters

other Graph

The graph to compare with, or null.

Returns

bool

true if both have the same nodes and edges.

Remarks

The in-adjacency does not count: a BiAdjacentGraph equals a Graph with the same nodes and edges.

Time: O(NodeCount + EdgeCount).

Equals(object?)

Returns whether other is a graph with the same nodes and edges.

public override sealed bool Equals(object? obj)

Parameters

obj object

Returns

bool

true if both have the same nodes and edges.

Remarks

The in-adjacency does not count: a BiAdjacentGraph equals a Graph with the same nodes and edges.

Time: O(NodeCount + EdgeCount).

ForEachEdge(EdgeConsumer)

Calls action for every edge with its source, target and edge index, in edge index order.

public void ForEachEdge(EdgeConsumer action)

Parameters

action EdgeConsumer

Called with (source, target, edgeIndex) for each edge.

Remarks

The source comes with each edge at no cost, whereas EdgeSource(int) searches for it.

Time: O(NodeCount + EdgeCount).

GetHashCode()

Returns a hash code over the nodes and edges, consistent with Equals(Graph?).

public override sealed int GetHashCode()

Returns

int

The hash code.

Remarks

It is computed on every call, so each lookup of a graph in a hash-based collection walks the whole graph. TopologyHash(Graph) gives a 64-bit hash to compute once and keep.

Time: O(NodeCount + EdgeCount).

HasOutNode(int, int)

Returns whether the edge node -> outNode exists.

public bool HasOutNode(int node, int outNode)

Parameters

node int

Node ID in 0..NodeCount-1.

outNode int

Node ID; a value out of range yields false.

Returns

bool

true if the edge exists.

Remarks

Time: O(log OutDegree(node)).

Exceptions

ArgumentOutOfRangeException

node is out of range.

Nodes()

Returns the node IDs 0..NodeCount-1 in ascending order.

public IEnumerable<int> Nodes()

Returns

IEnumerable<int>

The node IDs.

Remarks

Time: O(1) to create the sequence.

Of(ReadOnlySpan<int>, ReadOnlySpan<int>)

Returns a graph from the two arrays of its CSR layout, as Csr returns them and WriteTo(Stream) writes them.

public static Graph Of(ReadOnlySpan<int> outAdjacencyStart, ReadOnlySpan<int> outAdjacency)

Parameters

outAdjacencyStart ReadOnlySpan<int>

Where the out-nodes of each node start in outAdjacency, followed by EdgeCount; length NodeCount + 1.

outAdjacency ReadOnlySpan<int>

The out-nodes of all nodes, node after node; length EdgeCount.

Returns

Graph

The graph.

Examples

For example, the control flow of a method with a loop:

// blocks 0..5: entry, header, body, then, next, exit
int[] outAdjacencyStart = [0, 1, 3, 5, 6, 7, 7];
int[] outAdjacency =
[
    1,       // entry  -> header
    2, 5,    // header -> body, exit
    3, 4,    // body   -> then, next
    4,       // then   -> next
    1,       // next   -> header
];
Graph cfg = Graph.Of(outAdjacencyStart, outAdjacency);

Remarks

The out-nodes of node v are outAdjacency[outAdjacencyStart[v]..outAdjacencyStart[v + 1] - 1], and the position of an out-node in outAdjacency is the edge index of its edge. Both spans are copied and checked: the offsets start at 0, never decrease and end at outAdjacency.Length, and the out-nodes of each node are strictly ascending. For edges in any order or with duplicates, use GraphBuilder.

Time: O(NodeCount + EdgeCount).
Memory: 4 x (NodeCount + EdgeCount) bytes for the copies, which the result keeps.

Exceptions

ArgumentOutOfRangeException

An out-node is not in 0..NodeCount-1.

ArgumentException

outAdjacencyStart is empty, does not start at 0, decreases or does not end at outAdjacency.Length, the out-nodes of a node are not strictly ascending, or the spans hold more nodes or edges than a graph can have.

OutDegree(int)

Returns the out-degree of node. That is the number of edges with node as source.

public int OutDegree(int node)

Parameters

node int

Node ID in 0..NodeCount-1.

Returns

int

The out-degree.

Remarks

Time: O(1).

Exceptions

ArgumentOutOfRangeException

node is out of range.

OutEdgeEnd(int)

Returns the end, exclusive, of the edge index range of the out-edges of node; see OutEdgeStart(int).

public int OutEdgeEnd(int node)

Parameters

node int

Node ID in 0..NodeCount-1.

Returns

int

The end of the range, exclusive.

Remarks

Time: O(1).

Exceptions

ArgumentOutOfRangeException

node is out of range.

OutEdgeStart(int)

Returns the start of the edge index range of the out-edges of node. The out-edges are the edges with node as source.

public int OutEdgeStart(int node)

Parameters

node int

Node ID in 0..NodeCount-1.

Returns

int

The start of the range.

Examples

Here, the loop lists the methods that run calls, with the number of call sites of each call in siteCount:

for (int edge = calls.OutEdgeStart(run); edge < calls.OutEdgeEnd(run); edge++)
{
    output.WriteLine($"{names[calls.EdgeTarget(edge)]}: {siteCount[edge]}");
}
// load: 1
// save: 1
// show: 2

Remarks

Their edge indices are OutEdgeStart(node)..OutEdgeEnd(node)-1, in the order of OutNodes(int); the range is empty if node has no out-edges. A loop over the range reads the data of each edge from arrays indexed by edge index.

Time: O(1).

Exceptions

ArgumentOutOfRangeException

node is out of range.

OutNodes(int)

Returns the out-nodes of node in ascending order. These are the targets of the edges with node as source.

public SortedIntView OutNodes(int node)

Parameters

node int

Node ID in 0..NodeCount-1.

Returns

SortedIntView

The out-nodes.

Remarks

The result is a view of this graph's own array, not a copy.

Time: O(1).

Exceptions

ArgumentOutOfRangeException

node is out of range.

ReadFrom(Stream)

Reads a graph that WriteTo(Stream) wrote, with the same node IDs and edge indices.

public static Graph ReadFrom(Stream input)

Parameters

input Stream

The stream to read from; not closed.

Returns

Graph

The graph.

Examples

Here, the names of the methods of a program follow the graph:

Graph calls;
string[] names;
using (var input = new BinaryReader(File.OpenRead(file)))
{
    calls = Graph.ReadFrom(input.BaseStream);
    // equal to the graph written, edge indices included
    names = new string[calls.NodeCount];
    for (int method = 0; method < names.Length; method++)
    {
        names[method] = input.ReadString();
    }
}

Remarks

Reads exactly the bytes of the graph and leaves input right after them, where data written after the graph follows. The result has no in-adjacency, even if the stream was written from a BiAdjacentGraph and even when called as BiAdjacentGraph.ReadFrom(input); Of(Graph) builds it again.

The arrays are checked as by Of(ReadOnlySpan<int>, ReadOnlySpan<int>), but not copied. They grow with the data that arrives, so a header that announces more than the stream holds ends in an EndOfStreamException, not in an allocation of the announced size. Reads in blocks of up to 64 KiB, so input needs a BufferedStream only if other data shares it in small pieces.

Time: O(NodeCount + EdgeCount).
Memory: 4 x (NodeCount + EdgeCount) bytes for the result and up to a 64 KiB buffer; while an array grows, briefly up to 4 x max(NodeCount, EdgeCount) bytes more.

Exceptions

EndOfStreamException

The stream ends before the graph does.

InvalidDataException

A count in the header is negative or larger than a graph can have, or the arrays do not form a graph that Of(ReadOnlySpan<int>, ReadOnlySpan<int>) accepts, whose exception is then the inner exception.

IOException

Reading from the stream fails.

ToString()

Returns the node and edge counts and the out-nodes of the first nodes, for debuggers and logs.

public override sealed string ToString()

Returns

string

The text.

Examples

For the control flow of a method with a loop:

string text = cfg.ToString();
// Graph[nodes=6, edges=7] {0 -> [1], 1 -> [2, 5], 2 -> [3, 4], 3 -> [4],
//                          4 -> [1], 5 -> []}

Remarks

The text stays short however large the graph: it lists at most 16 nodes and 64 out-nodes in total. ... marks where it is cut - after the 16th node, or inside the list that would go beyond 64 out-nodes. A BiAdjacentGraph is named as such and lists its out-nodes. AdjacencyListOf(Graph) gives the whole graph as text.

Time: O(1), as the text is bounded.

UniAdjacentGraph()

Returns a graph with the same nodes and edges, without in-adjacency. A plain Graph returns itself, and a BiAdjacentGraph returns a Graph over its out-adjacency.

public virtual Graph UniAdjacentGraph()

Returns

Graph

This graph, or a graph over the out-adjacency of a BiAdjacentGraph.

Remarks

Time: O(1).

WriteTo(Stream)

Writes this graph to output, for ReadFrom(Stream) to read back with the same node IDs and edge indices.

public void WriteTo(Stream output)

Parameters

output Stream

The stream to write to; not closed.

Examples

Here, the names of the methods of a program follow the calls between them:

using (var output = new BinaryWriter(File.Create(file)))
{
    calls.WriteTo(output.BaseStream);
    foreach (string name in names)
    {
        output.Write(name);
    }
}

Remarks

Only the structure is written. Data in arrays indexed by node ID or edge index stays valid for the graph read back and can follow it in the same stream. A BiAdjacentGraph writes its out-adjacency only.

The format is the two arrays that Of(ReadOnlySpan<int>, ReadOnlySpan<int>) takes, preceded by the node count and the edge count. Every field is a signed 32-bit integer in little-endian byte order:

offset in bytes          size in bytes         field
0                        4                     nodeCount
4                        4                     edgeCount
8                        4 x (nodeCount + 1)   outAdjacencyStart
8 + 4 x (nodeCount + 1)  4 x edgeCount         outAdjacency

The arrays follow the rules of Of(ReadOnlySpan<int>, ReadOnlySpan<int>). Nothing else is written: no padding, checksum, magic number or version. So a graph takes exactly 8 + 4 x (nodeCount + 1 + edgeCount) bytes, and ReadFrom(Stream) recognizes foreign data only where it does not form a valid graph. Every implementation of Graphity reads and writes this format, so a graph written in one language can be read in another.

Writes in blocks of up to 64 KiB, so output needs a BufferedStream only if other data shares it in small pieces.

Time: O(NodeCount + EdgeCount).
Memory: none on a little-endian machine, where the blocks are written straight from the arrays of the graph; a 64 KiB buffer otherwise.

Exceptions

IOException

Writing to the stream fails.