Skip to content

Cluster LOD

A plain graphraum draws every node it is given, up to maxVisibleNodes (100,000 by default). Beyond that, 2D bins the nodes in view into density cells and 3D keeps only the first nodes in array order. Cluster LOD is the opt-in alternative for very large graphs: it groups nearby nodes into a tree once, and on every camera change it shows each region as small as it can without the eye noticing. Far regions are one glyph sized by how many nodes it holds, joined by aggregated edges. Regions you zoom into open up until you see the real nodes.

It lives in its own entry, so apps that do not use it pay nothing:

import { Graphraum } from "@yggy-tech/graphraum";
import { attachClusterLod, buildClusterTree, nodeColorKeys } from "@yggy-tech/graphraum/lod";
const dimensions = 3;
const tree = buildClusterTree({
dimensions,
edges, // Uint32Array, two node indices per edge
positions, // Float32Array, x y z per node
colors: nodeColorKeys(data.nodes), // optional, for the colour blend of the glyphs
});
const graph = new Graphraum(container, { mode: "3d" });
const lod = attachClusterLod(graph, tree, { data, element: container });
lod.detach(); // stops following the camera; call it before graph.destroy()

data is the full GraphraumData you built the tree from: node i has the position i of the tree, and edge k is the pair k. graphraum draws only the cut, so never call setData() yourself while the layer is attached.

To see it, run bun run dev:lod in the repository: 200,000 coloured blobs, ?n=5000000 for five million, ?mode=3d for 3D, ?animate=0 to switch the animation off, ?worker=0 to build on the main thread.

  • Use it when the graph is far above maxVisibleNodes, or when 3D must show every region instead of the first 100,000 nodes.
  • Skip it below a few tens of thousands of nodes. The plain renderer shows every node and every selected edge, and is simpler.
  • The graph needs positions up front. Compute them in a worker with the layout helpers or on your server.

Open a huge graph straight into the cluster view

Section titled “Open a huge graph straight into the cluster view”

Above a few hundred thousand nodes, do not build a GraphraumData at all. openClusterLod() takes the graph as typed arrays, builds the tree in a module worker, and draws only the cut:

import { Graphraum } from "@yggy-tech/graphraum";
import { openClusterLod } from "@yggy-tech/graphraum/lod";
const graph = new Graphraum(container, { mode: "2d" });
const lod = await openClusterLod(
graph,
{ dimensions: 2, positions, edges, colors }, // Float32Array, Uint32Array pairs, optional Uint32Array 0xRRGGBB
{
element: container,
// A real node's details come from you, only for nodes inside the cut.
node: (index, arrays) => ({ id: ids[index], label: names[index], position: { x: arrays.positions[index * 2], y: arrays.positions[index * 2 + 1] } }),
},
);
await lod.complete; // the aggregate edges are in

The promise resolves with the first cut drawn, built from the coarse tree: regions and glyphs show first, and the edges between them follow when lod.complete resolves (lod.getTimings() has both times and the worker’s build time). The renderer never receives more than maxDrawnNodes nodes and maxDrawnEdges edges. The full graph stays in typed arrays: no object per node, so five million nodes and fifteen million edges need a few hundred megabytes, not gigabytes.

  • Worker. The package finds lod-worker.js next to the bundle by default. Bundlers that do not follow new URL(..., import.meta.url) inside a dependency (Vite’s dependency pre-bundling, for one) need createWorker: () => new Worker(new URL("./my-worker.ts", import.meta.url), { type: "module" }), where my-worker.ts is serveClusterTreeWorker(self) from the same entry. worker: false builds on the main thread, with a paint between the two steps; that is also the fallback when workers are missing.
  • Transfer. By default the arrays are handed to the worker and detach on your side. Read positions, colours and edges through lod.arrays. With transfer: false the worker gets copies and you keep yours, at the price of the copy; a worker that fails to start then falls back to the main thread.
  • Real nodes. node(index, arrays) and edge(index, arrays) default to ids n<index> and e<index> with the position and colour from the arrays. Pass your own to add labels or sizes. lod.resolve(id), members(), frameCluster() and zoomToCluster() work as before, from the arrays.
  • Cancel. Pass signal to stop opening; afterwards lod.detach() also stops the worker.

At 1,000,000 nodes and 3,000,000 edges the first cut was drawn about 0.2 seconds after the call (Apple M5 Pro, headless Chromium, one run); see the scaling ladder for the full range.

The tree is plain typed arrays. buildClusterTree() takes about 0.7 seconds for a million nodes and three million edges on a laptop, so run it in a worker and hand the result over:

import { buildClusterTree, clusterTreeTransferables } from "@yggy-tech/graphraum/lod";
// worker
self.onmessage = ({ data: input }) => {
const tree = buildClusterTree(input);
self.postMessage(tree, clusterTreeTransferables(tree));
};

Tree options: colors is one 0xRRGGBB number per node (nodeColorKeys(data.nodes) reads hex colours); each cluster then keeps its three most common colours. leafSize (default 16) is how many nodes a leaf may hold before it splits, and maxNeighbors (default 32) caps the aggregated edges kept per cluster, heaviest first. weights gives one number per edge (default 1). A tree holds at most 8,388,608 nodes.

  • Size. A glyph is clearly bigger than a single node and grows with the square root of its member count, up to the size of its region.
  • Count. A compact label (950, 1.2k, 34k, 1.2M) is drawn over the glyph. It is hidden while the glyph is too small to hold it, and for groups under 8 nodes. The label is white with a dark halo, so it reads on light and dark themes.
  • Colour. With colors set on the tree, a glyph blends the colours of its members as soft blobs, one per dominant colour (the top three by share). A colour that holds 80 percent or more is shown alone, and colours under 8 percent are left out. See Blend colours in a node.
  • Edges. Width and opacity grow with the logarithm of the aggregated weight.

When the cut changes, a cluster that splits shrinks away while its children grow from its position out to theirs, and children that merge travel into their parent while it grows. It takes 200 ms (transitionMilliseconds, 0 for none). Nodes have no per-node opacity, so the fade is a change of size, not of transparency. Under prefers-reduced-motion: reduce every change swaps at once, and the zoom after a click jumps. While an animation runs, a newer camera position waits for it and is applied right after, so a fast zoom shows a chain of short animations. Changes that only add or drop elements, as a pan does, swap at once.

Each swap goes through applyDataPatch(), which names only the nodes and edges that arrived or left, so a cut change does not rebuild the graph’s buffers.

When more of the graph arrives, build a tree of everything loaded so far and hand it to handle.update(tree, { data }) instead of attaching a new layer. The new data must start with the nodes of the old, in the same order, as an append does. Every glyph and node glides from the element it grew out of to its new place and size, new ones grow in and dropped ones shrink away, and the camera stays. It takes 600 ms (updateMilliseconds, 0 for none); a newer update picks up where the running one is. Rebuild every few hundred milliseconds rather than on every batch, so each move has time to read.

OptionDefaultWhat it does
pixelThreshold10A cluster whose projected radius is under this many pixels is one glyph. Lower shows more detail.
maxDrawnNodes4000Clusters plus real nodes in one cut. The cut never passes it, whatever the graph size.
maxDrawnEdges8000Edges drawn. Edges between real nodes keep half the budget, so detail survives next to heavy aggregates.
cullMargin0.1Share of the viewport kept around it, so clusters just off screen are ready when you pan.
aggregateStylesize by count, colour blendReturn size, color, blend and the like for a glyph from its count, radius and depth.
aggregateEdgeStylewidth and opacity by weightReturn an edge style from the weight and a 0..1 strength.
labelstrueCount labels on glyphs.
clickToZoomtrueClick a glyph to zoom in on it.
onClusterClicknoneCalled with the cluster and its count when a glyph is clicked.
transitionMilliseconds200Length of the split and merge animation.
zoomMilliseconds450Length of the zoom after a click.
prefersReducedMotionthe system settingReturn true to skip all animation.
idPrefixcluster:Prefix of aggregate ids, so they never collide with yours.
fittrueFit the camera to the first cut.

The cut is chosen best first: the cluster that looks biggest on screen is opened next, until every cluster is under the threshold or the node budget is spent. Clusters outside the view are dropped. In 3D, clusters the camera is inside count as infinitely large, so they always open.

Aggregates are ordinary nodes to graphraum, so pick(), pickHit(), hover and selection report them with ids like cluster:123. Clicking a glyph zooms the camera in on its cluster (zoomToCluster(), 450 ms), which opens it; a drag that ends on a glyph does not count as a click, and a click on a real node does nothing extra, so your own selection code keeps working. Ask the layer what an id means:

const id = graph.pick(event.clientX, event.clientY);
const hit = id ? lod.resolve(id) : null;
if (hit?.kind === "cluster") {
lod.members(hit.cluster); // node indices of the cluster, as a Uint32Array
graph.setCameraState(lod.frameCluster(hit.cluster)); // or frame it yourself
}

resolve() returns { kind: "cluster", cluster, count }, { kind: "node", node } for a real node, or null.

lod.getDiagnostics() (and the onCut option) reports drawnAggregates, drawnNodes, drawnEdges, droppedEdges, cutDepth, cutMilliseconds and transitioning. graph.getDiagnostics() counts what graphraum was given, which is the cut.

  • Every cut change costs time in the size of the cut, not the graph. A pan that changes the cut every frame spends a few milliseconds per frame; lower maxDrawnNodes on slow devices.
  • Edges to clusters outside the view are not drawn, so edges stop near the screen edge.
  • Selection by id survives a cut for real nodes; an aggregate that stops being drawn loses its selection.
  • The colour summary of a cluster above the leaves merges the top colours of its children, so its shares are approximate.
  • Node drag, the focus lens and labels see the cut, not your full graph. Real nodes keep their own data; aggregates have no labels.
  • Nodes with identical positions cannot be split, so a very large pile at one point stays one aggregate.
  • With maxNeighbors smaller than the real number of neighbours, light aggregate edges can be missing.
  • The 3D cut assumes the camera graphraum creates: a 45 degree field of view with y up.
  • How aggregates look is still being tuned. Style them with aggregateStyle and aggregateEdgeStyle.