Skip to content

Algorithms

graphrs organizes 400+ graph algorithms into modular packages. Each package is independently installable and tree-shakable.

Package Overview

Algorithm Packages

PackageDescriptionFunctions
@graphrs/communityCommunity detectionlouvain, leiden, infomap, labelPropagation, walktrap, fastGreedy, spinglass, fluidCommunities
@graphrs/centralityCentrality measurespagerank, betweenness, closeness, eigenvector, hits, katz, harmonic
@graphrs/pathShortest paths & traversaldijkstra, bellmanFord, bfs, dfs, allPairsShortestPaths
@graphrs/layoutGraph layoutlayoutFR, layoutKK, layoutGraphopt, layoutSugiyama, layoutReingoldTilford, layoutCircle, layoutGrid, layoutStar, layoutRandom, layoutMDS, layoutDRL
@graphrs/generatorsGraph generatorserdosRenyi, barabasiAlbert, wattsStrogatz, stochasticBlockModel, complete, ring, lattice, star, tree, path
@graphrs/ioImport/exportreadGraphML, writeGraphML, readGML, writeGML, readDOT, writeDOT, readEdgeList, writeEdgeList, readPajek, writePajek
@graphrs/operatorsGraph transformsunion, intersection, difference, simplify, reverse, toDirected, toUndirected, inducedSubgraph, complement
@graphrs/flowNetwork flowmaxFlow, minCut, vertexConnectivity, edgeConnectivity, isConnected
@graphrs/isomorphismStructural matchingisIsomorphic, subgraphIsomorphic, canonicalPermutation, automorphismGroupSize

Integration Packages

PackageDescriptionWhat it does
@graphrs/g6AntV G6 adapterProvides G6-compatible layout functions, community coloring, and centrality sizing
@graphrs/react-flowReact Flow adapteruseGraphrsLayout hook for auto-positioning React Flow nodes

Choosing the Right Algorithm

Community Detection

AlgorithmSpeedQualityBest For
louvainFastGoodGeneral-purpose, first try
leidenFastBestWhen you need guaranteed connected communities
labelPropagationFastestVariableVery large graphs (>100k nodes)
infomapMediumBestInformation flow / routing networks
walktrapMediumGoodSmall-medium graphs with clear structure
fastGreedyFastGoodHierarchical community structure
spinglassSlowGoodWhen you need precise control (spin count)
fluidCommunitiesFastVariableWhen you know k (number of communities) in advance

Centrality Measures

AlgorithmMeasuresBest For
pagerankGlobal importanceRanking nodes by influence (web, social)
betweennessBridge / broker roleFinding bottlenecks and brokers
closenessDistance to all othersFinding nodes with fastest access
eigenvectorNeighbor importanceNodes connected to important nodes
hitsHub / authority scoresDirected networks (web link analysis)
katzAttenuated walk countNetworks with long-range influence
harmonicHarmonic mean distanceDisconnected graphs (graceful fallback)

Layout Algorithms

AlgorithmTypeBest For
layoutFRForce-directedGeneral-purpose visualization
layoutKKForce-directedEmphasizing shortest-path distances
layoutSugiyamaLayeredDAGs, hierarchies, workflows
layoutReingoldTilfordTreeTree structures
layoutCircleGeometricRing/cycle topologies
layoutGridGeometricUniform arrangement
layoutDRLForce-directedVery large graphs (>10k nodes)

Common Pattern

Every algorithm function follows the same pattern:

typescript
import { Graph } from '@graphrs/core';
import { someAlgorithm } from '@graphrs/some-package';

const graph = Graph.fromEdges([[0, 1], [1, 2], [2, 0]]);

// All algorithm functions are async
const result = await someAlgorithm(graph, {
  // optional typed options
});

Rules

  1. First argument is always a Graph instance
  2. Second argument is an optional typed options object
  3. Return value is always a Promise of a typed result
  4. WASM loading is handled automatically on first call

Result Types

Each algorithm family returns a specific result type:

typescript
// Community detection → CommunityResult
{ membership: number[], modularity: number, clusters: number }

// Centrality measures → CentralityResult
{ scores: number[] }

// Shortest path → PathResult
{ path: number[], distance: number }

// Layout → LayoutResult
{ positions: [number, number][] }

// Network flow → FlowResult
{ value: number, flow: number[] }

Async Behavior

All algorithm functions are async because the WASM module loads lazily:

typescript
// First call: loads WASM (~1-2ms), then runs algorithm
const result1 = await pagerank(graph);

// Subsequent calls: WASM already loaded, runs immediately
const result2 = await betweenness(graph);

The WASM module is a singleton — it loads once and is reused across all packages.

Combining Algorithms

A common pattern is chaining multiple algorithms for a full analysis pipeline:

typescript
import { Graph } from '@graphrs/core';
import { louvain } from '@graphrs/community';
import { pagerank } from '@graphrs/centrality';
import { layoutFR } from '@graphrs/layout';

const graph = Graph.fromEdges([
  [0,1],[1,2],[2,0],
  [3,4],[4,5],[5,3],
  [2,3],
]);

// Run in parallel — they're independent
const [communities, pr, layout] = await Promise.all([
  louvain(graph),
  pagerank(graph),
  layoutFR(graph),
]);

// Combine for visualization
const nodes = graph.nodes().map((id, i) => ({
  id,
  x: layout.positions[i]![0],
  y: layout.positions[i]![1],
  community: communities.membership[i],
  importance: pr.scores[i],
}));

Subpath Imports

For finer-grained imports, each package supports subpath exports:

typescript
// Import from subpath
import { dijkstra } from '@graphrs/path/dijkstra';
import { louvain } from '@graphrs/community';

// Equivalent barrel import
import { dijkstra } from '@graphrs/path';

MIT License (TS code) · GPL-2.0 (WASM binary)