/ proof-of-concept / cymsimweb
Sign in
proof-of-concept / cymsimweb
cymsimweb / src / cpu / simulator.ts
169 lines · 9.0 KBBlameHistoryRaw
1// Float64 reference time loop with exactly the structure of the GPU kernels: an element pass
2// (forces, sigma1 term, radiation accumulation), a hit pass (contact forces, release), a node
3// pass (gather, contact, lagged rigid-mode projection, leapfrog update, partial sums for the
4// next projection), and the exciter update. See THEORY.md.
5import { elementForces, strainEnergies } from "../model/forces.ts";
6import { HOLD_HEIGHT } from "../model/exciter.ts";
7import { DECIMATION_SPAN } from "../model/radiation.ts";
8import type { Setup } from "../model/setup.ts";
9import type { ChunkResult, Diagnostics, SimulatorBackend } from "../model/simulator.ts";
11export class CpuSimulator implements SimulatorBackend {
12 readonly kind = "cpu" as const;
13 private n = 0; // sub-step counter
14 private readonly q: Float64Array; private readonly v: Float64Array; private readonly nodeAcc: Float64Array;
15 private readonly vwPrev: Float64Array; // projected transverse velocity of the previous step (for the radiated acceleration)
16 private readonly ef: Float64Array; private readonly fc: Float64Array;
17 private readonly zs: Float64Array; private readonly vs: Float64Array; private readonly Fk: Float64Array; private readonly F: Float64Array;
18 private readonly Fmax: Float64Array; private readonly ncont: Uint32Array;
19 private partialsPrev = new Float64Array(12); private partialsNew = new Float64Array(12); // [0,6): Rm.(M v), [6,12): Rm.(M q)
20 private readonly acc: Float64Array; // (E, DECIMATION_SPAN) decimation accumulators
21 private readonly history: Float64Array;
22 private pending: { j: number; front: number; back: number }[] = [];
23 samplesDone = 0;
24 readonly maxChunk = 8192;
25 readonly setup: Setup; readonly movieEvery: number;
27 /** ``movieEvery`` > 0 captures w every that many audio samples. */
28 constructor(setup: Setup, movieEvery = 0) {
29 this.setup = setup; this.movieEvery = movieEvery;
30 const N = setup.mesh.n, E = setup.mesh.e, K = setup.schedule.K, P = setup.schedule.P;
31 this.q = new Float64Array(5 * N); this.v = new Float64Array(5 * N); this.nodeAcc = new Float64Array(N); this.vwPrev = new Float64Array(N);
32 this.ef = new Float64Array(15 * E); this.fc = new Float64Array(N);
33 this.zs = new Float64Array(K).fill(HOLD_HEIGHT); this.vs = new Float64Array(K);
34 this.Fk = new Float64Array(K * P); this.F = new Float64Array(K); this.Fmax = new Float64Array(K); this.ncont = new Uint32Array(K);
35 this.acc = new Float64Array(E * DECIMATION_SPAN); this.history = new Float64Array(E * setup.radiation.ringLength);
36 }
38 private step() {
39 const { shell: sh, mesh, schedule: sc, radiation: rad, dt, substeps: m } = this.setup;
40 const { tri } = mesh, N = mesh.n, E = mesh.e, n = this.n;
41 const sigma0 = this.setup.config.material.sigma0;
42 // ---- element pass
43 elementForces(sh, this.q, this.v, this.ef);
44 if (n >= 1) {
45 const s = n - 1, j0 = Math.floor(s / m), kk = s - j0 * m, W = DECIMATION_SPAN, taps = rad.taps;
46 if (kk === 0 && j0 > 0) this.finalizeSample(j0 - W / 2); // slot 0 = sample j0 - (W/2 - 1) of the previous j0
47 for (let e = 0; e < E; e++) {
48 const a = (this.nodeAcc[tri[3 * e]] + this.nodeAcc[tri[3 * e + 1]] + this.nodeAcc[tri[3 * e + 2]]) / 3;
49 for (let w = 0; w < W; w++) this.acc[e * W + w] += a * taps[w * m + kk];
50 }
51 }
52 // ---- hit pass
53 this.fc.fill(0);
54 for (let k = 0; k < sc.K; k++) {
55 let wmax = -Infinity;
56 const wp = new Float64Array(sc.P);
57 for (let p = 0; p < sc.P; p++) {
58 const b = (k * sc.P + p) * 3;
59 let w = sc.offsets[k * sc.P + p];
60 for (let i = 0; i < 3; i++) w += sc.weights[b + i] * this.q[5 * sc.nodes[b + i] + 2];
61 wp[p] = w; wmax = Math.max(wmax, w);
62 }
63 if (n === sc.releaseStep[k]) { this.zs[k] = wmax + sc.gap[k]; this.vs[k] = -sc.velocity[k]; }
64 const active = n >= sc.releaseStep[k];
65 let Ftot = 0;
66 for (let p = 0; p < sc.P; p++) {
67 const delta = Math.max(wp[p] - this.zs[k], 0);
68 const f = active ? sc.kPoint[k] * Math.pow(delta, sc.alpha[k]) : 0;
69 this.Fk[k * sc.P + p] = f; Ftot += f;
70 if (f > 0) { const b = (k * sc.P + p) * 3; for (let i = 0; i < 3; i++) this.fc[sc.nodes[b + i]] -= f * sc.weights[b + i]; }
71 }
72 this.F[k] = Ftot;
73 }
74 // ---- node pass
75 const { M, Minv, Rm, adjOffsets, adjEntries } = sh, L = 5 * N, c = this.partialsPrev;
76 this.partialsNew.fill(0);
77 const f = new Float64Array(5);
78 for (let nd = 0; nd < N; nd++) {
79 f.fill(0);
80 for (let a = adjOffsets[nd]; a < adjOffsets[nd + 1]; a++) {
81 const ent = adjEntries[a], e = (ent / 3) | 0, i = ent % 3;
82 for (let d = 0; d < 5; d++) f[d] += this.ef[15 * e + 5 * i + d];
83 }
84 f[2] += this.fc[nd];
85 for (let d = 0; d < 5; d++) {
86 const idx = 5 * nd + d;
87 // lagged projection: remove the rigid content that the previous step's update introduced
88 let vd = this.v[idx], qd = this.q[idx];
89 for (let k = 0; k < 6; k++) { const r = Rm[k * L + idx]; vd -= c[k] * r; qd -= c[6 + k] * r; }
90 const v1 = (vd + dt * f[d] * Minv[idx]) / (1 + 2 * sigma0 * dt);
91 // radiated acceleration from consecutive projected velocities, so that the rigid increment
92 // that the lagged projection removes one step later never radiates
93 if (d === 2) { this.nodeAcc[nd] = (vd - this.vwPrev[nd]) / dt; this.vwPrev[nd] = vd; }
94 const q1 = qd + dt * v1;
95 this.q[idx] = q1; this.v[idx] = v1;
96 for (let k = 0; k < 6; k++) { const r = Rm[k * L + idx] * M[idx]; this.partialsNew[k] += r * v1; this.partialsNew[6 + k] += r * q1; }
97 }
98 }
99 [this.partialsPrev, this.partialsNew] = [this.partialsNew, this.partialsPrev];
100 // ---- exciters
101 for (let k = 0; k < sc.K; k++) {
102 this.vs[k] += (dt * this.F[k]) / sc.mass[k]; this.zs[k] += dt * this.vs[k];
103 this.Fmax[k] = Math.max(this.Fmax[k], this.F[k]); if (this.F[k] > 0) this.ncont[k]++;
104 }
105 this.n++;
106 }
108 /** Slot 0 (audio sample j) of the accumulators is complete: store it, shift the slots, evaluate the listener pressure. */
109 private finalizeSample(j: number) {
110 const { radiation: rad, mesh } = this.setup, E = mesh.e, D = rad.ringLength, W = DECIMATION_SPAN;
111 for (let e = 0; e < E; e++) {
112 if (j >= 0) this.history[e * D + (j % D)] = this.acc[e * W];
113 for (let w = 0; w < W - 1; w++) this.acc[e * W + w] = this.acc[e * W + w + 1];
114 this.acc[e * W + W - 1] = 0;
115 }
116 if (j < 0) return;
117 let front = 0, back = 0;
118 for (let e = 0; e < E; e++) {
119 const jf = j - rad.i0F[e], jb = j - rad.i0B[e];
120 if (jf >= 1) front += rad.coefF[e] * (this.history[e * D + (jf % D)] * (1 - rad.frF[e]) + this.history[e * D + ((jf - 1) % D)] * rad.frF[e]);
121 if (jb >= 1) back += rad.coefB[e] * (this.history[e * D + (jb % D)] * (1 - rad.frB[e]) + this.history[e * D + ((jb - 1) % D)] * rad.frB[e]);
122 }
123 this.pending.push({ j, front, back });
124 }
126 async runChunk(nSamples: number): Promise<ChunkResult> {
127 const m = this.setup.substeps, N = this.setup.mesh.n, frames: Float32Array[] = [], frameSamples: number[] = [];
128 for (let s = 0; s < nSamples * m; s++) {
129 if (this.movieEvery > 0 && this.n % (m * this.movieEvery) === 0) {
130 const w = new Float32Array(N);
131 for (let nd = 0; nd < N; nd++) w[nd] = this.q[5 * nd + 2];
132 frames.push(w); frameSamples.push(this.n / m);
133 }
134 this.step();
135 }
136 this.samplesDone += nSamples;
137 const out = this.pending; this.pending = [];
138 const firstSample = out.length ? out[0].j : this.samplesDone;
139 return { firstSample, pressureFront: Float32Array.from(out, (o) => o.front), pressureBack: Float32Array.from(out, (o) => o.back), frames, frameSamples };
140 }
142 async diagnostics(): Promise<Diagnostics> {
143 const { shell: sh, schedule: sc, dt } = this.setup, N = sh.mesh.n;
144 let ke = 0, woh = 0;
145 for (let i = 0; i < 5 * N; i++) ke += 0.5 * sh.M[i] * this.v[i] * this.v[i];
146 for (let nd = 0; nd < N; nd++) woh = Math.max(woh, Math.abs(this.q[5 * nd + 2] / sh.hNode[nd]));
147 const { membrane, bending } = strainEnergies(sh, this.q);
148 let ex = 0;
149 for (let k = 0; k < sc.K; k++) ex += 0.5 * sc.mass[k] * this.vs[k] * this.vs[k];
150 return { time: this.n * dt, kinetic: ke, membrane, bending, exciters: ex, maxWoverH: woh,
151 hits: Array.from({ length: sc.K }, (_, k) => ({ peakForce: this.Fmax[k], contactTime: this.ncont[k] * dt, velocity: this.vs[k], height: this.zs[k] })) };
152 }
154 /** M-weighted rigid-mode content of the current velocity (the lagged projection leaves one step's increment). */
155 rigidContent(): number {
156 const { shell: sh } = this.setup, L = 5 * sh.mesh.n;
157 let worst = 0;
158 for (let k = 0; k < 6; k++) { let c = 0; for (let i = 0; i < L; i++) c += sh.Rm[k * L + i] * sh.M[i] * this.v[i]; worst = Math.max(worst, Math.abs(c)); }
159 return worst;
160 }
162 async displacement(): Promise<Float32Array> {
163 const N = this.setup.mesh.n, w = new Float32Array(N);
164 for (let nd = 0; nd < N; nd++) w[nd] = this.q[5 * nd + 2];
165 return w;
166 }
168 dispose() {}
↑↓ move↵openescclose