Layout
graphraum renders positioned nodes. Where the positions come from is up to you: a server, a worker, a saved file, or the force helpers in the package. Layout never blocks the first render.
Stream positions
Section titled “Stream positions”GraphraumLayoutPositions keeps a layout worker separate from the renderer. positions contains an XYZ triplet for each ID in nodeIds; its buffer can be transferred from a worker.
const layout: GraphraumLayoutPositions = { nodeIds: ["person:ada", "place:london"], positions: new Float32Array([20, 12, 0, -20, 8, 0]),};
graph.applyLayout(layout);Force layout
Section titled “Force layout”The package exports computeForcePositions() for a static layout, computeClusteredForcePositions() for data-defined coarse communities, and createForceSimulation() for incremental or worker-driven layouts. All accept ForceSettings; omitted settings use DEFAULT_FORCE_SETTINGS. Pass iterations to override the size-based default used by computeForcePositions().
import { createForceSimulation, DEFAULT_FORCE_SETTINGS } from "@yggy-tech/graphraum/layout";
const simulation = createForceSimulation({ dimensions: 3, edges: new Uint32Array([0, 1, 1, 2]), nodeCount: 3, settings: { ...DEFAULT_FORCE_SETTINGS, damping: 0.75, repulsion: 800 },});
simulation.step(0.35);The simulation recalculates and recenters its centroid after every step, so a live renderer can keep orbit controls focused without refitting the camera. In 2D every Z coordinate remains zero.
Layout styles
Section titled “Layout styles”ForceSettings.layoutStyle picks a layout preset: how nodes push each other apart, plus the spring, cluster and one-shot schedule that balance that push. Each style is a named choice, so more can be added later without changing what an existing name does. FORCE_LAYOUT_STYLES lists the supported names; an unknown name throws.
| Style | What it does | When to use it |
|---|---|---|
"classic" (default) | Every node is pushed away from 8 sampled nodes with a capped inverse-square force, whatever its degree. | Small graphs, and anything tuned against earlier releases. |
"edge-t" | Every edge end draws negativeSamples sampled nodes and pushes its node away with a bounded Student-t force, so a node with many edges gets more room. Groups separate and hubs stop piling up in the middle. Inspired by SNAP-tFDP; unlike the paper only the drawing node moves and only its own degree weights the push. | Degree-skewed graphs, for example documents with many facts, that otherwise end up as one tangled ball. |
A style scales three existing settings, so the same numbers give different effective forces in different styles:
| Style | Spring gain (springStrength, springStrengths) | Cluster gain (clusterStrength) | Repulsion | One-shot default steps | Explicit iterations cap |
|---|---|---|---|---|---|
"classic" | 1 | 1 | capped inverse-square, repulsion as given | forceIterationCount(nodeCount) | 64 |
"edge-t" | 10 | 2.5 | Student-t, 4 times repulsion / 400 | 8 times forceIterationCount(nodeCount) | 512 |
"edge-t" has two settings of its own, clamped like the others and ignored by "classic":
negativeSamples(default2, integer1to16): sampled nodes per edge end and step. A node makes at most 32 draws per step; a node that wants more (degree above 16 at the default) keeps 32 draws with a proportionally larger push, so a step never does more than 32 draws per node.tDegrees(default1,0.5to10): the tail of the force. Lower values keep distant groups pushing each other apart; higher values make the push more local.
const positions = computeForcePositions({ dimensions: 2, edges, nodeCount, settings: { ...DEFAULT_FORCE_SETTINGS, layoutStyle: "edge-t" },});Cost. Each step is O(edges + nodes) with no spatial index. Measured with Bun on Apple Silicon (2D, sparse random graphs, src/force-layout.quality.test.ts): a step costs about the same as "classic" at mean degree 3 (0.06 ms at 1k nodes, 0.6 ms at 10k, 6.3 ms at 100k) and about 2 times "classic" at mean degree 30 (2.6 ms against 1.3 ms at 10k nodes). The one-shot layout runs 8 times the steps, so computeForcePositions() takes about 0.1 s at 10k nodes, 0.4 s at 10k nodes with mean degree 30, and 0.8 s at 100k nodes. Run large one-shot layouts in a worker, or pass a smaller iterations.
Live switching. setSettings() takes a partial settings object and merges it into the current settings; omitted fields keep their value, and a NaN keeps the current value. It keeps positions, velocities, edges and clusters, so the graph moves from where it is into the new style over the next steps instead of jumping back to a fresh seed. Switching style changes the effective spring, cluster and repulsion forces at once (see the gains above). Per-edge linkDistances and springStrengths passed at creation are kept as they are; edges added later with addEdges() take the new linkDistance and springStrength. simulation.settings returns the effective settings after clamping.
const simulation = createForceSimulation({ dimensions: 2, edges, nodeCount });simulation.setSettings({ layoutStyle: "edge-t" });simulation.step(0.35);Quality. On the deterministic fixtures in src/force-layout.quality.test.ts, "edge-t" raises the group silhouette of a 400-node block model with hub documents from -0.22 to 0.37 (one-shot) and from -0.24 to 0.38 (live). On a held-out block model it was not tuned on it reaches 0.18 (one-shot) and 0.30 (live), where "classic" stays below -0.2. Edge-length variation drops from 0.39 to 0.20 on a chain and from 0.35 to 0.10 on a star forest. Edges between groups get longer, so edge lengths on block models vary more (0.39 to 0.49), and a very large hub can sit off the centre of its own star.
Checking which clusters are stable
Section titled “Checking which clusters are stable”A drawing can suggest groups that come from the seed and not from the graph. measureLayoutStability() runs the one-shot layout with several seeds and reports, per cluster, how much of each node’s neighbourhood survives. It also measures a degree-preserving shuffle of the graph, so you can see what a cluster scores by chance.
import { DEFAULT_FORCE_SETTINGS } from "@yggy-tech/graphraum/layout";import { measureLayoutStability } from "@yggy-tech/graphraum/diagnostics";
const { clusters, overall, placeboOverall } = measureLayoutStability( { clusters, dimensions: 2, edges, nodeCount, settings: { ...DEFAULT_FORCE_SETTINGS, layoutStyle: "edge-t" } }, { seeds: 5, neighbours: 10 },);A node’s stability is the average overlap (shared over union) of its 10 nearest nodes between every two runs, from 0 to 1. A cluster’s stability is the average over its nodes. Treat a cluster as real only when its stability is clearly above its placeboStability. clusters only labels nodes for scoring and does not pull them together. It lives in the separate @yggy-tech/graphraum/diagnostics entry, so it adds nothing to the main bundle. The check is deterministic, takes 2 to 32 seeds and up to 5,000 nodes, and its cost grows with the square of the node count. The "classic" one-shot layout scores close to its placebo on most graphs, so measure "edge-t". The Prove run reports the same score for its fixture as layoutStability.
Clusters in a live simulation
Section titled “Clusters in a live simulation”Pass clusters (one Uint32Array entry per node) to createForceSimulation() to keep data-defined communities together while the layout runs. The simulation seeds nodes around cluster centres exactly like computeClusteredForcePositions(), then adds a weak pull of every node towards its cluster centroid on each step. settings.clusterStrength scales the pull (default 0.02, range 0 to 0.1); 0 disables it, and it is ignored without clusters. The array length must equal nodeCount, and the simulation keeps its own copy. Cluster ids must be dense: every id has to be smaller than the node count (addNodes() checks against the new total), otherwise the call throws before changing anything. createForceSimulation() honours clusters, and so does computeForcePositions(), which runs a simulation; computeClusteredForcePositions() keeps its one-shot seeding and accepts sparse ids. Cluster centres are spaced by cluster size (up to 256 clusters), so a small cluster is seeded as close to its neighbours as a large one. With "edge-t" the push a node receives from other clusters also shrinks a little for small clusters (by the 0.25 power of the cluster size over the mean size), so a small group is not pushed far from the rest by the mass around it.
const simulation = createForceSimulation({ clusters: new Uint32Array([0, 0, 0, 1, 1, 1]), dimensions: 2, edges: new Uint32Array([0, 1, 1, 2, 3, 4, 4, 5, 2, 3]), nodeCount: 6, settings: { ...DEFAULT_FORCE_SETTINGS, clusterStrength: 0.04 },});
// A clustered simulation requires one cluster index per added node.// A new index starts a new cluster.simulation.addNodes(2, undefined, new Uint32Array([1, 2]));addNodes(count, initial?, clusters?) requires clusters (length count) when the simulation was created with clusters, and throws when it was created without them. Nodes added without initial positions start at the default seed and are drawn into their cluster by the pull.
Keeping positions when the graph changes
Section titled “Keeping positions when the graph changes”A graph that gains or loses nodes should not start over. Keep the previous positions (NaN for nodes that are new; drop the entry of a removed node and remap the indices), place the new nodes with placeNewNodes() from @yggy-tech/graphraum/layout-start, and pass the result as initialPositions with warmStart: true:
import { computeForcePositions } from "@yggy-tech/graphraum/layout";import { placeNewNodes } from "@yggy-tech/graphraum/layout-start";
const request = { dimensions: 2, edges, nodeCount };const next = computeForcePositions({ ...request, // Old positions by node index, NaN for new nodes; new nodes land next to their neighbours. initialPositions: placeNewNodes(request, previous), warmStart: true,});placeNewNodes() starts a new node a fraction of a link distance from the mean of its placed neighbours, so a new chain grows outward from the old graph. A new node without neighbours starts near the mean of its cluster (pass clusters in the request), or near the centre. Pass linkDistance if you changed it. With warmStart, nodes that have a start keep it, and a node without one (you skipped placeNewNodes()) keeps the default start or its anchor seed; anchors never pull a placed node back. computeForcePositions() then settles in 6 steps from an alpha of 0.05 instead of running the full schedule, so known nodes barely move. With createForceSimulation(), step with an alpha of 0.05 or lower. It works with both layout styles and with clusters and anchors.
On a graph with 5% more nodes the median settled node moved 0.18 link distances with both styles at 100,000 nodes and 300,000 edges. Placing and settling took 82 ms ("classic", 142 ms from scratch) and 122 ms ("edge-t", 1,600 ms from scratch).
Large graphs and the worker
Section titled “Large graphs and the worker”Run computeForcePositions() and createForceSimulation() in a worker and send positions back in transferable batches with graph.applyLayout(). The first batch can be drawn while the rest are still arriving, and the main thread only copies buffers. The Prove run in the playground times startup, transfer, compute and the first useful frame separately. At 100,000 nodes and 300,000 edges the "classic" layout took 0.5 ms to start the worker, 17 ms to hand over the edges and 120 ms to compute in a worker (headless Chromium with software WebGL, one run), so the layout is not what limits a large graph; drawing it is.
A precomputed layout from your server is the better choice when:
- many people open the same graph, so one layout is computed once and cached instead of in every browser;
- the graph is too large for a phone or a low-power laptop, or you use
"edge-t", whose one-shot layout runs eight times as many steps; - the graph changes rarely, and positions must be the same for everyone and between visits;
- the layout needs something the browser lacks, such as embeddings (
anchors), a different algorithm, or hours of compute; - the page has to draw the first frame with no layout wait at all.
Compute in the browser when the graph is built per user, changes often, or is small. Both can be mixed: load the server layout as initialPositions with warmStart: true, so edits settle locally instead of waiting for the server.
Multilevel layout for large graphs
Section titled “Multilevel layout for large graphs”computeMultilevelForcePositions() from @yggy-tech/graphraum/layout-multilevel solves the same force layout on smaller copies of the graph. It merges strongly linked nodes into groups, level after level, until about 200 super-nodes remain, lays those out with the regular force layout, then places every node at its group’s position and refines each finer level with a few steps. The expensive part, finding the global shape, runs on a few hundred nodes instead of every node. The default layout is unchanged; this is a separate, opt-in entry.
import { computeMultilevelForcePositions } from "@yggy-tech/graphraum/layout-multilevel";
const positions = computeMultilevelForcePositions( { dimensions: 3, edges, nodeCount, settings: { layoutStyle: "edge-t" } }, { coarsestSize: 200, refineSteps: 2, onPreview: (rough) => graph.applyLayout({ nodeIds, positions: rough }) },);It takes the same request as computeForcePositions() (both layout styles, clusters, anchors, initialPositions, settings, per-edge linkDistances and springStrengths) and returns the same nodeCount * 3 positions.
When to use it. Use it with layoutStyle: "edge-t" on graphs of about 5,000 nodes or more. On a sparse random graph with about 3 edges per node (one run per cell, one thread, Node on an Apple M5 Pro while the machine was busy) it took 76 ms instead of 180 ms at 10,000 nodes and 583 ms instead of 1,564 ms at 100,000 nodes in 2D, and 78 ms instead of 194 ms and 600 ms instead of 1,766 ms in 3D. The layout quality was close: normalised stress against hop distances (lower is better) was 0.215 against 0.195 and 0.204 against 0.217 in 2D, and 0.147 against 0.143 and 0.149 against 0.158 in 3D. Do not expect a speed-up with "classic": its one-shot layout already takes only about 15 steps, so the coarsening costs about what it saves. At 10,000 nodes it was on par (23 ms against 15 ms) and at 100,000 nodes it was slower (about 290 ms against 140 to 220 ms) at the same stress. Edge lengths are also less even than in the plain layout (a coefficient of variation of 0.59 to 0.71 against 0.38 to 0.52 for "classic" at 10,000 and 100,000 nodes), so run the plain layout when you need the most even edges.
A rough picture first. onPreview is called once, after the coarsest layout and before any refinement, with the whole graph placed from its groups. It already shows the global shape, so you can draw it while the refinement runs. The docs layout worker does this when you start it with algorithm: "multilevel" and posts the preview as a first batch; the Prove benchmark and bun run bench report the time to that first batch next to the total.
| Option | Meaning | Default |
|---|---|---|
coarsestSize | Stop merging at this many super-nodes, 8 to 5,000. | 200 |
levels | Most coarsening levels, 1 to 32. | as many as coarsestSize needs |
refineSteps | Force steps on the full graph after the coarsest layout, 1 to 16. Each coarser level gets one more step. "edge-t" runs twice as many. | 2 |
seed | Changes the random choices of the merging and the placement. The same seed gives the same positions. | 0 |
onPreview, onProgress | The rough picture, and the time of each phase (coarsen, coarsest, refine) per level. | none |
Predefined starts. initialPositions and anchors feed the coarsest layout: graphraum averages them per group, so a PCA or UMAP projection, a server layout or pivotMdsPositions() from @yggy-tech/graphraum/layout-start decides where the groups go, and the refinement then follows. clusters are respected: nodes of different clusters never merge, so a cluster keeps its shape at every level. Give the start in the same units as for computeForcePositions().
Limits.
- Graphs with at most
coarsestSizenodes, and graphs where almost nothing can be merged (no edges), use the plain force layout. - With
warmStart: truethere is no coarse pass: only the changed part settles (see below). - Many small clusters keep the coarsest level large, because groups never merge across clusters.
- A few steps per level replace the long schedule, so the result is a good layout, not an identical one. Compare with the plain layout on your graph before you switch.
computeMultilevelForcePositions()runs on one thread. Run it in a worker for large graphs, like the plain layout.
Workers. computeMultilevelForcePositionsAsync() takes the same request and options and refines the large levels (20,000 nodes or more) of an "edge-t" layout with workers. Each worker moves one region of the picture; it draws the same random push samples a single thread would, over all nodes, and the regions swap positions every two steps, so the layout stays close to the single-thread one. The coarsening and the coarsest layout stay on one thread. Options: workers (0 or 1 is one thread; default one fewer than the logical cores, at most 8), createWorker (starts layout-multilevel-worker.js; bundlers such as Vite find it next to the entry by default) and sharedMemory (default on when the page is cross-origin isolated). The "classic" style, small graphs, hosts without workers and a failing worker all fall back to one thread. The result is deterministic for a seed and a worker count.
On a sparse random graph with about 3 edges per node (median of 3 runs, bun run bench, Apple M5 Pro, 8 workers, machine busy with other work), the refinement took 1,094 ms instead of 1,826 ms at 1,000,000 nodes and 360 ms instead of 450 ms at 300,000 nodes. At 100,000 nodes it was on par (150 ms against 144 ms), and the whole layout time did not change because loading the result into the page dominates. Stress, edge length spread and neighbourhood overlap matched the single-thread layout within 0.1% at 100,000 nodes; below about 40,000 nodes no worker starts and the result is identical. At 5,000,000 nodes neither version fits in the browser.
Warm start. With warmStart: true and initialPositions, only the changed part settles; every other node keeps its position exactly. New nodes (a NaN start position) begin at the mean of their placed neighbours. Pass previous: { edges, nodeCount, anchors } of the earlier layout and nodes whose edges or anchors changed count as well, together with their neighbours up to two hops away. If more than half of the graph changed, the whole graph settles.
Unfolding long chains
Section titled “Unfolding long chains”A random start knots a long thin structure (a process chain, a version history, a timeline), and local forces cannot undo a fold that spans the whole graph. Pass your own start with initialPositions, and let @yggy-tech/graphraum/layout-start compute one from graph distances:
import { computeForcePositions } from "@yggy-tech/graphraum/layout";import { pivotMdsPositions } from "@yggy-tech/graphraum/layout-start";
const request = { dimensions: 2, edges, nodeCount, settings: { linkDistance: 24 } };const positions = computeForcePositions({ ...request, initialPositions: pivotMdsPositions({ ...request, linkDistance: 24 }),});pivotMdsPositions() measures hop distances from 20 well-spread pivot nodes and embeds them with classical multidimensional scaling, so a chain starts as a line with one hop per link distance. It is deterministic and costs about as much as a few layout steps (about 45 ms for 10,000 nodes in the measured runs). It lives in its own entry, so the main bundle does not grow; pass the same linkDistance you give the layout.
initialPositions is nodeCount * 3 values (XYZ per node, Z ignored in 2D). A node with a NaN value keeps the default start. Infinite values and a wrong length throw. It works with createForceSimulation() and computeForcePositions().
- Disconnected graphs: each component is laid out on its own and the components are packed side by side. Nodes without any edge get NaN and keep the default start.
anchorsstill seed the nodes they anchor, on top ofinitialPositions.- With
clusters,initialPositionsreplaces the cluster seeding for the nodes it covers, and the cluster pull (clusterStrength) then gathers each cluster. - Make the start about as large as the relaxed layout. A start squeezed into the smaller random extent did not unfold in the measurements.
- Nodes added later with
addNodes()use the default start.
On a 2 by 400 grid strip (800 nodes, default one-shot schedule) a random start leaves 163 to 169 folds in the "classic" style and 35 to 37 in "edge-t"; the pivot start leaves 0 to 4. A bridged strip such as a rolled sheet is only partly unfolded.
To steer a layout with embeddings, see Guided layout.