Repository navigation
Expand file tree
/
Copy pathengine-matrix.js
More file actions
962 lines (862 loc) · 45.6 KB
/
Copy pathengine-matrix.js
File metadata and controls
962 lines (862 loc) · 45.6 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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
/* ====================================================================
ENGINE — Matrix methods (LU decomposition, Sheet 07)
----------------------------------------------------------------------
First engine that factors a MATRIX instead of root-finding on f(x).
Implements Doolittle LU decomposition with PARTIAL PIVOTING (PA = LU),
recorded as a step-by-step action log: pivot searches, row swaps, and
each individual row elimination with its multiplier. Optionally the
matrix is entered augmented with one extra column (vector b), in which
case the run continues through forward substitution (Ly = Pb) and back
substitution (Ux = y) so the sheet also solves Ax = b and reports
det(A) = ±∏ U[k][k].
Requires core.js (shared plumbing + method registry) loaded first.
Follows the exact engine contract of engine-bracketing.js /
engine-open.js: merge methods into NAW.METHODS, subscribe with
NAW.onMethodChange(), guard every shared-button handler with
isActive(), and restore any shared page chrome this engine hid when
its sheet stops being active — so the four existing sheets behave
byte-for-byte identically whether or not this file is loaded.
==================================================================== */
(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. Everything hidden here is restored
verbatim in onMethodChange() when the sheet is left, so other
methods never notice this file exists.
================================================================ */
const CHROME = {
fxField: $('fx-field'), // f(x) input row (hidden — LU needs no function)
matrixWrap: $('matrix-fieldset'), // matrix A textarea (shown — this sheet's input)
aField: $('a-field'), // "a" bound input (hidden — meaningless here)
trueRootFld: $('true-root-field'), // true root (hidden — no iterations)
bracketFld: $('bracket-fieldset'), // bracket auto/manual (hidden — no brackets)
stopFld: $('stop-fieldset'), // stop-after criteria (hidden — direct method)
hWrap: $('h-field-wrap'), // step h (kept hidden — belongs to Sheet 08)
};
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; // {L, U, perm, det, singular, y, x, n, hasB, swaps}
let _exIdx = 0;
const isActive = () => (NAW.getActiveMethod() in METHODS);
/* ================================================================
EXAMPLES — cycled by the shared "Load an example" button.
Plain rows here; the LAST column is only present when the
example solves Ax = b (augmented).
================================================================ */
const EXAMPLES = [
{ m: '4 -1 0\n-1 4 -1\n 0 -1 4', note: 'Tridiagonal, dominant diagonal — no pivoting needed, det = 56' },
{ m: '2 1 1\n4 -6 0\n-2 7 2', note: 'Classic 3×3 — partial pivoting swaps R1 ↔ R2' },
{ m: '4 3 10\n6 3 15', note: '2×2 with b — solves Ax = b, x = (2.5, 0)' },
{ m: ' 2 1 -1 8\n-3 -1 2 -11\n-2 1 2 -3', note: 'Augmented 3×3 — unique solution x = (2, 3, −1)' },
];
/* ================================================================
METHODS REGISTRY ENTRY (merged into the shared core registry)
================================================================ */
const METHODS = {
ludecomp: {
id: 'ludecomp',
num: '07',
docTitle: 'LU Decomposition',
heroTitleHTML: 'LU decomposition,<br>factored <span class="accent">step by step</span>.',
heroSub: 'Give it a square matrix and watch Gaussian elimination factor it into L and U — every pivot choice, row swap, and multiplier logged, with det(A) and the solution of Ax = b when you add a right-hand column.',
metaMethod: 'LU decomposition (Doolittle, partial pivoting)',
metaOrder: 'Direct method — finite, exact up to rounding',
metaNeeds: 'square matrix A (extra column ⇒ Ax = b)',
cLabel: 'multiplier',
cColHeader: 'Multiplier / pivot',
graphAria: 'Animated elimination grid showing the LU factorization progressing',
heroGraphAria: 'Animated demo of LU elimination with partial pivoting',
needsMsg: 'LU needs a square matrix 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
One row per line; cells separated by spaces and/or commas.
Every cell goes through the shared parseVal, so pi, e, sqrt(2),
2*pi, -1/2 … all work. If every row has exactly one extra cell,
that column becomes the vector b (augmented system).
================================================================ */
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 row 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 matrix.' };
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 };
}
/* ================================================================
LU ALGORITHM — Doolittle with partial pivoting, fully logged.
Multipliers are stored in-place below the diagonal of the working
copy (classic textbook trick), so the animation literally shows L
growing inside A. Every step snapshots the CURRENT matrix as
formatted strings so later mutation can't alter earlier frames.
Returns { steps, result } — result carries the final L, U,
permutation, determinant and (if b was given) y and x vectors.
================================================================ */
const z0 = v => (Object.is(v, -0) ? 0 : v);
function luFactorize(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 matrix [A | b], size ${n}×${n + 1} — goal: PA = LU, then Ly = Pb and Ux = y.`
: `Matrix A, size ${n}×${n} — goal: PA = LU via Gaussian elimination with partial pivoting.`,
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 moves the largest entry onto the diagonal — this keeps the factors numerically stable and records the permutation P.`,
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 matrix is singular or nearly singular, so LU 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${i + 1},${k + 1} = 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] = m; // store the multiplier — it becomes L's entry
}
}
/* ── extract L and U from the working copy ── */
const L = [], U = [];
for (let i = 0; i < n; i++) {
L.push([]); U.push([]);
for (let j = 0; j < n; j++) {
if (j < i) { L[i][j] = z0(M[i][j]); U[i][j] = 0; }
else if (j === i){ L[i][j] = 1; U[i][j] = z0(M[i][j]); }
else { L[i][j] = 0; U[i][j] = z0(M[i][j]); }
}
}
/* Singular ⇔ any diagonal entry of U is (numerically) zero.
Note this also catches the last pivot of an odd-sized run where
the k-loop above never checks it. */
const singular = U.some((row, i) => Math.abs(U[i][i]) < 1e-12);
const det = (swaps % 2 ? -1 : 1) * U.reduce((acc, row, i) => acc * U[i][i], 1);
const result = { n, hasB, L, U, perm, swaps, det, singular, y: null, x: null };
/* ── final summary step (factorization part) ── */
steps.push({
kind: 'final', desc: 'Factorization complete — PA = LU',
detail: `det(A) = ${swaps % 2 ? '(−1)' : '(+1)'} · ∏U[k][k] = (${U.map((_, i) => fmt(z0(U[i][i]))).join(' · ')}) = ${fmt(z0(det))}` +
(singular ? ' ⚠ a diagonal entry of U is ~0 → A is singular.' : ''),
mat: snap(), hi: [], star: null, ann: null, val: fmt(z0(det)),
});
/* ── substitutions (only when b was supplied and A is invertible) ── */
if (hasB && !failed && !singular) {
const y = new Array(n);
for (let i = 0; i < n; i++) {
let s = b[i];
const terms = [];
for (let j = 0; j < i; j++) {
s -= L[i][j] * y[j];
terms.push(`${fmt(z0(L[i][j]))}·${fmt(z0(y[j]))}`);
}
y[i] = z0(s);
steps.push({
kind: 'substF', desc: `Forward substitute — y${i + 1}`,
detail: `Ly = Pb: y${i + 1} = ${fmt(z0(b[i]))}` +
(terms.length ? ` − (${terms.join(' + ')})` : '') + ` = ${fmt(y[i])}`,
mat: snap(), hi: Array.from({ length: n }, (_, t) => ({ r: i, c: t })),
star: null, ann: { row: i, text: `y${i + 1}=${fmt(y[i])}` }, val: fmt(y[i]),
});
}
result.y = y;
const x = new Array(n);
for (let i = n - 1; i >= 0; i--) {
let s = y[i];
const terms = [];
for (let j = i + 1; j < n; j++) {
s -= U[i][j] * x[j];
terms.push(`${fmt(z0(U[i][j]))}·${fmt(z0(x[j]))}`);
}
x[i] = z0(s / U[i][i]);
steps.push({
kind: 'substB', desc: `Back substitute — x${i + 1}`,
detail: `Ux = y: x${i + 1} = (${fmt(z0(y[i]))}` +
(terms.length ? ` − (${terms.join(' + ')})` : '') + `) / ${fmt(z0(U[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(', ')} ) · by construction PAx = Pb, with P recording ${swaps} row swap${swaps === 1 ? '' : 's'}.`,
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: 'A diagonal entry of U is (numerically) zero — A is singular, so Ax = b has no unique solution. The factorization steps above are still shown.',
mat: snap(), hi: [], star: null, ann: null, val: 'singular',
});
}
return { steps, result, failed };
}
/* ================================================================
RENDER: MAIN GRAPH — animated matrix grid
Non-final steps draw the working (augmented) matrix with the
active cells highlighted; final/done steps draw the separated
L and U factors plus P, det and the solution vector.
================================================================ */
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"/>`;
const isEndStep = (s.kind === 'final' || s.kind === 'done');
if (!isEndStep) {
/* ── 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;
let fill = belowDiag && parseFloat(s.mat.cells[i][j]) !== 0
? `rgba(${pal.verdigrisRGB},.10)` : '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.curve : 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>`;
/* 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},.10)" 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">stored multiplier (becomes L)</text>`;
} else {
/* ── final layout: L and U side by side + P, det, x ── */
const cs = Math.max(34, Math.min(52, Math.floor(230 / n)));
const gy = Math.round(104 + (230 - n * cs) / 2);
const lx = Math.round(W * 0.06), ux = Math.round(W * 0.34);
const drawFac = (Mat, label, ox) => {
svg += `<text x="${ox}" y="${gy - 16}" font-size="13" fill="${pal.axis}" font-family="IBM Plex Mono,monospace" font-weight="600">${label}</text>`;
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++) {
const x = ox + j * cs, y = gy + i * cs;
const v = Mat[i][j];
const nz = Math.abs(v) > 1e-14 || (label === 'L' && i === j);
svg += `<rect x="${x + 1}" y="${y + 1}" width="${cs - 2}" height="${cs - 2}" rx="2" fill="${nz ? `rgba(${pal.verdigrisRGB},.12)` : 'transparent'}" stroke="rgba(${pal.gridRGB},.35)" stroke-width="0.8"/>`;
const txt = fmt(nz ? v : 0);
const fs = txt.length > 8 ? 9 : (cs > 46 ? 12 : 10);
svg += `<text x="${x + cs / 2}" y="${y + cs / 2 + fs / 3}" text-anchor="middle" font-size="${fs}" fill="${nz ? pal.curve : pal.tick}" font-family="IBM Plex Mono,monospace">${txt}</text>`;
}
};
drawFac(st.L, 'L (lower, unit diagonal)', lx);
drawFac(st.U, 'U (upper)', ux);
const px = Math.round(W * 0.63);
let py = gy + 4;
svg += `<text x="${px}" y="${py}" font-size="13" fill="${pal.axis}" font-family="IBM Plex Mono,monospace" font-weight="600">P — row order</text>`;
py += 20;
svg += `<text x="${px}" y="${py}" font-size="11" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">[${st.perm.map(i => i + 1).join(', ')}]</text>`;
py += 30;
svg += `<text x="${px}" y="${py}" font-size="13" fill="${pal.axis}" font-family="IBM Plex Mono,monospace" font-weight="600">det(A)</text>`;
py += 20;
svg += `<text x="${px}" y="${py}" font-size="12" fill="${pal.copper}" font-family="IBM Plex Mono,monospace">${fmt(z0(st.det))}</text>`;
if (st.x) {
py += 30;
svg += `<text x="${px}" y="${py}" font-size="13" fill="${pal.axis}" font-family="IBM Plex Mono,monospace" font-weight="600">solution x</text>`;
py += 20;
svg += `<text x="${px}" y="${py}" font-size="12" fill="${pal.copper}" font-family="IBM Plex Mono,monospace">( ${st.x.map(v => fmt(v)).join(', ')} )</text>`;
}
if (st.singular) {
py += 30;
svg += `<text x="${px}" y="${py}" font-size="11" fill="${pal.danger}" font-family="IBM Plex Mono,monospace">⚠ singular — U has a ~0 pivot</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 === 'substF' || s.kind === 'substB') ? s.val :
(s.kind === 'final' || 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">A ∈ ℝ<sup>${st.n}×${st.n}</sup>${st.hasB ? ' , b ∈ ℝ<sup>' + st.n + '</sup>' : ''} — entered as ${st.hasB ? 'an augmented' : 'a plain'} matrix</div>
</div>
<div class="sol-group">
<div class="sol-lbl">Factorization — PA = LU (Doolittle, 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>L = unit lower triangular — the stored multipliers</code></div>
<div class="bc-row"><code>U = upper triangular — the eliminated matrix</code></div>
<div class="bc-row ivt-row">
<code>det(A) = ${st.swaps % 2 ? '(−1)' : '(+1)'} · ∏U[k][k] = ${fmt(z0(st.det))}</code>
<span class="sign-pill ${st.singular ? 'neg' : 'ok'}">${st.singular ? '⚠ singular' : '✓ invertible'}</span>
<span class="ivt-note">→ ${st.swaps} row swap${st.swaps === 1 ? '' : 's'} recorded in P</span>
</div>
</div>
</div>
${st.x ? `
<div class="sol-group">
<div class="sol-lbl">Result — solving Ax = b via Ly = Pb, Ux = y</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">PA = LU</span>
<span class="conv-chip">✓ ${escHtml(last.desc)}</span>
<span class="ae-note">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 =
`LU decomposition (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 =
`Multipliers are stored below the diagonal as elimination proceeds — that region becomes L; ` +
`the remaining upper triangle is U. P lists the swapped row order (partial pivoting).`;
D.tBody.innerHTML = '';
_steps.forEach((s, i) => {
const tr = document.createElement('tr');
if (i === _idx) tr.classList.add('active-row');
if (s.kind === 'final' || 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 a matrix 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 } = luFactorize(A, b);
_steps = steps;
_result = result;
if (failed)
showStatus('Zero pivot encountered — the matrix is singular. The partial elimination is still shown below.', 'error');
else if (result.singular && result.hasB)
showStatus('A is singular — U has a (numerically) zero diagonal entry, so Ax = b has no unique solution. Factorization steps are shown.', 'error');
else if (result.singular)
showStatus('Note: A is singular (a U diagonal entry 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 === 'final' || 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>`;
}
const facRow = (label, Mat, accent) => {
const body = Mat.map(r => r.map(v => fmt(z0(v))).join(' ')).join('<br>');
return `<div style="flex:1;min-width:180px">
<div style="font-size:10px;color:#7B93B0;letter-spacing:.08em;text-transform:uppercase;margin-bottom:6px">${label}</div>
<div style="background:#081729;border-radius:3px;padding:10px 14px;font-family:monospace;font-size:12px;color:${accent};line-height:1.6">${body}</div>
</div>`;
};
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 · LU Decomposition</div>
<div style="font-size:20px;font-weight:700;color:#EDEAE0;font-family:monospace">PA = LU <span style="font-size:12px;color:#7B93B0">(Doolittle · 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">Factors</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 matrix' : '✓ invertible'}</span>
${st.x ? `<span style="color:#E2945F">x = ( ${st.x.map(v => fmt(v)).join(', ')} )</span>` : ''}
${st.y ? `<span style="color:#7B93B0">y = ( ${st.y.map(v => fmt(v)).join(', ')} )</span>` : ''}
</div>
<div style="display:flex;gap:18px;margin-bottom:14px;flex-wrap:wrap">
${facRow('L — lower (unit diagonal)', st.L, '#7FA68C')}
${facRow('U — upper', st.U, '#EDEAE0')}
</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 matrix
================================================================ */
function initHero() {
const pal = NAW.graphPalette();
if (_heroTmr) { clearInterval(_heroTmr); _heroTmr = null; }
const demoA = [[2, 1, 1], [4, -6, 0], [-2, 7, 2]];
const { steps: hSteps } = luFactorize(demoA, null);
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 = 34;
const gx = Math.round(W * 0.32 - (n * 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;
let fill = belowDiag && Math.abs(parseFloat(s.mat.cells[i][j])) > 0
? `rgba(${pal.verdigrisRGB},.12)` : '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 ? 8 : 10;
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>`;
}
svg += `<text x="${gx + n * cs + 26}" 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 > 30) {
svg += `<text x="${gx + n * cs + 26}" y="${ly}" font-size="9.5" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${escHtml(line)}</text>`;
line = wd; ly += 14;
if (ly > gy + 130) break;
} else line = (line ? line + ' ' : '') + wd;
}
if (ly <= gy + 130 && line)
svg += `<text x="${gx + n * cs + 26}" y="${ly}" font-size="9.5" 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 } = luFactorize(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; }
}
});
})();