Graphity for TypeScript 3.0.0
    Preparing search index...

    Variable GraphsConst

    Graphs: {
        adjacencyListOf(graph: Graph): string;
        diff(before: Graph, after: Graph): GraphDiff;
        dominatorTree(dominators: Dominators): Graph;
        edgeMapping(
            newGraph: Graph,
            oldGraph: Graph,
            newToOld: NodeMapping,
        ): EdgeMapping;
        edgePartition(
            condensedGraph: Graph,
            partition: NodePartition,
        ): EdgePartition;
        findCycle(graph: Graph): Int32Array;
        isBipartite(graph: Graph): boolean;
        isDag(graph: Graph): boolean;
        isForest(graph: Graph): boolean;
        isPath(graph: Graph): boolean;
        isStronglyConnected(graph: Graph): boolean;
        isTree(graph: Graph): boolean;
        isUndirectedForest(graph: Graph): boolean;
        isUndirectedTree(graph: Graph): boolean;
        isWeaklyConnected(graph: Graph): boolean;
        reachableFrom(
            graph: Graph,
            sourceOrSources: number | IntList,
        ): SortedIntView;
        remapped(graph: Graph, newToOld: NodeMapping): Graph;
        rootNodes(graph: BiAdjacentGraph): SortedIntView;
        topologyHash(graph: Graph): bigint;
        transitiveClosure(graph: Graph): Graph;
        transitiveReduction(dag: Graph): Graph;
        transposedEdgeMapping(graph: Graph): EdgeMapping;
    } = ...

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

    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 method combines their data.

    A shape check without a prefix reads the graph as directed. One prefixed undirected reads it as undirected, as Components.ccsOf does: each edge connects its source and target both ways, and the edges a -> b and b -> a count as one. isBipartite and isWeaklyConnected 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.

    Type Declaration

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

        Each line ends with a line feed. For the control flow of a method with a loop:

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

        Unlike Graph.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 some tens of millions of edges is longer than a JavaScript string can be (2^29 - 24 characters in V8, where Java allows 2^31 - 9) and ends in the engine's RangeError: Invalid string length (Java: an OutOfMemoryError).

        Time: O(nodeCount + edgeCount). Memory: 1 byte per character for the result; while it runs, about as much again.

        Parameters

        • graph: Graph

          the graph to list

        Returns string

        the adjacency list, one line per node

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

        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.

        Parameters

        • before: Graph

          the older graph

        • after: Graph

          the newer graph, with the same node count

        Returns GraphDiff

        the added and removed edges

        Error if the node counts differ

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

        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 Ancestry.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.

        Parameters

        • dominators: Dominators

          the dominators of a graph

        Returns Graph

        the dominator tree

    • edgeMapping: function
      • Returns the edge mapping from newGraph to oldGraph that goes with the node mapping newToOld.

        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. Here, siteCount holds the number of call sites of each call by edge index of calls, and the subgraph loading from the example at Graphs.remapped takes these counts along:

        const loadingSiteCount = Graphs.edgeMapping(loading, calls, newToOld).gather(
        siteCount,
        );
        // 1 for load -> parse and for load -> read, 2 for parse -> parse

        For the opposite direction, from the edges of oldGraph to those of newGraph, invert the result with EdgeMapping.inverted. The transposed graph needs Graphs.transposedEdgeMapping 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.

        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

        Error if newToOld.indexCount !== newGraph.nodeCount

        RangeError if a node of newGraph maps to an ID that is not a node of oldGraph

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

        The edges from group g to group h all map to the condensed edge g -> h, which is edge condensedGraph.edgeIndexOf(g, h). EdgePartition.edgesOf lists them, and the reduce method of the result combines their data. An edge inside a group, or from or to a node in no group, maps to -1. Here, byPackage groups the methods of a program by package. Its condensed graph packageCalls holds the calls between packages (see NodePartition.of). byPackageCall tells which calls between methods are behind the call from service to model:

        const byPackageCall = Graphs.edgePartition(packageCalls, byPackage);
        const serviceToModel = packageCalls.edgeIndexOf(service, model);
        const behind = byPackageCall.edgesOf(serviceToModel);
        // behind: [5, 7] - the calls load -> parse and save -> format

        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.

        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

        Error if condensedGraph.nodeCount is not partition.groupCount

    • findCycle: function
      • Returns the nodes of a cycle of graph in the order of its edges, or an empty array if graph is a DAG.

        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. Here, the cycle in the dependencies between the packages of a program:

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

        For a cycle inside a given SCC, search the subgraph of its nodes from Graphs.remapped; 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.

        Parameters

        • graph: Graph

          the graph to search

        Returns Int32Array

        the nodes of the cycle, each once, or an empty array; a new array that must not be modified (Java: unmodifiable)

        Error if a depth-first path is longer than 2^30 - 5 nodes

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

        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.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is bipartite

        Error if graph has more than 2^30 - 5 nodes

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

        Graphs.findCycle 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.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph has no cycle

        Error if a depth-first path is longer than 2^30 - 5 nodes

    • isForest: function
      • 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.

        The empty graph is a forest. For the undirected reading, see Graphs.isUndirectedForest.

        Time: O(nodeCount + edgeCount). Memory: 8 x nodeCount bytes while it runs.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is a forest

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

        The empty graph is a path.

        Time: O(nodeCount + edgeCount). Memory: 8 x nodeCount bytes while it runs.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is a path

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

        Answers without the partition of Components.sccsOf. 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, Sccs.isStronglyConnected answers in O(1). The empty graph is strongly connected, and so is a single node. For the undirected reading, see Graphs.isWeaklyConnected.

        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.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if every node reaches every other

        Error if a depth-first path is longer than 2^30 - 5 nodes

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

        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 Graphs.isUndirectedTree. The empty graph is a tree.

        Time: O(nodeCount + edgeCount). Memory: 8 x nodeCount bytes while it runs.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is a tree

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

        Unlike for Graphs.isForest, 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.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is a forest when read as undirected

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

        Unlike for Graphs.isTree, 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.

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is a tree when read as undirected

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

        Answers without the partition of Components.wccsOf, 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 Graphs.isStronglyConnected.

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

        Parameters

        • graph: Graph

          the graph to check

        Returns boolean

        true if graph is weakly connected

    • reachableFrom: function
      • Returns the nodes reachable from source, or from at least one of sources, in ascending order and with the sources included (Java: two overloads, one with a single source).

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

        Time: O(number of sources + 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.

        Parameters

        • graph: Graph

          the graph to search

        • sourceOrSources: number | IntList

          a node ID in 0..nodeCount-1, or a list of them

        Returns SortedIntView

        the reachable nodes

        RangeError if a source is out of range

    • remapped: function
      • Returns graph with its nodes renumbered by newToOld: node i of the result is node newToOld.get(i) of graph.

        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: NodeMapping.forSubgraph selects nodes, NodeMapping.forPermutation and NodeMapping.reindex reorder all of them. Data on the nodes follows with the gather methods of the mapping, data on the edges with Graphs.edgeMapping. 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:

        const newToOld = NodeMapping.forSubgraph(Graphs.reachableFrom(calls, load));
        const loading = Graphs.remapped(calls, newToOld);
        const loadingNames = new Array<string>(loading.nodeCount);
        newToOld.gather(names, loadingNames);
        // loadingNames: [load, parse, read]
        // loading: load -> parse, load -> read, parse -> parse

        To merge nodes into groups instead, use NodePartition.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.

        Parameters

        • graph: Graph

          the graph to renumber

        • newToOld: NodeMapping

          the node of graph for each node of the result

        Returns Graph

        the renumbered graph

        Error if a node of the result maps to -1, or two map to the same node

        RangeError if a node of the result maps to an ID that is not a node of graph

    • rootNodes: function
    • topologyHash: function
      • Returns a 64-bit hash of the nodes and edges of graph, consistent with Graph.equals. The hash is a signed 64-bit bigint, which has the value range of Java's long.

        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 Graph.hashCode, 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 engine; 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 Graph.equals where it matters.

        Time: O(nodeCount + edgeCount).

        Parameters

        • graph: Graph

          the graph to hash

        Returns bigint

        the hash

    • transitiveClosure: function
      • 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.

        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, Graphs.reachableFrom 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) / 32 + resultEdgeCount log nodeCount), with sccCount the number of SCCs; the rows are processed in 32-bit words, where Java takes 64 bits at a time. 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.

        Parameters

        • graph: Graph

          the graph to close

        Returns Graph

        the transitive closure

        Error if the closure has more edges than a graph can have, or graph has more than 2^30 - 5 nodes

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

        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 / 32); the rows are processed in 32-bit words, where Java takes 64 bits at a time. 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.

        Parameters

        • dag: Graph

          the DAG to reduce

        Returns Graph

        the transitive reduction

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

    • transposedEdgeMapping: function
      • Returns the edge mapping from the transposed graph of graph to graph.

        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. 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:

        const calledBy = BiAdjacentGraph.of(calls).transposed();
        const calledBySiteCount = Graphs.transposedEdgeMapping(calls).gather(siteCount);
        for (
        let edge = calledBy.outEdgeStart(parse);
        edge < calledBy.outEdgeEnd(parse);
        edge++
        ) {
        console.log(`${names[calledBy.edgeTarget(edge)]}: ${calledBySiteCount[edge]}`);
        }
        // load: 1
        // parse: 2

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

        Parameters

        • graph: Graph

          the graph whose transposed graph is mapped to it

        Returns EdgeMapping

        the edge mapping from the transposed graph to graph