@graphty/webgpu-graph-algorithms 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +27 -21
  2. package/dist/browser.js +1 -1
  3. package/dist/chunks/{context-CRbw2Wyo.js → context-BR7fx3vR.js} +47 -5
  4. package/dist/chunks/context-BR7fx3vR.js.map +1 -0
  5. package/dist/node.js +1 -1
  6. package/dist/src/accelerator.d.ts +12 -10
  7. package/dist/src/accelerator.d.ts.map +1 -1
  8. package/dist/src/accelerator.js +32 -10
  9. package/dist/src/accelerator.js.map +1 -1
  10. package/dist/src/constants.d.ts +47 -0
  11. package/dist/src/constants.d.ts.map +1 -1
  12. package/dist/src/constants.js +47 -0
  13. package/dist/src/constants.js.map +1 -1
  14. package/dist/src/index.d.ts +7 -4
  15. package/dist/src/index.d.ts.map +1 -1
  16. package/dist/src/index.js +9 -5
  17. package/dist/src/index.js.map +1 -1
  18. package/dist/src/kernel/prelude.d.ts.map +1 -1
  19. package/dist/src/kernel/prelude.js +4 -1
  20. package/dist/src/kernel/prelude.js.map +1 -1
  21. package/dist/src/kernels.d.ts +3 -3
  22. package/dist/src/kernels.d.ts.map +1 -1
  23. package/dist/src/kernels.js +27 -11
  24. package/dist/src/kernels.js.map +1 -1
  25. package/dist/src/layouts/force-simulation.d.ts +3 -1
  26. package/dist/src/layouts/force-simulation.d.ts.map +1 -1
  27. package/dist/src/layouts/force-simulation.js +13 -3
  28. package/dist/src/layouts/force-simulation.js.map +1 -1
  29. package/dist/src/layouts/forceatlas2.d.ts +1 -3
  30. package/dist/src/layouts/forceatlas2.d.ts.map +1 -1
  31. package/dist/src/layouts/forceatlas2.js +2 -191
  32. package/dist/src/layouts/forceatlas2.js.map +1 -1
  33. package/dist/src/layouts/fruchterman-reingold.d.ts +195 -0
  34. package/dist/src/layouts/fruchterman-reingold.d.ts.map +1 -0
  35. package/dist/src/layouts/fruchterman-reingold.js +579 -0
  36. package/dist/src/layouts/fruchterman-reingold.js.map +1 -0
  37. package/dist/src/layouts/model-common.d.ts +102 -0
  38. package/dist/src/layouts/model-common.d.ts.map +1 -0
  39. package/dist/src/layouts/model-common.js +198 -0
  40. package/dist/src/layouts/model-common.js.map +1 -0
  41. package/dist/src/layouts/spring-electrical.d.ts +179 -0
  42. package/dist/src/layouts/spring-electrical.d.ts.map +1 -0
  43. package/dist/src/layouts/spring-electrical.js +508 -0
  44. package/dist/src/layouts/spring-electrical.js.map +1 -0
  45. package/dist/src/types/accelerator.d.ts +7 -3
  46. package/dist/src/types/accelerator.d.ts.map +1 -1
  47. package/dist/src/types/layout.d.ts +32 -0
  48. package/dist/src/types/layout.d.ts.map +1 -1
  49. package/dist/src/types/options.d.ts +43 -1
  50. package/dist/src/types/options.d.ts.map +1 -1
  51. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts +5 -2
  52. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts.map +1 -1
  53. package/dist/src/wgsl/fa2-attraction.wgsl.js +6 -1
  54. package/dist/src/wgsl/fa2-attraction.wgsl.js.map +1 -1
  55. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts +7 -2
  56. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts.map +1 -1
  57. package/dist/src/wgsl/fa2-integrate.wgsl.js +28 -2
  58. package/dist/src/wgsl/fa2-integrate.wgsl.js.map +1 -1
  59. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts +4 -2
  60. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts.map +1 -1
  61. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js +14 -5
  62. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js.map +1 -1
  63. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts +8 -1
  64. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts.map +1 -1
  65. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js +33 -0
  66. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js.map +1 -1
  67. package/dist/tsconfig.build.tsbuildinfo +1 -1
  68. package/dist/webgpu-graph-algorithms.js +1358 -284
  69. package/dist/webgpu-graph-algorithms.js.map +1 -1
  70. package/package.json +6 -4
  71. package/src/accelerator.ts +46 -12
  72. package/src/constants.ts +70 -0
  73. package/src/index.ts +15 -5
  74. package/src/kernel/prelude.ts +6 -0
  75. package/src/kernels.ts +27 -11
  76. package/src/layouts/force-simulation.ts +20 -3
  77. package/src/layouts/forceatlas2.ts +17 -220
  78. package/src/layouts/fruchterman-reingold.ts +737 -0
  79. package/src/layouts/model-common.ts +228 -0
  80. package/src/layouts/spring-electrical.ts +666 -0
  81. package/src/types/accelerator.ts +15 -3
  82. package/src/types/layout.ts +36 -0
  83. package/src/types/options.ts +45 -1
  84. package/src/wgsl/fa2-attraction.wgsl.ts +6 -1
  85. package/src/wgsl/fa2-integrate.wgsl.ts +28 -2
  86. package/src/wgsl/fa2-repulsion-exact.wgsl.ts +14 -5
  87. package/src/wgsl/fa2-stats-finalize.wgsl.ts +33 -0
  88. package/dist/chunks/context-CRbw2Wyo.js.map +0 -1
@@ -0,0 +1,737 @@
1
+ /**
2
+ * Fruchterman-Reingold on the exact repulsion tier (spec 7.20; contract 3.13): the ForceModel that ForceSimulation
3
+ * drives -- the K1 K2 K3 K5 sequence per iteration and toScene per batch (no K4: no speed controller), the constant
4
+ * override set (`LAW` 1 on K2 / K3, `APPLY` 1 on K5, `STATS_MODE` 1 on K1, PD-1), the per-iteration Fa2Params values
5
+ * with the cooling schedule's temperature (PD-5), the controller resets and the stats decoder -- plus the option
6
+ * resolver and `createFruchtermanReingold`. The model shares FA2's four kernels, buffers and blocks: `oldForce` is
7
+ * allocated, bound and never read (K5 compiles `SWING_MODE = 1`, PD-2 / PD-20); the mass lane is 1 for every node
8
+ * and weights are ignored (PD-11); the `fixed` option resolves at load through ModelInputs.fixed (PD-6); a
9
+ * `setParams({ fixed })` patch is E_INVALID_ARGUMENT (PD-16).
10
+ *
11
+ * The temperature index (PD-5): the simulation hands paramsFor the GLOBAL iteration index, which load() restarts at 0
12
+ * and reheat() does not touch. The model keeps `tempOrigin` (the global index at which the temperature index is 0):
13
+ * onLoad sets it to 0; onReheat arms `pendingReheat`; the first paramsFor(global) after it sets
14
+ * `tempOrigin = global - floor(0.7 * iterations)`, so the temperature restarts at floor(0.7 * iterations) exactly as
15
+ * the CPU's reheat() does. The temperature is `max(0, 0.1 - dt * (global - tempOrigin))`, dt = 0.1 / (iterations + 1);
16
+ * at 0 nothing moves and the settle window closes the run (DEP-P5-C: the budget restarts at 0, the temperature does
17
+ * not).
18
+ */
19
+
20
+ import { type GraphSnapshot, type NodeMask } from "@graphty/graph-format";
21
+
22
+ import {
23
+ FA2_FLAG_ADAPTIVE,
24
+ FR_ADAPTIVE_MAX_ITERATIONS,
25
+ FR_DEFAULTS,
26
+ FR_REHEAT_FRACTION,
27
+ FR_START_TEMPERATURE,
28
+ MAX_ITERATIONS_PER_STEP,
29
+ TRACE_RECORD_BYTES,
30
+ UNIFORM_SLOT_BYTES,
31
+ } from "../constants.js";
32
+ import { type GpuContext } from "../context.js";
33
+ import { BufferUsage } from "../device/webgpu-constants.js";
34
+ import { WebGpuGraphError } from "../errors.js";
35
+ import { type CommandBatch } from "../kernel/batch.js";
36
+ import { type DispatchPlan, plan1d } from "../kernel/dispatch.js";
37
+ import { type BoundKernel, type Kernel } from "../kernel/kernel.js";
38
+ import { type UniformBlock, type UniformValues } from "../kernel/struct-block.js";
39
+ import { type WgslModuleSpec } from "../kernel/wgsl.js";
40
+ import { FA2_PARAMS, FA2_STATE, FA2_TRACE, FILL_PARAMS, graphBindings, kernelSpec } from "../kernels.js";
41
+ import {
42
+ type FruchtermanReingoldStats,
43
+ type FruchtermanReingoldTraceRecord,
44
+ type GpuLayoutSimulation,
45
+ type GpuLayoutTuning,
46
+ type ResolvedLayoutTuning,
47
+ } from "../types/layout.js";
48
+ import { type Binding } from "../types/memory.js";
49
+ import { type FruchtermanReingoldOptions, type ResolvedFruchtermanReingoldOptions } from "../types/options.js";
50
+ import {
51
+ type BufferSpec,
52
+ type ForceModel,
53
+ ForceSimulation,
54
+ type ModelInputs,
55
+ type ModelResources,
56
+ type StateWriter,
57
+ } from "./force-simulation.js";
58
+ import { resolveLayoutTuning } from "./forceatlas2.js";
59
+ import {
60
+ describeValue,
61
+ FILL_PARAMS_BUFFER,
62
+ FORCE_BYTES_PER_NODE,
63
+ invalid,
64
+ isPositiveInteger,
65
+ type Overrides,
66
+ pickCenter,
67
+ pickDim,
68
+ pickNumber,
69
+ pickSeed,
70
+ scalar,
71
+ seedWord,
72
+ subset,
73
+ vector,
74
+ } from "./model-common.js";
75
+
76
+ // ============================================================ constants
77
+
78
+ /** The stage names of one iteration in dispatch order plus the per-batch toScene (spec 7.20: no K4). */
79
+ const FR_STAGES = ["K1", "K2", "K3", "K5", "toScene"] as const;
80
+
81
+ /** The one-workgroup dispatch of K1 (spec 7.4). */
82
+ const ONE_WORKGROUP: DispatchPlan = { x: 1, y: 1, z: 1, items: 1, stride: null };
83
+
84
+ /** The model's override set, constant for every option record (PD-1, PD-20). */
85
+ const FR_OVERRIDES: Overrides = Object.freeze({
86
+ LINLOG: false,
87
+ DISTRIBUTED: false,
88
+ TIER: 0,
89
+ SWING_MODE: 1,
90
+ STRONG_GRAVITY: false,
91
+ GRAVITY_CENTER: 0,
92
+ LAW: 1,
93
+ APPLY: 1,
94
+ STATS_MODE: 1,
95
+ });
96
+
97
+ /** Every override each kernel accepts, with its default (the names its registry entry declares). */
98
+ const K1_DEFAULTS: Overrides = { STATS_MODE: 0 };
99
+ const K2_DEFAULTS: Overrides = {
100
+ LINLOG: false,
101
+ DISTRIBUTED: false,
102
+ TIER: 0,
103
+ USE_PERM: false,
104
+ HAS_WEIGHTS: false,
105
+ LAW: 0,
106
+ };
107
+ const K3_DEFAULTS: Overrides = { SWING_MODE: 0, STRONG_GRAVITY: false, GRAVITY_CENTER: 0, LAW: 0 };
108
+ const K5_DEFAULTS: Overrides = { SWING_MODE: 0, APPLY: 0 };
109
+
110
+ /** The resolved record with no option given: FR_DEFAULTS plus the null / origin defaults. */
111
+ const DEFAULT_RESOLVED: ResolvedFruchtermanReingoldOptions = Object.freeze<ResolvedFruchtermanReingoldOptions>({
112
+ ...FR_DEFAULTS,
113
+ center: [0, 0, 0],
114
+ seed: null,
115
+ });
116
+
117
+ // ============================================================ the resolver
118
+
119
+ /**
120
+ * The `k` option: undefined keeps the fallback; null, 0 and NaN mean the auto default (null); else a finite
121
+ * number > 0.
122
+ * @param given - the value given
123
+ * @param fallback - the previous record's value or the default
124
+ * @returns k or null
125
+ */
126
+ function resolveK(given: number | null | undefined, fallback: number | null): number | null {
127
+ if (given === undefined) {
128
+ return fallback;
129
+ }
130
+ if (given === null || given === 0 || Number.isNaN(given)) {
131
+ return null;
132
+ }
133
+ return pickNumber("k", given, 1, (v) => v > 0, "> 0 or null");
134
+ }
135
+
136
+ /**
137
+ * The `cooling` option: undefined keeps the fallback; else one of the two schedule names.
138
+ * @param given - the value given
139
+ * @param fallback - the previous record's value or the default
140
+ * @returns the schedule
141
+ */
142
+ function pickCooling(given: unknown, fallback: "linear" | "adaptive"): "linear" | "adaptive" {
143
+ if (given === undefined) {
144
+ return fallback;
145
+ }
146
+ if (given === "linear" || given === "adaptive") {
147
+ return given;
148
+ }
149
+ throw invalid("cooling", given, '"linear" | "adaptive"');
150
+ }
151
+
152
+ /**
153
+ * Applies FR_DEFAULTS to the option record and validates every range (spec 7.20, 9.3). `k`: null, 0 and NaN mean the
154
+ * auto default `1 / sqrt(n)` (the CPU's `if (!k)`, `layout/src/simulation/fruchterman-reingold.ts:140-152`); a
155
+ * negative or infinite k is E_INVALID_ARGUMENT. `iterations` is an integer >= 0 (0: settled at load); under
156
+ * `cooling: "adaptive"` it is only the run's cap and a fresh record without one gets FR_ADAPTIVE_MAX_ITERATIONS. `fixed` is a
157
+ * NodeMask, a bool node column name or null. With `previous` the record is a PATCH over it and `maxInFlight` may not
158
+ * change (the uniform ring is sized by it at construction).
159
+ * @param options - the caller's options (or a setParams patch)
160
+ * @param previous - the current resolved record when resolving a patch
161
+ * @returns the frozen resolved record
162
+ */
163
+ export function resolveFruchtermanReingoldOptions(
164
+ options: FruchtermanReingoldOptions | undefined,
165
+ previous?: ResolvedFruchtermanReingoldOptions,
166
+ ): ResolvedFruchtermanReingoldOptions {
167
+ const o: FruchtermanReingoldOptions = options ?? {};
168
+ const base = previous ?? DEFAULT_RESOLVED;
169
+ if (previous !== undefined && o.maxInFlight !== undefined && o.maxInFlight !== previous.maxInFlight) {
170
+ throw new WebGpuGraphError(
171
+ "E_INVALID_ARGUMENT",
172
+ `maxInFlight cannot change after creation (the uniform ring is sized by it): got ${describeValue(o.maxInFlight)}, current ${previous.maxInFlight}`,
173
+ { argument: "maxInFlight", value: o.maxInFlight, expected: previous.maxInFlight },
174
+ );
175
+ }
176
+ const fixed: unknown = o.fixed === undefined ? base.fixed : o.fixed;
177
+ if (fixed !== null && typeof fixed !== "string" && !(fixed instanceof Uint32Array)) {
178
+ throw invalid("fixed", fixed, "a NodeMask (Uint32Array), the name of a bool node column, or null");
179
+ }
180
+ const cooling = pickCooling(o.cooling, base.cooling);
181
+ // under adaptive cooling `iterations` is only a cap: a fresh record without one gets the adaptive budget, not the schedule's 50
182
+ const iterationsFallback =
183
+ previous === undefined && cooling === "adaptive" && o.iterations === undefined
184
+ ? FR_ADAPTIVE_MAX_ITERATIONS
185
+ : base.iterations;
186
+ const resolved: ResolvedFruchtermanReingoldOptions = {
187
+ k: resolveK(o.k, base.k),
188
+ iterations: pickNumber(
189
+ "iterations",
190
+ o.iterations,
191
+ iterationsFallback,
192
+ (v) => Number.isInteger(v) && v >= 0,
193
+ "an integer >= 0",
194
+ ),
195
+ cooling,
196
+ fixed: fixed as NodeMask | string | null,
197
+ dim: pickDim(o.dim, base.dim),
198
+ scale: pickNumber("scale", o.scale, base.scale, (v) => v > 0, "> 0"),
199
+ center: pickCenter(o.center, base.center),
200
+ seed: pickSeed(o.seed, base.seed),
201
+ settleThreshold: pickNumber("settleThreshold", o.settleThreshold, base.settleThreshold, (v) => v >= 0, ">= 0"),
202
+ settleWindow: pickNumber(
203
+ "settleWindow",
204
+ o.settleWindow,
205
+ base.settleWindow,
206
+ isPositiveInteger,
207
+ "an integer >= 1",
208
+ ),
209
+ iterationsPerStep: pickNumber(
210
+ "iterationsPerStep",
211
+ o.iterationsPerStep,
212
+ base.iterationsPerStep,
213
+ (v) => isPositiveInteger(v) && v <= MAX_ITERATIONS_PER_STEP,
214
+ `an integer in [1, ${MAX_ITERATIONS_PER_STEP}]`,
215
+ ),
216
+ maxInFlight: pickNumber("maxInFlight", o.maxInFlight, base.maxInFlight, isPositiveInteger, "an integer >= 1"),
217
+ };
218
+ return Object.freeze(resolved);
219
+ }
220
+
221
+ /**
222
+ * The fixed mask of a load (spec 7.12; the rule of `layout/src/simulation/fruchterman-reingold.ts:576-606` minus its
223
+ * "previous pins" clause, which ForceSimulation.load() implements by keeping the words on a same-size reload): a
224
+ * string names a bool node column (E_INVALID_ARGUMENT when absent or not bool); a mask is copied; null takes the
225
+ * role-"fixed" bool column when present, else null (leave the words as they are).
226
+ * @param s - the snapshot being loaded
227
+ * @param spec - the resolved `fixed` option
228
+ * @returns the mask words to apply at load, or null
229
+ */
230
+ function resolveFixed(s: GraphSnapshot, spec: NodeMask | string | null): NodeMask | null {
231
+ const words = Math.ceil(s.nodeCount / 32);
232
+ if (typeof spec === "string") {
233
+ const column = s.nodes.get(spec);
234
+ if (column === null) {
235
+ throw invalid(
236
+ "fixed",
237
+ spec,
238
+ `the name of a bool node column (the snapshot holds no node column "${spec}")`,
239
+ );
240
+ }
241
+ if (column.dtype !== "bool") {
242
+ throw invalid("fixed", spec, `the name of a bool node column ("${spec}" is ${column.dtype})`);
243
+ }
244
+ return new Uint32Array(column.data.subarray(0, words));
245
+ }
246
+ if (spec !== null) {
247
+ if (spec.length < words) {
248
+ throw invalid("fixed", spec.length, `a mask of at least ${words} words for ${s.nodeCount} nodes`);
249
+ }
250
+ return new Uint32Array(spec.subarray(0, words));
251
+ }
252
+ const byRole = s.nodes.byRole("fixed");
253
+ if (byRole !== null && byRole.dtype === "bool") {
254
+ return new Uint32Array(byRole.data.subarray(0, words));
255
+ }
256
+ return null;
257
+ }
258
+
259
+ // ============================================================ the model
260
+
261
+ /** Everything bind() produced for one load(): the kernels, their bind groups and the dispatch plans of this n. */
262
+ interface BoundModel {
263
+ readonly n: number;
264
+ /** plan1d(n): K2, K3, K5, toScene. */
265
+ readonly plan: DispatchPlan;
266
+ /** plan1d(3n): the fill of force (3 words per node). */
267
+ readonly fillPlan: DispatchPlan;
268
+ readonly k1: Kernel;
269
+ readonly k1Bound: BoundKernel;
270
+ readonly k2: Kernel;
271
+ /** null when arcCount === 0 (K2 is not recorded; the fill below zeroes force instead, spec 7.5). */
272
+ readonly k2Bound: BoundKernel | null;
273
+ readonly k3: Kernel;
274
+ readonly k3Bound: BoundKernel;
275
+ readonly k5: Kernel;
276
+ readonly k5Bound: BoundKernel;
277
+ readonly toScene: Kernel;
278
+ readonly toSceneBound: BoundKernel;
279
+ readonly fill: Kernel;
280
+ /** The fill of `force` (arcCount === 0 only). */
281
+ readonly fillForceBound: BoundKernel | null;
282
+ }
283
+
284
+ /** The Fruchterman-Reingold model (spec 7.20: K1 K2 K3 K5 per iteration; toScene once per batch). Stages: ["K1", "K2", "K3", "K5", "toScene"]. */
285
+ export class FruchtermanReingoldModel implements ForceModel<FruchtermanReingoldOptions, FruchtermanReingoldStats> {
286
+ /** The model kind of spec 7.19. */
287
+ readonly kind = "fruchtermanReingold";
288
+ /** The stage names in dispatch order (the `upTo` vocabulary of recordIteration and debugRunStages). */
289
+ readonly stages: readonly ["K1", "K2", "K3", "K5", "toScene"] = FR_STAGES;
290
+ /** Fa2Params: the per-iteration uniform block (the simulation writes the shared fields into it). */
291
+ readonly params: UniformBlock = FA2_PARAMS;
292
+ /** Fa2State: the state header block. */
293
+ readonly state: UniformBlock = FA2_STATE;
294
+ /** Fa2Trace: one record per iteration of a batch. */
295
+ readonly trace: UniformBlock = FA2_TRACE;
296
+ /** The resolved GPU-only tuning this model was created with. */
297
+ readonly tuning: ResolvedLayoutTuning;
298
+
299
+ /** The option record the model holds: the constructor's record, replaced by onSetParams() ONLY (as FA2's). */
300
+ private current: ResolvedFruchtermanReingoldOptions;
301
+ /** The global iteration index at which the temperature index is 0 (PD-5). */
302
+ private tempOrigin = 0;
303
+ /** Armed by onReheat(); consumed by the next paramsFor(), which re-anchors tempOrigin (PD-5). */
304
+ private pendingReheat = false;
305
+ private resources: ModelResources | null = null;
306
+ private bound: BoundModel | null = null;
307
+ /** The K1-K5 compute pass of the batch being recorded, keyed by CommandBatch.id (one pass per batch, contract 4.4). */
308
+ private openPass: { readonly id: number; readonly pass: GPUComputePassEncoder } | null = null;
309
+
310
+ /**
311
+ * Creates the model for one simulation.
312
+ * @param tuning - the resolved GPU-only tuning (the tier rule; compat has no effect on this model)
313
+ * @param resolved - the resolved option record at creation
314
+ */
315
+ constructor(tuning: ResolvedLayoutTuning, resolved: ResolvedFruchtermanReingoldOptions) {
316
+ this.tuning = tuning;
317
+ this.current = resolved;
318
+ }
319
+
320
+ /**
321
+ * force 12n and oldForce 12n (zeroed; bound and never read, PD-2) plus the 256-byte FillParams uniform buffer the
322
+ * fill dispatch reads. n = 0 reports one node's worth of bytes so no zero-length buffer is ever created.
323
+ * @param n - the node count
324
+ * @param _dim - the layout dimension (the force arrays are stride 3 in both)
325
+ * @returns the three model-owned buffer specs
326
+ */
327
+ buffers(n: number, _dim: 2 | 3): readonly BufferSpec[] {
328
+ const bytes = Math.max(1, n) * FORCE_BYTES_PER_NODE;
329
+ const usage = BufferUsage.STORAGE | BufferUsage.COPY_SRC | BufferUsage.COPY_DST;
330
+ return [
331
+ { name: "force", byteLength: bytes, usage, zero: true },
332
+ { name: "oldForce", byteLength: bytes, usage, zero: true },
333
+ {
334
+ name: FILL_PARAMS_BUFFER,
335
+ byteLength: UNIFORM_SLOT_BYTES,
336
+ usage: BufferUsage.UNIFORM | BufferUsage.COPY_DST,
337
+ zero: false,
338
+ },
339
+ ];
340
+ }
341
+
342
+ /**
343
+ * Mass 1 for every node and no weights (PD-11: FR has no mass and ignores weights), the fixed mask of the
344
+ * `fixed` option applied at load (PD-6). The tier rule is the simulation's (load() throws for the grid tier
345
+ * before calling this).
346
+ * @param s - the snapshot being loaded
347
+ * @param options - the simulation's current option record
348
+ * @returns the per-load inputs
349
+ */
350
+ inputs(s: GraphSnapshot, options: FruchtermanReingoldOptions): ModelInputs {
351
+ const resolved = resolveFruchtermanReingoldOptions(options, this.current);
352
+ return {
353
+ mass: new Float32Array(s.nodeCount).fill(1),
354
+ weights: { data: null, source: "none", column: null },
355
+ fixed: resolveFixed(s, resolved.fixed),
356
+ };
357
+ }
358
+
359
+ /**
360
+ * The constant FR override set (PD-1): no option changes a law, so setParams never recompiles.
361
+ * @param _options - an option record (unused: the set is constant)
362
+ * @returns the model's own override set
363
+ */
364
+ overrides(_options: FruchtermanReingoldOptions): Overrides {
365
+ return FR_OVERRIDES;
366
+ }
367
+
368
+ /**
369
+ * The six module specs of an override set in dispatch order -- K1, K2, K3, K5, toScene, fill -- each with only the
370
+ * override names its entry declares (K2 also USE_PERM / HAS_WEIGHTS), for warm() and the compile matrix.
371
+ * @param overrides - the merged override set (the model's plus USE_PERM / HAS_WEIGHTS)
372
+ * @param _subgroups - accepted for the ForceModel interface and unused (the composer picks the twin from caps)
373
+ * @returns the specs
374
+ */
375
+ specs(overrides: Overrides, _subgroups: boolean): readonly WgslModuleSpec[] {
376
+ return [
377
+ kernelSpec("fa2-stats-finalize", subset(overrides, K1_DEFAULTS)),
378
+ kernelSpec("fa2-attraction", subset(overrides, K2_DEFAULTS)),
379
+ kernelSpec("fa2-repulsion-exact", subset(overrides, K3_DEFAULTS)),
380
+ kernelSpec("fa2-integrate", subset(overrides, K5_DEFAULTS)),
381
+ kernelSpec("fa2-to-scene"),
382
+ kernelSpec("fill"),
383
+ ];
384
+ }
385
+
386
+ /**
387
+ * Compiles (through the cache) and binds every kernel against the buffers of this load(): K1, K2 (or the fill of
388
+ * force when arcCount === 0), K3, K5, toScene; writes the FillParams { count: 3n, value: 0, mode: 0 } into the
389
+ * model's uniform buffer. With n === 0 nothing is bound.
390
+ * @param resources - the graph, the shared and model buffers, the ring and the cache
391
+ * @param overrides - the merged override set
392
+ */
393
+ async bind(resources: ModelResources, overrides: Overrides): Promise<void> {
394
+ this.dropBound();
395
+ this.resources = resources;
396
+ const { n, pipelines, caps, core, perm, ring, device } = resources;
397
+ if (n === 0) {
398
+ return;
399
+ }
400
+ // sequential on purpose: PipelineCache.get compiles inside a validation scope, one stack per device
401
+ const k1 = await pipelines.kernel(kernelSpec("fa2-stats-finalize", subset(overrides, K1_DEFAULTS)));
402
+ const k2 = await pipelines.kernel(kernelSpec("fa2-attraction", subset(overrides, K2_DEFAULTS)));
403
+ const k3 = await pipelines.kernel(kernelSpec("fa2-repulsion-exact", subset(overrides, K3_DEFAULTS)));
404
+ const k5 = await pipelines.kernel(kernelSpec("fa2-integrate", subset(overrides, K5_DEFAULTS)));
405
+ const toScene = await pipelines.kernel(kernelSpec("fa2-to-scene"));
406
+ const fill = await pipelines.kernel(kernelSpec("fill"));
407
+ if (this.resources !== resources) {
408
+ // a newer bind() superseded this one while the pipelines compiled; its own bind groups stand
409
+ return;
410
+ }
411
+ const pos = resources.buffer("positions");
412
+ const scene = resources.buffer("scenePositions");
413
+ const fixed = resources.buffer("fixed");
414
+ const partials = resources.buffer("partials");
415
+ const state = resources.buffer("state");
416
+ const trace = resources.buffer("trace");
417
+ const force = resources.buffer("force");
418
+ const oldForce = resources.buffer("oldForce");
419
+ const fillParamsBuffer = resources.buffer(FILL_PARAMS_BUFFER);
420
+ const params = ring.binding(FA2_PARAMS);
421
+ const fillParams: Binding = {
422
+ buffer: fillParamsBuffer.buffer,
423
+ offset: fillParamsBuffer.offset,
424
+ size: FILL_PARAMS.byteLength,
425
+ window: null,
426
+ };
427
+ const fillBytes = new ArrayBuffer(FILL_PARAMS.byteLength);
428
+ FILL_PARAMS.write(new DataView(fillBytes), { count: 3 * n, value: 0, mode: 0 });
429
+ device.queue.writeBuffer(fillParamsBuffer.buffer, fillParamsBuffer.offset, fillBytes);
430
+ const hasArcs = core.colIdx !== null;
431
+ const wg = k1.workgroupSize;
432
+ this.bound = {
433
+ n,
434
+ plan: plan1d(n, wg, caps),
435
+ fillPlan: plan1d(3 * n, wg, caps),
436
+ k1,
437
+ k1Bound: k1.bind({ partials, S: state, T: trace, P: params }),
438
+ k2,
439
+ k2Bound: hasArcs
440
+ ? k2.bind({ ...graphBindings(core, perm, resources.weights), pos, force, P: params })
441
+ : null,
442
+ k3,
443
+ k3Bound: k3.bind({ pos, S: state, force, oldForce, fixedMask: fixed, partials, P: params }),
444
+ k5,
445
+ k5Bound: k5.bind({ force, oldForce, fixedMask: fixed, S: state, pos, partials, P: params }),
446
+ toScene,
447
+ toSceneBound: toScene.bind({ pos, scene, P: params }),
448
+ fill,
449
+ fillForceBound: hasArcs ? null : fill.bind({ dst: force, P: fillParams }),
450
+ };
451
+ }
452
+
453
+ /**
454
+ * The Fa2Params values of one iteration: the FA2 fields at their neutral values (scalingRatio, gravity and
455
+ * jitterTolerance 0), `frK` = k or 1 / sqrt(n), and this iteration's temperature (PD-5 anchors here). Under
456
+ * `cooling: "adaptive"` the flags carry FA2_FLAG_ADAPTIVE and the kernels take the temperature from the state
457
+ * block instead (K1 updates it, K5 reads it); the uniform's value is then the start temperature and unused. The
458
+ * simulation overwrites the shared fields with the same values and OR-s in its own flags.
459
+ * @param iteration - the GLOBAL iteration index
460
+ * @param options - the simulation's current option record
461
+ * @returns the uniform values
462
+ */
463
+ paramsFor(iteration: number, options: FruchtermanReingoldOptions): UniformValues {
464
+ const { n } = this.requireResources();
465
+ const resolved = resolveFruchtermanReingoldOptions(options, this.current);
466
+ const { nearMax, extentFactor } = this.tuning;
467
+ const adaptive = resolved.cooling === "adaptive";
468
+ return {
469
+ n,
470
+ dim: resolved.dim,
471
+ flags: adaptive ? FA2_FLAG_ADAPTIVE : 0,
472
+ tierStart: 0,
473
+ tierEnd: n,
474
+ iterationIndex: iteration,
475
+ seed: seedWord(resolved.seed),
476
+ nearMax,
477
+ scalingRatio: 0,
478
+ gravity: 0,
479
+ jitterTolerance: 0,
480
+ scale: resolved.scale,
481
+ center: [resolved.center[0], resolved.center[1], resolved.center[2], 0],
482
+ settleThreshold: resolved.settleThreshold,
483
+ extentFactor,
484
+ gridMax: 0,
485
+ levels: 0,
486
+ pad: [0, 0, 0, 0],
487
+ frK: resolved.k ?? 1 / Math.sqrt(n),
488
+ temperature: adaptive ? FR_START_TEMPERATURE : this.temperatureAt(iteration, resolved),
489
+ };
490
+ }
491
+
492
+ /**
493
+ * Records one iteration into the batch: K1, K2 (or the fill of force when arcCount === 0), K3, K5 in the batch's
494
+ * ONE compute pass (opened by the first call of a batch and reused by every later call with the same batch.id),
495
+ * then toScene in a second pass that ends it, stopping after stage `upTo` when given. With n === 0 nothing is
496
+ * recorded; a call before bind() completed is E_NOT_LOADED (never a silent no-op).
497
+ * @param batch - the batch being recorded
498
+ * @param slot - the UniformRing slot holding this iteration's Fa2Params
499
+ * @param tier - "exact" (the grid tier is E_UNSUPPORTED until P4)
500
+ * @param upTo - a stage name to stop after; undefined records every stage including toScene
501
+ */
502
+ recordIteration(batch: CommandBatch, slot: number, tier: "exact" | "grid", upTo?: string): void {
503
+ if (tier === "grid") {
504
+ throw new WebGpuGraphError("E_UNSUPPORTED", "the grid repulsion tier lands in P4", {
505
+ feature: "repulsion.grid",
506
+ hint: 'pass repulsion: "exact"',
507
+ });
508
+ }
509
+ const resources = this.requireResources();
510
+ const stop = upTo === undefined ? FR_STAGES.length - 1 : this.stageIndex(upTo);
511
+ const { bound } = this;
512
+ if (bound === null) {
513
+ if (resources.n === 0) {
514
+ return;
515
+ }
516
+ throw new WebGpuGraphError(
517
+ "E_NOT_LOADED",
518
+ "the Fruchterman-Reingold model is not bound (bind() has not completed)",
519
+ { state: "loaded" },
520
+ );
521
+ }
522
+ const offset = resources.ring.offsetOf(slot);
523
+ const pass = this.openPass !== null && this.openPass.id === batch.id ? this.openPass.pass : batch.pass("fr");
524
+ this.openPass = { id: batch.id, pass };
525
+ bound.k1.dispatch(pass, bound.k1Bound, ONE_WORKGROUP, [offset]);
526
+ if (stop < 1) {
527
+ return;
528
+ }
529
+ if (bound.k2Bound !== null) {
530
+ bound.k2.dispatch(pass, bound.k2Bound, bound.plan, [offset]);
531
+ } else if (bound.fillForceBound !== null) {
532
+ bound.fill.dispatch(pass, bound.fillForceBound, bound.fillPlan, [0]);
533
+ }
534
+ if (stop < 2) {
535
+ return;
536
+ }
537
+ bound.k3.dispatch(pass, bound.k3Bound, bound.plan, [offset]);
538
+ if (stop < 3) {
539
+ return;
540
+ }
541
+ bound.k5.dispatch(pass, bound.k5Bound, bound.plan, [offset]);
542
+ if (stop < 4) {
543
+ return;
544
+ }
545
+ this.openPass = null;
546
+ const scenePass = batch.pass("fa2-to-scene");
547
+ bound.toScene.dispatch(scenePass, bound.toSceneBound, bound.plan, [offset]);
548
+ }
549
+
550
+ /**
551
+ * temperature = 0.1 (what stats reads before the first batch lands), kineticEnergy = 0; the temperature index
552
+ * restarts at 0 (PD-5).
553
+ * @param state - the state writer of the simulation
554
+ */
555
+ onLoad(state: StateWriter): void {
556
+ this.resetAdaptive(state);
557
+ state.set("kineticEnergy", 0);
558
+ this.tempOrigin = 0;
559
+ this.pendingReheat = false;
560
+ }
561
+
562
+ /**
563
+ * temperature = 0.1, the adaptive controller's energy = +infinity (the first fold always counts as a fall) and
564
+ * its progress counter = 0: the state K1 reads under `cooling: "adaptive"`, and what stats reads before the first
565
+ * batch lands under either schedule.
566
+ * @param state - the state writer of the simulation
567
+ */
568
+ private resetAdaptive(state: StateWriter): void {
569
+ state.set("temperature", FR_START_TEMPERATURE);
570
+ state.set("frEnergy", Number.POSITIVE_INFINITY);
571
+ state.set("frProgress", 0);
572
+ }
573
+
574
+ /**
575
+ * Arms the re-anchoring of the temperature index at floor(0.7 * iterations), placed by the next paramsFor (PD-5);
576
+ * under `cooling: "adaptive"` restarts the controller at the start temperature instead.
577
+ * @param state - the state writer of the simulation
578
+ */
579
+ onReheat(state: StateWriter): void {
580
+ this.pendingReheat = true;
581
+ if (this.current.cooling === "adaptive") {
582
+ this.resetAdaptive(state);
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Replaces the record (a new k or budget takes effect at the next paramsFor: a new dt, a new frK; no recompile).
588
+ * The PD-16 `fixed` check already ran in the simulation's resolve callback.
589
+ * @param patch - the setParams patch
590
+ * @param _state - the state writer of the simulation (nothing to write)
591
+ */
592
+ onSetParams(patch: Partial<FruchtermanReingoldOptions>, _state: StateWriter): void {
593
+ this.current = resolveFruchtermanReingoldOptions(patch, this.current);
594
+ }
595
+
596
+ /**
597
+ * Decodes the state header and the k trace records of a completed batch into FruchtermanReingoldStats: the exact
598
+ * tier with null grid fields, msPerIteration null (the simulation owns the clock), the temperature K1 wrote.
599
+ * @param state - a DataView over the 256-byte state header
600
+ * @param trace - a DataView over the k Fa2Trace records of the batch
601
+ * @returns the stats
602
+ */
603
+ readStats(state: DataView, trace: DataView): FruchtermanReingoldStats {
604
+ const header = FA2_STATE.read(state);
605
+ const centroid = vector(header, "centroid");
606
+ const records: FruchtermanReingoldTraceRecord[] = [];
607
+ const count = Math.floor(trace.byteLength / TRACE_RECORD_BYTES);
608
+ for (let i = 0; i < count; i++) {
609
+ const record = FA2_TRACE.read(trace, i * TRACE_RECORD_BYTES);
610
+ records.push({
611
+ temperature: scalar(record, "modelScalar"),
612
+ meanDisplacement: scalar(record, "meanDisplacement"),
613
+ settledCount: scalar(record, "settledCount"),
614
+ });
615
+ }
616
+ return {
617
+ iteration: scalar(header, "iteration"),
618
+ meanDisplacement: scalar(header, "meanDisplacement"),
619
+ rmsRadius: scalar(header, "rmsRadius"),
620
+ layoutRadius: scalar(header, "radius"),
621
+ centroid: [centroid[0], centroid[1], centroid[2]],
622
+ repulsionTier: "exact",
623
+ maxCellOccupancy: null,
624
+ outsideGrid: null,
625
+ msPerIteration: null,
626
+ temperature: scalar(header, "temperature"),
627
+ trace: records,
628
+ };
629
+ }
630
+
631
+ /**
632
+ * The temperature of a global iteration (PD-5): a pending reheat re-anchors tempOrigin so this iteration's
633
+ * temperature index is floor(0.7 * iterations); then max(0, 0.1 - dt * index), dt = 0.1 / (iterations + 1).
634
+ * @param global - the global iteration index
635
+ * @param resolved - the current record
636
+ * @returns the temperature (f64; the uniform slot rounds it to f32)
637
+ */
638
+ private temperatureAt(global: number, resolved: ResolvedFruchtermanReingoldOptions): number {
639
+ if (this.pendingReheat) {
640
+ this.tempOrigin = global - Math.floor(FR_REHEAT_FRACTION * resolved.iterations);
641
+ this.pendingReheat = false;
642
+ }
643
+ const dt = FR_START_TEMPERATURE / (resolved.iterations + 1);
644
+ return Math.max(0, FR_START_TEMPERATURE - dt * (global - this.tempOrigin));
645
+ }
646
+
647
+ /**
648
+ * The resources of the last bind(), or E_NOT_LOADED before it.
649
+ * @returns the resources
650
+ */
651
+ private requireResources(): ModelResources {
652
+ if (this.resources === null) {
653
+ throw new WebGpuGraphError(
654
+ "E_NOT_LOADED",
655
+ "the Fruchterman-Reingold model has not been bound (load() first)",
656
+ { state: "created" },
657
+ );
658
+ }
659
+ return this.resources;
660
+ }
661
+
662
+ /**
663
+ * The index of a stage name in FR_STAGES, or E_INVALID_ARGUMENT.
664
+ * @param upTo - the stage name
665
+ * @returns its index
666
+ */
667
+ private stageIndex(upTo: string): number {
668
+ for (let i = 0; i < FR_STAGES.length; i++) {
669
+ if (FR_STAGES[i] === upTo) {
670
+ return i;
671
+ }
672
+ }
673
+ throw invalid("upTo", upTo, FR_STAGES.join(" | "));
674
+ }
675
+
676
+ /** Drops the bind groups of the previous bind() (the buffers changed) and forgets the pass of a batch recorded before the rebind. */
677
+ private dropBound(): void {
678
+ this.openPass = null;
679
+ const { bound } = this;
680
+ if (bound === null) {
681
+ return;
682
+ }
683
+ for (const kernel of [bound.k1, bound.k2, bound.k3, bound.k5, bound.toScene, bound.fill]) {
684
+ kernel.invalidate();
685
+ }
686
+ this.bound = null;
687
+ }
688
+ }
689
+
690
+ // ============================================================ the factory
691
+
692
+ /**
693
+ * The resolve callback of the simulation's setParams: the PD-16 `fixed` check first (fixed is applied at load; a
694
+ * rejected patch leaves the simulation unchanged because ForceSimulation.setParams runs this before any state moves),
695
+ * then the patch over the current record, re-validated.
696
+ * @param patch - the setParams patch
697
+ * @param current - the simulation's current option record
698
+ * @returns the new record
699
+ */
700
+ function resolvePatch(
701
+ patch: Partial<FruchtermanReingoldOptions>,
702
+ current: FruchtermanReingoldOptions,
703
+ ): FruchtermanReingoldOptions {
704
+ if ("fixed" in patch) {
705
+ throw new WebGpuGraphError("E_INVALID_ARGUMENT", "setParams({ fixed }) is not a live option (spec 7.12)", {
706
+ argument: "fixed",
707
+ value: patch.fixed,
708
+ expected: "absent",
709
+ hint: "use setFixed(mask); fixed is applied at load()",
710
+ });
711
+ }
712
+ return resolveFruchtermanReingoldOptions(patch, resolveFruchtermanReingoldOptions(current));
713
+ }
714
+
715
+ /**
716
+ * Spec 3.3 createFruchtermanReingold, verbatim: a GpuLayoutSimulation running Fruchterman-Reingold on the exact
717
+ * repulsion tier with the option defaults of spec 7.20 and the GPU-only tuning of GpuLayoutTuning.
718
+ * @param ctx - the context (E_DISPOSED / E_DEVICE_LOST through assertReady)
719
+ * @param options - the Fruchterman-Reingold options and the GPU-only tuning knobs in one record
720
+ * @returns the simulation in state "created"; load() next
721
+ */
722
+ export function createFruchtermanReingold(
723
+ ctx: GpuContext,
724
+ options?: FruchtermanReingoldOptions & GpuLayoutTuning,
725
+ ): GpuLayoutSimulation<FruchtermanReingoldOptions, FruchtermanReingoldStats> {
726
+ ctx.assertReady();
727
+ const resolved = resolveFruchtermanReingoldOptions(options);
728
+ const tuning = resolveLayoutTuning(options);
729
+ const model = new FruchtermanReingoldModel(tuning, resolved);
730
+ return new ForceSimulation<FruchtermanReingoldOptions, FruchtermanReingoldStats>(
731
+ ctx,
732
+ model,
733
+ resolved,
734
+ tuning,
735
+ resolvePatch,
736
+ );
737
+ }