-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine-gauss.js
More file actions
902 lines (805 loc) · 43.5 KB
/
Copy pathengine-gauss.js
File metadata and controls
902 lines (805 loc) · 43.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
/* ====================================================================
ENGINE — Gaussian elimination with partial pivoting (Sheet 09)
----------------------------------------------------------------------
The direct-method sibling of Sheet 07 (LU decomposition): takes the
SAME augmented-matrix input (one equation per row, rightmost column
becomes b), reduces [A | b] to upper triangular form using partial
pivoting, then back-substitutes for x₁ … xₙ one variable at a time.
Difference from the LU sheet, conceptually: LU factors and STORES
the multipliers as a reusable L·U product; plain Gaussian elimination
just wipes each eliminated entry to zero and pushes forward — the
multiplier is shown in its step, then discarded. Every step of that
story is logged for the animation: pivot searches, row swaps, each
individual row operation (R₃ −= m·R₁), the completed triangular
system, and each back-substituted variable.
Requires core.js loaded first. Follows the shared engine contract:
merge into NAW.METHODS, subscribe to NAW.onMethodChange(), guard
every shared-button handler with isActive(), and restore any shared
page chrome this sheet hid when it stops being active — none of the
other eight sheets behave any differently whether or not this loads.
==================================================================== */
(function () {
'use strict';
const NAW = window.NAW;
const {
$, D, parseVal, fmt,
escHtml, showStatus, clearStatus,
dl, ts, canvasBlob, mkCaptureOverlay, waitFrames,
} = NAW;
/* ================================================================
SHARED PAGE CHROME this engine temporarily reconfigures while
its own sheet is active (restored verbatim on leave).
================================================================ */
const CHROME = {
fxField: $('fx-field'), // f(x) input row (hidden — no function here)
matrixWrap: $('matrix-fieldset'), // matrix textarea (shown — this sheet's input)
aField: $('a-field'), // "a" bound input (hidden — meaningless here)
trueRootFld: $('true-root-field'), // true root (hidden — direct method)
bracketFld: $('bracket-fieldset'), // bracket auto/manual (hidden — no brackets)
stopFld: $('stop-fieldset'), // stop-after criteria (hidden — not iterative)
hWrap: $('h-field-wrap'), // step h (kept hidden — Sheet 08's input)
};
function applySheetChrome() {
if (CHROME.fxField) CHROME.fxField.hidden = true;
if (CHROME.matrixWrap) CHROME.matrixWrap.hidden = false;
if (CHROME.aField) CHROME.aField.hidden = true;
if (CHROME.trueRootFld) CHROME.trueRootFld.hidden = true;
if (CHROME.bracketFld) CHROME.bracketFld.hidden = true;
if (CHROME.stopFld) CHROME.stopFld.hidden = true;
if (CHROME.hWrap) CHROME.hWrap.hidden = true;
}
function restoreChrome() {
if (CHROME.fxField) CHROME.fxField.hidden = false;
if (CHROME.matrixWrap) CHROME.matrixWrap.hidden = true;
if (CHROME.aField) CHROME.aField.hidden = false;
if (CHROME.trueRootFld) CHROME.trueRootFld.hidden = false;
if (CHROME.bracketFld) CHROME.bracketFld.hidden = false;
if (CHROME.stopFld) CHROME.stopFld.hidden = false;
if (CHROME.hWrap) CHROME.hWrap.hidden = true;
/* put the a/b inputs back exactly the way the bracketing engine's
own radio-change handler leaves them for the current mode */
const modeEl = document.querySelector('[name="bracketMode"]:checked');
const manual = modeEl ? modeEl.value === 'manual' : false;
if (D.aInput) {
D.aInput.disabled = !manual;
D.aInput.placeholder = manual ? 'e.g. 1 or pi/2' : 'auto-detected on Solve';
if (!manual) D.aInput.value = '';
}
if (D.bInput) {
D.bInput.disabled = !manual;
D.bInput.placeholder = manual ? 'e.g. 2 or e' : 'auto-detected on Solve';
if (!manual) D.bInput.value = '';
}
}
/* ================================================================
STATE
================================================================ */
let _steps = [];
let _idx = 0;
let _playTmr = null;
let _heroTmr = null;
let _result = null; // {n, hasB, U, c, perm, swaps, det, singular, x}
let _exIdx = 0;
const isActive = () => (NAW.getActiveMethod() in METHODS);
/* ================================================================
EXAMPLES — cycled by the shared "Load an example" button.
Each row = one linear equation: coefficients of x, y, z… then
the right-hand side. Last example omits b (pure reduction).
================================================================ */
const EXAMPLES = [
{ m: ' 2 1 -1 8\n-3 -1 2 -11\n-2 1 2 -3', note: 'Classic 3×3 system — unique solution x = (2, 3, −1)' },
{ m: '1 1 1 6\n0 2 5 -4\n2 5 -1 27', note: 'Textbook system — solution x = (5, 3, −2)' },
{ m: '0 1 1 5\n2 1 -1 1\n1 -1 2 5', note: 'Zero leading coefficient forces a row swap R1 ↔ R2 — x = (1, 2, 3)' },
{ m: '3 2 7\n1 4 9', note: 'Quick 2×2 — solution x = (1, 2)' },
{ m: '2 1 1\n4 -6 0\n-2 7 2', note: 'No b column — pure reduction to upper triangular, det = −16' },
];
/* ================================================================
METHODS REGISTRY ENTRY (merged into the shared core registry)
================================================================ */
const METHODS = {
gauss: {
id: 'gauss',
num: '09',
docTitle: 'Gaussian Elimination',
heroTitleHTML: 'Gaussian elimination,<br>reduced <span class="accent">row by row</span>.',
heroSub: 'Type your equations as coefficient rows and watch [A | b] get driven to upper triangular form — every pivot choice, row swap, and row operation logged — then back-substitution peels off x₃, x₂, x₁ one at a time.',
metaMethod: 'Gaussian elimination (partial pivoting)',
metaOrder: 'Direct method — finite, exact up to rounding',
metaNeeds: 'square system Ax = b (augmented rows)',
cLabel: 'multiplier',
cColHeader: 'Multiplier / value',
graphAria: 'Animated elimination grid showing Gaussian reduction progressing',
heroGraphAria: 'Animated demo of Gaussian elimination with partial pivoting',
needsMsg: 'Gaussian elimination needs a square system with at least one nonzero pivot per column.',
hideB: true,
shapeCopy: {
'read-a-label': 'stage',
'read-b-label': 'pivot |value|',
'read-fc-label': 'action',
},
},
};
Object.assign(NAW.METHODS, METHODS);
/* ================================================================
MATRIX PARSING — same contract as the LU sheet: one row per line,
cells split on spaces/commas, every cell through the shared
parseVal (pi, sqrt(2), -1/2 … all work). Exactly one extra cell
per row ⇒ that column is the vector b.
================================================================ */
function parseMatrix(text) {
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(l => l.length);
if (!lines.length) return { err: 'Enter a matrix — one equation per line.' };
const rows = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].length > 200) return { err: `Row ${i + 1} is too long (max 200 characters per row).` };
const cells = lines[i].split(/[,\s]+/).filter(s => s.length);
if (!cells.length) return { err: `Row ${i + 1} is empty.` };
const vals = [];
for (let j = 0; j < cells.length; j++) {
const v = parseVal(cells[j]);
if (isNaN(v)) return { err: `Cannot evaluate cell (row ${i + 1}, col ${j + 1}): "${cells[j]}". Use numbers or expressions like pi, sqrt(2), -1/2.` };
vals.push(v);
}
rows.push(vals);
}
const widths = new Set(rows.map(r => r.length));
if (widths.size !== 1) return { err: 'All rows must have the same number of cells.' };
const w = rows[0].length;
const n = rows.length;
if (n < 2) return { err: 'Need at least a 2×2 system.' };
if (n > 6) return { err: 'Maximum supported size is 6×6 (keep the animation readable).' };
if (w !== n && w !== n + 1)
return { err: `Got ${n} row(s) with ${w} cell(s) each — expected a square ${n}×${n} matrix, or ${n}×${n + 1} with the extra column as b.` };
const hasB = (w === n + 1);
const A = rows.map(r => r.slice(0, n));
const b = hasB ? rows.map(r => r[n]) : null;
return { A, b, n, hasB };
}
/* ================================================================
GAUSSIAN ELIMINATION — partial pivoting, fully logged.
Forward phase drives [A | b] to upper triangular [U′ | c],
wiping each eliminated entry to an explicit zero (unlike LU,
nothing is stored below the diagonal). Back phase solves U′x = c
from the bottom up. Every step snapshots the CURRENT matrix as
formatted strings so later mutation can't alter earlier frames.
================================================================ */
const z0 = v => (Object.is(v, -0) ? 0 : v);
function gaussEliminate(A, bIn) {
const n = A.length;
const hasB = !!bIn;
const M = A.map(r => r.map(z0));
const b = hasB ? bIn.map(z0) : null;
const perm = Array.from({ length: n }, (_, i) => i); // perm[j] = original row now in slot j
let swaps = 0;
const steps = [];
const snap = () => ({
cells: M.map(r => r.map(v => fmt(z0(v)))),
b: hasB ? b.map(v => fmt(z0(v))) : null,
});
steps.push({
kind: 'init', desc: 'Start',
detail: hasB
? `Augmented system [A | b], size ${n}×${n + 1} — goal: reduce to upper triangular, then back-substitute.`
: `Matrix A, size ${n}×${n} — goal: reduce to upper triangular form via partial-pivoted elimination.`,
mat: snap(), hi: [], star: null, ann: null, val: null,
});
let failed = false;
for (let k = 0; k < n - 1; k++) {
/* ── pivot search: largest |entry| at/below the diagonal ── */
let p = k;
for (let i = k + 1; i < n; i++)
if (Math.abs(M[i][k]) > Math.abs(M[p][k])) p = i;
steps.push({
kind: 'pivot', desc: `Pivot search — column ${k + 1}`,
detail: `Largest magnitude at or below row ${k + 1} is |A[${p + 1}][${k + 1}]| = ${fmt(Math.abs(z0(M[p][k])))}${p === k ? ' — already on the diagonal.' : `, at row ${p + 1}.`}`,
mat: snap(),
hi: Array.from({ length: n - k }, (_, t) => ({ r: k + t, c: k })),
star: { r: p, c: k }, ann: null,
val: fmt(Math.abs(z0(M[p][k]))),
});
/* ── row swap if needed ── */
if (p !== k) {
const tmp = M[p]; M[p] = M[k]; M[k] = tmp;
if (hasB) { const tb = b[p]; b[p] = b[k]; b[k] = tb; }
const tp = perm[p]; perm[p] = perm[k]; perm[k] = tp;
swaps++;
steps.push({
kind: 'swap', desc: `Row swap — R${p + 1} ↔ R${k + 1}`,
detail: `Partial pivoting puts the largest available entry on the diagonal — better numerical stability than eliminating with a tiny pivot.`,
mat: snap(),
hi: [{ r: k, c: k }, { r: p, c: k }], star: { r: k, c: k }, ann: null,
val: `R${p + 1}↔R${k + 1}`,
});
}
/* ── singularity guard ── */
if (Math.abs(M[k][k]) < 1e-14) {
steps.push({
kind: 'fail', desc: `Zero pivot in column ${k + 1}`,
detail: 'Every candidate pivot is (numerically) zero — the system is singular or nearly singular, so elimination cannot continue.',
mat: snap(), hi: [{ r: k, c: k }], star: null, ann: null, val: '0',
});
failed = true;
break;
}
/* ── eliminate below the pivot, one row at a time ── */
for (let i = k + 1; i < n; i++) {
const m = M[i][k] / M[k][k];
steps.push({
kind: 'elim', desc: `Eliminate A[${i + 1}][${k + 1}]`,
detail: `m = A[${i + 1}][${k + 1}] / A[${k + 1}][${k + 1}] = ${fmt(z0(M[i][k]))} / ${fmt(z0(M[k][k]))} = ${fmt(z0(m))} → R${i + 1} −= ${fmt(z0(m))}·R${k + 1}`,
mat: snap(),
hi: [{ r: i, c: k }, { r: k, c: k }],
star: { r: k, c: k },
ann: { row: i, text: `×${fmt(z0(m))}` },
val: fmt(z0(m)),
});
for (let j = k; j < n; j++) M[i][j] -= m * M[k][j];
if (hasB) b[i] -= m * b[k];
M[i][k] = 0; // wiped, not stored — this is what separates Gauss from LU
}
}
/* Singular ⇔ elimination died midway, or the LAST diagonal entry
(which the k-loop above never tests) is numerically zero. */
const singular = failed || Math.abs(M[n - 1][n - 1]) < 1e-12;
const det = (swaps % 2 ? -1 : 1) * M.reduce((acc, row, i) => acc * M[i][i], 1);
const result = { n, hasB, U: M.map(r => r.slice()), c: hasB ? b.slice() : null,
perm, swaps, det, singular, x: null };
/* ── reduction-complete step ── */
steps.push({
kind: 'tri', desc: 'Upper triangular reached',
detail: `Diagonal product: (${M.map((_, i) => fmt(z0(M[i][i]))).join(' · ')}) → det(A) = ${swaps % 2 ? '±' : ''}${fmt(z0(det))}` +
(singular ? ' ⚠ a pivot ended up ~0 → singular.' : '') +
(hasB && !singular ? ' Ready to back-substitute.' :
hasB ? ' Cannot back-substitute a singular system.' :
' Add an extra column b to also solve Ax = b.'),
mat: snap(),
hi: Array.from({ length: n }, (_, t) => ({ r: t, c: t })),
star: null, ann: null, val: fmt(z0(det)),
});
/* ── back-substitution (only when b was supplied and invertible) ── */
if (hasB && !failed && !singular) {
const x = new Array(n);
for (let i = n - 1; i >= 0; i--) {
let s = b[i];
const terms = [];
for (let j = i + 1; j < n; j++) {
s -= M[i][j] * x[j];
terms.push(`${fmt(z0(M[i][j]))}·${fmt(z0(x[j]))}`);
}
x[i] = z0(s / M[i][i]);
steps.push({
kind: 'substB', desc: `Back substitute — x${i + 1}`,
detail: `x${i + 1} = (${fmt(z0(b[i]))}` +
(terms.length ? ` − (${terms.join(' + ')})` : '') + `) / ${fmt(z0(M[i][i]))} = ${fmt(x[i])}`,
mat: snap(), hi: Array.from({ length: n }, (_, t) => ({ r: i, c: t })),
star: null, ann: { row: i, text: `x${i + 1}=${fmt(x[i])}` }, val: fmt(x[i]),
});
}
result.x = x;
steps.push({
kind: 'done', desc: 'System solved — Ax = b',
detail: `x = ( ${x.map(v => fmt(v)).join(', ')} ) · obtained without forming L or U explicitly — ${swaps} row swap${swaps === 1 ? '' : 's'} recorded.`,
mat: snap(), hi: [], star: null, ann: null,
val: `x = (${x.map(v => fmt(v)).join(', ')})`,
});
} else if (hasB && singular && !failed) {
steps.push({
kind: 'fail', desc: 'Cannot solve Ax = b',
detail: 'The final pivot is (numerically) zero — A is singular, so Ax = b has no unique solution. The reduction steps above are still shown.',
mat: snap(), hi: [], star: null, ann: null, val: 'singular',
});
}
return { steps, result, failed };
}
/* ================================================================
RENDER: MAIN GRAPH — animated matrix grid (single layout for all
step kinds: unlike LU there's only ever ONE matrix on stage, the
progressively triangularising [A | b]).
================================================================ */
function renderGraph(idx) {
const pal = NAW.graphPalette();
if (!_steps.length || !_result) return;
const s = _steps[idx];
const st = _result;
const W = 800, H = 456;
const n = st.n, hasB = st.hasB;
let svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}">`;
/* faint blueprint grid backdrop, matching the other sheets */
for (let i = 0; i <= 8; i++)
svg += `<line x1="${(72 + i * 88).toFixed(1)}" y1="30" x2="${(72 + i * 88).toFixed(1)}" y2="${H - 82}" stroke="rgba(${pal.gridRGB},.12)" stroke-width="1"/>`;
for (let i = 0; i <= 6; i++)
svg += `<line x1="72" y1="${(30 + i * 57.3).toFixed(1)}" x2="${W - 24}" y2="${(30 + i * 57.3).toFixed(1)}" stroke="rgba(${pal.gridRGB},.12)" stroke-width="1"/>`;
/* ── working matrix grid ── */
const cols = n + (hasB ? 1 : 0);
const cs = Math.max(34, Math.min(56, Math.floor(250 / n)));
const gapB = hasB ? 12 : 0;
const gridW = cols * cs + gapB;
const gx = Math.round(W * 0.42 - gridW / 2);
const gy = Math.round(96 + (250 - n * cs) / 2);
/* bracket rails (matrix notation look) */
svg += `<line x1="${gx - 14}" y1="${gy - 6}" x2="${gx - 14}" y2="${gy + n * cs + 6}" stroke="${pal.axis}" stroke-width="1.6"/>`;
svg += `<line x1="${gx + n * cs + (hasB ? gapB : 0) + 8}" y1="${gy - 6}" x2="${gx + n * cs + (hasB ? gapB : 0) + 8}" y2="${gy + n * cs + 6}" stroke="${pal.axis}" stroke-width="1.6"/>`;
/* column headers */
for (let j = 0; j < n; j++)
svg += `<text x="${gx + j * cs + cs / 2}" y="${gy - 12}" text-anchor="middle" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${j + 1}</text>`;
if (hasB)
svg += `<text x="${gx + n * cs + gapB + cs / 2}" y="${gy - 12}" text-anchor="middle" font-size="10" fill="${pal.copper}" font-family="IBM Plex Mono,monospace">b</text>`;
for (let i = 0; i < n; i++)
svg += `<text x="${gx - 20}" y="${gy + i * cs + cs / 2 + 4}" text-anchor="end" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">R${i + 1}</text>`;
const hiSet = new Set((s.hi || []).map(h => h.r + ',' + h.c));
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
const x = gx + j * cs, y = gy + i * cs;
const key = i + ',' + j;
const isHi = hiSet.has(key);
const isStar = s.star && s.star.r === i && s.star.c === j;
const belowDiag = j < i;
const zeroed = belowDiag && parseFloat(s.mat.cells[i][j]) === 0;
let fill = zeroed ? `rgba(${pal.verdigrisRGB},.07)` : 'transparent';
if (isHi) fill = `rgba(${pal.copperRGB},.22)`;
svg += `<rect x="${x + 1}" y="${y + 1}" width="${cs - 2}" height="${cs - 2}" rx="2" fill="${fill}" stroke="${isStar ? pal.verdigris : `rgba(${pal.gridRGB},.35)`}" stroke-width="${isStar ? 2.2 : 0.8}"/>`;
const txt = s.mat.cells[i][j];
const fs = txt.length > 8 ? 9 : (cs > 46 ? 13 : 11);
const col = isStar ? pal.verdigris : (isHi ? pal.copper : (belowDiag ? pal.tick : pal.axis));
svg += `<text x="${x + cs / 2}" y="${y + cs / 2 + fs / 3}" text-anchor="middle" font-size="${fs}" fill="${col}" font-family="IBM Plex Mono,monospace">${txt}</text>`;
}
if (hasB) {
const x = gx + n * cs + gapB;
const isHi = hiSet.has(i + ',' + n);
svg += `<rect x="${x + 1}" y="${gy + i * cs + 1}" width="${cs - 2}" height="${cs - 2}" rx="2" fill="${isHi ? `rgba(${pal.copperRGB},.22)` : 'transparent'}" stroke="rgba(${pal.gridRGB},.35)" stroke-width="0.8"/>`;
const txt = s.mat.b[i];
const fs = txt.length > 8 ? 9 : (cs > 46 ? 13 : 11);
svg += `<text x="${x + cs / 2}" y="${gy + i * cs + cs / 2 + fs / 3}" text-anchor="middle" font-size="${fs}" fill="${pal.copper}" font-family="IBM Plex Mono,monospace">${txt}</text>`;
}
/* multiplier / substitution annotation at the row's left */
if (s.ann && s.ann.row === i) {
svg += `<text x="${gx - 24}" y="${gy + i * cs + cs / 2 + 4}" text-anchor="end" font-size="11" fill="${pal.copper}" font-family="IBM Plex Mono,monospace" font-weight="600">${escHtml(s.ann.text)}</text>`;
}
}
/* right-hand explanation panel */
const px = Math.max(gx + gridW + 36, Math.round(W * 0.62));
svg += `<text x="${px}" y="${gy + 18}" font-size="11" fill="${pal.tick}" font-family="IBM Plex Mono,monospace" letter-spacing="1">STEP ${idx + 1}/${_steps.length}</text>`;
svg += `<text x="${px}" y="${gy + 44}" font-size="15" fill="${pal.axis}" font-family="IBM Plex Sans Condensed,sans-serif" font-weight="600">${escHtml(s.desc)}</text>`;
const words = s.detail.split(' ');
let line = '', ly = gy + 68;
for (const wd of words) {
if ((line + ' ' + wd).trim().length > 34) {
svg += `<text x="${px}" y="${ly}" font-size="11" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${escHtml(line)}</text>`;
line = wd; ly += 17;
if (ly > gy + 220) { svg += `<text x="${px}" y="${ly}" font-size="11" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">…</text>`; break; }
} else line = (line ? line + ' ' : '') + wd;
}
if (ly <= gy + 220 && line)
svg += `<text x="${px}" y="${ly}" font-size="11" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${escHtml(line)}</text>`;
/* solution callout on the final step */
if (s.kind === 'done' && st.x) {
svg += `<rect x="${px - 8}" y="${gy + 232}" width="${Math.min(300, W - px - 16)}" height="34" rx="3" fill="rgba(${pal.copperRGB},.14)" stroke="${pal.copper}" stroke-width="1"/>`;
svg += `<text x="${px}" y="${gy + 254}" font-size="13" fill="${pal.copper}" font-family="IBM Plex Mono,monospace" font-weight="600">x = ( ${st.x.map(v => fmt(v)).join(', ')} )</text>`;
}
/* legend */
const legY = gy + n * cs + 30;
svg += `<rect x="${gx}" y="${legY}" width="10" height="10" rx="2" fill="rgba(${pal.copperRGB},.22)" stroke="${pal.copper}" stroke-width="1"/>`;
svg += `<text x="${gx + 16}" y="${legY + 9}" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">active cells</text>`;
svg += `<rect x="${gx + 110}" y="${legY}" width="10" height="10" rx="2" fill="transparent" stroke="${pal.verdigris}" stroke-width="2"/>`;
svg += `<text x="${gx + 126}" y="${legY + 9}" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">pivot</text>`;
svg += `<rect x="${gx + 190}" y="${legY}" width="10" height="10" rx="2" fill="rgba(${pal.verdigrisRGB},.07)" stroke="rgba(${pal.gridRGB},.35)"/>`;
svg += `<text x="${gx + 206}" y="${legY + 9}" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">eliminated (zero)</text>`;
/* step overlay bar (same visual language as the other graphs) */
svg += `<rect x="78" y="36" width="380" height="20" rx="2" fill="rgba(${pal.bgDeepRGB},.75)"/>`;
svg += `<text x="85" y="50" font-size="11" fill="${pal.axis}" font-family="IBM Plex Mono,monospace">Step ${idx + 1} of ${_steps.length} · ${escHtml(s.desc)}</text>`;
svg += '</svg>';
D.bisGr.innerHTML = svg;
/* readings row */
const pivotVal = s.kind === 'pivot' ? s.val : '—';
const multVal = (s.kind === 'elim' || s.kind === 'substB' || s.kind === 'tri') ? s.val :
(s.kind === 'done') ? s.val : '—';
D.readA.textContent = (s.kind === 'pivot' || s.kind === 'swap' || s.kind === 'elim')
? `col ${((s.hi && s.hi[0]) ? s.hi[0].c : 0) + 1}` : '—';
D.readB.textContent = pivotVal;
D.readC.textContent = multVal;
D.readFc.textContent = s.kind.toUpperCase();
if (idx === _steps.length - 1) {
D.readConvW.hidden = false;
D.readConv.textContent = s.desc;
} else {
D.readConvW.hidden = true;
}
D.stepInd.textContent = `Step ${idx + 1} of ${_steps.length}`;
D.prevBtn.disabled = (idx === 0);
D.nextBtn.disabled = (idx >= _steps.length - 1);
Array.from(D.tBody.querySelectorAll('tr')).forEach((r, i) => {
r.classList.toggle('active-row', i === idx);
});
}
/* ================================================================
RENDER: SOLUTION BOX
================================================================ */
function renderSolBox() {
const st = _result;
const last = _steps[_steps.length - 1];
D.solBox.innerHTML = `
<div class="sol-group">
<div class="sol-lbl">Input</div>
<div class="sol-eq">${st.hasB ? `[A | b] ∈ ℝ<sup>${st.n}×${st.n + 1}</sup> — ${st.n} equations, ${st.n} unknowns` : `A ∈ ℝ<sup>${st.n}×${st.n}</sup> — entered without a b column`}</div>
</div>
<div class="sol-group">
<div class="sol-lbl">Row reduction — [A | b] → [U′ | c] (partial pivoting)</div>
<div class="bracket-box">
<div class="bc-row"><code>P = [${st.perm.map(i => i + 1).join(', ')}] (rows of A, in this order)</code></div>
<div class="bc-row"><code>Forward phase: ${_steps.filter(s => s.kind === 'elim').length} row operation${_steps.filter(s => s.kind === 'elim').length === 1 ? '' : 's'}, ${st.swaps} swap${st.swaps === 1 ? '' : 's'} → upper triangular</code></div>
<div class="bc-row ivt-row">
<code>det(A) = ${st.swaps % 2 ? '(−1)' : '(+1)'} · ∏pivots = ${fmt(z0(st.det))}</code>
<span class="sign-pill ${st.singular ? 'neg' : 'ok'}">${st.singular ? '⚠ singular' : '✓ invertible'}</span>
<span class="ivt-note">→ ${st.singular ? 'no unique solution exists' : 'back-substitution solves the system uniquely'}</span>
</div>
</div>
</div>
${st.x ? `
<div class="sol-group">
<div class="sol-lbl">Result — back-substitution from the bottom row up</div>
<div class="result-row">
<span class="root-chip">x = ( ${st.x.map(v => fmt(v)).join(', ')} )</span>
<span class="conv-chip">✓ ${escHtml(last.desc)}</span>
</div>
</div>` : `
<div class="sol-group">
<div class="sol-lbl">Result</div>
<div class="result-row">
<span class="root-chip">[U′${st.hasB ? ' | c' : ''}]</span>
<span class="conv-chip">✓ ${escHtml(last.desc)}</span>
<span class="ae-note">${st.hasB ? 'system is singular — see the log for where it stalled' : 'add an extra column b to also solve Ax = b'}</span>
</div>
</div>`}
`;
}
/* ================================================================
RENDER: ITERATION TABLE — the action log
================================================================ */
function renderTable() {
D.tHead.innerHTML = ['Step', 'Operation', 'Details', 'Value']
.map(h => `<th>${h}</th>`).join('');
D.capSum.textContent =
`Gaussian elimination (partial pivoting) · ${_result.n}×${_result.n}` +
` · ${_steps.length} logged step${_steps.length !== 1 ? 's' : ''}` +
` · det(A) ≈ ${fmt(z0(_result.det))}${_result.x ? ` · x = (${_result.x.map(v => fmt(v)).join(', ')})` : ''}`;
D.tblNote.textContent =
`Each row operation zeroes one entry below the pivot — those entries stay zero (grey-green) for the rest of the run. ` +
`After the forward phase, back-substitution recovers x from the bottom row upward.`;
D.tBody.innerHTML = '';
_steps.forEach((s, i) => {
const tr = document.createElement('tr');
if (i === _idx) tr.classList.add('active-row');
if (s.kind === 'tri' || s.kind === 'done' || s.kind === 'fail')
tr.classList.add('converged-row');
tr.innerHTML = [
`<td>${i + 1}</td>`,
`<td style="text-transform:none;">${escHtml(s.desc)}</td>`,
`<td style="text-align:left;text-transform:none;white-space:normal;max-width:420px;">${escHtml(s.detail)}</td>`,
`<td class="c-val">${s.val != null ? escHtml(String(s.val)) : '—'}</td>`,
].join('');
D.tBody.appendChild(tr);
});
}
/* ================================================================
SOLVE
================================================================ */
function solve(e) {
if (!isActive()) return;
e?.preventDefault();
clearStatus();
if (_playTmr) { clearInterval(_playTmr); _playTmr = null; D.playBtn.textContent = '▶'; }
const raw = $('matrix-input').value.trim();
if (!raw) return showStatus('Enter your equations first — one row per line.');
if (raw.length > 2000) return showStatus('Matrix input is too long (max 2000 characters).');
const parsed = parseMatrix(raw);
if (parsed.err) return showStatus(parsed.err);
const { A, b } = parsed;
const { steps, result, failed } = gaussEliminate(A, b);
_steps = steps;
_result = result;
if (failed)
showStatus('Zero pivot encountered — the system is singular. The partial reduction is still shown below.', 'error');
else if (result.singular && result.hasB)
showStatus('A is singular — the final pivot is (numerically) zero, so Ax = b has no unique solution. Reduction steps are shown.', 'error');
else if (result.singular)
showStatus('Note: A is singular (a pivot is ~0) — det(A) ≈ 0.', 'error');
_idx = 0;
D.solSec.hidden = false;
D.vizSec.hidden = false;
D.tblSec.hidden = false;
renderSolBox();
renderTable();
renderGraph(0);
D.solSec.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
/* ================================================================
PLAYBACK
================================================================ */
function goTo(idx) {
if (!isActive() || !_steps.length) return;
_idx = Math.max(0, Math.min(idx, _steps.length - 1));
renderGraph(_idx);
}
function togglePlay() {
if (!isActive() || !_steps.length) return;
if (_playTmr) {
clearInterval(_playTmr); _playTmr = null;
D.playBtn.textContent = '▶';
D.playBtn.setAttribute('aria-label', 'Play');
} else {
if (_idx >= _steps.length - 1) _idx = -1;
D.playBtn.textContent = '⏸';
D.playBtn.setAttribute('aria-label', 'Pause');
_playTmr = setInterval(() => {
_idx++;
if (_idx >= _steps.length) {
clearInterval(_playTmr); _playTmr = null;
D.playBtn.textContent = '▶';
D.playBtn.setAttribute('aria-label', 'Play');
return;
}
renderGraph(_idx);
}, +D.speedSel.value);
}
}
/* ================================================================
RESET / HIDE
================================================================ */
function hideResults() {
if (_playTmr) { clearInterval(_playTmr); _playTmr = null; D.playBtn.textContent = '▶'; }
clearStatus();
D.solSec.hidden = true;
D.vizSec.hidden = true;
D.tblSec.hidden = true;
_steps = []; _idx = 0; _result = null;
D.prevBtn.disabled = true;
D.nextBtn.disabled = true;
}
function reset() {
if (!isActive()) return;
hideResults();
const mi = $('matrix-input');
if (mi) mi.value = '';
}
/* ================================================================
EXPORTS — same off-screen landscape pipeline as the other engines
================================================================ */
function buildExportEl() {
const st = _result;
const last = _steps[_steps.length - 1];
const date = new Date().toLocaleDateString(undefined, { year:'numeric', month:'short', day:'numeric' });
const thS = 'padding:6px 9px;text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.06em;color:#7B93B0;border-bottom:2px solid rgba(61,102,148,.5);white-space:nowrap;background:#0e2140';
const tdB = 'padding:5px 9px;border-bottom:1px solid rgba(61,102,148,.2);text-align:left;white-space:normal;font-size:11px';
let rows = '';
for (let i = 0; i < _steps.length; i++) {
const s = _steps[i];
const rowBg = (s.kind === 'tri' || s.kind === 'done') ? 'background:rgba(127,166,140,.1)' : '';
rows += `<tr style="${rowBg}">
<td style="${tdB}">${i + 1}</td>
<td style="${tdB};color:#EDEAE0;white-space:nowrap">${escHtml(s.desc)}</td>
<td style="${tdB};color:#AEC0D6">${escHtml(s.detail)}</td>
<td style="${tdB};color:#E2945F;white-space:nowrap">${s.val != null ? escHtml(String(s.val)) : '—'}</td>
</tr>`;
}
/* the finished triangular system, pretty-printed */
const triBody = st.U.map((r, i) =>
r.map(v => fmt(z0(v))).join(' ') +
(st.c ? ' <span style="color:#E2945F">' + fmt(z0(st.c[i])) + '</span>' : '')
).join('<br>');
const inner = `
<div style="padding:28px 36px 20px;font-family:sans-serif;color:#EDEAE0;font-size:13px;line-height:1.5">
<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:18px;padding-bottom:14px;border-bottom:1px solid rgba(61,102,148,.45)">
<div>
<div style="font-size:10px;color:#7B93B0;letter-spacing:.1em;text-transform:uppercase;margin-bottom:5px">Numerical Analysis Workbench · Gaussian Elimination</div>
<div style="font-size:20px;font-weight:700;color:#EDEAE0;font-family:monospace">[A${st.hasB ? ' | b' : ''}] → [U′${st.hasB ? ' | c' : ''}] <span style="font-size:12px;color:#7B93B0">(partial pivoting · ${st.n}×${st.n})</span></div>
</div>
<div style="font-size:11px;color:#7B93B0;text-align:right;flex-shrink:0;margin-left:24px;font-family:monospace">
${escHtml(date)}<br>
<span style="color:#E2945F;font-size:17px;font-weight:700">det(A) ≈ ${fmt(z0(st.det))}</span><br>
${_steps.length} logged step${_steps.length !== 1 ? 's' : ''}${last.kind === 'done' ? ' · <span style="color:#7FA68C">✓ solved</span>' : ''}
</div>
</div>
<div style="background:#081729;border-radius:3px;padding:11px 16px;margin-bottom:14px;font-family:monospace;font-size:12px;display:flex;gap:24px;flex-wrap:wrap;align-items:center">
<span style="color:#7B93B0;font-size:10px;text-transform:uppercase;letter-spacing:.08em">Summary</span>
<span>P = [${st.perm.map(i => i + 1).join(', ')}]</span>
<span>${st.swaps} swap${st.swaps === 1 ? '' : 's'}</span>
<span style="color:${st.singular ? '#D9776B' : '#7FA68C'}">${st.singular ? '⚠ singular system' : '✓ invertible'}</span>
${st.x ? `<span style="color:#E2945F">x = ( ${st.x.map(v => fmt(v)).join(', ')} )</span>` : ''}
</div>
<div style="margin-bottom:14px">
<div style="font-size:10px;color:#7B93B0;letter-spacing:.08em;text-transform:uppercase;margin-bottom:6px">Reduced upper-triangular system${st.hasB ? ' [U′ | c]' : ''}</div>
<div style="background:#081729;border-radius:3px;padding:10px 14px;font-family:monospace;font-size:12px;color:#EDEAE0;line-height:1.6">${triBody}</div>
</div>
<table style="width:100%;border-collapse:collapse;font-family:monospace;font-size:12px">
<thead><tr>${['Step','Operation','Details','Value'].map(h => `<th style="${thS}">${h}</th>`).join('')}</tr></thead>
<tbody>${rows}</tbody>
</table>
<div style="font-size:10px;color:#7B93B0;padding-top:10px;margin-top:10px;border-top:1px dashed rgba(61,102,148,.4);display:flex;justify-content:space-between;font-family:monospace">
<span>S.M. Mehedy Kawser · mehedy.netlify.app</span>
<span>Generated ${escHtml(date)}</span>
</div>
</div>`;
const wrap = document.createElement('div');
wrap.style.cssText = 'position:fixed;top:0;left:0;width:1120px;background:#173A60;z-index:99998;overflow:visible;pointer-events:none';
wrap.innerHTML = inner;
document.body.appendChild(wrap);
return wrap;
}
async function exportImage() {
if (!isActive() || !_steps.length) return;
const btn = D.expImg;
btn.textContent = 'Capturing…'; btn.disabled = true;
const overlay = mkCaptureOverlay('Preparing Image…');
const exportEl = buildExportEl();
await waitFrames();
try {
const canvas = await html2canvas(exportEl, {
backgroundColor: '#173A60', scale: 2, logging: false, useCORS: true, allowTaint: true,
width: 1120, height: exportEl.scrollHeight, windowWidth: 1200, scrollX: 0, scrollY: 0
});
dl(await canvasBlob(canvas), `${NAW.getActiveMethod()}_${ts()}.png`);
} catch (err) { alert('Image export failed: ' + err.message); }
finally {
exportEl.remove(); overlay.remove();
btn.textContent = 'Download as image'; btn.disabled = false;
}
}
async function exportPDF() {
if (!isActive() || !_steps.length) return;
const btn = D.expPdf;
btn.textContent = 'Generating…'; btn.disabled = true;
const overlay = mkCaptureOverlay('Preparing PDF…');
const exportEl = buildExportEl();
await waitFrames();
try {
const canvas = await html2canvas(exportEl, {
backgroundColor: '#173A60', scale: 2, logging: false, useCORS: true, allowTaint: true,
width: 1120, height: exportEl.scrollHeight, windowWidth: 1200, scrollX: 0, scrollY: 0
});
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({ orientation: 'landscape', unit: 'pt', format: 'a4' });
const pgW = pdf.internal.pageSize.getWidth();
const pgH = pdf.internal.pageSize.getHeight();
const imgData = canvas.toDataURL('image/png');
const imgH = (canvas.height / canvas.width) * pgW;
if (imgH <= pgH) {
pdf.addImage(imgData, 'PNG', 0, 0, pgW, imgH);
} else {
let yOff = 0;
while (yOff < imgH) {
if (yOff > 0) pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, -yOff, pgW, imgH);
yOff += pgH;
}
}
pdf.save(`${NAW.getActiveMethod()}_${ts()}.pdf`);
} catch (err) { alert('PDF export failed: ' + err.message); }
finally {
exportEl.remove(); overlay.remove();
btn.textContent = 'Download as PDF'; btn.disabled = false;
}
}
function exportGIF() {
if (!isActive() || !_steps.length) return;
NAW.exportGraphGIF({
svgEl: D.bisGr,
totalSteps: _steps.length,
gotoStep: goTo,
currentIdx: _idx,
filename: `${NAW.getActiveMethod()}_${ts()}.gif`,
button: D.expGif,
});
}
/* ================================================================
HERO ANIMATION — always-running demo on a fixed classic system
================================================================ */
function initHero() {
const pal = NAW.graphPalette();
if (_heroTmr) { clearInterval(_heroTmr); _heroTmr = null; }
const demoA = [[2, 1, -1], [-3, -1, 2], [-2, 1, 2]];
const demoB = [8, -11, -3];
const { steps: hSteps } = gaussEliminate(demoA, demoB);
const draw = idx => {
const s = hSteps[Math.min(idx, hSteps.length - 1)];
D.heroLbl.textContent = `step ${idx + 1}`;
const W = 520, H = 240;
const n = 3, cs = 30, gapB = 8;
const gx = Math.round(W * 0.30 - (n * cs + gapB + cs) / 2);
const gy = Math.round((H - n * cs) / 2);
let svg = `<svg viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg">`;
const hiSet = new Set((s.hi || []).map(h => h.r + ',' + h.c));
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
const x = gx + j * cs, y = gy + i * cs;
const isHi = hiSet.has(i + ',' + j);
const isStar = s.star && s.star.r === i && s.star.c === j;
const belowDiag = j < i;
const zeroed = belowDiag && parseFloat(s.mat.cells[i][j]) === 0;
let fill = zeroed ? `rgba(${pal.verdigrisRGB},.08)` : 'transparent';
if (isHi) fill = `rgba(${pal.copperRGB},.22)`;
svg += `<rect x="${x + 1}" y="${y + 1}" width="${cs - 2}" height="${cs - 2}" rx="2" fill="${fill}" stroke="${isStar ? pal.verdigris : `rgba(${pal.gridRGB},.4)`}" stroke-width="${isStar ? 2 : 0.8}"/>`;
const txt = s.mat.cells[i][j];
const fs = txt.length > 7 ? 7.5 : 9.5;
svg += `<text x="${x + cs / 2}" y="${y + cs / 2 + 3.5}" text-anchor="middle" font-size="${fs}" fill="${isStar ? pal.verdigris : (isHi ? pal.copper : pal.axis)}" font-family="IBM Plex Mono,monospace">${txt}</text>`;
}
const bx = gx + n * cs + gapB;
const isHiB = hiSet.has(i + ',' + n);
svg += `<rect x="${bx + 1}" y="${gy + i * cs + 1}" width="${cs - 2}" height="${cs - 2}" rx="2" fill="${isHiB ? `rgba(${pal.copperRGB},.22)` : 'transparent'}" stroke="rgba(${pal.gridRGB},.4)" stroke-width="0.8"/>`;
const bt = s.mat.b[i];
svg += `<text x="${bx + cs / 2}" y="${gy + i * cs + cs / 2 + 3.5}" text-anchor="middle" font-size="${bt.length > 7 ? 7.5 : 9.5}" fill="${isHiB ? pal.copper : pal.axis}" font-family="IBM Plex Mono,monospace">${bt}</text>`;
if (s.ann && s.ann.row === i) {
svg += `<text x="${gx - 8}" y="${gy + i * cs + cs / 2 + 3.5}" text-anchor="end" font-size="9" fill="${pal.copper}" font-family="IBM Plex Mono,monospace" font-weight="600">${escHtml(s.ann.text)}</text>`;
}
}
svg += `<text x="${gx + n * cs + gapB + cs + 22}" y="${gy + 16}" font-size="12" fill="${pal.axis}" font-family="IBM Plex Sans Condensed,sans-serif" font-weight="600">${escHtml(s.desc)}</text>`;
const words = s.detail.split(' ');
let line = '', ly = gy + 38;
for (const wd of words) {
if ((line + ' ' + wd).trim().length > 26) {
svg += `<text x="${gx + n * cs + gapB + cs + 22}" y="${ly}" font-size="9" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${escHtml(line)}</text>`;
line = wd; ly += 13;
if (ly > gy + 140) break;
} else line = (line ? line + ' ' : '') + wd;
}
if (ly <= gy + 140 && line)
svg += `<text x="${gx + n * cs + gapB + cs + 22}" y="${ly}" font-size="9" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${escHtml(line)}</text>`;
svg += '</svg>';
D.heroGr.innerHTML = svg;
};
draw(0);
let hi = 0;
_heroTmr = setInterval(() => { hi = (hi + 1) % hSteps.length; draw(hi); }, 1500);
}
/* ================================================================
EVENT LISTENERS (every shared button guarded by isActive())
================================================================ */
$('bisection-form').addEventListener('submit', solve);
$('reset-btn').addEventListener('click', reset);
D.prevBtn.addEventListener('click', () => goTo(_idx - 1));
D.nextBtn.addEventListener('click', () => goTo(_idx + 1));
D.playBtn.addEventListener('click', togglePlay);
D.speedSel.addEventListener('change', () => {
if (isActive() && _playTmr) { togglePlay(); togglePlay(); }
});
D.expImg.addEventListener('click', exportImage);
D.expPdf.addEventListener('click', exportPDF);
D.expGif.addEventListener('click', exportGIF);
D.precisionIn.addEventListener('input', () => {
if (isActive() && _steps.length) {
/* re-parse so every snapshot reformats at the new precision */
const raw = $('matrix-input').value.trim();
const parsed = raw ? parseMatrix(raw) : null;
if (parsed && !parsed.err) {
const { steps, result } = gaussEliminate(parsed.A, parsed.b);
_steps = steps; _result = result;
renderSolBox();
}
renderTable();
renderGraph(Math.min(_idx, _steps.length - 1));
}
});
$('load-example').addEventListener('click', () => {
if (!isActive()) return;
const ex = EXAMPLES[_exIdx++ % EXAMPLES.length];
const mi = $('matrix-input');
if (mi) mi.value = ex.m;
clearStatus();
showStatus(`Example loaded: ${ex.note}`, 'success');
});
/* ================================================================
METHOD-CHANGE HOOK
Enter: hide this sheet's irrelevant shared chrome, start the hero.
Leave: restore every shared element byte-for-byte, stop the hero,
clear results — the other engines' sheets look untouched.
================================================================ */
NAW.onMethodChange((newId, oldId) => {
if (newId in METHODS) {
applySheetChrome();
initHero();
} else if (oldId in METHODS) {
restoreChrome();
hideResults();
if (_heroTmr) { clearInterval(_heroTmr); _heroTmr = null; }
}
});
})();