Skip to main content

BiAdjacentGraph

Struct BiAdjacentGraph 

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

A Graph that also holds the in-nodes of every node, for algorithms that follow edges against their direction.

BiAdjacentGraph::of builds the in-adjacency of a graph - the in-nodes of every node. The result has the node IDs and edge indices of the graph and shares the out-nodes of every node, called its out-adjacency. Algorithms that need in-nodes, such as Dominators, take a BiAdjacentGraph, so that the in-adjacency is built once and serves all of them. transposed reverses every edge without copying, and uni_adjacent_graph drops the in-adjacency again.

Java’s BiAdjacentGraph extends Graph; this type dereferences to its Graph instead. So every method of a graph applies, and a &BiAdjacentGraph is accepted where a &Graph is. The graph remembers its in-adjacency, so BiAdjacentGraph::of on it takes the in-adjacency over in O(1).

The in-nodes of a node are in ascending order, like its out-nodes. A BiAdjacentGraph equals a Graph with the same nodes and edges. Instances are immutable and safe to share between threads (Send and Sync).

use graphity_core::{BiAdjacentGraph, GraphBuilder};

let mut b = GraphBuilder::new();
b.add_nodes(3);
b.add_edge_pairs(&[0, 2, 1, 2]);
let graph = BiAdjacentGraph::of(&b.build());
assert_eq!(graph.in_nodes(2), [0, 1]);
assert_eq!(graph.out_nodes(0), [2]);
assert_eq!(graph.transposed().out_nodes(2), [0, 1]);

Memory: 8 x (node_count + edge_count) bytes, half of it for the out-adjacency, which is shared with the graph it was built from.

Implementations§

Source§

impl BiAdjacentGraph

Source

pub fn of(graph: &Graph) -> BiAdjacentGraph

Returns a BiAdjacentGraph with the nodes and edges of graph, building its in-adjacency.

Node IDs and edge indices stay the same, and the out-adjacency is shared with graph, not copied. The in-adjacency is built anew on every call, not cached: keep the result to use it more than once. If graph already is bi-adjacent, that is, the graph of a BiAdjacentGraph, the result shares its in-adjacency.

Time: O(node_count + edge_count), or O(1) if already bi-adjacent. Memory: +4 x (node_count + edge_count) bytes, or none if already bi-adjacent.

Source

pub fn as_graph(&self) -> &Graph

Returns this graph as a plain &Graph; the same as dereferencing.

Time: O(1).

Source

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

Returns the in-degree of node. That is the number of edges with node as target.

Time: O(1).

§Panics

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

Source

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

Returns the in-nodes of node in ascending order. These are the sources of the edges with node as target.

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 has_in_node(&self, node: u32, in_node: u32) -> bool

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

Time: O(log in_degree(node)).

§Panics

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

Source

pub fn transposed(&self) -> BiAdjacentGraph

Returns the transposed graph as a view of this graph’s arrays. The transposed graph has every edge reversed.

Node IDs stay the same, edge indices do not: edge e of the transposed graph is in general not the reverse of edge e of this graph. transposed_edge_index translates one edge index, and graphs::transposed_edge_mapping translates all of them.

A plain Graph needs its in-adjacency first: BiAdjacentGraph::of(&graph).transposed(). Here, the packages of a program that depend on model, directly or indirectly, are the ones reachable from it against the direction of the dependencies:

let model = 4;
let used_by = BiAdjacentGraph::of(&dependencies).transposed();
let affected = graphs::reachable_from(&used_by, model);
// affected: [0, 2, 3, 4, 5] - app, ui, service, model and storage

Time: O(1).

Source

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

Returns the edge index that edge edge_index has in the transposed graph.

Called on transposed, it translates back: transposed().transposed_edge_index(transposed_edge_index(e)) == e. To translate every edge, graphs::transposed_edge_mapping needs one pass instead of a search per edge; it maps from the transposed graph to this one.

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 degree(&self, node: u32) -> u32

Returns the degree of node. Equivalent to in_degree(node) + out_degree(node).

It counts edges, not neighbors: a self-loop counts twice, and so do the edges node -> v and v -> node, although v is one neighbor.

Time: O(1).

§Panics

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

Source

pub fn neighbors(&self, node: u32) -> SortedIntView<'static>

Returns the neighbors of node in ascending order and without duplicates. These are its in-nodes and out-nodes.

Unlike in_nodes and out_nodes, which are views, the result is a copy, merged on every call.

Time: O(in_degree(node) + out_degree(node)). Memory: up to 4 x (in_degree(node) + out_degree(node)) bytes for the result; while it runs, up to as much again if a neighbor is both an in-node and an out-node.

§Panics

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

Source

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

Returns whether neighbor is a neighbor of node; a neighbor out of range yields false. Equivalent to has_out_node(node, neighbor) || has_in_node(node, neighbor).

Time: O(log out_degree(node) + log in_degree(node)).

§Panics

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

Source

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

Returns whether node is a root node. Equivalent to in_degree(node) == 0.

graphs::root_nodes returns all root nodes.

Time: O(1).

§Panics

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

Methods from Deref<Target = Graph>§

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 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 BiAdjacentGraph

Source§

fn clone(&self) -> BiAdjacentGraph

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 BiAdjacentGraph

Source§

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

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

impl Deref for BiAdjacentGraph

Source§

type Target = Graph

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Graph

Dereferences the value.
Source§

impl Display for BiAdjacentGraph

Source§

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

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

impl Eq for BiAdjacentGraph

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 BiAdjacentGraph

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 BiAdjacentGraph

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<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§

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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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.