Skip to main content

Graph

Struct Graph 

Source
pub struct Graph { /* private fields */ }
Expand description

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

Nodes are the u32 IDs 0..node_count(). Edges are numbered by edge index 0..edge_count(), 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. Graph::of 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. write_to and read_from 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 BiAdjacentGraph::of builds and which also gives the transposed graph. Algorithms are not methods of the graph but modules and types of their own, such as components, top_order and Dominators; the crate documentation lists them by topic.

Instances are immutable and safe to share between threads (Send and Sync). The arrays of a graph are reference-counted, so a clone shares them in O(1). So do the results that keep their graph, such as a NodePartition.

Memory: 4 x (node_count + edge_count) bytes.

A graph has at most 2^31 - 10 nodes and 2^31 - 9 edges.

Implementations§

Source§

impl Graph

Source

pub fn of( out_adjacency_start: &[u32], out_adjacency: &[u32], ) -> Result<Graph, GraphError>

Returns a graph from the two arrays of its CSR layout, as csr returns them and write_to writes them.

The out-nodes of node v are out_adjacency[out_adjacency_start[v]..out_adjacency_start[v + 1]], and the position of an out-node in out_adjacency is the edge index of its edge. out_adjacency_start holds where the out-nodes of each node start, followed by the edge count, so its length is node_count + 1; out_adjacency holds the out-nodes of all nodes, node after node. For example, the control flow of a method with a loop:

// blocks 0 to 5: entry, header, body, then, next, exit
let out_adjacency_start = [0, 1, 3, 5, 6, 7, 7];
let out_adjacency = [
    1, // entry -> header
    2, 5, // header -> body, exit
    3, 4, // body -> then, next
    4, // then -> next
    1, // next -> header
];
let cfg = Graph::of(&out_adjacency_start, &out_adjacency)?;

Both arrays are copied and checked: the offsets start at 0, never decrease and end at out_adjacency.len(), and the out-nodes of each node are strictly ascending. For edges in any order or with duplicates, use GraphBuilder. from_csr takes Vecs over without the copy.

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

§Errors

An IndexOutOfBounds error if an out-node is not in 0..node_count; an InvalidArgument error if out_adjacency_start is empty, does not start at 0, decreases or does not end at out_adjacency.len(), the out-nodes of a node are not strictly ascending, or the arrays hold more nodes or edges than a graph can have.

Source

pub fn from_csr( out_adjacency_start: Vec<u32>, out_adjacency: Vec<u32>, ) -> Result<Graph, GraphError>

Returns a graph from the two arrays of its CSR layout, which the caller hands over: Graph::of without the copy.

The arrays are checked as by Graph::of, and the graph takes over the buffers of the vectors. A vector with spare capacity is shrunk to its length first, as by Vec::into_boxed_slice. Java’s package-private ofOwned, public here for crates that compute CSR arrays themselves, such as graphity-controlflow.

Time: O(node_count + edge_count). Memory: none beyond the vectors, unless one has spare capacity.

§Errors

As for Graph::of.

Source

pub fn write_to<W: Write>(&self, out: W) -> Result<()>

Writes this graph to out, for read_from to read back with the same node IDs and edge indices.

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. Here, the names of the methods of a program follow the calls between them:

let mut out = BufWriter::new(File::create(file)?);
calls.write_to(&mut out)?;
for name in names {
    writeln!(out, "{name}")?;
}
out.flush()?;

A BiAdjacentGraph writes its out-adjacency only. out is taken by value: lend it with &mut out to keep using it, and flush it yourself; this call neither flushes nor closes it. Passed by value, it is dropped when the call returns, which closes a File and flushes a BufWriter without reporting an error.

The format is the two arrays that Graph::of 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                      node_count
4                          4                      edge_count
8                          4 x (node_count + 1)   out_adjacency_start
8 + 4 x (node_count + 1)   4 x edge_count         out_adjacency

The arrays follow the rules of Graph::of. Nothing else is written: no padding, checksum, magic number or version. So a graph takes exactly 8 + 4 x (node_count + 1 + edge_count) bytes, and read_from 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 out needs a BufWriter only if other data shares it in small pieces, as in the example.

use graphity_core::{Graph, GraphBuilder};

let mut b = GraphBuilder::new();
b.add_nodes(3);
b.add_path(&[0, 1, 2]);
let graph = b.build();

let mut bytes = Vec::new();
graph.write_to(&mut bytes)?;
assert_eq!(bytes.len(), 8 + 4 * (3 + 1 + 2));
assert_eq!(Graph::read_from(bytes.as_slice())?, graph);

Time: O(node_count + edge_count). Memory: a 64 KiB buffer.

§Errors

Any error of out.

Source

pub fn read_from<R: Read>(input: R) -> Result<Graph>

Reads a graph that write_to wrote, with the same node IDs and edge indices.

Reads exactly the bytes of the graph and leaves input right after them, where data written after the graph follows. Here, that data is the names of the methods of a program:

let mut input = BufReader::new(File::open(file)?);
// equal to the graph written, edge indices included
let calls = Graph::read_from(&mut input)?;
let mut names = Vec::with_capacity(calls.node_count() as usize);
for name in input.lines().take(calls.node_count() as usize) {
    names.push(name?);
}

input is taken by value, so that &mut input lends it; read_from does not close it. Passed by value, it is dropped when the call returns. The result has no in-adjacency, even if the stream was written from a BiAdjacentGraph; BiAdjacentGraph::of builds it again.

The arrays are checked as by Graph::of, but not copied. They grow with the data that arrives, so a header that announces more than the stream holds ends in an UnexpectedEof error, not in an allocation of the announced size. Reads in blocks of up to 64 KiB, so input needs a BufReader only if other data shares it in small pieces.

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

§Errors
  • UnexpectedEof if the stream ends before the graph does - Java’s EOFException;
  • InvalidData if a count in the header is negative or larger than a graph can have, or the arrays do not form a graph that Graph::of accepts, whose GraphError is then the source of the error;
  • any other error of input.
Source

pub fn node_count(&self) -> u32

Returns the number of nodes.

Time: O(1).

Source

pub fn edge_count(&self) -> u32

Returns the number of edges.

Time: O(1).

Source

pub fn is_empty(&self) -> bool

Returns whether this graph has no nodes. Equivalent to node_count() == 0.

Time: O(1).

Source

pub fn out_degree(&self, node: u32) -> u32

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

Time: O(1).

§Panics

With an index out of bounds message if node is not in 0..node_count().

Source

pub fn out_nodes(&self, node: u32) -> SortedIntView<'_>

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

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

Time: O(1).

§Panics

With an index out of bounds message if node is not in 0..node_count().

Source

pub fn out_edge_start(&self, node: u32) -> u32

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

Their edge indices are out_edge_start(node)..out_edge_end(node), in the order of out_nodes; 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. Here, it lists the methods that run calls, with the number of call sites of each call in site_count:

for edge in calls.out_edge_start(run)..calls.out_edge_end(run) {
    writeln!(
        out,
        "{}: {}",
        names[calls.edge_target(edge) as usize],
        site_count[edge as usize]
    )?;
}
// load: 1
// save: 1
// show: 2

Time: O(1).

§Panics

With an index out of bounds message if node is not in 0..node_count().

Source

pub fn out_edge_end(&self, node: u32) -> u32

Returns the end, exclusive, of the edge index range of the out-edges of node; see out_edge_start.

Time: O(1).

§Panics

With an index out of bounds message if node is not in 0..node_count().

Source

pub fn nodes(&self) -> Range<u32> ⓘ

Returns the node IDs 0..node_count(), in ascending order - Java’s IntStream, as a range.

Time: O(1) to create the range.

Source

pub fn for_each_edge(&self, action: impl FnMut(u32, u32, u32))

Calls action for every edge with its source, target and edge index, in edge index order - Java’s EdgeConsumer is a closure here.

The source comes with each edge at no cost, whereas edge_source searches for it.

let weights = vec![1.5; graph.edge_count() as usize];
let mut total = 0.0;
graph.for_each_edge(|_source, _target, edge_index| total += weights[edge_index as usize]);
assert_eq!(total, 1.5);

Time: O(node_count + edge_count).

Source

pub fn edge_target(&self, edge_index: u32) -> u32

Returns the target of edge edge_index.

Time: O(1).

§Panics

With an index out of bounds message if edge_index is not in 0..edge_count().

Source

pub fn edge_source(&self, edge_index: u32) -> u32

Returns the source of edge edge_index.

Unlike the target, the source is searched for; for_each_edge gives every edge with its source without a search.

Time: O(log node_count).

§Panics

With an index out of bounds message if edge_index is not in 0..edge_count().

Source

pub fn has_out_node(&self, node: u32, out_node: u32) -> bool

Returns whether the edge node -> out_node exists; an out_node out of range yields false.

Time: O(log out_degree(node)).

§Panics

With an index out of bounds message if node is not in 0..node_count().

Source

pub fn edge_index_of(&self, source: u32, target: u32) -> Option<u32>

Returns the edge index of the edge source -> target, or None if there is none - Java’s -1; a target out of range yields None.

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. Here, calls was built with one edge per call site, and the call sites of each call are counted:

let mut site_count = vec![0; calls.edge_count() as usize];
for site in &call_sites {
    site_count[calls.edge_index_of(site.caller, site.callee).unwrap() as usize] += 1;
}
// 2 for run -> show and for parse -> parse, 1 for every other edge

Time: O(log out_degree(source)).

§Panics

With an index out of bounds message if source is not in 0..node_count().

Source

pub fn contains_self_loop(&self, node: u32) -> bool

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

Time: O(log out_degree(node)).

§Panics

With an index out of bounds message if node is not in 0..node_count().

Source

pub fn uni_adjacent_graph(&self) -> Graph

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

The result shares the out-adjacency of this graph; nothing is copied. Once only the result is kept, the in-adjacency is freed.

Time: O(1).

Trait Implementations§

Source§

impl AsRef<Graph> for BiAdjacentGraph

Source§

fn as_ref(&self) -> &Graph

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Graph

Source§

fn clone(&self) -> Graph

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Graph

The same bounded text as Display.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Graph

Writes the node and edge counts and the out-nodes of the first nodes, for debuggers and logs - Java’s toString. For the control flow of a method with a loop:

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

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. The graph of a BiAdjacentGraph is named as such and lists its out-nodes. graphs::adjacency_list_of gives the whole graph as text.

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

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Graph

Source§

impl From<Graph> for BiAdjacentGraph

Source§

fn from(graph: Graph) -> Self

BiAdjacentGraph::of for a graph that is handed over.

Source§

impl Hash for Graph

Hashes the nodes and edges, consistent with equality.

The hash is computed on every call, so each lookup of a graph in a hash-based collection walks the whole graph. graphs::topology_hash gives a 64-bit hash to compute once and keep.

Time: O(node_count + edge_count).

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Graph

Two graphs are equal if they have the same nodes and edges.

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

Time: O(node_count + edge_count).

Source§

fn eq(&self, other: &Graph) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<BiAdjacentGraph> for Graph

Source§

fn eq(&self, other: &BiAdjacentGraph) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Graph> for BiAdjacentGraph

Source§

fn eq(&self, other: &Graph) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl Freeze for Graph

§

impl RefUnwindSafe for Graph

§

impl Send for Graph

§

impl Sync for Graph

§

impl Unpin for Graph

§

impl UnsafeUnpin for Graph

§

impl UnwindSafe for Graph

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.