Skip to content

⚠ Early release: v0.3.2.sophistry is not ready for production use. Until 1.0, any minor release may break the API; expect missing features and bugs too.Stability and versioning

Fields and graphs

Two kinds of plot that draw many related pieces from one description: a vector field from a function, and a network graph from vertices and edges. Both are core definitions (vectorField, streamLines, networkGraph, diGraph in @sophistry/core; <VectorField>, <StreamLines>, <NetworkGraph>, <DiGraph> in @sophistry/solidjs), and both work inside an <Axes> or plane (see Coordinate systems) or on their own.

A vector field is one function drawn two ways. <VectorField> samples it onto a lattice of arrows; <StreamLines> integrates it with RK4 and draws the flow lines. Both take function as (point) => vector in data coordinates inside an <Axes> or plane, and in scene units outside one.

import { Axes, Stage, StreamLines, VectorField } from "@sophistry/solidjs";
const swirl = ({ x, y }: { x: number; y: number }) => ({ x: -y, y: x });
export const Scene = () => (
<Stage units={10}>
<Axes xRange={[-3, 3, 1]} yRange={[-3, 3, 1]} width={7} height={7}>
<VectorField function={swirl} step={0.75} ramp="viridis" />
<StreamLines function={swirl} noise={0.2} />
</Axes>
</Stage>
);

Magnitude is measured on screen, after mapping through the coordinate system, since that is what a reader compares. Colour follows magnitude through ramp (a stop list, colormap name or function) cut into bands; each band is one node, so a large field stays cheap, and a progress reveal goes band by band.

Inside an <Axes> or plane, fields paint over the grid and under the axes and their numbers (zIndex −0.5, exported as UNDER_AXES_Z_INDEX), so the numbers stay readable. Pass zIndex to change that.

Useful knobs: xRange / yRange / step (or xStep / yStep) / columns for the lattice, and magnitudeRange to pin the colour scale; for arrows maxLength and lengthFunction; for stream lines virtualTime, steps, noise (deterministic seed jitter, 0 for an exact lattice), seeds, direction, minSpeed, and colorAlong to colour each line by the magnitude along it. Animate dashOffset against a dash pattern for flow that moves.

fieldHandle(node) is the imperative half of a field node: vectorAt(point) returns the vector at a field-space point in scene units, and streamlineAt(point) the flow line through it, ready for moveAlong so a particle can ride the field.

Vector field

The phase portrait of a pendulum as arrows colored by their length.

VectorFieldPendulum.tsx
3 collapsed lines
import { draw, track } from "@sophistry/core";
import { Axes, Stage, usePlayer, VectorField } from "@sophistry/solidjs";
import { onSettled } from "solid-js";
export default function VectorFieldPendulum() {
const { play } = usePlayer();
const drawn = track(0);
onSettled(() => {
void play(draw(drawn, { duration: 2 }));
});
return (
<Stage units={14}>
<Axes
xRange={[-5, 5, 1]}
yRange={[-3, 3, 1]}
width={11}
height={6}
xLabel="angle"
yLabel="speed"
>
<VectorField
function={({ x, y }) => ({ x: y, y: -Math.sin(x) })}
progress={drawn}
/>
</Axes>
</Stage>
);
}

<NetworkGraph> is Manim’s Graph and <DiGraph> is its directed twin. (The function plotter is <FunctionGraph>.) A graph is vertices (strings or numbers) and edges (pairs or { source, target }), laid out by a function.

import { NetworkGraph, Stage } from "@sophistry/solidjs";
export const Scene = () => (
<Stage units={12}>
<NetworkGraph
vertices={[8, 3, 10, 1, 6]}
edges={[
[8, 3],
[8, 10],
[3, 1],
[3, 6],
]}
layout="tree"
layoutOptions={{ root: 8 }}
layoutScale={{ width: 8, height: 3.6 }}
labels
vertexConfigs={{ 6: { color: "tomato" } }}
/>
</Stage>
);

A layout is a pure function (graph, options) => Map<vertexId, point>. A name is sugar for a built-in: "spring" (the default, a deterministic Fruchterman-Reingold), "tree" (Reingold-Tilford over a spanning forest), "circular", "grid", "shell", "partite" and "explicit". Your own function drops into the same slot, and every layout is testable outside a scene:

2 collapsed lines
import type { GraphLayout } from "@sophistry/core/geometry";
import { NetworkGraph, Stage } from "@sophistry/solidjs";
const alongASine: GraphLayout = (graph) =>
new Map(graph.vertices.map((id, i) => [id, { x: i, y: Math.sin(i) }]));
export const Scene = () => (
<Stage units={12}>
<NetworkGraph
vertices={["a", "b", "c", "d"]}
edges={[
["a", "b"],
["c", "d"],
]}
layout={alongASine}
/>
</Stage>
);

Layout results are fitted to layoutScale around the graph’s center, uniformly by default so a circular layout stays a circle. The built-in layout table is graphLayouts in @sophistry/core/geometry.

Network layouts

One set of vertices and edges placed three ways by changing only the layout prop.

NetworkLayouts.tsx
3 collapsed lines
import { draw, track } from "@sophistry/core";
import { NetworkGraph, Stage, Text, usePlayer } from "@sophistry/solidjs";
import { onSettled } from "solid-js";
const vertices = [1, 2, 3, 4, 5, 6];
const edges: [number, number][] = [
[1, 2],
[1, 3],
[2, 4],
[2, 5],
[3, 6],
];
export default function NetworkLayouts() {
const { play } = usePlayer();
const drawn = track(0);
onSettled(() => {
void play(draw(drawn, { duration: 2 }));
});
return (
<Stage units={14}>
<NetworkGraph
vertices={vertices}
edges={edges}
layout="circular"
center={{ x: -4.6, y: 0 }}
progress={drawn}
/>
<NetworkGraph
vertices={vertices}
edges={edges}
layout="tree"
layoutOptions={{ root: 1 }}
layoutScale={{ width: 3.5, height: 3.5 }}
center={{ x: 0, y: 0 }}
progress={drawn}
/>
<NetworkGraph
vertices={vertices}
edges={edges}
layout="grid"
layoutScale={{ width: 3.5, height: 2 }}
center={{ x: 4.6, y: 0 }}
progress={drawn}
/>
<Text text="circular" x={-4.6} y={-3.2} />
<Text text="tree" x={0} y={-3.2} />
<Text text="grid" x={4.6} y={-3.2} />
</Stage>
);
}

There is no change_layout: two layouts are two Maps, and blending them is a derive over a track that valueTo drives.

vertexConfig / edgeConfig are shared defaults and vertexConfigs / edgeConfigs override them per vertex or edge (edge keys come from edgeKey(u, v) in @sophistry/core/geometry, which is "u v" for plain ids). They are ordinary props, so pass a derive and highlighting a traversal is a function of the visited set: pathEdges(walk) turns a vertex walk into the pairs to light. renderVertex and renderEdge replace the default disc or line with nodes of your own.

networkHandle(node) reads the graph from outside: positionOf(id), positions(), radiusOf(id), vertexIds(), edgeKeys(), and vertexHandle(id) / edgeHandle(u, v), which return the drawn node itself (for nextTo or a surrounding rectangle). The handle is empty until the graph’s first commit.

For a worked traversal, see the algorithm visualizer recipe.

Breadth-first traversal

A BFS over a small graph. The visit order is computed once; a single step counter drives which vertices and edges are lit.

GraphTraversal.tsx
10 collapsed lines
import { derive, hold, sequence, track, valueTo } from "@sophistry/core";
import { edgeKey } from "@sophistry/core/geometry";
import {
NetworkGraph,
Stage,
Text,
usePlayer,
useScene,
} from "@sophistry/solidjs";
import { onSettled } from "solid-js";
const vertices = ["a", "b", "c", "d", "e", "f", "g"];
const edges: [string, string][] = [
["a", "b"],
["a", "c"],
["b", "d"],
["b", "e"],
["c", "f"],
["c", "g"],
["e", "f"],
];
/** Visit order plus the edge each vertex was discovered through. */
function bfs(start: string) {
const order = [start];
const via = new Map<string, [string, string]>();
for (let head = 0; head < order.length; head++) {
const u = order[head];
for (const [s, t] of edges) {
const v = s === u ? t : t === u ? s : undefined;
if (v && !order.includes(v)) {
order.push(v);
via.set(v, [u, v]);
}
}
}
return { order, via };
}
function Traversal() {
const theme = useScene().theme;
const { play, signal } = usePlayer();
const { order, via } = bfs("a");
// How many vertices have been visited so far; the only moving part.
const step = track(0);
const visited = derive(step, (step) => order.slice(0, Math.round(step)));
const vertexConfigs = derive([visited, theme], (visited, theme) =>
Object.fromEntries(
visited.map((v) => [v, { color: theme.palette.highlight }]),
),
);
const edgeConfigs = derive([visited, theme], (visited, theme) =>
Object.fromEntries(
visited.flatMap((v) => {
const edge = via.get(v);
return edge
? [
[
edgeKey(...edge),
{ stroke: theme.palette.highlight, strokeWidth: 0.07 },
],
]
: [];
}),
),
);
onSettled(() => {
void (async () => {
while (!signal.aborted) {
await play(
sequence(
hold(0.6),
valueTo(step, order.length, { duration: 4, easing: "linear" }),
hold(1.2),
valueTo(step, 0, { duration: 0.6 }),
),
);
}
})();
});
return (
<>
<NetworkGraph
vertices={vertices}
edges={edges}
layout="tree"
layoutOptions={{ root: "a" }}
layoutScale={{ width: 8, height: 4 }}
labels
vertexConfigs={vertexConfigs}
edgeConfigs={edgeConfigs}
/>
<Text
text={derive(
visited,
(visited) => `visited: ${visited.join(" ") || "-"}`,
)}
y={-3.4}
fontSize={0.4}
/>
</>
);
}
export default function GraphTraversal() {
return (
<Stage units={12} aspect={1.5}>
<Traversal />
</Stage>
);
}

Each vertex and edge is its own node, so drawing is capped at the first 400 vertices and 1500 edges (thinned evenly). Layout is never capped, so positionOf works for every vertex.