Skip to content

Algorithms

Choose graph algorithms by task; read each executor and cancellation contract.

#Graph algorithms

The algorithm family includes synchronous searches and paths, spanning and cut algorithms, centrality measures and clustering, plus larger async whole-graph algorithms. For example:

const result = cy.elements().breadthFirstSearch({
roots: cy.getElementById('a'),
directed: true,
visit(node, edge, previous, index, depth) {
if (node.id() === 'goal') return true;
},
});
console.log(result.found, result.path);

The roots argument is a collection, not a selector string. The callback receives the visited node, incoming edge, node it came from, visit index and depth; returning true stops and records that node as found, while false stops without a found node. Search callbacks and result fields are documented on breadthFirstSearch() and depthFirstSearch(). Async whole-graph algorithms return a promise augmented with cancel(). Cancelling a pending run rejects that promise with CancelledError; a synchronous CPU run may already have settled before cancel() is called. Executor availability and failures are specific to each method. The API reference describes the full options, result shapes and errors.

Call forms use ele. when reading the first element and eles. for collection operations and writes. A single element is still a collection, so these methods can be called on either kind of handle.

#eles.breadthFirstSearch(rootOrOptions?, visitOrDirected?, directed?)

// Breadth-first search over this collection's subgraph
eles.breadthFirstSearch(rootOrOptions?: SearchOptions | Collection<any, any, any> | undefined, visitOrDirected?: boolean | SearchVisitFn | undefined, directed?: boolean | undefined): SearchResult

Breadth-first search over this collection's subgraph. Roots are visited in breadth-first order. Multiple callback roots are visited in reverse input order because the initial queue prepends each root; with no roots, the result is empty.

Parameters
NameDescription
rootOrOptions: SearchOptions | Collection<any, any, any> | undefined?

Starting node or an object containing root, visit and directed.

visitOrDirected: boolean | SearchVisitFn | undefined?

Visit callback, or a direction flag when no callback is needed.

directed: boolean | undefined?

True to follow outgoing edges only; defaults to false.

Returns SearchResult

{ path, found }: path records roots in input order and discoveries in breadth-first insertion order, with each discovery edge before its node. It can include nodes queued but not visited when the callback stops early. found is the matched node or an empty collection when no callback returned true.

Example

const result = eles.breadthFirstSearch({ root: cy.getElementById('a'), directed: true });
console.log(result.path.nodes().map(node => node.id())); // ['a', 'b', 'c']

Example graph and handle setup

Throws

if a root is given as a selector string

Also spelled eles.bfs.

#eles.depthFirstSearch(rootOrOptions?, visitOrDirected?, directed?)

// Depth-first search over this collection's subgraph
eles.depthFirstSearch(rootOrOptions?: SearchOptions | Collection<any, any, any> | undefined, visitOrDirected?: boolean | SearchVisitFn | undefined, directed?: boolean | undefined): SearchResult

Depth-first search over this collection's subgraph. It shares the root, callback, direction and result contract of breadthFirstSearch, but explores the most recently discovered branch first.

Parameters
NameDescription
rootOrOptions: SearchOptions | Collection<any, any, any> | undefined?

Starting node or an object containing root, visit and directed.

visitOrDirected: boolean | SearchVisitFn | undefined?

Visit callback, or a direction flag when no callback is needed.

directed: boolean | undefined?

True to follow outgoing edges only; defaults to false.

Returns SearchResult

{ path, found }; path contains visited nodes and their discovery edges in depth-first callback order

Example

const result = eles.depthFirstSearch({ root: cy.getElementById('a'), directed: true });
console.log(result.path.nodes().length); // 3

Example graph and handle setup

Throws

if a root is given as a selector string

Also spelled eles.dfs.

#eles.dijkstra(options)

// Compute single-source shortest paths from a root over this collection's subgraph using Dijkstra's algorithm
eles.dijkstra(options: DijkstraOptions): DijkstraResult

Compute single-source shortest paths from a root over this collection's subgraph using Dijkstra's algorithm. The caller is responsible for using non-negative edge weights; the library does not validate the weight function's mathematical properties.

Parameters
NameDescription
options: DijkstraOptions

{ root, weight, directed }. The root must be a node in this collection. weight(edge) returns a number and defaults to 1; directed: true follows outgoing edges only.

Fields of options
NameDescription
root: Collection | null?

Starting node in this collection; required at runtime.

weight: WeightFn?

Non-negative edge cost; defaults to 1 for each edge.

directed: boolean?

Follow outgoing edges only when true; defaults to false.

Returns DijkstraResult

{ distanceTo, pathTo }; an unreachable node has infinite distance and its pathTo() collection contains that node alone. A node outside this subgraph has undefined distance and an empty path.

Example

const result = eles.dijkstra({ root: cy.getElementById('a'), directed: true, weight: edge => edge.data('weight') });
console.log(result.distanceTo(cy.getElementById('c'))); // 5

Example graph and handle setup

Throws

if root is missing or is not a node in this collection

#eles.dijkstra(root, weight?, directed?)

// Compute shortest paths with positional arguments
eles.dijkstra(root: Collection, weight?: WeightFn, directed?: boolean): DijkstraResult

Compute shortest paths with positional arguments. Use non-negative weights.

Parameters
NameDescription
root: Collection

a node in this collection

weight: WeightFn?

the edge cost function; defaults to a cost of 1

directed: boolean?

true to follow outgoing edges only; defaults to false

Returns DijkstraResult

shortest-path distanceTo() and pathTo() functions; unreachable nodes have infinite distance, nodes outside this subgraph have undefined distance

Example

const result = eles.dijkstra(cy.getElementById('a'), edge => edge.data('weight'), true);
console.log(result.distanceTo(cy.getElementById('c'))); // 5

Example graph and handle setup

Throws

if root is missing or is not a node in this collection

#eles.aStar(options?)

// Find an A path between two nodes in this collection's subgraph
eles.aStar(options?: AStarOptions): AStarResult

Find an A* path between two nodes in this collection's subgraph. The heuristic defaults to zero, reducing the search to Dijkstra's ordering. The search closes nodes without reopening them; shortest-path guarantees require non-negative costs and a consistent heuristic. The library does not validate those mathematical properties.

Parameters
NameDescription
options: AStarOptions?

{ root, goal, weight, heuristic, directed }. Root and goal must belong to this collection; weight(edge) defaults to 1, heuristic(node) defaults to 0, and directed: true follows outgoing edges only.

Fields of options
NameDescription
root: Collection | null?
goal: Collection | null?
weight: WeightFn?
heuristic: AStarHeuristicFn?
directed: boolean?
Returns AStarResult

{ found, distance, path, steps }; when no path exists, found is false and distance and path are undefined

Example

const result = eles.aStar({ root: cy.getElementById('a'), goal: cy.getElementById('c'), weight: edge => edge.data('weight') });
console.log(result.distance); // 5

Example graph and handle setup

Throws

if root or goal is missing or outside this collection

#eles.bellmanFord(options?)

// Compute single-source shortest paths with Bellman–Ford
eles.bellmanFord(options?: BellmanFordOptions): BellmanFordResult

Compute single-source shortest paths with Bellman–Ford. Unlike dijkstra(), this algorithm supports negative edge weights and reports reachable negative-weight cycles. Undirected, every edge is both arcs, so a negative edge reachable from the root is itself a negative cycle .

Parameters
NameDescription
options: BellmanFordOptions?

{ root, weight, directed, findNegativeWeightCycles }. The root must belong to this collection; weight(edge) defaults to 1 and directed: true follows outgoing edges only. Set findNegativeWeightCycles: false to stop after detecting a cycle without constructing cycle collections.

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
findNegativeWeightCycles: boolean?
Returns BellmanFordResult

distance and path accessors, hasNegativeWeightCycle, and negativeWeightCycles (collections describing detected cycles); unreachable nodes have infinite distance and an empty path

Example

const result = eles.bellmanFord({ root: cy.getElementById('a'), weight: edge => edge.data('weight') });
console.log(result.distanceTo(cy.getElementById('c'))); // 5

Example graph and handle setup

Throws

if root is missing or does not contain a node

#eles.floydWarshall(options?)

// Floyd–Warshall all-pairs shortest paths
eles.floydWarshall(options?: FloydWarshallOptions): AlgoRun<FloydWarshallResult>

Floyd–Warshall all-pairs shortest paths. O(n³) — for a single source prefer dijkstra/bellmanFord. Async: the expensive whole-graph tier returns promises, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the maths runs; 'cpu' is the reproducible reference.

Parameters
NameDescription
options: FloydWarshallOptions?

{ weight, directed, executor }

Fields of options
NameDescription
weight: WeightFn?
directed: boolean?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<FloydWarshallResult>

a promise of the { distance, path } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.floydWarshall({ executor: 'cpu' });
const result = await run;
console.log(result.distance(cy.getElementById('a'), cy.getElementById('c'))); // 2

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#Spanning

#eles.kruskal(weight?)

// Build a minimum spanning forest of this collection, treating its edges as undirected
eles.kruskal(weight?: WeightFn): Collection<NodeData, EdgeData>

Build a minimum spanning forest of this collection, treating its edges as undirected. Equal-weight edges retain collection order. Disconnected input produces one tree per connected component.

Parameters
NameDescription
weight: WeightFn?

(edge) => number; defaults to unit weights

Returns Collection<NodeData, EdgeData>

a collection containing all input nodes and the accepted forest edges, in acceptance order

Example

const forest = eles.kruskal(edge => edge.data('weight'));
console.log(forest.edges().length); // 2

Example graph and handle setup

#Connectivity and Eulerian paths

#eles.tarjanStronglyConnected()

// Partition this collection's directed subgraph into strongly connected components
eles.tarjanStronglyConnected(): TarjanStronglyConnectedResult

Partition this collection's directed subgraph into strongly connected components. Traversal follows edge direction; self-loops do not join otherwise separate nodes. The implementation is iterative, so deep graphs do not consume the JavaScript call stack.

Returns TarjanStronglyConnectedResult

{ components, cut }: each component collection contains its nodes and internal edges; cut contains edges between components

Example

console.log(eles.tarjanStronglyConnected().components.length); // 3

Example graph and handle setup

Also spelled eles.tsc, eles.tscc, eles.tarjanStronglyConnectedComponents.

#eles.hopcroftTarjanBiconnected()

// Find undirected biconnected components and articulation points in this collection's subgraph
eles.hopcroftTarjanBiconnected(): HopcroftTarjanBiconnectedResult

Find undirected biconnected components and articulation points in this collection's subgraph. The component partition follows the parent-edge rule: all edges back to the DFS parent are skipped, including parallel edges.

Returns HopcroftTarjanBiconnectedResult

{ components, cut }: each component is a collection of its nodes and edges, and cut contains articulation-point nodes. Each component also absorbs subgraph edges incident to its non-cut nodes, as this implementation defines its component sets.

Example

console.log(eles.hopcroftTarjanBiconnected().cut.map(node => node.id())); // ['b']

Example graph and handle setup

Also spelled eles.htbc, eles.htb, eles.hopcroftTarjanBiconnectedComponents.

#eles.hierholzer(rootOrOptions?, directed?)

// Find an Eulerian trail or circuit over this collection's edges
eles.hierholzer(rootOrOptions?: HierholzerOptions | Collection<any, any, any> | undefined, directed?: boolean | undefined): HierholzerResult

Find an Eulerian trail or circuit over this collection's edges. The directed mode checks directed degree balance; the default treats edges as undirected. A requested root must be a valid starting node for the trail.

Parameters
NameDescription
rootOrOptions: HierholzerOptions | Collection<any, any, any> | undefined?

Starting node or an options object; omit to choose an eligible node.

directed: boolean | undefined?

True to follow outgoing edges only; defaults to false.

Returns HierholzerResult

{ found, trail }; trail is undefined when no trail exists. Collections are sets, so a node visited more than once appears only once in the trail collection.

Example

const result = eles.hierholzer({ root: cy.getElementById('a'), directed: false });
console.log(result.found); // true

Example graph and handle setup

Throws

if a supplied root is a selector string

#Cut

#eles.kargerStein()

// Estimate an undirected global minimum cut with the randomized Karger–Stein contraction algorithm
eles.kargerStein(): KargerSteinResult

Estimate an undirected global minimum cut with the randomized Karger–Stein contraction algorithm. Connected input is required for its guarantee. Random choices mean repeated runs may produce different partitions; the minimum-cut result is probabilistic.

Returns KargerSteinResult

{ cut, components, partition1, partition2 }; cut contains crossing edges and the two partitions contain the corresponding nodes

Example

// The exact cut can vary; this path graph's minimum cut has one edge.
console.log(eles.kargerStein().cut.edges().length); // 1

Example graph and handle setup

Throws

if fewer than two nodes are present or a contraction reaches a graph with no edges

#Centrality

#eles.pageRank(options?)

// PageRank over the subgraph
eles.pageRank(options?: PageRankOptions): AlgoRun<PageRankResult>

PageRank over the subgraph. Undirected by default — each edge is walked both ways, as NetworkX and igraph do — and directed: true follows source → target only. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the power method runs; 'cpu' is the reproducible reference.

Parameters
NameDescription
options: PageRankOptions?

{ dampingFactor, precision, iterations, weight, directed, executor }; dampingFactor is the textbook α in (0, 1], default 0.85

Fields of options
NameDescription
dampingFactor: number?

the probability of following an out-edge rather than teleporting — the textbook α, in (0, 1] (default 0.85)

precision: number?
iterations: number?
weight: WeightFn?
directed: boolean?

walk edges source → target only (default false: an undirected run walks each edge both ways, as NetworkX and igraph do)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<PageRankResult>

a promise of { rank }, a per-node accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.pageRank({ executor: 'cpu' });
const result = await run;
console.log(result.rank(cy.getElementById('c')) > 0); // true

Example graph and handle setup

Throws

if executor or dampingFactor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.degreeCentrality(options?)

// Compute Opsahl's generalized degree for one node in this collection
eles.degreeCentrality(options?: DegreeCentralityOptions): DegreeCentralityResult

Compute Opsahl's generalized degree for one node in this collection. alpha interpolates between counting edges (0) and summing their weights (1); intermediate values combine both. Directed results separate incoming and outgoing degree.

Parameters
NameDescription
options: DegreeCentralityOptions?

{ root, weight, alpha, directed }; root is required, weight(edge) defaults to 1, alpha defaults to 0, and directed defaults to false

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
alpha: number?

0 = count degree, 1 = weight sum (Opsahl's generalized degree)

normalization: 'max' | 'size'?

read by degreeCentralityNormalized only: 'max' (default) divides by the largest degree, 'size' by n − 1 — NetworkX's degree_centrality and igraph's normalized = TRUE

Returns DegreeCentralityResult

{ degree }, or { indegree, outdegree } when directed

Example

const result = eles.degreeCentrality({ root: cy.getElementById('b') });
console.log(result.degree); // 2

Example graph and handle setup

Throws

if root is missing or does not contain a node

Also spelled eles.dc.

#eles.degreeCentralityNormalized(options?)

// Compute each node's Opsahl generalized degree and normalize against the maximum in this collection (default) or, under normalization: 'size', against n − 1 — NetworkX's degreecentrality and igraph's normalized = TRUE (a lone node scores 1, as in NetworkX)
eles.degreeCentralityNormalized(options?: DegreeCentralityOptions): DegreeCentralityNormalizedResult

Compute each node's Opsahl generalized degree and normalize against the maximum in this collection (default) or, under normalization: 'size', against n − 1 — NetworkX's degree_centrality and igraph's normalized = TRUE (a lone node scores 1, as in NetworkX). Directed in- and out-degree are normalized independently. Nodes outside the collection's captured subgraph read as zero.

Parameters
NameDescription
options: DegreeCentralityOptions?

{ weight, alpha, directed, normalization }; the shared option type also allows root, which this all-node method ignores. weight(edge) defaults to 1, alpha defaults to 0, directed defaults to false and normalization to 'max'

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
alpha: number?

0 = count degree, 1 = weight sum (Opsahl's generalized degree)

normalization: 'max' | 'size'?

read by degreeCentralityNormalized only: 'max' (default) divides by the largest degree, 'size' by n − 1 — NetworkX's degree_centrality and igraph's normalized = TRUE

Returns DegreeCentralityNormalizedResult

a degree(node) accessor, or indegree(node) and outdegree(node) accessors when directed. Each divides by its corresponding maximum or by n − 1; under 'max' results are in [0, 1] when weights and alpha produce nonnegative finite degrees. These numeric constraints are not validated.

Example

const result = eles.degreeCentralityNormalized();
console.log(result.degree(cy.getElementById('b'))); // 1

Example graph and handle setup

Throws

if normalization is neither 'max' nor 'size'

Also spelled eles.dcn, eles.degreeCentralityNormalised.

#eles.closenessCentrality(options?)

// Closeness centrality of one node — how near it is, by shortest path, to the rest of the collection
eles.closenessCentrality(options?: ClosenessCentralityOptions): number

Closeness centrality of one node — how near it is, by shortest path, to the rest of the collection. Harmonic (default): Σ 1/d, an unreachable node contributing 0. harmonic: false: the classic (n − 1)/Σd, and over r reachable nodes the Wasserman–Faust (r/Σd)·(r/(n − 1)) — NetworkX's definition. Directed runs sum distances from the node (direction: 'out', default, as R igraph and graph-tool) or to it ('in', as NetworkX and Neo4j GDS).

Parameters
NameDescription
options: ClosenessCentralityOptions?

{ root, weight, directed, direction, harmonic }

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
direction: 'out' | 'in'?

which distances a directed run sums: 'out' (default) from the node to the others — R igraph's mode = "out" and graph-tool's — or 'in', from the others to the node — NetworkX's, Neo4j GDS's and Boldi–Vigna's. Ignored when undirected.

harmonic: boolean?

Σ 1/d (default, tolerates disconnection), or the classic (n − 1)/Σd with the Wasserman–Faust correction: over the r nodes reachable, (r/Σd)·(r/(n − 1)), 0 when none is

normalization: 'max' | 'size'?

read by closenessCentralityNormalized only: 'max' (default) divides by the largest score; 'size' divides a harmonic score by n − 1 (igraph's and graph-tool's normalized harmonic centrality) and leaves a classic one as is, (n − 1) already being in its formula

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Read by the whole-collection closenessCentralityNormalized only — the single-root closenessCentrality is a cheap Dijkstra walk and stays synchronous on the CPU. Unweighted runs walk a BFS per source on either executor (72.3); weighted runs relax Floyd–Warshall.

Returns number

the closeness score

Example

console.log(eles.closenessCentrality({ root: cy.getElementById('b') })); // 2

Example graph and handle setup

Throws

if root is not a node of the collection, or direction is neither 'out' nor 'in'

Also spelled eles.cc.

#eles.closenessCentralityNormalized(options?)

// Closeness centrality for every node, normalized to [0, 1]
eles.closenessCentralityNormalized(options?: ClosenessCentralityOptions): AlgoRun<ClosenessCentralityNormalizedResult>

Closeness centrality for every node, normalized to [0, 1]. Async: the whole-collection form is the all-pairs tier, so like floydWarshall it returns a promise and executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks where it runs; 'cpu' is the reproducible reference. Unweighted runs walk a BFS per source, O(n·(n+E)) — on the worker pool too (one source range per worker, bit-identical to 'cpu'; under 'auto' a sparse graph takes the pool first from 512 nodes, using workers for sparse graphs, and a dense one the GPU first); weighted runs relax Floyd–Warshall, O(n³), and take the offload lane (one pool worker). The single-root closenessCentrality stays synchronous.

Each score is closenessCentrality's for that node (the same harmonic and direction), divided by the largest.

normalization: 'size' divides a harmonic score by n − 1 instead, igraph's and graph-tool's normalized harmonic centrality, and leaves a classic score, which already carries n − 1, as is.

Parameters
NameDescription
options: ClosenessCentralityOptions?

{ weight, directed, direction, harmonic, normalization, executor }

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
direction: 'out' | 'in'?

which distances a directed run sums: 'out' (default) from the node to the others — R igraph's mode = "out" and graph-tool's — or 'in', from the others to the node — NetworkX's, Neo4j GDS's and Boldi–Vigna's. Ignored when undirected.

harmonic: boolean?

Σ 1/d (default, tolerates disconnection), or the classic (n − 1)/Σd with the Wasserman–Faust correction: over the r nodes reachable, (r/Σd)·(r/(n − 1)), 0 when none is

normalization: 'max' | 'size'?

read by closenessCentralityNormalized only: 'max' (default) divides by the largest score; 'size' divides a harmonic score by n − 1 (igraph's and graph-tool's normalized harmonic centrality) and leaves a classic one as is, (n − 1) already being in its formula

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Read by the whole-collection closenessCentralityNormalized only — the single-root closenessCentrality is a cheap Dijkstra walk and stays synchronous on the CPU. Unweighted runs walk a BFS per source on either executor (72.3); weighted runs relax Floyd–Warshall.

Returns AlgoRun<ClosenessCentralityNormalizedResult>

a promise of a closeness accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.closenessCentralityNormalized({ executor: 'cpu' });
const result = await run;
console.log(result.closeness(cy.getElementById('b')) > 0); // true

Example graph and handle setup

Throws

if executor, direction or normalization is invalid; rejects if executor: 'gpu' or 'workers' is unavailable in this environment, or 'workers' is asked of a weighted run

Also spelled eles.ccn, eles.closenessCentralityNormalised.

#eles.betweennessCentrality(options?)

// Betweenness centrality — how often each node lies on shortest paths between other pairs: the sum over pairs s ≠ v ≠ t of the share of shortest s–t paths through v, each unordered pair counted once when undirected (Freeman's definition, NetworkX's and igraph's unnormalized score)
eles.betweennessCentrality(options?: BetweennessCentralityOptions): AlgoRun<BetweennessCentralityResult>

Betweenness centrality — how often each node lies on shortest paths between other pairs: the sum over pairs s ≠ v ≠ t of the share of shortest s–t paths through v, each unordered pair counted once when undirected (Freeman's definition, NetworkX's and igraph's unnormalized score). betweennessNormalized divides by the largest score. Async: returns a promise, and executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks where the Brandes sweep runs. Weighted runs have no GPU path: 'auto' takes the worker pool (one source range per worker, f64-tight to 'cpu' and bit-stable across pool sizes) from 128 nodes and an explicit 'gpu' rejects; unweighted runs keep the GPU first under 'auto', then the pool from 256 nodes where no adapter fits.

betweennessNormalized divides by the largest score, or under normalization: 'size' by the pairs a node can sit between — (n − 1)(n − 2)/2 undirected, (n − 1)(n − 2) directed — as NetworkX's normalized=True and igraph's normalized = TRUE.

Parameters
NameDescription
options: BetweennessCentralityOptions?

{ weight, directed, normalization, executor }

Fields of options
NameDescription
weight: WeightFn | null?
directed: boolean?
normalization: 'max' | 'size'?

how betweennessNormalized scales: 'max' (default) divides by the largest score, 'size' by the number of pairs a node can sit between — (n − 1)(n − 2)/2 undirected, (n − 1)(n − 2) directed — as NetworkX's normalized=True and igraph's normalized = TRUE do

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Weighted runs have no GPU path: 'auto' uses workers from 128 nodes when available, and an explicit 'gpu' rejects. Unweighted runs prefer a suitable GPU under 'auto', then workers where no adapter fits.

Returns AlgoRun<BetweennessCentralityResult>

a promise of the { betweenness, betweennessNormalized } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.betweennessCentrality({ executor: 'cpu' });
const result = await run;
console.log(result.betweenness(cy.getElementById('b')) > 0); // true

Example graph and handle setup

Throws

if executor or normalization is invalid; rejects if executor: 'gpu' is unavailable or the run is weighted

Also spelled eles.bc.

#eles.katzCentrality(options?)

// Katz centrality — attenuated walk counting, where a node is central when many short walks end at it and a walk of length k is worth alphaᵏ
eles.katzCentrality(options?: KatzCentralityOptions): AlgoRun<KatzCentralityResult>

Katz centrality — attenuated walk counting, where a node is central when many short walks end at it and a walk of length k is worth alphaᵏ. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the iteration runs; like pageRank, 'auto' always uses the sparse CPU iteration and the GPU path serves an explicit 'gpu'. katzNormalized divides by the largest score, or by the scores' Euclidean norm under normalization: 'l2' — NetworkX's normalized=True.

Parameters
NameDescription
options: KatzCentralityOptions?

{ alpha, beta, maxIterations, tolerance, directed, weight, normalization, executor }

Fields of options
NameDescription
alpha: number?

the walk attenuation per step (default 0.1); must be positive, and under 1/λ_max of the adjacency for the iteration to converge

beta: number?

the baseline every node starts each step with (default 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 200)

tolerance: number?

stop once Σ|Δx| < n · tolerance (default 1e-6)

directed: boolean?

count incoming walks only

weight: WeightFn?
normalization: 'max' | 'l2'?

how katzNormalized scales: 'max' (default) divides by the largest score, 'l2' by the scores' Euclidean norm — NetworkX's katz_centrality(normalized=True)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Like pageRank, 'auto' stays on the sparse CPU iteration at every measured size (KATZ_GPU_MIN_N); the GPU path serves an explicit 'gpu'.

Returns AlgoRun<KatzCentralityResult>

a promise of the { katz, katzNormalized } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.katzCentrality({ executor: 'cpu' });
const result = await run;
console.log(result.katz(cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, alpha, beta or normalization is invalid; rejects if executor: 'gpu' is unavailable in this environment

#Similarity, diffusion and resistance

#eles.neighborhoodSimilarity(options?)

// Neighborhood similarity — pairwise Jaccard, cosine or overlap coefficients over neighbor sets (deduped; loops excluded; directed: true compares out-neighborhoods)
eles.neighborhoodSimilarity(options?: NeighborhoodSimilarityOptions): AlgoRun<NeighborhoodSimilarityResult>

Neighborhood similarity — pairwise Jaccard, cosine or overlap coefficients over neighbor sets (deduped; loops excluded; directed: true compares out-neighborhoods). The result is all-pairs, so it holds O(n²) counts like floydWarshall. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto') picks where the shared-neighbor counts are computed — under 'auto' the GPU's A·Aᵀ matmul is used only on graphs dense enough to beat the CPU's wedge walk (a mean degree of 64).

Parameters
NameDescription
options: NeighborhoodSimilarityOptions?

{ metric, directed, executor }

Fields of options
NameDescription
metric: SimilarityMetric?

the normalization (default 'jaccard')

directed: boolean?

compare out-neighborhoods instead of undirected ones

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' routes to the GPU only on graphs dense enough that the O(n³) matmul beats the CPU's O(n² + Σ deg²) wedge walk.

Returns AlgoRun<NeighborhoodSimilarityResult>

a promise of the { similarity } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.neighborhoodSimilarity({ executor: 'cpu' });
const result = await run;
console.log(result.similarity(cy.getElementById('a'), cy.getElementById('a'))); // 1

Example graph and handle setup

Throws

if executor or metric is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.simRank(options?)

// SimRank — "two nodes are similar when their neighbors are similar", the Jeh–Widom recursive fixed point, iterated as dense products S′ = C·Q·S·Qᵀ
eles.simRank(options?: SimRankOptions): AlgoRun<SimRankResult>

SimRank — "two nodes are similar when their neighbors are similar", the Jeh–Widom recursive fixed point, iterated as dense products S′ = C·Q·S·Qᵀ. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the iteration runs — under 'auto' the GPU from 256 nodes at any density. The undirected default compares all neighbors; directed: true compares the classic in-neighborhoods. All-pairs (O(n²) memory).

Parameters
NameDescription
options: SimRankOptions?

{ dampingFactor, maxIterations, tolerance, directed, executor }

Fields of options
NameDescription
dampingFactor: number?

the decay per neighborhood step (default 0.8); must sit in (0, 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 50)

tolerance: number?

stop once max |Δs| ≤ tolerance (default 1e-4)

directed: boolean?

compare in-neighborhoods (the classic form) instead of undirected ones

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' takes the GPU from GPU_MIN_N nodes at any density (72.6: the products beat the per-pair CPU iteration everywhere).

Returns AlgoRun<SimRankResult>

a promise of the { similarity } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.simRank({ executor: 'cpu' });
const result = await run;
console.log(result.similarity(cy.getElementById('a'), cy.getElementById('a'))); // 1

Example graph and handle setup

Throws

if executor or dampingFactor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.randomWalkWithRestart(options?)

// Random walk with restart — network propagation from a seeds collection: a walker follows edges with probability 1−c and restarts at the seeds with probability c, and the stationary distribution scores every node by proximity to the seeds
eles.randomWalkWithRestart(options?: RandomWalkWithRestartOptions): AlgoRun<RandomWalkWithRestartResult>

Random walk with restart — network propagation from a seeds collection: a walker follows edges with probability 1−c and restarts at the seeds with probability c, and the stationary distribution scores every node by proximity to the seeds. Async; the vector iteration is O(E) per step on the CPU, so there is no GPU path — an explicit executor: 'gpu' rejects and points at randomWalkWithRestartProximity. A node with no out-edges sends the walker back to the seeds (dangling: 'restart', default — NetworkX's personalised PageRank), so scores sum to 1; dangling: 'absorb' ends the walk there instead, and scores can sum below 1.

Parameters
NameDescription
options: RandomWalkWithRestartOptions?

{ seeds, restartProbability, maxIterations, tolerance, directed, weight, dangling, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the walk restarts at (required for the seed form)

restartProbability: number?

the restart probability c (default 0.15); must sit in (0, 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 200)

tolerance: number?

stop once the L1 step drops under tolerance (default 1e-6) — per column, for the proximity form

directed: boolean?

walk out-edges only

weight: WeightFn?
dangling: 'restart' | 'absorb'?

where a walker at a node with no out-edges goes: 'restart' (default) back to the seeds, as NetworkX's personalised PageRank does, so scores sum to 1; 'absorb' nowhere — the walk ends there and its mass is lost

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the proximity form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<RandomWalkWithRestartResult>

a promise of the { score } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.randomWalkWithRestart({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.score(cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, restartProbability or dangling is invalid, or if seeds holds no node of the collection

#eles.randomWalkWithRestartProximity(options?)

// All-pairs random-walk-with-restart proximity — the full matrix S = c·(I − (1−c)·W)⁻¹, whose column s is the walk restarting at s
eles.randomWalkWithRestartProximity(options?: RandomWalkWithRestartOptions): AlgoRun<RandomWalkWithRestartProximityResult>

All-pairs random-walk-with-restart proximity — the full matrix S = c·(I − (1−c)·W)⁻¹, whose column s is the walk restarting at s. Async: executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks between one sparse solve per column on the CPU, the same solves spread over the worker pool (matching 'cpu') and the dense Neumann iteration on the GPU — under 'auto' the GPU from 256 nodes at any density, else the pool from 128. All-pairs (O(n²) memory). dangling is the seed form's: dead ends restart at the column's node by default, or absorb.

Parameters
NameDescription
options: RandomWalkWithRestartOptions?

{ restartProbability, maxIterations, tolerance, directed, weight, dangling, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the walk restarts at (required for the seed form)

restartProbability: number?

the restart probability c (default 0.15); must sit in (0, 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 200)

tolerance: number?

stop once the L1 step drops under tolerance (default 1e-6) — per column, for the proximity form

directed: boolean?

walk out-edges only

weight: WeightFn?
dangling: 'restart' | 'absorb'?

where a walker at a node with no out-edges goes: 'restart' (default) back to the seeds, as NetworkX's personalised PageRank does, so scores sum to 1; 'absorb' nowhere — the walk ends there and its mass is lost

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the proximity form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<RandomWalkWithRestartProximityResult>

a promise of the { proximity } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.randomWalkWithRestartProximity({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.proximity(cy.getElementById('a'), cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, restartProbability or dangling is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.heatDiffusion(options?)

// Heat diffusion from a seeds collection: unit heat spread over the seeds flows along edges for time, through the kernel exp(−t·L) of the weighted Laplacian
eles.heatDiffusion(options?: HeatDiffusionOptions): AlgoRun<HeatDiffusionResult>

Heat diffusion from a seeds collection: unit heat spread over the seeds flows along edges for time, through the kernel exp(−t·L) of the weighted Laplacian. Total heat is conserved under the default laplacian: 'combinatorial'; 'normalized' diffuses over I − D^{-½}AD^{-½} instead, whose spectrum is bounded whatever the degrees — hubs neither hoard nor flood — at the price of conservation. Async; the vector form is O(E) per series term on the CPU, so there is no GPU path — an explicit executor: 'gpu' rejects and points at heatKernel. Edges are read undirected with positive weights.

Parameters
NameDescription
options: HeatDiffusionOptions?

{ seeds, time, weight, laplacian, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the heat starts on (required for the seed form)

time: number?

how long the heat flows (default 0.1); must be positive

weight: WeightFn?
laplacian: HeatLaplacian?

which Laplacian drives the diffusion (default 'combinatorial', L = D − A, heat-conserving); 'normalized' is I − D^{-½}AD^{-½}, whose spectrum is bounded by 2 so the scaling exponent depends on time alone — heat is then not conserved

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the kernel form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<HeatDiffusionResult>

a promise of the { score } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.heatDiffusion({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.score(cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, time or laplacian is invalid, if seeds holds no node of the collection, or if an edge weight is not positive

#eles.heatKernel(options?)

// The all-pairs heat kernel exp(−t·L) — heat(from, to) is the heat at to after unit heat starts at from (symmetric)
eles.heatKernel(options?: HeatDiffusionOptions): AlgoRun<HeatKernelResult>

The all-pairs heat kernel exp(−t·L) — heat(from, to) is the heat at to after unit heat starts at from (symmetric). Async: executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks between per-column sparse series on the CPU, the same columns spread over the worker pool (bit-identical to 'cpu') and the dense scaling-and-squaring chain on the GPU — under 'auto' the GPU from 256 nodes at any density, else the pool from 256. laplacian ('combinatorial' | 'normalized', default 'combinatorial') picks L = D − A or I − D^{-½}AD^{-½}. All-pairs (O(n²) memory).

Parameters
NameDescription
options: HeatDiffusionOptions?

{ time, weight, laplacian, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the heat starts on (required for the seed form)

time: number?

how long the heat flows (default 0.1); must be positive

weight: WeightFn?
laplacian: HeatLaplacian?

which Laplacian drives the diffusion (default 'combinatorial', L = D − A, heat-conserving); 'normalized' is I − D^{-½}AD^{-½}, whose spectrum is bounded by 2 so the scaling exponent depends on time alone — heat is then not conserved

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the kernel form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<HeatKernelResult>

a promise of the { heat } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.heatKernel({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.heat(cy.getElementById('a'), cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, time or laplacian is invalid, or if an edge weight is not positive

#eles.effectiveResistance(options?)

// Effective resistance and commute time — the graph as a resistor network
eles.effectiveResistance(options?: EffectiveResistanceOptions): AlgoRun<EffectiveResistanceResult>

Effective resistance and commute time — the graph as a resistor network. Weights are conductances by default, the convention of the papers that define the weighted measure; weightAs: 'resistance' reads them as resistances, NetworkX's default. resistance(a, b) comes from the Laplacian pseudo-inverse, commuteTime(a, b) the expected round-trip steps of the random walk (component volume × resistance). Pairs in different components answer Infinity. Async: executor ('cpu' | 'gpu' | 'auto', default 'auto') picks between dense f64 elimination on the CPU and Newton–Schulz matmul iteration on the GPU; both are O(n³), so 'auto' takes the GPU on size alone.

Parameters
NameDescription
options: EffectiveResistanceOptions?

{ weight, weightAs, executor }

Fields of options
NameDescription
weight: WeightFn?
weightAs: 'conductance' | 'resistance'?

what weight measures: 'conductance' (default, a heavier edge conducts more) or 'resistance' (a heavier edge resists more — NetworkX's invert_weight=True default)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<EffectiveResistanceResult>

a promise of the { resistance, commuteTime } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.effectiveResistance({ executor: 'cpu' });
const result = await run;
console.log(result.resistance(cy.getElementById('a'), cy.getElementById('c')) > 0); // true

Example graph and handle setup

Throws

if executor or weightAs is invalid; rejects if an edge weight is not positive or executor: 'gpu' is unavailable

#Structural measures

#eles.triangleCount(options?)

// Triangle counting: per-node triangle counts, local clustering coefficients, and the collection's transitivity, read over the simple undirected graph (direction ignored, parallel edges collapsed, loops excluded)
eles.triangleCount(options?: TriangleCountOptions): AlgoRun<TriangleCountResult>

Triangle counting: per-node triangle counts, local clustering coefficients, and the collection's transitivity, read over the simple undirected graph (direction ignored, parallel edges collapsed, loops excluded). Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the counting runs — under 'auto' the GPU's A²∘A matmul is used only on graphs dense enough to beat the CPU's sparse walk (a mean degree of 64).

Parameters
NameDescription
options: TriangleCountOptions?

{ executor }

Fields of options
NameDescription
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' routes to the GPU only on graphs dense enough that the O(n³) matmul beats the CPU's O(Σ deg²) sparse walk.

Returns AlgoRun<TriangleCountResult>

a promise of { triangles, clusteringCoefficient, totalTriangles, transitivity } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.triangleCount({ executor: 'cpu' });
const result = await run;
console.log(result.totalTriangles); // 0

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.motifCensus(options?)

// The triad census — every three-node subgraph classified into the sixteen Holland–Leinhardt classes ('003' … '300'; '030T' is the feed-forward loop)
eles.motifCensus(options?: MotifCensusOptions): AlgoRun<MotifCensusResult>

The triad census — every three-node subgraph classified into the sixteen Holland–Leinhardt classes ('003' … '300'; '030T' is the feed-forward loop). The counts sum to C(n, 3). Async: executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks between sparse wedge walks on the CPU and matmul trace products on the GPU — under 'auto' the GPU only on dense graphs (a mean degree of 64). directed: false reads every edge as mutual, so only 003 / 102 / 201 / 300 (empty / one-edge / path / triangle) can be non-zero.

Parameters
NameDescription
options: MotifCensusOptions?

{ directed, executor }

Fields of options
NameDescription
directed: boolean?

read edge direction (default true — the census is a directed notion; false reads every edge as mutual, so only 003/102/201/ 300 can be non-zero)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' routes to the GPU only on graphs dense enough that the O(n³) trace products beat the CPU's O(Σ deg²) wedge walks.

Returns AlgoRun<MotifCensusResult>

a promise of { counts } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.motifCensus({ executor: 'cpu' });
const result = await run;
console.log(result.counts['021C']); // 1

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#ele.degree(includeLoops?)

// The first element's total degree, in + out, answered in O(1) off the adjacency index
ele.degree(includeLoops?: boolean): number | undefined

The first element's total degree, in + out, answered in O(1) off the adjacency index.

This is a singular accessor — it reports one node's degree, not a collection-wide figure. For the sum over the whole collection use totalDegree().

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count (each contributes 2)

Returns number | undefined

the degree, or undefined when the first element is not a live node

Example

console.log(eles.degree()); // 1

Example graph and handle setup

#ele.outdegree(includeLoops?)

// The first element's out-degree, in O(1)
ele.outdegree(includeLoops?: boolean): number | undefined

The first element's out-degree, in O(1). Singular, like degree().

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the out-degree, or undefined when not a live node

Example

console.log(eles.outdegree()); // 1

Example graph and handle setup

#ele.indegree(includeLoops?)

// The first element's in-degree, in O(1)
ele.indegree(includeLoops?: boolean): number | undefined

The first element's in-degree, in O(1). Singular, like degree().

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the in-degree, or undefined when not a live node

Example

console.log(eles.indegree()); // 0

Example graph and handle setup

#eles.minDegree(includeLoops?)

// The smallest total degree among the collection's nodes
eles.minDegree(includeLoops?: boolean): number | undefined

The smallest total degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the minimum degree, or undefined when there are no nodes

Example

console.log(eles.minDegree()); // 1

Example graph and handle setup

#eles.maxDegree(includeLoops?)

// The largest total degree among the collection's nodes
eles.maxDegree(includeLoops?: boolean): number | undefined

The largest total degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the maximum degree, or undefined when there are no nodes

Example

console.log(eles.maxDegree()); // 2

Example graph and handle setup

#eles.minIndegree(includeLoops?)

// The smallest in-degree among the collection's nodes
eles.minIndegree(includeLoops?: boolean): number | undefined

The smallest in-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the minimum in-degree, or undefined when there are no nodes

Example

console.log(eles.minIndegree()); // 0

Example graph and handle setup

#eles.maxIndegree(includeLoops?)

// The largest in-degree among the collection's nodes
eles.maxIndegree(includeLoops?: boolean): number | undefined

The largest in-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the maximum in-degree, or undefined when there are no nodes

Example

console.log(eles.maxIndegree()); // 1

Example graph and handle setup

#eles.minOutdegree(includeLoops?)

// The smallest out-degree among the collection's nodes
eles.minOutdegree(includeLoops?: boolean): number | undefined

The smallest out-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the minimum out-degree, or undefined when there are no nodes

Example

console.log(eles.minOutdegree()); // 0

Example graph and handle setup

#eles.maxOutdegree(includeLoops?)

// The largest out-degree among the collection's nodes
eles.maxOutdegree(includeLoops?: boolean): number | undefined

The largest out-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the maximum out-degree, or undefined when there are no nodes

Example

console.log(eles.maxOutdegree()); // 1

Example graph and handle setup

#eles.totalDegree(includeLoops?)

// The summed degree of every node in the collection — the whole-collection figure that degree() deliberately is not
eles.totalDegree(includeLoops?: boolean): number

The summed degree of every node in the collection — the whole-collection figure that degree() deliberately is not.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number

the total degree (0 when there are no nodes)

Example

console.log(eles.totalDegree()); // 4

Example graph and handle setup

#Clustering

#eles.kMeans(options?)

// k-means clustering in attribute space
eles.kMeans(options?: KClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

k-means clustering in attribute space. Works on handles and attributes accessors rather than on graph structure.

Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker for a named distance) picks where the iteration runs; 'cpu' is the reproducible reference. A custom distance function is called inside the iteration, so it runs on the calling thread under 'cpu' and 'auto', and 'workers' rejects it.

Parameters
NameDescription
options: KClusteringOptions?

{ k, attributes, distance, maxIterations, sensitivityThreshold, executor }, with attributes as plain functions

Fields of options
NameDescription
k: number?
m: number?
sensitivityThreshold: number?
distance: DistanceMetric?
maxIterations: number?
attributes: KAttributeFn[]?
testMode: boolean?
testCentroids: number | FeatureCentroid[] | Collection[] | null?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.kMeans({ k: 2, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment, or executor: 'workers' is given a custom distance function

#eles.kMedoids(options?)

// k-medoids clustering — like k-means, but cluster centres are actual elements, which makes it robust to outliers
eles.kMedoids(options?: KClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

k-medoids clustering — like k-means, but cluster centres are actual elements, which makes it robust to outliers. Async, with the same executor contract as kMeans.

Parameters
NameDescription
options: KClusteringOptions?

as kMeans

Fields of options
NameDescription
k: number?
m: number?
sensitivityThreshold: number?
distance: DistanceMetric?
maxIterations: number?
attributes: KAttributeFn[]?
testMode: boolean?
testCentroids: number | FeatureCentroid[] | Collection[] | null?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.kMedoids({ k: 2, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable, if executor: 'workers' is given a custom distance function, or if k exceeds the node count

#eles.fuzzyCMeans(options?)

// Fuzzy c-means clustering: each element gets a degree of membership in every cluster rather than one hard assignment
eles.fuzzyCMeans(options?: KClusteringOptions): AlgoRun<FuzzyCMeansResult>

Fuzzy c-means clustering: each element gets a degree of membership in every cluster rather than one hard assignment. Async, with the same executor contract as kMeans.

Parameters
NameDescription
options: KClusteringOptions?

as kMeans, plus the fuzziness exponent

Fields of options
NameDescription
k: number?
m: number?
sensitivityThreshold: number?
distance: DistanceMetric?
maxIterations: number?
attributes: KAttributeFn[]?
testMode: boolean?
testCentroids: number | FeatureCentroid[] | Collection[] | null?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<FuzzyCMeansResult>

a promise of { clusters, degreeOfMembership } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.fuzzyCMeans({ k: 2, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.clusters.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment, or executor: 'workers' is given a custom distance function

Also spelled eles.fcm.

#eles.hierarchicalClustering(options?)

// Agglomerative hierarchical clustering
eles.hierarchicalClustering(options?: HierarchicalClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

Agglomerative hierarchical clustering. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the distance matrix is built; the merge chain itself is sequential and runs with the reference — in-thread, or on the pool worker for a named distance and a 'min' / 'max' / 'mean' linkage. A custom distance function or a per-pair linkage consults the metric inside the run, on the calling thread, and 'workers' rejects them. Threshold mode merges every closest pair at most threshold apart, a merge at exactly threshold included, as SciPy's fcluster and R's cutree.

Parameters
NameDescription
options: HierarchicalClusteringOptions?

{ attributes, distance, linkage, mode, threshold, dendrogramDepth, executor }

Fields of options
NameDescription
distance: DistanceMetric?
linkage: string?

linkage criterion: 'min' (single), 'max' (complete), 'mean', or per-pair

mode: 'threshold' | 'dendrogram'?
threshold: number?

threshold mode merges pairs at most this far apart (default Infinity)

addDendrogram: boolean?
dendrogramDepth: number?
attributes: HierarchicalAttributeFn[]?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.hierarchicalClustering({ attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment, or executor: 'workers' is given a custom distance function or a per-pair linkage

Also spelled eles.hca.

#eles.markovClustering(options?)

// Markov clustering (MCL) — flow simulation over the graph, so unlike the attribute-space algorithms this one clusters by structure
eles.markovClustering(options?: MarkovClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

Markov clustering (MCL) — flow simulation over the graph, so unlike the attribute-space algorithms this one clusters by structure.

Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the expand/inflate iteration runs; 'cpu' is the reproducible reference. maxIterations defaults to 100 (as Python markov_clustering and R MCL), and pruneThreshold (default 0) drops each inflated matrix's entries under it, keeping each column's largest, as markov_clustering's pruning_threshold does.

Parameters
NameDescription
options: MarkovClusteringOptions?

{ attributes, expandFactor, inflateFactor, multFactor, maxIterations, pruneThreshold, executor }

Fields of options
NameDescription
expandFactor: number?
inflateFactor: number?
multFactor: number?
maxIterations: number?

the iteration cap (default 100, as Python markov_clustering and R MCL)

pruneThreshold: number?

after each inflation, drop entries under this to 0, keeping each column's largest (default 0: no pruning) — Python markov_clustering's pruning_threshold

attributes: MarkovAttributeFn[]?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.markovClustering({ executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor or pruneThreshold is invalid; rejects if executor: 'gpu' is unavailable in this environment

Also spelled eles.mcl.

#eles.affinityPropagation(options?)

// Affinity propagation, which picks exemplars by message passing and so needs no target cluster count
eles.affinityPropagation(options?: AffinityPropagationOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

Affinity propagation, which picks exemplars by message passing and so needs no target cluster count.

Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the message passing runs; 'cpu' is the reproducible reference.

Parameters
NameDescription
options: AffinityPropagationOptions?

{ attributes, distance, preference, damping, minIterations, maxIterations, executor }

Fields of options
NameDescription
distance: DistanceMetric?
preference: AffinityPreference?
damping: number?
maxIterations: number?
minIterations: number?
attributes: AffinityAttributeFn[]?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = cy.nodes().affinityPropagation({ damping: 0.5, preference: 0, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable, or if damping/preference are invalid

Also spelled eles.ap.

All guides · Alphabetical API index · Read continuously