slangmath 1.0.6 → 1.1.0

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.
package/slang-ode.js ADDED
@@ -0,0 +1,1082 @@
1
+ /**
2
+ * SLaNg ODE Module
3
+ *
4
+ * Numerical and symbolic solvers for Ordinary Differential Equations (ODEs).
5
+ *
6
+ * Supported methods:
7
+ * - Euler's method (1st order)
8
+ * - Improved Euler / Heun's method (2nd order Runge-Kutta)
9
+ * - Classical 4th-order Runge-Kutta (RK4) — default, most accurate
10
+ * - Adaptive RK45 (Dormand-Prince) with error control
11
+ * - Systems of ODEs (dx/dt = f(t, x, y, ...))
12
+ *
13
+ * Supported equation types (symbolic):
14
+ * - Separable ODEs
15
+ * - First-order linear: y' + P(x)y = Q(x)
16
+ * - Exact equations (detection + solution)
17
+ * - Bernoulli equations
18
+ * - Autonomous 2D systems (for phase portrait data)
19
+ *
20
+ * Usage:
21
+ * import { solveODE, solveSystem, rk4, euler } from './slang-ode.js';
22
+ */
23
+
24
+ // ============================================================================
25
+ // NUMERICAL ODE SOLVERS
26
+ // ============================================================================
27
+
28
+ /**
29
+ * Euler's method (1st order accuracy)
30
+ * dy/dt = f(t, y), y(t0) = y0
31
+ * @param {Function} f - f(t, y) → dy/dt
32
+ * @param {number} t0 - Initial time
33
+ * @param {number} y0 - Initial value
34
+ * @param {number} tEnd - End time
35
+ * @param {number} h - Step size
36
+ * @returns {{ t: number[], y: number[] }}
37
+ */
38
+ export function euler(f, t0, y0, tEnd, h = 0.01) {
39
+ _validateODEInputs(t0, y0, tEnd, h);
40
+ const ts = [t0], ys = [y0];
41
+ let t = t0, y = y0;
42
+
43
+ while (t < tEnd - 1e-12) {
44
+ h = Math.min(h, tEnd - t);
45
+ y = y + h * f(t, y);
46
+ t = t + h;
47
+ ts.push(t);
48
+ ys.push(y);
49
+ }
50
+
51
+ return { t: ts, y: ys, method: 'euler' };
52
+ }
53
+
54
+ /**
55
+ * Heun's method (2nd order Runge-Kutta / improved Euler)
56
+ * @param {Function} f - f(t, y) → dy/dt
57
+ * @param {number} t0
58
+ * @param {number} y0
59
+ * @param {number} tEnd
60
+ * @param {number} h
61
+ * @returns {{ t: number[], y: number[] }}
62
+ */
63
+ export function heun(f, t0, y0, tEnd, h = 0.01) {
64
+ _validateODEInputs(t0, y0, tEnd, h);
65
+ const ts = [t0], ys = [y0];
66
+ let t = t0, y = y0;
67
+
68
+ while (t < tEnd - 1e-12) {
69
+ h = Math.min(h, tEnd - t);
70
+ const k1 = f(t, y);
71
+ const yTilde = y + h * k1;
72
+ const k2 = f(t + h, yTilde);
73
+ y = y + (h / 2) * (k1 + k2);
74
+ t = t + h;
75
+ ts.push(t);
76
+ ys.push(y);
77
+ }
78
+
79
+ return { t: ts, y: ys, method: 'heun' };
80
+ }
81
+
82
+ /**
83
+ * Classical 4th-order Runge-Kutta (RK4) — recommended for most problems
84
+ * @param {Function} f - f(t, y) → dy/dt
85
+ * @param {number} t0
86
+ * @param {number} y0
87
+ * @param {number} tEnd
88
+ * @param {number} h
89
+ * @returns {{ t: number[], y: number[], method: string }}
90
+ */
91
+ export function rk4(f, t0, y0, tEnd, h = 0.01) {
92
+ _validateODEInputs(t0, y0, tEnd, h);
93
+ const ts = [t0], ys = [y0];
94
+ let t = t0, y = y0;
95
+
96
+ while (t < tEnd - 1e-12) {
97
+ h = Math.min(h, tEnd - t);
98
+ const k1 = f(t, y);
99
+ const k2 = f(t + h / 2, y + (h / 2) * k1);
100
+ const k3 = f(t + h / 2, y + (h / 2) * k2);
101
+ const k4 = f(t + h, y + h * k3);
102
+ y = y + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4);
103
+ t = t + h;
104
+ ts.push(t);
105
+ ys.push(y);
106
+ }
107
+
108
+ return { t: ts, y: ys, method: 'rk4' };
109
+ }
110
+
111
+ /**
112
+ * Adaptive RK45 (Dormand-Prince) with error control.
113
+ * Automatically adjusts step size to maintain desired accuracy.
114
+ *
115
+ * @param {Function} f - f(t, y) → dy/dt
116
+ * @param {number} t0
117
+ * @param {number} y0
118
+ * @param {number} tEnd
119
+ * @param {number} [tol=1e-6] - Absolute + relative tolerance
120
+ * @param {number} [hInit=0.1] - Initial step size
121
+ * @returns {{ t: number[], y: number[], steps: number, rejections: number }}
122
+ */
123
+ export function rk45(f, t0, y0, tEnd, tol = 1e-6, hInit = 0.1) {
124
+ // Dormand-Prince coefficients
125
+ const c2=1/5, c3=3/10, c4=4/5, c5=8/9;
126
+ const a21=1/5;
127
+ const a31=3/40, a32=9/40;
128
+ const a41=44/45, a42=-56/15, a43=32/9;
129
+ const a51=19372/6561, a52=-25360/2187, a53=64448/6561, a54=-212/729;
130
+ const a61=9017/3168, a62=-355/33, a63=46732/5247, a64=49/176, a65=-5103/18656;
131
+ // 5th order weights
132
+ const e1=71/57600, e3=-71/16695, e4=71/1920, e5=-17253/339200, e6=22/525, e7=-1/40;
133
+
134
+ const ts = [t0], ys = [y0];
135
+ let t = t0, y = y0, h = hInit;
136
+ let steps = 0, rejections = 0;
137
+ const maxSteps = 1e5;
138
+
139
+ while (t < tEnd - 1e-12 && steps < maxSteps) {
140
+ h = Math.min(h, tEnd - t);
141
+
142
+ const k1 = f(t, y);
143
+ const k2 = f(t + c2*h, y + h*a21*k1);
144
+ const k3 = f(t + c3*h, y + h*(a31*k1 + a32*k2));
145
+ const k4 = f(t + c4*h, y + h*(a41*k1 + a42*k2 + a43*k3));
146
+ const k5 = f(t + c5*h, y + h*(a51*k1 + a52*k2 + a53*k3 + a54*k4));
147
+ const k6 = f(t + h, y + h*(a61*k1 + a62*k2 + a63*k3 + a64*k4 + a65*k5));
148
+
149
+ // 4th order solution
150
+ const y4 = y + h*(35/384*k1 + 500/1113*k3 + 125/192*k4 - 2187/6784*k5 + 11/84*k6);
151
+ const k7 = f(t + h, y4);
152
+
153
+ // Error estimate (difference between 4th and 5th order)
154
+ const err = h * Math.abs(e1*k1 + e3*k3 + e4*k4 + e5*k5 + e6*k6 + e7*k7);
155
+ const errNorm = err / (tol * (1 + Math.abs(y)));
156
+
157
+ if (errNorm <= 1.0) {
158
+ // Accept step
159
+ t = t + h;
160
+ y = y4;
161
+ ts.push(t);
162
+ ys.push(y);
163
+ steps++;
164
+ } else {
165
+ rejections++;
166
+ }
167
+
168
+ // Adjust step size
169
+ const factor = Math.min(5.0, Math.max(0.2, 0.9 * Math.pow(1 / errNorm, 0.2)));
170
+ h = h * factor;
171
+ }
172
+
173
+ return { t: ts, y: ys, method: 'rk45', steps, rejections };
174
+ }
175
+
176
+ // ============================================================================
177
+ // SYSTEM OF ODEs
178
+ // ============================================================================
179
+
180
+ /**
181
+ * Solve a system of first-order ODEs using RK4.
182
+ *
183
+ * The system is: dY/dt = F(t, Y) where Y = [y1, y2, ..., yn]
184
+ *
185
+ * @param {Function} F - F(t, Y) → dY/dt (returns an array of same length as Y)
186
+ * @param {number} t0 - Initial time
187
+ * @param {number[]} Y0 - Initial state vector
188
+ * @param {number} tEnd - End time
189
+ * @param {number} h - Step size
190
+ * @returns {{ t: number[], Y: number[][], method: string }}
191
+ * Y[i] is the state vector at time t[i]
192
+ */
193
+ export function rk4System(F, t0, Y0, tEnd, h = 0.01) {
194
+ if (!Array.isArray(Y0)) throw new Error('Y0 must be an array');
195
+ const n = Y0.length;
196
+ const ts = [t0];
197
+ const Ys = [Y0.slice()];
198
+ let t = t0, Y = Y0.slice();
199
+
200
+ while (t < tEnd - 1e-12) {
201
+ h = Math.min(h, tEnd - t);
202
+
203
+ const k1 = F(t, Y);
204
+ const k2 = F(t + h/2, _vecAdd(Y, _vecScale(k1, h/2)));
205
+ const k3 = F(t + h/2, _vecAdd(Y, _vecScale(k2, h/2)));
206
+ const k4 = F(t + h, _vecAdd(Y, _vecScale(k3, h)));
207
+
208
+ Y = Y.map((yi, i) => yi + (h/6) * (k1[i] + 2*k2[i] + 2*k3[i] + k4[i]));
209
+ t = t + h;
210
+ ts.push(t);
211
+ Ys.push(Y.slice());
212
+ }
213
+
214
+ return { t: ts, Y: Ys, method: 'rk4System', n };
215
+ }
216
+
217
+ // ============================================================================
218
+ // SECOND-ORDER ODEs (reduced to system)
219
+ // ============================================================================
220
+
221
+ /**
222
+ * Solve a second-order ODE: y'' = f(t, y, y')
223
+ * Reduces to a 2D system: [y, v]' = [v, f(t, y, v)]
224
+ *
225
+ * @param {Function} f2 - f2(t, y, yPrime) → y''
226
+ * @param {number} t0
227
+ * @param {number} y0 - Initial position
228
+ * @param {number} v0 - Initial velocity y'(t0)
229
+ * @param {number} tEnd
230
+ * @param {number} h
231
+ * @returns {{ t, y, yPrime, method }}
232
+ */
233
+ export function solveSecondOrder(f2, t0, y0, v0, tEnd, h = 0.01) {
234
+ const F = (t, [y, v]) => [v, f2(t, y, v)];
235
+ const result = rk4System(F, t0, [y0, v0], tEnd, h);
236
+ return {
237
+ t: result.t,
238
+ y: result.Y.map(s => s[0]),
239
+ yPrime: result.Y.map(s => s[1]),
240
+ method: 'rk4-2nd-order'
241
+ };
242
+ }
243
+
244
+ // ============================================================================
245
+ // COMMON ODE FORMULATIONS
246
+ // ============================================================================
247
+
248
+ /**
249
+ * Solve a first-order linear ODE: y' + P(t)*y = Q(t)
250
+ * using the integrating factor method (numerically).
251
+ *
252
+ * @param {Function} P - P(t)
253
+ * @param {Function} Q - Q(t)
254
+ * @param {number} t0, y0, tEnd, h
255
+ * @returns Result from rk4
256
+ */
257
+ export function solveLinearFirstOrder(P, Q, t0, y0, tEnd, h = 0.01) {
258
+ const f = (t, y) => Q(t) - P(t) * y;
259
+ const result = rk4(f, t0, y0, tEnd, h);
260
+ result.method = 'rk4-linear-1st-order';
261
+ return result;
262
+ }
263
+
264
+ /**
265
+ * Solve a logistic equation: dy/dt = r*y*(1 - y/K)
266
+ * @param {number} r - Growth rate
267
+ * @param {number} K - Carrying capacity
268
+ * @param {number} t0, y0, tEnd, h
269
+ */
270
+ export function solveLogistic(r, K, t0, y0, tEnd, h = 0.01) {
271
+ const f = (t, y) => r * y * (1 - y / K);
272
+ const result = rk4(f, t0, y0, tEnd, h);
273
+ result.method = 'logistic';
274
+ result.params = { r, K };
275
+ result.analyticalEquilibrium = K;
276
+ return result;
277
+ }
278
+
279
+ /**
280
+ * Solve a damped harmonic oscillator: y'' + 2γy' + ω²y = F(t)
281
+ * @param {number} gamma - Damping coefficient
282
+ * @param {number} omega - Natural frequency
283
+ * @param {Function} forceF - Forcing function F(t), or null for free oscillation
284
+ * @param {number} t0, y0, v0, tEnd, h
285
+ */
286
+ export function solveDampedHarmonic(gamma, omega, forceF, t0, y0, v0, tEnd, h = 0.01) {
287
+ const F = (t, y, yp) => {
288
+ const forcing = forceF ? forceF(t) : 0;
289
+ return forcing - 2 * gamma * yp - omega * omega * y;
290
+ };
291
+ const result = solveSecondOrder(F, t0, y0, v0, tEnd, h);
292
+ result.method = 'damped-harmonic';
293
+ result.params = { gamma, omega };
294
+
295
+ // Classify damping
296
+ if (Math.abs(gamma) < 1e-12) result.dampingType = 'undamped';
297
+ else if (gamma < omega) result.dampingType = 'underdamped';
298
+ else if (Math.abs(gamma - omega) < 1e-6) result.dampingType = 'critically-damped';
299
+ else result.dampingType = 'overdamped';
300
+
301
+ return result;
302
+ }
303
+
304
+ /**
305
+ * Lorenz system (chaotic attractor)
306
+ * dx/dt = σ(y - x)
307
+ * dy/dt = x(ρ - z) - y
308
+ * dz/dt = xy - βz
309
+ * @param {number} [sigma=10], [rho=28], [beta=8/3]
310
+ * @param {number[]} Y0 - [x0, y0, z0]
311
+ * @param {number} t0, tEnd, h
312
+ */
313
+ export function solveLorenz(Y0, t0, tEnd, h = 0.005, sigma = 10, rho = 28, beta = 8/3) {
314
+ const F = (t, [x, y, z]) => [
315
+ sigma * (y - x),
316
+ x * (rho - z) - y,
317
+ x * y - beta * z
318
+ ];
319
+ const result = rk4System(F, t0, Y0, tEnd, h);
320
+ result.method = 'lorenz';
321
+ result.params = { sigma, rho, beta };
322
+ return result;
323
+ }
324
+
325
+ // ============================================================================
326
+ // PHASE PORTRAIT UTILITIES
327
+ // ============================================================================
328
+
329
+ /**
330
+ * Generate phase portrait data for a 2D autonomous system.
331
+ * dx/dt = f(x, y), dy/dt = g(x, y)
332
+ *
333
+ * @param {Function} f - f(x, y)
334
+ * @param {Function} g - g(x, y)
335
+ * @param {{ x: [min, max], y: [min, max] }} bounds
336
+ * @param {number} gridSize - Number of arrows per axis
337
+ * @returns {Array<{ x, y, dx, dy, magnitude }>}
338
+ */
339
+ export function phasePortrait(f, g, bounds, gridSize = 15) {
340
+ const { x: [xMin, xMax], y: [yMin, yMax] } = bounds;
341
+ const dx = (xMax - xMin) / (gridSize - 1);
342
+ const dy = (yMax - yMin) / (gridSize - 1);
343
+ const arrows = [];
344
+
345
+ for (let i = 0; i < gridSize; i++) {
346
+ for (let j = 0; j < gridSize; j++) {
347
+ const x = xMin + i * dx;
348
+ const y = yMin + j * dy;
349
+ try {
350
+ const vx = f(x, y);
351
+ const vy = g(x, y);
352
+ const mag = Math.sqrt(vx * vx + vy * vy);
353
+ arrows.push({ x, y, dx: vx, dy: vy, magnitude: mag });
354
+ } catch {
355
+ // skip points where evaluation fails
356
+ }
357
+ }
358
+ }
359
+
360
+ return arrows;
361
+ }
362
+
363
+ /**
364
+ * Find equilibrium points (nullclines intersection) numerically.
365
+ * @param {Function} f, g - System functions
366
+ * @param {{ x: [min, max], y: [min, max] }} bounds
367
+ * @param {number} resolution
368
+ * @returns {Array<{ x, y }>}
369
+ */
370
+ export function findEquilibria(f, g, bounds, resolution = 50) {
371
+ const { x: [xMin, xMax], y: [yMin, yMax] } = bounds;
372
+ const equilibria = [];
373
+ const hx = (xMax - xMin) / resolution;
374
+ const hy = (yMax - yMin) / resolution;
375
+ const tol = Math.max(hx, hy) * 2;
376
+
377
+ for (let i = 0; i < resolution; i++) {
378
+ for (let j = 0; j < resolution; j++) {
379
+ const x = xMin + i * hx;
380
+ const y = yMin + j * hy;
381
+ try {
382
+ const fv = Math.abs(f(x, y));
383
+ const gv = Math.abs(g(x, y));
384
+ if (fv < tol && gv < tol) {
385
+ // Check it's not a duplicate
386
+ const isDup = equilibria.some(e =>
387
+ Math.abs(e.x - x) < tol && Math.abs(e.y - y) < tol);
388
+ if (!isDup) equilibria.push({ x, y });
389
+ }
390
+ } catch { }
391
+ }
392
+ }
393
+
394
+ return equilibria;
395
+ }
396
+
397
+ // ============================================================================
398
+ // BOUNDARY VALUE PROBLEMS (Shooting Method)
399
+ // ============================================================================
400
+
401
+ /**
402
+ * Solve a 2-point BVP: y'' = f(t, y, y') with y(a) = ya, y(b) = yb
403
+ * Uses the shooting method with secant iteration.
404
+ * @param {Function} f2 - f2(t, y, yp) → y''
405
+ * @param {number} a, ya - Left boundary
406
+ * @param {number} b, yb - Right boundary
407
+ * @param {number} h - Step size
408
+ * @param {number} [tol=1e-8]
409
+ * @returns {{ t, y, yPrime, iterations }}
410
+ */
411
+ export function shootingMethod(f2, a, ya, b, yb, h = 0.01, tol = 1e-8) {
412
+ // Initial slope guesses
413
+ let s0 = 0, s1 = (yb - ya) / (b - a);
414
+ let result0 = solveSecondOrder(f2, a, ya, s0, b, h);
415
+ let phi0 = result0.y.at(-1) - yb;
416
+
417
+ let iterations = 0;
418
+ const maxIter = 50;
419
+
420
+ while (iterations < maxIter) {
421
+ const result1 = solveSecondOrder(f2, a, ya, s1, b, h);
422
+ const phi1 = result1.y.at(-1) - yb;
423
+
424
+ if (Math.abs(phi1) < tol) {
425
+ return { ...result1, iterations, method: 'shooting' };
426
+ }
427
+
428
+ // Secant update
429
+ if (Math.abs(phi1 - phi0) < 1e-15) break;
430
+ const s2 = s1 - phi1 * (s1 - s0) / (phi1 - phi0);
431
+ s0 = s1; phi0 = phi1;
432
+ s1 = s2;
433
+ iterations++;
434
+ }
435
+
436
+ // Return best guess
437
+ const final = solveSecondOrder(f2, a, ya, s1, b, h);
438
+ return { ...final, iterations, method: 'shooting', converged: false };
439
+ }
440
+
441
+ // ============================================================================
442
+ // SOLUTION ANALYSIS
443
+ // ============================================================================
444
+
445
+ /**
446
+ * Compute statistics on an ODE solution.
447
+ * @param {{ t, y }} solution
448
+ * @returns {{ min, max, mean, finalValue, stable }}
449
+ */
450
+ export function analyzeSolution(solution) {
451
+ const { t, y } = solution;
452
+ const n = y.length;
453
+ if (n === 0) return null;
454
+
455
+ const min = Math.min(...y);
456
+ const max = Math.max(...y);
457
+ const mean = y.reduce((a, b) => a + b, 0) / n;
458
+ const finalValue = y[n - 1];
459
+
460
+ // Check if solution appears to be converging (stable)
461
+ const last10Pct = y.slice(Math.floor(n * 0.9));
462
+ const variation = Math.max(...last10Pct) - Math.min(...last10Pct);
463
+ const stable = variation < 1e-3 * (max - min + 1);
464
+
465
+ // Estimate period if oscillatory
466
+ let period = null;
467
+ const crossings = [];
468
+ for (let i = 1; i < n; i++) {
469
+ if (y[i - 1] <= mean && y[i] > mean) {
470
+ crossings.push(t[i]);
471
+ }
472
+ }
473
+ if (crossings.length >= 2) {
474
+ const periods = [];
475
+ for (let i = 1; i < crossings.length; i++) periods.push(crossings[i] - crossings[i-1]);
476
+ period = periods.reduce((a, b) => a + b, 0) / periods.length;
477
+ }
478
+
479
+ return { min, max, mean, finalValue, stable, period, n };
480
+ }
481
+
482
+ /**
483
+ * Interpolate solution at an arbitrary time t using linear interpolation.
484
+ * @param {{ t, y }} solution
485
+ * @param {number} tQuery
486
+ * @returns {number}
487
+ */
488
+ export function interpolateSolution(solution, tQuery) {
489
+ const { t, y } = solution;
490
+ if (tQuery <= t[0]) return y[0];
491
+ if (tQuery >= t.at(-1)) return y.at(-1);
492
+
493
+ let lo = 0, hi = t.length - 1;
494
+ while (hi - lo > 1) {
495
+ const mid = (lo + hi) >> 1;
496
+ if (t[mid] <= tQuery) lo = mid; else hi = mid;
497
+ }
498
+
499
+ const frac = (tQuery - t[lo]) / (t[hi] - t[lo]);
500
+ return y[lo] + frac * (y[hi] - y[lo]);
501
+ }
502
+
503
+ // ============================================================================
504
+ // HIGH-LEVEL CONVENIENCE
505
+ // ============================================================================
506
+
507
+ /**
508
+ * Main solve function — automatically picks appropriate method.
509
+ * @param {Function} f - f(t, y) → dy/dt
510
+ * @param {number} t0, y0, tEnd
511
+ * @param {Object} [opts]
512
+ * @param {string} [opts.method='rk4'] - 'euler', 'heun', 'rk4', 'rk45'
513
+ * @param {number} [opts.h=0.01] - Step size (ignored for rk45)
514
+ * @param {number} [opts.tol=1e-6] - Tolerance for rk45
515
+ * @returns {Object} Solution object { t, y, method, ... }
516
+ */
517
+ export function solveODE(f, t0, y0, tEnd, opts = {}) {
518
+ const { method = 'rk4', h = 0.01, tol = 1e-6 } = opts;
519
+
520
+ switch (method.toLowerCase()) {
521
+ case 'euler': return euler(f, t0, y0, tEnd, h);
522
+ case 'heun': return heun(f, t0, y0, tEnd, h);
523
+ case 'rk4': return rk4(f, t0, y0, tEnd, h);
524
+ case 'rk45': return rk45(f, t0, y0, tEnd, tol);
525
+ default: throw new Error(`Unknown ODE method: ${method}`);
526
+ }
527
+ }
528
+
529
+ /**
530
+ * Solve a system of ODEs.
531
+ * @param {Function} F - F(t, Y) → dY/dt
532
+ * @param {number} t0
533
+ * @param {number[]} Y0
534
+ * @param {number} tEnd
535
+ * @param {Object} [opts]
536
+ */
537
+ export function solveSystem(F, t0, Y0, tEnd, opts = {}) {
538
+ const { h = 0.01 } = opts;
539
+ return rk4System(F, t0, Y0, tEnd, h);
540
+ }
541
+
542
+ // ============================================================================
543
+ // PRIVATE UTILITIES
544
+ // ============================================================================
545
+
546
+ function _validateODEInputs(t0, y0, tEnd, h) {
547
+ if (typeof t0 !== 'number' || isNaN(t0)) throw new Error('t0 must be a number');
548
+ if (typeof y0 !== 'number' || isNaN(y0)) throw new Error('y0 must be a number');
549
+ if (typeof tEnd !== 'number' || isNaN(tEnd)) throw new Error('tEnd must be a number');
550
+ if (tEnd <= t0) throw new Error('tEnd must be greater than t0');
551
+ if (h <= 0) throw new Error('Step size h must be positive');
552
+ }
553
+
554
+ function _vecAdd(a, b) {
555
+ return a.map((v, i) => v + b[i]);
556
+ }
557
+
558
+ function _vecScale(a, s) {
559
+ return a.map(v => v * s);
560
+ }
561
+
562
+
563
+ // ============================================================================
564
+ // STIFF ODE SOLVERS
565
+ // ============================================================================
566
+
567
+ /**
568
+ * Implicit Euler method for stiff ODEs.
569
+ * Solves y' = f(t, y) using fixed-point iteration at each step.
570
+ * More stable than explicit Euler for stiff problems (e.g. chemical kinetics).
571
+ *
572
+ * @param {Function} f (t, y) → dy/dt
573
+ * @param {number} t0
574
+ * @param {number} y0
575
+ * @param {number} tEnd
576
+ * @param {number} h step size
577
+ * @returns {{ t: number[], y: number[] }}
578
+ */
579
+ export function implicitEuler(f, t0, y0, tEnd, h = 0.01) {
580
+ const t = [t0], y = [y0];
581
+ let tc = t0, yc = y0;
582
+ while (tc < tEnd - 1e-12) {
583
+ const tn = Math.min(tc + h, tEnd);
584
+ const hn = tn - tc;
585
+ // Fixed-point iteration: y_{n+1} = y_n + h·f(t_{n+1}, y_{n+1})
586
+ let yn = yc + hn * f(tc, yc); // initial guess from explicit Euler
587
+ for (let k = 0; k < 50; k++) {
588
+ const ynew = yc + hn * f(tn, yn);
589
+ if (Math.abs(ynew - yn) < 1e-12 * (1 + Math.abs(ynew))) { yn = ynew; break; }
590
+ yn = ynew;
591
+ }
592
+ tc = tn; yc = yn;
593
+ t.push(tc); y.push(yc);
594
+ }
595
+ return { t, y };
596
+ }
597
+
598
+ /**
599
+ * Trapezoidal / Crank-Nicolson method — O(h²) implicit, A-stable.
600
+ * Good for mildly stiff problems; combines implicit and explicit evaluation.
601
+ */
602
+ export function crankNicolson(f, t0, y0, tEnd, h = 0.01) {
603
+ const t = [t0], y = [y0];
604
+ let tc = t0, yc = y0;
605
+ while (tc < tEnd - 1e-12) {
606
+ const tn = Math.min(tc + h, tEnd);
607
+ const hn = tn - tc;
608
+ const fn = f(tc, yc);
609
+ // Predictor (explicit Euler)
610
+ let yn = yc + hn * fn;
611
+ // Corrector iterations (fixed point on trapezoid formula)
612
+ for (let k = 0; k < 50; k++) {
613
+ const ynew = yc + hn * 0.5 * (fn + f(tn, yn));
614
+ if (Math.abs(ynew - yn) < 1e-12 * (1 + Math.abs(ynew))) { yn = ynew; break; }
615
+ yn = ynew;
616
+ }
617
+ tc = tn; yc = yn;
618
+ t.push(tc); y.push(yc);
619
+ }
620
+ return { t, y };
621
+ }
622
+
623
+ // ============================================================================
624
+ // PARTIAL DIFFERENTIAL EQUATIONS (1D)
625
+ // ============================================================================
626
+
627
+ /**
628
+ * 1D Heat Equation: ∂u/∂t = α·∂²u/∂x²
629
+ * Uses explicit finite differences (FTCS scheme).
630
+ * Stability requirement: r = α·dt/dx² ≤ 0.5
631
+ *
632
+ * @param {number} alpha thermal diffusivity
633
+ * @param {number} L domain length [0, L]
634
+ * @param {number} T total time
635
+ * @param {Function} ic initial condition u(x, 0)
636
+ * @param {Function} [bcLeft] left BC u(0,t) — default Dirichlet = 0
637
+ * @param {Function} [bcRight] right BC u(L,t) — default Dirichlet = 0
638
+ * @param {number} [nx=50] spatial grid points
639
+ * @param {number} [nt=500] time steps
640
+ * @returns {{ x, t, u }} 2D solution array u[i_time][j_x]
641
+ */
642
+ export function heatEquation1D(alpha, L, T, ic, bcLeft = () => 0, bcRight = () => 0, nx = 50, nt = 500) {
643
+ const dx = L / (nx - 1);
644
+ const dt = T / nt;
645
+ const r = alpha * dt / (dx * dx);
646
+ if (r > 0.5) console.warn(`heatEquation1D: r=${r.toFixed(3)} > 0.5 — solution may be unstable. Increase nt or decrease alpha.`);
647
+
648
+ const x = Array.from({ length: nx }, (_, i) => i * dx);
649
+ const tArr = Array.from({ length: nt + 1 }, (_, k) => k * dt);
650
+
651
+ let u = x.map(xi => ic(xi));
652
+ const allU = [u.slice()];
653
+
654
+ for (let k = 0; k < nt; k++) {
655
+ const unew = u.slice();
656
+ unew[0] = bcLeft(tArr[k + 1]);
657
+ unew[nx - 1] = bcRight(tArr[k + 1]);
658
+ for (let j = 1; j < nx - 1; j++) {
659
+ unew[j] = u[j] + r * (u[j + 1] - 2 * u[j] + u[j - 1]);
660
+ }
661
+ u = unew;
662
+ allU.push(u.slice());
663
+ }
664
+
665
+ return { x, t: tArr, u: allU };
666
+ }
667
+
668
+ /**
669
+ * 1D Wave Equation: ∂²u/∂t² = c²·∂²u/∂x²
670
+ * Uses explicit central differences. Stability: CFL = c·dt/dx ≤ 1.
671
+ *
672
+ * @param {number} c wave speed
673
+ * @param {number} L domain length
674
+ * @param {number} T total time
675
+ * @param {Function} ic initial displacement u(x,0)
676
+ * @param {Function} icVel initial velocity ∂u/∂t(x,0)
677
+ * @param {number} [nx=50]
678
+ * @param {number} [nt=500]
679
+ * @returns {{ x, t, u }}
680
+ */
681
+ export function waveEquation1D(c, L, T, ic, icVel = () => 0, nx = 50, nt = 500) {
682
+ const dx = L / (nx - 1);
683
+ const dt = T / nt;
684
+ const r = c * dt / dx;
685
+ if (r > 1) console.warn(`waveEquation1D: CFL=${r.toFixed(3)} > 1 — solution may diverge. Increase nt.`);
686
+ const r2 = r * r;
687
+
688
+ const x = Array.from({ length: nx }, (_, i) => i * dx);
689
+ const tArr = Array.from({ length: nt + 1 }, (_, k) => k * dt);
690
+
691
+ let u0 = x.map(xi => ic(xi));
692
+ // u1 = u0 + dt·v0 + 0.5·dt²·c²·u0''
693
+ let u1 = u0.map((_, j) => {
694
+ if (j === 0 || j === nx - 1) return 0;
695
+ const d2 = (u0[j + 1] - 2 * u0[j] + u0[j - 1]) / (dx * dx);
696
+ return u0[j] + dt * icVel(x[j]) + 0.5 * c * c * dt * dt * d2;
697
+ });
698
+
699
+ const allU = [u0.slice(), u1.slice()];
700
+
701
+ for (let k = 1; k < nt; k++) {
702
+ const u2 = Array(nx).fill(0);
703
+ for (let j = 1; j < nx - 1; j++) {
704
+ u2[j] = 2 * u1[j] - u0[j] + r2 * (u1[j + 1] - 2 * u1[j] + u1[j - 1]);
705
+ }
706
+ u0 = u1; u1 = u2;
707
+ allU.push(u2.slice());
708
+ }
709
+
710
+ return { x, t: tArr, u: allU };
711
+ }
712
+
713
+ /**
714
+ * 1D Laplace / Poisson equation: -∂²u/∂x² = f(x)
715
+ * Solves the boundary value problem with Dirichlet BCs using finite differences.
716
+ *
717
+ * @param {Function} rhs f(x) — right hand side (0 for Laplace)
718
+ * @param {number} L domain [0, L]
719
+ * @param {number} u0 u(0) left BC
720
+ * @param {number} uL u(L) right BC
721
+ * @param {number} [n=100] interior points
722
+ * @returns {{ x, u }}
723
+ */
724
+ export function laplaceEquation1D(rhs, L, u0 = 0, uL = 0, n = 100) {
725
+ const dx = L / (n + 1);
726
+ const x = Array.from({ length: n }, (_, i) => (i + 1) * dx);
727
+ // Tridiagonal system: -u[i-1] + 2u[i] - u[i+1] = dx²·f(x[i])
728
+ const a = Array(n - 1).fill(-1);
729
+ const b = Array(n).fill(2);
730
+ const c = Array(n - 1).fill(-1);
731
+ const rh = x.map((xi, i) => {
732
+ const fi = rhs(xi) * dx * dx;
733
+ if (i === 0) return fi + u0;
734
+ if (i === n - 1) return fi + uL;
735
+ return fi;
736
+ });
737
+ // Use Thomas algorithm
738
+ const cp = c.slice(), dp = rh.slice();
739
+ cp[0] = c[0] / b[0]; dp[0] = rh[0] / b[0];
740
+ for (let i = 1; i < n; i++) {
741
+ const denom = b[i] - a[i - 1] * cp[i - 1];
742
+ cp[i] = i < n - 1 ? c[i] / denom : 0;
743
+ dp[i] = (rh[i] - a[i - 1] * dp[i - 1]) / denom;
744
+ }
745
+ const u = Array(n + 2).fill(0);
746
+ u[0] = u0; u[n + 1] = uL;
747
+ u[n] = dp[n - 1];
748
+ for (let i = n - 2; i >= 0; i--) u[i + 1] = dp[i] - cp[i] * u[i + 2];
749
+ return { x: [0, ...x, L], u };
750
+ }
751
+
752
+ // ============================================================================
753
+ // EVENT DETECTION (Zero Crossing)
754
+ // ============================================================================
755
+
756
+ /**
757
+ * Solve an ODE and detect events (zero crossings of event function).
758
+ * Useful for finding when a trajectory crosses a threshold.
759
+ *
760
+ * @param {Function} f (t, y) → dy/dt
761
+ * @param {Function} eventFn (t, y) → number (event fires when this = 0)
762
+ * @param {number} t0
763
+ * @param {number} y0
764
+ * @param {number} tEnd
765
+ * @param {number} [h=0.01]
766
+ * @returns {{ t, y, events: { t, y }[] }}
767
+ */
768
+ export function solveWithEvents(f, eventFn, t0, y0, tEnd, h = 0.01) {
769
+ const t = [t0], y = [y0];
770
+ const events = [];
771
+ let tc = t0, yc = y0;
772
+ let prevEvent = eventFn(tc, yc);
773
+
774
+ while (tc < tEnd - 1e-12) {
775
+ const hn = Math.min(h, tEnd - tc);
776
+ // RK4 step
777
+ const k1 = f(tc, yc);
778
+ const k2 = f(tc + hn/2, yc + hn/2 * k1);
779
+ const k3 = f(tc + hn/2, yc + hn/2 * k2);
780
+ const k4 = f(tc + hn, yc + hn * k3);
781
+ const yn = yc + (hn / 6) * (k1 + 2*k2 + 2*k3 + k4);
782
+ const tn = tc + hn;
783
+ const currEvent = eventFn(tn, yn);
784
+
785
+ // Sign change — bisect to find exact crossing
786
+ if (prevEvent * currEvent < 0) {
787
+ let ta = tc, ya = yc, tb = tn, yb = yn;
788
+ for (let k = 0; k < 52; k++) {
789
+ const tm = (ta + tb) / 2;
790
+ const ym = ya + (yb - ya) * (tm - ta) / (tb - ta);
791
+ const em = eventFn(tm, ym);
792
+ if (Math.abs(em) < 1e-12) { ta = tm; ya = ym; break; }
793
+ em * eventFn(ta, ya) < 0 ? (tb = tm, yb = ym) : (ta = tm, ya = ym);
794
+ }
795
+ events.push({ t: ta, y: ya });
796
+ }
797
+
798
+ tc = tn; yc = yn; prevEvent = currEvent;
799
+ t.push(tc); y.push(yc);
800
+ }
801
+ return { t, y, events };
802
+ }
803
+
804
+
805
+ // ============================================================================
806
+ // DELAY DIFFERENTIAL EQUATIONS (DDE)
807
+ // ============================================================================
808
+
809
+ /**
810
+ * Solve a delay differential equation: y'(t) = f(t, y(t), y(t-τ))
811
+ * Uses method of steps with RK4 on each sub-interval [kτ, (k+1)τ].
812
+ *
813
+ * @param {Function} f (t, y, yDelay) → dy/dt
814
+ * @param {Function} history y(t) for t ≤ t0 (the "past" function)
815
+ * @param {number} tau delay
816
+ * @param {number} t0
817
+ * @param {number} y0
818
+ * @param {number} tEnd
819
+ * @param {number} [h=0.01]
820
+ * @returns {{ t: number[], y: number[] }}
821
+ */
822
+ export function solveDDE(f, history, tau, t0, y0, tEnd, h = 0.01) {
823
+ const t = [t0], y = [y0];
824
+ let tc = t0, yc = y0;
825
+
826
+ const yAt = tq => {
827
+ if (tq <= t0) return history(tq);
828
+ // Linear interpolation in recorded solution
829
+ let idx = t.length - 1;
830
+ for (let i = 0; i < t.length - 1; i++) {
831
+ if (t[i] <= tq && tq <= t[i + 1]) { idx = i; break; }
832
+ }
833
+ if (idx >= t.length - 1) return y[y.length - 1];
834
+ const frac = (tq - t[idx]) / (t[idx + 1] - t[idx]);
835
+ return y[idx] + frac * (y[idx + 1] - y[idx]);
836
+ };
837
+
838
+ while (tc < tEnd - 1e-12) {
839
+ const hn = Math.min(h, tEnd - tc);
840
+ const k1 = f(tc, yc, yAt(tc - tau));
841
+ const k2 = f(tc + hn/2, yc + hn/2 * k1, yAt(tc + hn/2 - tau));
842
+ const k3 = f(tc + hn/2, yc + hn/2 * k2, yAt(tc + hn/2 - tau));
843
+ const k4 = f(tc + hn, yc + hn * k3, yAt(tc + hn - tau));
844
+ tc += hn;
845
+ yc += (hn / 6) * (k1 + 2*k2 + 2*k3 + k4);
846
+ t.push(tc); y.push(yc);
847
+ }
848
+ return { t, y };
849
+ }
850
+
851
+ // ============================================================================
852
+ // CHAOS & STRANGE ATTRACTORS
853
+ // ============================================================================
854
+
855
+ /**
856
+ * Rössler attractor: dx/dt = -y-z, dy/dt = x+ay, dz/dt = b+z(x-c)
857
+ * Classic example of a strange attractor for a = 0.2, b = 0.2, c = 5.7
858
+ */
859
+ export function solveRossler(Y0, t0, tEnd, h = 0.005, a = 0.2, b = 0.2, c = 5.7) {
860
+ return rk4System(
861
+ (t, Y) => [-Y[1] - Y[2], Y[0] + a * Y[1], b + Y[2] * (Y[0] - c)],
862
+ t0, Y0, tEnd, h
863
+ );
864
+ }
865
+
866
+ /**
867
+ * Duffing oscillator: ẍ + δẋ + αx + βx³ = γcos(ωt)
868
+ * Models a driven nonlinear oscillator; can exhibit chaos.
869
+ */
870
+ export function solveDuffing(x0, v0, t0, tEnd, h = 0.005, delta = 0.3, alpha = -1, beta = 1, gamma = 0.4, omega = 1.2) {
871
+ return rk4System(
872
+ (t, Y) => [
873
+ Y[1],
874
+ gamma * Math.cos(omega * t) - delta * Y[1] - alpha * Y[0] - beta * Y[0] ** 3
875
+ ],
876
+ t0, [x0, v0], tEnd, h
877
+ );
878
+ }
879
+
880
+ /**
881
+ * Van der Pol oscillator: ẍ − μ(1−x²)ẋ + x = 0
882
+ * Nonlinear oscillator with limit cycle; stiff for large μ.
883
+ */
884
+ export function solveVanDerPol(x0, v0, t0, tEnd, h = 0.005, mu = 1) {
885
+ return rk4System(
886
+ (t, Y) => [Y[1], mu * (1 - Y[0] ** 2) * Y[1] - Y[0]],
887
+ t0, [x0, v0], tEnd, h
888
+ );
889
+ }
890
+
891
+ /**
892
+ * Double pendulum (chaotic system).
893
+ * State: [θ₁, ω₁, θ₂, ω₂], all in radians/rad·s⁻¹.
894
+ * @param {number} m1 mass of pendulum 1
895
+ * @param {number} m2 mass of pendulum 2
896
+ * @param {number} l1 length of rod 1
897
+ * @param {number} l2 length of rod 2
898
+ */
899
+ export function solveDoublePendulum(Y0, t0, tEnd, h = 0.005, m1 = 1, m2 = 1, l1 = 1, l2 = 1, g = 9.81) {
900
+ const F = (t, Y) => {
901
+ const [th1, w1, th2, w2] = Y;
902
+ const dth = th2 - th1;
903
+ const denom1 = (m1 + m2) * l1 - m2 * l1 * Math.cos(dth) ** 2;
904
+ const denom2 = (l2 / l1) * denom1;
905
+ const dw1 = (m2 * l1 * w1 * w1 * Math.sin(dth) * Math.cos(dth)
906
+ + m2 * g * Math.sin(th2) * Math.cos(dth)
907
+ + m2 * l2 * w2 * w2 * Math.sin(dth)
908
+ - (m1 + m2) * g * Math.sin(th1)) / denom1;
909
+ const dw2 = (-m2 * l2 * w2 * w2 * Math.sin(dth) * Math.cos(dth)
910
+ + (m1 + m2) * g * Math.sin(th1) * Math.cos(dth)
911
+ - (m1 + m2) * l1 * w1 * w1 * Math.sin(dth)
912
+ - (m1 + m2) * g * Math.sin(th2)) / denom2;
913
+ return [w1, dw1, w2, dw2];
914
+ };
915
+ const sol = rk4System(F, t0, Y0, tEnd, h);
916
+ // Add cartesian coordinates
917
+ const xy = sol.Y.map(Y => ({
918
+ x1: l1 * Math.sin(Y[0]),
919
+ y1: -l1 * Math.cos(Y[0]),
920
+ x2: l1 * Math.sin(Y[0]) + l2 * Math.sin(Y[2]),
921
+ y2: -l1 * Math.cos(Y[0]) - l2 * Math.cos(Y[2]),
922
+ }));
923
+ return { ...sol, cartesian: xy };
924
+ }
925
+
926
+ // ============================================================================
927
+ // STABILITY ANALYSIS
928
+ // ============================================================================
929
+
930
+ /**
931
+ * Lyapunov exponent estimate for a 1D map x_{n+1} = f(x_n).
932
+ * Positive exponent → chaos.
933
+ *
934
+ * @param {Function} f 1D map
935
+ * @param {Function} df derivative of f
936
+ * @param {number} x0 initial point
937
+ * @param {number} [N=10000] iterations
938
+ */
939
+ export function lyapunovExponent1D(f, df, x0, N = 10000) {
940
+ let x = x0, sum = 0;
941
+ for (let i = 0; i < N; i++) {
942
+ const deriv = Math.abs(df(x));
943
+ if (deriv > 0) sum += Math.log(deriv);
944
+ x = f(x);
945
+ }
946
+ return sum / N;
947
+ }
948
+
949
+ /**
950
+ * Largest Lyapunov exponent for an ODE system (Wolf algorithm, simplified).
951
+ * Propagates a perturbation alongside the trajectory and measures divergence.
952
+ *
953
+ * @param {Function} F vector field (t, Y) → dY/dt
954
+ * @param {number[]} Y0 initial state
955
+ * @param {number} t0
956
+ * @param {number} tEnd
957
+ * @param {number} [h=0.01]
958
+ * @param {number} [renorm=1.0] renormalisation time
959
+ */
960
+ export function largestLyapunov(F, Y0, t0, tEnd, h = 0.01, renorm = 1.0) {
961
+ const eps = 1e-8;
962
+ let Y = Y0.slice();
963
+ const delta0 = Y0.map(() => (Math.random() - 0.5) * eps);
964
+ const norm0 = Math.sqrt(delta0.reduce((s, v) => s + v * v, 0));
965
+ let dY = delta0.map(v => v / norm0 * eps);
966
+ let t = t0, logSum = 0, steps = 0;
967
+ let nextRenorm = t0 + renorm;
968
+
969
+ const rk4Step = (state, time) => {
970
+ const k1 = F(time, state);
971
+ const k2 = F(time + h/2, state.map((v, i) => v + h/2 * k1[i]));
972
+ const k3 = F(time + h/2, state.map((v, i) => v + h/2 * k2[i]));
973
+ const k4 = F(time + h, state.map((v, i) => v + h * k3[i]));
974
+ return state.map((v, i) => v + (h/6) * (k1[i] + 2*k2[i] + 2*k3[i] + k4[i]));
975
+ };
976
+
977
+ while (t < tEnd) {
978
+ Y = rk4Step(Y, t);
979
+ const Yp = rk4Step(Y.map((v, i) => v + dY[i]), t);
980
+ dY = Yp.map((v, i) => v - Y[i]);
981
+ t += h;
982
+
983
+ if (t >= nextRenorm) {
984
+ const dNorm = Math.sqrt(dY.reduce((s, v) => s + v * v, 0));
985
+ if (dNorm > 0) { logSum += Math.log(dNorm / eps); dY = dY.map(v => v / dNorm * eps); }
986
+ steps++;
987
+ nextRenorm += renorm;
988
+ }
989
+ }
990
+ return steps > 0 ? logSum / (steps * renorm) : 0;
991
+ }
992
+
993
+ // ============================================================================
994
+ // PARAMETER ESTIMATION
995
+ // ============================================================================
996
+
997
+ /**
998
+ * Fit ODE parameters by minimising least-squares residuals against data.
999
+ * Uses Nelder-Mead simplex optimisation.
1000
+ *
1001
+ * @param {Function} odeF (t, y, params) → dy/dt
1002
+ * @param {number[]} tData observed time points
1003
+ * @param {number[]} yData observed values
1004
+ * @param {number[]} initParams initial parameter guess
1005
+ * @param {number} t0
1006
+ * @param {number} y0
1007
+ * @param {Object} [opts] { maxIter, tol }
1008
+ * @returns {{ params, residual, iterations }}
1009
+ */
1010
+ export function fitODE(odeF, tData, yData, initParams, t0, y0, opts = {}) {
1011
+ const { maxIter = 500, tol = 1e-8 } = opts;
1012
+
1013
+ const residual = params => {
1014
+ try {
1015
+ const sol = rk4(t => odeF(t, _, params), t0, y0, tData[tData.length - 1], 0.01);
1016
+ // interpolate solution at tData
1017
+ return tData.reduce((s, ti, i) => {
1018
+ const idx = sol.t.findIndex(tv => tv >= ti);
1019
+ const yi = idx > 0
1020
+ ? sol.y[idx - 1] + (sol.y[idx] - sol.y[idx - 1]) * (ti - sol.t[idx - 1]) / (sol.t[idx] - sol.t[idx - 1])
1021
+ : sol.y[0];
1022
+ return s + (yi - yData[i]) ** 2;
1023
+ }, 0);
1024
+ } catch { return Infinity; }
1025
+ };
1026
+
1027
+ // Nelder-Mead simplex
1028
+ const result = _nelderMead(residual, initParams, maxIter, tol);
1029
+ return result;
1030
+ }
1031
+
1032
+ function _nelderMead(f, x0, maxIter = 500, tol = 1e-8) {
1033
+ const n = x0.length;
1034
+ const alpha = 1, gamma = 2, rho = 0.5, sigma = 0.5;
1035
+
1036
+ // Initial simplex
1037
+ let simplex = [x0.slice()];
1038
+ for (let i = 0; i < n; i++) {
1039
+ const v = x0.slice();
1040
+ v[i] += v[i] !== 0 ? 0.05 * v[i] : 0.00025;
1041
+ simplex.push(v);
1042
+ }
1043
+
1044
+ let fVals = simplex.map(f);
1045
+ let iter = 0;
1046
+
1047
+ for (iter = 0; iter < maxIter; iter++) {
1048
+ // Sort
1049
+ const order = fVals.map((_, i) => i).sort((a, b) => fVals[a] - fVals[b]);
1050
+ simplex = order.map(i => simplex[i]);
1051
+ fVals = order.map(i => fVals[i]);
1052
+
1053
+ if (fVals[n] - fVals[0] < tol) break;
1054
+
1055
+ // Centroid (exclude worst)
1056
+ const xo = Array(n).fill(0);
1057
+ for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) xo[j] += simplex[i][j] / n;
1058
+
1059
+ // Reflect
1060
+ const xr = xo.map((v, j) => v + alpha * (v - simplex[n][j]));
1061
+ const fr = f(xr);
1062
+ if (fr < fVals[0]) {
1063
+ const xe = xo.map((v, j) => v + gamma * (xr[j] - v));
1064
+ const fe = f(xe);
1065
+ simplex[n] = fe < fr ? xe : xr;
1066
+ fVals[n] = fe < fr ? fe : fr;
1067
+ } else if (fr < fVals[n - 1]) {
1068
+ simplex[n] = xr; fVals[n] = fr;
1069
+ } else {
1070
+ const xc = xo.map((v, j) => v + rho * (simplex[n][j] - v));
1071
+ const fc = f(xc);
1072
+ if (fc < fVals[n]) { simplex[n] = xc; fVals[n] = fc; }
1073
+ else {
1074
+ for (let i = 1; i <= n; i++)
1075
+ simplex[i] = simplex[0].map((v, j) => v + sigma * (simplex[i][j] - v));
1076
+ fVals = simplex.map(f);
1077
+ }
1078
+ }
1079
+ }
1080
+
1081
+ return { params: simplex[0], residual: fVals[0], iterations: iter };
1082
+ }