English
Graph algorithms and traversal
The core answers questions about a graph without drawing it: topological order and cycles (topologicalOrder, findGraphCycles), shortest paths, node search and filters, connected components, degree, betweenness and PageRank centrality, Louvain communities that graphCommunityGroups turns into NetworkGraph groups, and traverseGraph, which walks upstream or downstream within a hop limit, with edge filters, a node limit and the paths it took. All of them are written as loops, so a 12,000-node chain is fine, and they terminate on cycles.
Use them to highlight what depends on a node, to order work, to find the bottleneck of a process, or to load a graph one hop at a time (see graph expansion).
Minimal example
ts
import { traverseGraph, topologicalOrder } from '@eightkk/vue-weave/core'
const nodes = [{ id: 'ore' }, { id: 'steel' }, { id: 'frame' }, { id: 'bike' }]
const edges = [
{ id: 'e1', from: 'ore', to: 'steel' },
{ id: 'e2', from: 'steel', to: 'frame' },
{ id: 'e3', from: 'frame', to: 'bike' },
]
const downstream = traverseGraph({ nodes, edges }, ['steel'], { direction: 'forward', maxHops: 2 })
// downstream.nodeIds: ['steel', 'frame', 'bike']
const order = topologicalOrder(nodes, edges)
// <NetworkGraph :highlighted-node-ids="new Set(downstream.nodeIds)" ... />Examples: Bill of materials, Linked views. Types: traverseGraph, GraphTraversalResult, topologicalOrder.
Graph algorithms
All helpers validate input with indexGraph (unknown endpoints, duplicate IDs and bad ports throw Error) and never mutate their arguments.
| Export | Purpose |
|---|---|
| topologicalOrder(nodes, edges) | { order, acyclic, blocked } using Kahn's algorithm, input order breaks ties. blocked lists nodes on or behind a cycle; a self-loop is a cycle. |
| findGraphCycles(nodes, edges) | Node IDs of each strongly connected component with more than one node, plus each self-looping node. Iterative Tarjan; deterministic order. |
| shortestGraphPath(nodes, edges, fromId, toId, { directed = true, weight }) | { nodeIds, edgeIds, distance } or null when unreachable. Breadth-first without weight, Dijkstra with it (weights must be finite and nonnegative, otherwise RangeError). Unknown IDs throw Error. |
| searchGraphNodes(nodes, query, { fields }) | Case-insensitive substring match on id and label (both by default). An empty query matches every node. A field other than id or label throws RangeError (Unknown search field). |
| filterGraph(nodes, edges, match, { neighborhood = 0, fields }) | match is a predicate or a text query. Returns { nodes, edges }: matching nodes plus everything within neighborhood hops (via graphNeighborhood) and the edges with both endpoints kept. With a text query, fields is checked as in searchGraphNodes. |
Related exported types: GraphIndex, GraphFilterOptions, GraphNodeMatch, GraphSearchOptions, GraphPathResult, ShortestGraphPathOptions, TopologicalOrderResult.
Graph analysis
Headless metrics for large graphs, exported from @eightkk/vue-weave/core. Like the algorithms above they validate input with indexGraph (unknown endpoints and duplicate IDs throw Error), are deterministic (no randomness), iterate instead of recursing and never mutate their arguments. Results are keyed by node ID in input order.
| Export | Purpose |
|---|---|
| graphComponents(nodes, edges) | Weakly connected components as string[][]. Members follow input order, components are ordered by their first member, isolated nodes are single components. |
| graphDegreeCentrality(nodes, edges, { direction = 'both', normalized = false }) | Map of degree per node. Every edge counts once, so parallel edges add up; a self-loop adds 1 to 'in', 1 to 'out' and 2 to 'both'. normalized divides by n − 1 (0 for fewer than two nodes), so values can exceed 1 with parallel edges or self-loops. |
| graphBetweennessCentrality(nodes, edges, { directed = true, normalized = true, weight }) | Brandes' algorithm: breadth-first without weight, Dijkstra with a binary heap with it (weights finite and greater than 0, otherwise RangeError). O(V·E), so use it on graphs up to a few thousand nodes. Parallel edges are distinct shortest paths, self-loops are ignored, lengths within a relative 1e-12 are equal. Normalized by (n − 1)(n − 2) when directed and by (n − 1)(n − 2) / 2 when undirected (each unordered pair counted once); 0 for fewer than three nodes. |
| graphPageRank(nodes, edges, { damping = 0.85, tolerance = 1e-6, maxIterations = 100, weight }) | { scores, iterations, converged } by power iteration. Scores sum to 1; dangling nodes spread their score uniformly; parallel edges add their weights; self-loops are ordinary links. damping must be in [0, 1), tolerance finite and greater than 0, maxIterations a positive integer, weights finite and nonnegative, otherwise RangeError. converged is false when the iteration cap stopped the run. |
| detectGraphCommunities(nodes, edges, { resolution = 1, weight }) | { communities, modularity } by the Louvain method (local moving plus aggregation until no node moves). Edges are treated as undirected and weights (finite, greater than 0) add up. Communities are ordered by their first member's input position with members in input order; modularity uses the given resolution and is 0 without edges. |
| graphCommunityGroups(communities, { idPrefix = 'community-', label, minSize = 2 }) | GraphGroup[] for the NetworkGraph groups prop. IDs are idPrefix + (index + 1) with the index taken from communities, so skipped communities leave gaps and the rest stay stable. label(members, index) defaults to Community N. Communities smaller than minSize produce no group. Group IDs must not collide with node IDs because collapsing uses the group ID for the proxy node; change idPrefix if needed. A node in two communities throws Error. |
ts
import { detectGraphCommunities, graphCommunityGroups } from '@eightkk/vue-weave/core'
const { communities } = detectGraphCommunities(nodes, edges)
const groups = graphCommunityGroups(communities, { label: members => `${members.length} nodes` })Related exported types: GraphDegreeCentralityOptions, GraphBetweennessOptions, GraphPageRankOptions, GraphPageRankResult, GraphCommunityOptions, GraphCommunityResult, GraphCommunityGroupsOptions.
Traversal filters, limits and paths
traverseGraph takes three opt-in options next to direction and maxHops. Without them the result is exactly { nodeIds, edgeIds, unknownIds }, as before.
ts
import { graphTracePath, traverseGraph } from '@eightkk/vue-weave/core'
const impact = traverseGraph(graph, [failedId], {
direction: 'forward',
edgeFilter: (edge, direction) => edge.relation === 'feeds', // follow one relation only
maxNodes: 200,
paths: true,
})
impact.truncated // nodes where a limit stopped the walk: offer "show more" there
graphTracePath(impact, someId)?.edgeIds // why someId is affected: the edges from the failed node to it| Option | Contract |
|---|---|
edgeFilter(edge, direction) | Follows only the edges for which it returns true. edge has the edge type of the graph; direction is the walk that meets the edge ('forward' or 'backward', so a filter can follow different relations upstream and downstream). Called at most once per edge and walk, in discovery order, also for the edges of nodes at the hop limit (to find truncated nodes). Errors it throws propagate. Throws TypeError when it is not a function (edgeFilter must be a function: <type>). |
maxNodes | Largest length of nodeIds: a positive integer or Infinity (default), else RangeError (maxNodes must be a positive integer or Infinity). The known starts count and are always kept, even when there are more of them than maxNodes; unknown start IDs do not count. A node counts once, however many walks reach it, so a node admitted by one walk costs nothing when the other reaches it. Nodes are admitted nearest first: with 'both', the two walks advance together one hop at a time (all nodes k hops away in the backward walk, then in the forward walk, then hop k + 1), so one direction cannot use up the cap before the other starts. Edges to nodes that were left out are not followed. nodeIds keeps its order (starts, then the backward walk, then the forward walk, each in discovery order). |
paths | true records via and multiplyReachedIds. Throws TypeError when it is not a boolean (paths must be a boolean: <type>). |
Optional result fields, present only when edgeFilter, maxNodes or paths: true is given (pass maxNodes: Infinity to get truncated for the hop limit alone):
| Field | Contract |
|---|---|
truncated: GraphTraversalTruncation[] | { nodeId, direction, reason }, once per node and walk, in the order the walks met them: the reached nodes with accepted edges that a walk did not follow because a limit stopped it. reason is 'max-hops' for a node maxHops edges from a start that has accepted edges to nodes the walk has not reached, 'max-nodes' for a node with an edge to a node that maxNodes left out. Empty when the walk was complete. A node whose only edges the filter rejects is never truncated. |
via: GraphTraversalVia | With paths: true: { forward?, backward? }, one Map per walk that ran, from each node that walk reached (starts excepted) to its first step { edgeId, previousId }. Walks are breadth-first, so the step lies on a path with the fewest hops within that walk. There is one map per walk because a node can be reached upstream and downstream; following one map back always gives a path in one direction. |
multiplyReachedIds: string[] | With paths: true: the reached nodes, starts excepted, into which more than one followed edge leads (in any walk), so that more than one path reaches them, in nodeIds order. |
Maps keyed by node ID follow collapseGraphGroups (owners, mergedEdges) and the graph expansion state; lists of IDs follow nodeIds and unknownIds.
graphTracePath(result, nodeId, { direction }?) follows via back from nodeId to a start and returns { direction, nodeIds, edgeIds } from the start to the node (edgeIds has one entry fewer than nodeIds). Without direction it uses the walk with the shorter path, the backward walk on a tie. A start gives { nodeIds: [nodeId], edgeIds: [] } without direction. It returns undefined for a node the walk did not reach, throws Error for a result without via (graphTracePath needs a traverseGraph result made with paths: true) or with steps that form a cycle, and RangeError for a direction other than 'forward' or 'backward'. It loops, so a path of any length is fine.