Use Rust graph solver in React viewer
This commit is contained in:
parent
2c13f36da7
commit
4e7d352583
7 changed files with 285 additions and 4 deletions
|
|
@ -38,7 +38,7 @@ export function GraphScreen({ state }: { state: EpiphanyGraphsState }) {
|
|||
The public viewer API is intentionally coarse:
|
||||
|
||||
- `layoutMode`: `layered`, `stress`, `force`, or `combined-force`
|
||||
- `motion`: viewer-owned force tuning for combined-force layouts
|
||||
- `motion`: viewer-owned force tuning for Rust-solver combined-force layouts
|
||||
- `performance`: `quality`, `balanced`, `fast`, or explicit `simulationBudgetMs` realtime knobs
|
||||
- `selection`, `focusSelection`, `expandedNode`, and callbacks for app integration
|
||||
- typed state and event payloads
|
||||
|
|
@ -227,7 +227,7 @@ It consumes the typed Epiphany graph state shape directly:
|
|||
|
||||
and packages:
|
||||
|
||||
- viewer-owned layout modes
|
||||
- Rust hybrid solver layout through bundled WASM
|
||||
- zoom and pan
|
||||
- zoom-gated label and detail pop-in
|
||||
- node, edge, and code-ref inspection
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ was how we got the little public API landfill.
|
|||
- `graphs.links` show cross-graph correspondences instead of vanishing into a sidecar file
|
||||
- zoom reveals more node detail instead of trying to print the whole phone book at once
|
||||
- selection opens purpose, mechanism, metaphor, status, and code references in a detail pane
|
||||
- `layoutMode="combined-force"` gives clients the compact ELK shape plus live force motion
|
||||
- `layoutMode="combined-force"` gives clients the Rust hybrid solver shape plus live force motion
|
||||
|
||||
## Install
|
||||
|
||||
|
|
@ -41,6 +41,20 @@ This writes:
|
|||
- `dist/index.d.ts`
|
||||
- `dist/demo/`
|
||||
|
||||
## Rust Solver WASM
|
||||
|
||||
The viewer uses `epiphany-graph-rs` as its layout authority. The bundled WASM is
|
||||
checked into `src/lib/solver-wasm-bytes.ts` so the package builds without a separate
|
||||
asset pipeline.
|
||||
|
||||
Regenerate it after changing `E:\Projects\epiphany-graph-rs`:
|
||||
|
||||
```powershell
|
||||
npm run build:solver:wasm
|
||||
```
|
||||
|
||||
ELK remains only as a fallback if the Rust solver fails to instantiate.
|
||||
|
||||
## Use In Another App
|
||||
|
||||
```tsx
|
||||
|
|
@ -80,7 +94,7 @@ the warehouse inventory.
|
|||
|
||||
- `layered`: stable default for hierarchy-heavy graphs
|
||||
- `stress`: compact overview shape for dense graphs
|
||||
- `force`: ELK force layout without browser-side motion
|
||||
- `force`: Rust hybrid solver with a looser organic force balance
|
||||
- `combined-force`: compact overview plus viewer-owned force motion
|
||||
|
||||
`layoutMode` accepts one mode for both graphs or per-graph modes:
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
"build": "npm run build:lib && npm run build:demo",
|
||||
"build:lib": "tsup src/index.ts --format esm,cjs --dts --external react --external react-dom --clean",
|
||||
"build:demo": "vite build --outDir dist/demo",
|
||||
"build:solver:wasm": "powershell -ExecutionPolicy Bypass -File ./scripts/Build-RustSolverWasm.ps1",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"tune:simulation": "node ./scripts/tune-simulation-profile.mjs",
|
||||
"preview": "vite preview"
|
||||
|
|
|
|||
28
web/epiphany-graph-viewer/scripts/Build-RustSolverWasm.ps1
Normal file
28
web/epiphany-graph-viewer/scripts/Build-RustSolverWasm.ps1
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
param(
|
||||
[string]$SolverRoot = "E:\Projects\epiphany-graph-rs"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$packageRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
|
||||
$solverRootPath = Resolve-Path $SolverRoot
|
||||
|
||||
Push-Location $solverRootPath
|
||||
try {
|
||||
rustup target add wasm32-unknown-unknown | Out-Host
|
||||
cargo build --release --target wasm32-unknown-unknown | Out-Host
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$wasmPath = Join-Path $solverRootPath "target\wasm32-unknown-unknown\release\epiphany_graph_rs.wasm"
|
||||
$outputPath = Join-Path $packageRoot "src\lib\solver-wasm-bytes.ts"
|
||||
$base64 = [Convert]::ToBase64String([IO.File]::ReadAllBytes($wasmPath))
|
||||
|
||||
@(
|
||||
"export const epiphanyGraphSolverWasmBase64 =",
|
||||
" `"$base64`";"
|
||||
) | Set-Content -LiteralPath $outputPath -Encoding UTF8
|
||||
|
||||
Write-Host "Updated $outputPath"
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import ELK from "elkjs/lib/elk.bundled.js";
|
||||
import { layoutWithRustSolver } from "./solver-wasm";
|
||||
import type {
|
||||
EpiphanyGraph,
|
||||
EpiphanyGraphEdge,
|
||||
|
|
@ -65,6 +66,22 @@ async function layoutGraph(
|
|||
links: EpiphanyGraphLink[],
|
||||
mode: EpiphanyGraphLayoutMode = "layered",
|
||||
viewport?: LayoutViewport,
|
||||
): Promise<GraphLayout> {
|
||||
try {
|
||||
return await layoutGraphWithRustSolver(graphKey, graph, links, mode, viewport);
|
||||
} catch (error) {
|
||||
console.warn("Epiphany Rust graph solver failed; falling back to ELK.", error);
|
||||
}
|
||||
|
||||
return layoutGraphWithElk(graphKey, graph, links, mode, viewport);
|
||||
}
|
||||
|
||||
async function layoutGraphWithElk(
|
||||
graphKey: GraphKey,
|
||||
graph: EpiphanyGraph,
|
||||
links: EpiphanyGraphLink[],
|
||||
mode: EpiphanyGraphLayoutMode = "layered",
|
||||
viewport?: LayoutViewport,
|
||||
): Promise<GraphLayout> {
|
||||
const algorithm = elkAlgorithmForMode(mode);
|
||||
const nodeDegrees = buildNodeDegrees(graph);
|
||||
|
|
@ -148,6 +165,91 @@ async function layoutGraph(
|
|||
};
|
||||
}
|
||||
|
||||
async function layoutGraphWithRustSolver(
|
||||
graphKey: GraphKey,
|
||||
graph: EpiphanyGraph,
|
||||
links: EpiphanyGraphLink[],
|
||||
mode: EpiphanyGraphLayoutMode,
|
||||
viewport?: LayoutViewport,
|
||||
): Promise<GraphLayout> {
|
||||
const sizingAlgorithm = sizingAlgorithmForMode(mode);
|
||||
const nodeDegrees = buildNodeDegrees(graph);
|
||||
const linkCounts = buildLinkCounts(graphKey, links);
|
||||
const nodeIndex = new Map(graph.nodes.map((node, index) => [node.id, index]));
|
||||
const sizes = graph.nodes.map((node) =>
|
||||
estimateNodeSize(node, graphKey, sizingAlgorithm, graph.nodes.length, viewport)
|
||||
);
|
||||
const edgePairs: number[] = [];
|
||||
for (const edge of graph.edges) {
|
||||
const source = nodeIndex.get(edge.source_id);
|
||||
const target = nodeIndex.get(edge.target_id);
|
||||
if (source == null || target == null) {
|
||||
continue;
|
||||
}
|
||||
edgePairs.push(source, target);
|
||||
}
|
||||
|
||||
const coordinates = await layoutWithRustSolver({
|
||||
nodeWeights: new Float32Array(
|
||||
graph.nodes.map((node, index) => {
|
||||
const degree = nodeDegrees.get(node.id) ?? 0;
|
||||
const linkCount = linkCounts.get(node.id) ?? 0;
|
||||
return Math.max(0.25, 1 + degree * 0.16 + linkCount * 0.24 + (sizes[index].width * sizes[index].height) / 80_000);
|
||||
}),
|
||||
),
|
||||
edgePairs: new Uint32Array(edgePairs),
|
||||
...rustSolverConfigFor(graphKey, mode),
|
||||
});
|
||||
|
||||
const positionedNodes: PositionedNode[] = graph.nodes.map((node, index) => {
|
||||
const size = sizes[index];
|
||||
const degree = nodeDegrees.get(node.id) ?? 0;
|
||||
const linkCount = linkCounts.get(node.id) ?? 0;
|
||||
const offset = index * 4;
|
||||
return {
|
||||
...node,
|
||||
code_refs: node.code_refs ?? [],
|
||||
graphKey,
|
||||
x: coordinates[offset] - size.width / 2,
|
||||
y: coordinates[offset + 1] - size.height / 2,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
degree,
|
||||
linkCount,
|
||||
badgeText: nodeBadgeText(node.title),
|
||||
fill: nodeFill(graphKey, node.status),
|
||||
stroke: nodeStroke(graphKey, node.status),
|
||||
};
|
||||
});
|
||||
const separatedNodes = normalizeNodeBounds(resizeNodesForSeparation(positionedNodes, sizingAlgorithm));
|
||||
const nodeLookup = new Map(separatedNodes.map((node) => [node.id, node]));
|
||||
const positionedEdges: PositionedEdge[] = graph.edges.map((source, index) => {
|
||||
const resolvedId = resolveEdgeId(source, index);
|
||||
const fallbackPoints = straightEdgePoints(source, nodeLookup);
|
||||
return {
|
||||
...source,
|
||||
id: source.id ?? null,
|
||||
label: source.label ?? null,
|
||||
mechanism: source.mechanism ?? null,
|
||||
code_refs: source.code_refs ?? [],
|
||||
graphKey,
|
||||
resolvedId,
|
||||
points: fallbackPoints,
|
||||
path: pointsToPath(fallbackPoints),
|
||||
midpoint: edgeMidpoint(fallbackPoints),
|
||||
};
|
||||
});
|
||||
|
||||
const bounds = layoutBounds(separatedNodes);
|
||||
return {
|
||||
graphKey,
|
||||
width: Math.max(720, bounds.width),
|
||||
height: Math.max(520, bounds.height),
|
||||
nodes: separatedNodes,
|
||||
edges: positionedEdges,
|
||||
};
|
||||
}
|
||||
|
||||
function layoutModeFor(
|
||||
graphKey: GraphKey,
|
||||
mode: EpiphanyGraphLayoutModeConfig,
|
||||
|
|
@ -171,6 +273,37 @@ function elkAlgorithmForMode(mode: EpiphanyGraphLayoutMode) {
|
|||
return "org.eclipse.elk.layered";
|
||||
}
|
||||
|
||||
function sizingAlgorithmForMode(mode: EpiphanyGraphLayoutMode) {
|
||||
return mode === "layered" ? "org.eclipse.elk.layered" : "org.eclipse.elk.stress";
|
||||
}
|
||||
|
||||
function rustSolverConfigFor(graphKey: GraphKey, mode: EpiphanyGraphLayoutMode) {
|
||||
if (mode === "layered") {
|
||||
return {
|
||||
iterations: graphKey === "architecture" ? 320 : 300,
|
||||
rankGap: graphKey === "architecture" ? 170 : 150,
|
||||
nodeGap: graphKey === "architecture" ? 96 : 112,
|
||||
edgeLength: graphKey === "architecture" ? 150 : 180,
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === "force") {
|
||||
return {
|
||||
iterations: graphKey === "architecture" ? 520 : 420,
|
||||
rankGap: graphKey === "architecture" ? 130 : 120,
|
||||
nodeGap: graphKey === "architecture" ? 92 : 112,
|
||||
edgeLength: graphKey === "architecture" ? 190 : 230,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
iterations: graphKey === "architecture" ? 380 : 320,
|
||||
rankGap: graphKey === "architecture" ? 145 : 132,
|
||||
nodeGap: graphKey === "architecture" ? 92 : 116,
|
||||
edgeLength: graphKey === "architecture" ? 180 : 220,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeNodeBounds(nodes: PositionedNode[]): PositionedNode[] {
|
||||
const bounds = layoutBounds(nodes);
|
||||
if (bounds.minX >= 0 && bounds.minY >= 0) {
|
||||
|
|
|
|||
2
web/epiphany-graph-viewer/src/lib/solver-wasm-bytes.ts
Normal file
2
web/epiphany-graph-viewer/src/lib/solver-wasm-bytes.ts
Normal file
File diff suppressed because one or more lines are too long
103
web/epiphany-graph-viewer/src/lib/solver-wasm.ts
Normal file
103
web/epiphany-graph-viewer/src/lib/solver-wasm.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import { epiphanyGraphSolverWasmBase64 } from "./solver-wasm-bytes";
|
||||
|
||||
type SolverExports = {
|
||||
memory: WebAssembly.Memory;
|
||||
epiphany_graph_alloc_f32: (count: number) => number;
|
||||
epiphany_graph_dealloc_f32: (ptr: number, count: number) => void;
|
||||
epiphany_graph_alloc_u32: (count: number) => number;
|
||||
epiphany_graph_dealloc_u32: (ptr: number, count: number) => void;
|
||||
epiphany_graph_layout_2d: (
|
||||
nodeWeightsPtr: number,
|
||||
nodeCount: number,
|
||||
edgePairsPtr: number,
|
||||
edgeCount: number,
|
||||
outputPtr: number,
|
||||
iterations: number,
|
||||
rankGap: number,
|
||||
nodeGap: number,
|
||||
edgeLength: number,
|
||||
) => number;
|
||||
};
|
||||
|
||||
export type RustGraphLayoutInput = {
|
||||
nodeWeights: Float32Array;
|
||||
edgePairs: Uint32Array;
|
||||
iterations: number;
|
||||
rankGap: number;
|
||||
nodeGap: number;
|
||||
edgeLength: number;
|
||||
};
|
||||
|
||||
let solverPromise: Promise<SolverExports> | null = null;
|
||||
|
||||
export async function layoutWithRustSolver(input: RustGraphLayoutInput): Promise<Float32Array> {
|
||||
const solver = await loadSolver();
|
||||
const nodeCount = input.nodeWeights.length;
|
||||
const edgeCount = input.edgePairs.length / 2;
|
||||
const nodeWeightsPtr = solver.epiphany_graph_alloc_f32(nodeCount);
|
||||
const edgePairsPtr = solver.epiphany_graph_alloc_u32(input.edgePairs.length);
|
||||
const outputPtr = solver.epiphany_graph_alloc_f32(nodeCount * 4);
|
||||
|
||||
try {
|
||||
new Float32Array(solver.memory.buffer, nodeWeightsPtr, nodeCount).set(input.nodeWeights);
|
||||
new Uint32Array(solver.memory.buffer, edgePairsPtr, input.edgePairs.length).set(input.edgePairs);
|
||||
const status = solver.epiphany_graph_layout_2d(
|
||||
nodeWeightsPtr,
|
||||
nodeCount,
|
||||
edgePairsPtr,
|
||||
edgeCount,
|
||||
outputPtr,
|
||||
input.iterations,
|
||||
input.rankGap,
|
||||
input.nodeGap,
|
||||
input.edgeLength,
|
||||
);
|
||||
if (status !== 0) {
|
||||
throw new Error(`Rust graph solver failed with status ${status}`);
|
||||
}
|
||||
|
||||
return new Float32Array(
|
||||
new Float32Array(solver.memory.buffer, outputPtr, nodeCount * 4),
|
||||
);
|
||||
} finally {
|
||||
solver.epiphany_graph_dealloc_f32(nodeWeightsPtr, nodeCount);
|
||||
solver.epiphany_graph_dealloc_u32(edgePairsPtr, input.edgePairs.length);
|
||||
solver.epiphany_graph_dealloc_f32(outputPtr, nodeCount * 4);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSolver(): Promise<SolverExports> {
|
||||
solverPromise ??= WebAssembly.instantiate(wasmBytes(), {}).then((result) => {
|
||||
const exports = result.instance.exports as Partial<SolverExports>;
|
||||
if (
|
||||
!(exports.memory instanceof WebAssembly.Memory) ||
|
||||
typeof exports.epiphany_graph_alloc_f32 !== "function" ||
|
||||
typeof exports.epiphany_graph_dealloc_f32 !== "function" ||
|
||||
typeof exports.epiphany_graph_alloc_u32 !== "function" ||
|
||||
typeof exports.epiphany_graph_dealloc_u32 !== "function" ||
|
||||
typeof exports.epiphany_graph_layout_2d !== "function"
|
||||
) {
|
||||
throw new Error("Rust graph solver wasm is missing required exports.");
|
||||
}
|
||||
|
||||
return exports as SolverExports;
|
||||
});
|
||||
|
||||
return solverPromise;
|
||||
}
|
||||
|
||||
function wasmBytes() {
|
||||
const maybeBuffer = (globalThis as { Buffer?: { from: (value: string, encoding: "base64") => { toString: (encoding: "binary") => string } } }).Buffer;
|
||||
const binary =
|
||||
typeof atob === "function"
|
||||
? atob(epiphanyGraphSolverWasmBase64)
|
||||
: maybeBuffer?.from(epiphanyGraphSolverWasmBase64, "base64").toString("binary");
|
||||
if (!binary) {
|
||||
throw new Error("No base64 decoder is available for the Rust graph solver wasm.");
|
||||
}
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
Loading…
Reference in a new issue