-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
917 lines (793 loc) · 27.4 KB
/
index.html
File metadata and controls
917 lines (793 loc) · 27.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PCA Image Compression</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0f0f0f;
color: #e0e0e0;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
}
h1 {
margin: 2rem 0 0.5rem;
font-size: 1.8rem;
font-weight: 600;
color: #fff;
}
.subtitle {
color: #888;
margin-bottom: 2rem;
font-size: 0.95rem;
}
.upload-area {
border: 2px dashed #333;
border-radius: 12px;
padding: 3rem 4rem;
text-align: center;
cursor: pointer;
transition: border-color 0.2s, background 0.2s;
background: #1a1a1a;
margin-bottom: 1.5rem;
}
.upload-area:hover, .upload-area.dragover {
border-color: #5b8def;
background: #1a1a2a;
}
.upload-area p { color: #888; margin-top: 0.5rem; font-size: 0.9rem; }
.upload-area .icon { font-size: 2rem; margin-bottom: 0.5rem; }
#fileInput { display: none; }
.controls {
background: #1a1a1a;
border-radius: 12px;
padding: 1.5rem 2rem;
width: 90%;
max-width: 700px;
margin-bottom: 1.5rem;
display: none;
}
.controls label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
}
.slider-row {
display: flex;
align-items: center;
gap: 1rem;
}
.slider-row input[type="range"] {
flex: 1;
accent-color: #5b8def;
height: 6px;
}
.slider-row .value {
min-width: 80px;
text-align: right;
font-variant-numeric: tabular-nums;
color: #5b8def;
font-weight: 600;
}
.info-row {
display: flex;
justify-content: space-between;
margin-top: 0.75rem;
font-size: 0.85rem;
color: #888;
}
.images {
display: flex;
gap: 2rem;
width: 90%;
max-width: 1200px;
margin-bottom: 2rem;
flex-wrap: wrap;
justify-content: center;
}
.image-box {
flex: 1;
min-width: 300px;
max-width: 580px;
background: #1a1a1a;
border-radius: 12px;
padding: 1rem;
display: none;
}
.image-box h3 {
margin-bottom: 0.75rem;
font-size: 1rem;
font-weight: 500;
color: #aaa;
}
.image-box canvas, .image-box img {
width: 100%;
border-radius: 8px;
background: #000;
}
/* Insights panel */
.insights {
width: 90%;
max-width: 1200px;
margin-bottom: 2rem;
display: none;
}
.insights h2 {
font-size: 1.3rem;
font-weight: 600;
color: #fff;
margin-bottom: 1rem;
}
.insights-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.25rem;
}
@media (max-width: 768px) {
.insights-grid { grid-template-columns: 1fr; }
}
.insight-card {
background: #1a1a1a;
border-radius: 12px;
padding: 1.25rem;
}
.insight-card h3 {
font-size: 0.95rem;
font-weight: 500;
color: #aaa;
margin-bottom: 0.75rem;
}
.insight-card canvas {
width: 100%;
height: 180px;
border-radius: 8px;
background: #111;
}
.insight-card p {
font-size: 0.82rem;
color: #777;
margin-top: 0.6rem;
line-height: 1.5;
}
.how-it-works {
background: #1a1a1a;
border-radius: 12px;
padding: 1.5rem;
grid-column: 1 / -1;
}
.how-it-works h3 {
font-size: 1.05rem;
font-weight: 600;
color: #ccc;
margin-bottom: 1rem;
}
.step-list {
list-style: none;
padding: 0;
}
.step-list li {
position: relative;
padding-left: 2.5rem;
margin-bottom: 1rem;
font-size: 0.88rem;
color: #999;
line-height: 1.6;
}
.step-list li::before {
content: attr(data-step);
position: absolute;
left: 0;
top: 0;
width: 1.7rem;
height: 1.7rem;
background: #5b8def22;
color: #5b8def;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
font-size: 0.8rem;
}
.step-list li strong { color: #ccc; }
.stats-row {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
margin-top: 0.75rem;
}
.stat-box {
background: #111;
border-radius: 8px;
padding: 0.75rem 1rem;
flex: 1;
min-width: 140px;
}
.stat-box .stat-label {
font-size: 0.75rem;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 0.25rem;
}
.stat-box .stat-value {
font-size: 1.2rem;
font-weight: 600;
color: #5b8def;
font-variant-numeric: tabular-nums;
}
.stat-box .stat-sub {
font-size: 0.75rem;
color: #555;
margin-top: 0.15rem;
}
#status {
color: #5b8def;
margin-bottom: 1rem;
font-size: 0.9rem;
min-height: 1.2em;
}
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid #5b8def;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
vertical-align: middle;
margin-right: 6px;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
</head>
<body>
<h1>PCA Image Compression</h1>
<p class="subtitle">Upload an image and adjust the number of principal components</p>
<div class="upload-area" id="uploadArea">
<div class="icon">📁</div>
<strong>Click or drag & drop an image</strong>
<p>Supports PNG, JPG, BMP, WebP</p>
</div>
<input type="file" id="fileInput" accept="image/*">
<div id="status"></div>
<div class="controls" id="controls">
<label for="componentSlider">Principal Components</label>
<div class="slider-row">
<input type="range" id="componentSlider" min="1" max="100" value="50">
<span class="value" id="componentValue">50 / 100</span>
</div>
<div class="info-row">
<span id="compressionRatio">Compression ratio: —</span>
<span id="imageSize">Image: —</span>
</div>
</div>
<div class="images">
<div class="image-box" id="originalBox">
<h3>Original</h3>
<canvas id="originalCanvas"></canvas>
</div>
<div class="image-box" id="compressedBox">
<h3>Compressed</h3>
<canvas id="compressedCanvas"></canvas>
</div>
</div>
<div class="insights" id="insights">
<h2>PCA Insights</h2>
<div class="stats-row" id="statsRow">
<div class="stat-box">
<div class="stat-label">Variance Retained</div>
<div class="stat-value" id="statVariance">—</div>
<div class="stat-sub">of total information kept</div>
</div>
<div class="stat-box">
<div class="stat-label">Components Used</div>
<div class="stat-value" id="statComponents">—</div>
<div class="stat-sub" id="statComponentsSub">out of — possible</div>
</div>
<div class="stat-box">
<div class="stat-label">Compression Ratio</div>
<div class="stat-value" id="statRatio">—</div>
<div class="stat-sub">smaller than original</div>
</div>
<div class="stat-box">
<div class="stat-label">Top Eigenvalue</div>
<div class="stat-value" id="statTopEigen">—</div>
<div class="stat-sub">dominance of 1st component</div>
</div>
</div>
<div class="insights-grid">
<div class="insight-card">
<h3>Scree Plot — Eigenvalues</h3>
<canvas id="screePlot"></canvas>
<p>Each bar is an eigenvalue — the "importance" of that principal component.
Taller bars capture more variance. The steep drop-off shows most information
is in the first few components.</p>
</div>
<div class="insight-card">
<h3>Cumulative Variance Explained</h3>
<canvas id="variancePlot"></canvas>
<p>Shows how much total information is retained as you add components.
The dashed line marks your current selection. When the curve flattens,
adding more components gives diminishing returns.</p>
</div>
<div class="insight-card">
<h3>Top 3 Eigenvectors (Red Channel)</h3>
<canvas id="eigenvectorPlot"></canvas>
<p>Eigenvectors are the "directions" PCA finds in pixel-space. Each one
represents a pattern across all columns of the image. The 1st eigenvector
captures the dominant pattern; subsequent ones capture finer details.</p>
</div>
<div class="insight-card">
<h3>Per-Component Variance Share</h3>
<canvas id="pieChart"></canvas>
<p>Shows how the total variance is distributed among your selected components
plus the discarded remainder. A large "discarded" slice means significant
information loss.</p>
</div>
<div class="how-it-works">
<h3>How PCA Image Compression Works</h3>
<ol class="step-list">
<li data-step="1">
<strong>Split into channels.</strong>
The image is separated into Red, Green, and Blue matrices.
Each matrix has dimensions <em>height x width</em> — every row is a row of pixels.
</li>
<li data-step="2">
<strong>Center the data.</strong>
The mean pixel value of each column is subtracted. This shifts the data so
PCA can find directions of maximum spread (variance).
</li>
<li data-step="3">
<strong>Compute the covariance matrix.</strong>
A <em>width x width</em> matrix is computed, measuring how pixel columns
vary together. Highly correlated columns (e.g. nearby pixels) will have
large covariance values.
</li>
<li data-step="4">
<strong>Find eigenvalues and eigenvectors.</strong>
The covariance matrix is decomposed. Each <strong>eigenvector</strong> is a
direction of variation in the image, and its <strong>eigenvalue</strong>
tells you how much variance that direction captures. Bigger eigenvalue = more
important pattern.
</li>
<li data-step="5">
<strong>Project onto top-k components.</strong>
Instead of storing all pixel values, we project each row onto the top
<em>k</em> eigenvectors. This compresses each row from <em>width</em>
values down to <em>k</em> values — the "scores" for each principal component.
</li>
<li data-step="6">
<strong>Reconstruct.</strong>
Multiply the scores back by the eigenvectors and add the means back.
With fewer components, fine details are lost but the overall structure remains.
The storage goes from <em>height x width</em> to
<em>height x k + k x width</em> (scores + eigenvectors).
</li>
</ol>
</div>
</div>
</div>
<canvas id="hiddenCanvas" style="display:none;"></canvas>
<script type="module">
import { PCA } from 'https://esm.sh/ml-pca@4.1.1';
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const controls = document.getElementById('controls');
const slider = document.getElementById('componentSlider');
const componentValue = document.getElementById('componentValue');
const compressionRatio = document.getElementById('compressionRatio');
const imageSizeEl = document.getElementById('imageSize');
const statusEl = document.getElementById('status');
const originalCanvas = document.getElementById('originalCanvas');
const compressedCanvas = document.getElementById('compressedCanvas');
const originalBox = document.getElementById('originalBox');
const compressedBox = document.getElementById('compressedBox');
const hiddenCanvas = document.getElementById('hiddenCanvas');
let imageData = null;
let imgWidth = 0;
let imgHeight = 0;
let debounceTimer = null;
// Max dimension to keep processing reasonable
const MAX_DIM = 400;
uploadArea.addEventListener('click', () => fileInput.click());
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('dragover'));
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
if (e.dataTransfer.files.length) handleFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', () => {
if (fileInput.files.length) handleFile(fileInput.files[0]);
});
function handleFile(file) {
if (!file.type.startsWith('image/')) return;
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => loadImage(img);
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
function loadImage(img) {
let w = img.width;
let h = img.height;
// Scale down if needed
if (w > MAX_DIM || h > MAX_DIM) {
const scale = MAX_DIM / Math.max(w, h);
w = Math.round(w * scale);
h = Math.round(h * scale);
}
imgWidth = w;
imgHeight = h;
hiddenCanvas.width = w;
hiddenCanvas.height = h;
const ctx = hiddenCanvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
imageData = ctx.getImageData(0, 0, w, h);
// Show original
originalCanvas.width = w;
originalCanvas.height = h;
originalCanvas.getContext('2d').putImageData(imageData, 0, 0);
originalBox.style.display = 'block';
compressedBox.style.display = 'block';
controls.style.display = 'block';
imageSizeEl.textContent = `Image: ${w} × ${h}`;
// Set slider max to min(width, height)
const maxComponents = Math.min(w, h);
slider.max = maxComponents;
slider.value = Math.min(Math.round(maxComponents / 2), maxComponents);
updateLabel();
compress();
}
function updateLabel() {
componentValue.textContent = `${slider.value} / ${slider.max}`;
}
slider.addEventListener('input', () => {
updateLabel();
clearTimeout(debounceTimer);
debounceTimer = setTimeout(compress, 150);
});
function extractChannel(data, channel, width, height) {
// Returns a 2D array: rows × cols
const matrix = [];
for (let r = 0; r < height; r++) {
const row = [];
for (let c = 0; c < width; c++) {
row.push(data[(r * width + c) * 4 + channel]);
}
matrix.push(row);
}
return matrix;
}
function compressChannel(matrix, nComponents) {
const pca = new PCA(matrix, { scale: false, center: true });
const projected = pca.predict(matrix, { nComponents });
const reconstructed = pca.invert(projected);
const height = matrix.length;
const width = matrix[0].length;
const result = [];
for (let r = 0; r < height; r++) {
const row = new Array(width);
for (let c = 0; c < width; c++) {
row[c] = Math.max(0, Math.min(255, Math.round(reconstructed.get(r, c))));
}
result.push(row);
}
return { result, pca };
}
async function compress() {
const nComponents = parseInt(slider.value);
if (!imageData) return;
setStatus('<span class="spinner"></span> Compressing…');
// Yield to let the UI update
await new Promise(r => setTimeout(r, 10));
try {
const data = imageData.data;
const w = imgWidth;
const h = imgHeight;
const redMatrix = extractChannel(data, 0, w, h);
const greenMatrix = extractChannel(data, 1, w, h);
const blueMatrix = extractChannel(data, 2, w, h);
const redResult = compressChannel(redMatrix, nComponents);
const greenResult = compressChannel(greenMatrix, nComponents);
const blueResult = compressChannel(blueMatrix, nComponents);
const redComp = redResult.result;
const greenComp = greenResult.result;
const blueComp = blueResult.result;
// Use PCA from red channel for insight charts
const pca = redResult.pca;
// Reconstruct image
compressedCanvas.width = w;
compressedCanvas.height = h;
const ctx = compressedCanvas.getContext('2d');
const newImageData = ctx.createImageData(w, h);
for (let r = 0; r < h; r++) {
for (let c = 0; c < w; c++) {
const i = (r * w + c) * 4;
newImageData.data[i] = redComp[r][c];
newImageData.data[i + 1] = greenComp[r][c];
newImageData.data[i + 2] = blueComp[r][c];
newImageData.data[i + 3] = 255;
}
}
ctx.putImageData(newImageData, 0, 0);
// Compression ratio
const originalSize = w * h * 3;
const compressedSize = 3 * (nComponents * (h + w) + w);
const ratio = (originalSize / compressedSize).toFixed(1);
compressionRatio.textContent = `Compression ratio: ${ratio}×`;
// Draw insight charts
drawInsights(pca, nComponents, Math.min(w, h), ratio);
setStatus(`Done — ${nComponents} component${nComponents > 1 ? 's' : ''} used`);
} catch (err) {
console.error(err);
setStatus('Error during compression: ' + err.message);
}
}
function drawInsights(pca, nComponents, maxComponents, ratio) {
document.getElementById('insights').style.display = 'block';
const eigenvalues = pca.getEigenvalues();
const explainedVar = pca.getExplainedVariance();
const cumulativeVar = pca.getCumulativeVariance();
const loadings = pca.getLoadings();
// Stats
const cumVarRetained = cumulativeVar[nComponents - 1];
document.getElementById('statVariance').textContent = (cumVarRetained * 100).toFixed(1) + '%';
document.getElementById('statComponents').textContent = nComponents;
document.getElementById('statComponentsSub').textContent = `out of ${maxComponents} possible`;
document.getElementById('statRatio').textContent = ratio + 'x';
const topEigenPct = (explainedVar[0] * 100).toFixed(1);
document.getElementById('statTopEigen').textContent = topEigenPct + '%';
// How many components to show in charts (cap at 30 for readability)
const chartN = Math.min(maxComponents, 30);
drawScreePlot(eigenvalues, chartN, nComponents);
drawVariancePlot(cumulativeVar, chartN, nComponents);
drawEigenvectorPlot(loadings, maxComponents);
drawPieChart(explainedVar, nComponents);
}
function setupCanvas(id) {
const canvas = document.getElementById(id);
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
return { ctx, w: rect.width, h: rect.height };
}
function drawScreePlot(eigenvalues, n, nComponents) {
const { ctx, w, h } = setupCanvas('screePlot');
const pad = { top: 15, right: 15, bottom: 25, left: 45 };
const plotW = w - pad.left - pad.right;
const plotH = h - pad.top - pad.bottom;
ctx.clearRect(0, 0, w, h);
const vals = eigenvalues.slice(0, n);
const maxVal = Math.max(...vals);
const barW = Math.max(2, (plotW / n) - 2);
// Axis labels
ctx.fillStyle = '#555';
ctx.font = '10px system-ui';
ctx.textAlign = 'center';
ctx.fillText('Component Index', pad.left + plotW / 2, h - 3);
ctx.save();
ctx.translate(10, pad.top + plotH / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText('Eigenvalue', 0, 0);
ctx.restore();
for (let i = 0; i < vals.length; i++) {
const barH = (vals[i] / maxVal) * plotH;
const x = pad.left + (i / n) * plotW + 1;
const y = pad.top + plotH - barH;
ctx.fillStyle = i < nComponents ? '#5b8def' : '#333';
ctx.fillRect(x, y, barW, barH);
}
// Cutoff line
const cutX = pad.left + (nComponents / n) * plotW;
ctx.strokeStyle = '#ef5b5b';
ctx.lineWidth = 1.5;
ctx.setLineDash([4, 3]);
ctx.beginPath();
ctx.moveTo(cutX, pad.top);
ctx.lineTo(cutX, pad.top + plotH);
ctx.stroke();
ctx.setLineDash([]);
// Label
ctx.fillStyle = '#ef5b5b';
ctx.font = '10px system-ui';
ctx.textAlign = 'left';
ctx.fillText(`k=${nComponents}`, cutX + 4, pad.top + 12);
}
function drawVariancePlot(cumulativeVar, n, nComponents) {
const { ctx, w, h } = setupCanvas('variancePlot');
const pad = { top: 15, right: 15, bottom: 25, left: 45 };
const plotW = w - pad.left - pad.right;
const plotH = h - pad.top - pad.bottom;
ctx.clearRect(0, 0, w, h);
const vals = cumulativeVar.slice(0, n);
// Axis labels
ctx.fillStyle = '#555';
ctx.font = '10px system-ui';
ctx.textAlign = 'center';
ctx.fillText('Components', pad.left + plotW / 2, h - 3);
// Y-axis ticks
ctx.textAlign = 'right';
for (let pct of [0, 0.25, 0.5, 0.75, 1.0]) {
const y = pad.top + plotH - pct * plotH;
ctx.fillStyle = '#444';
ctx.fillText((pct * 100).toFixed(0) + '%', pad.left - 5, y + 3);
ctx.strokeStyle = '#222';
ctx.lineWidth = 0.5;
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(pad.left + plotW, y);
ctx.stroke();
}
// Fill area
ctx.beginPath();
ctx.moveTo(pad.left, pad.top + plotH);
for (let i = 0; i < vals.length; i++) {
const x = pad.left + (i / (n - 1)) * plotW;
const y = pad.top + plotH - vals[i] * plotH;
ctx.lineTo(x, y);
}
ctx.lineTo(pad.left + ((vals.length - 1) / (n - 1)) * plotW, pad.top + plotH);
ctx.closePath();
ctx.fillStyle = '#5b8def18';
ctx.fill();
// Line
ctx.beginPath();
for (let i = 0; i < vals.length; i++) {
const x = pad.left + (i / (n - 1)) * plotW;
const y = pad.top + plotH - vals[i] * plotH;
i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.strokeStyle = '#5b8def';
ctx.lineWidth = 2;
ctx.stroke();
// Dashed line at current selection
const selX = pad.left + ((nComponents - 1) / (n - 1)) * plotW;
const selY = pad.top + plotH - cumulativeVar[nComponents - 1] * plotH;
ctx.strokeStyle = '#ef5b5b';
ctx.lineWidth = 1.5;
ctx.setLineDash([4, 3]);
ctx.beginPath();
ctx.moveTo(selX, pad.top + plotH);
ctx.lineTo(selX, selY);
ctx.lineTo(pad.left, selY);
ctx.stroke();
ctx.setLineDash([]);
// Dot
ctx.beginPath();
ctx.arc(selX, selY, 4, 0, Math.PI * 2);
ctx.fillStyle = '#ef5b5b';
ctx.fill();
// Label
ctx.fillStyle = '#ef5b5b';
ctx.font = '10px system-ui';
ctx.textAlign = 'left';
ctx.fillText((cumulativeVar[nComponents - 1] * 100).toFixed(1) + '%', selX + 6, selY - 4);
}
function drawEigenvectorPlot(loadings, maxComponents) {
const { ctx, w, h } = setupCanvas('eigenvectorPlot');
const pad = { top: 15, right: 15, bottom: 25, left: 20 };
const plotW = w - pad.left - pad.right;
const plotH = h - pad.top - pad.bottom;
ctx.clearRect(0, 0, w, h);
const nVecs = Math.min(3, maxComponents);
const nFeatures = loadings.rows;
const colors = ['#5b8def', '#ef5b5b', '#5befa0'];
const labels = ['PC1', 'PC2', 'PC3'];
// Axis
ctx.fillStyle = '#555';
ctx.font = '10px system-ui';
ctx.textAlign = 'center';
ctx.fillText('Feature Index (pixel column)', pad.left + plotW / 2, h - 3);
// Zero line
const zeroY = pad.top + plotH / 2;
ctx.strokeStyle = '#333';
ctx.lineWidth = 0.5;
ctx.beginPath();
ctx.moveTo(pad.left, zeroY);
ctx.lineTo(pad.left + plotW, zeroY);
ctx.stroke();
// Find global max for scaling
let absMax = 0;
for (let v = 0; v < nVecs; v++) {
for (let f = 0; f < nFeatures; f++) {
absMax = Math.max(absMax, Math.abs(loadings.get(f, v)));
}
}
for (let v = 0; v < nVecs; v++) {
ctx.beginPath();
ctx.strokeStyle = colors[v];
ctx.lineWidth = 1.5;
for (let f = 0; f < nFeatures; f++) {
const x = pad.left + (f / (nFeatures - 1)) * plotW;
const val = loadings.get(f, v);
const y = zeroY - (val / absMax) * (plotH / 2) * 0.9;
f === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.stroke();
}
// Legend
for (let v = 0; v < nVecs; v++) {
const lx = pad.left + 8 + v * 50;
ctx.fillStyle = colors[v];
ctx.fillRect(lx, pad.top, 12, 3);
ctx.font = '10px system-ui';
ctx.textAlign = 'left';
ctx.fillText(labels[v], lx + 16, pad.top + 5);
}
}
function drawPieChart(explainedVar, nComponents) {
const { ctx, w, h } = setupCanvas('pieChart');
ctx.clearRect(0, 0, w, h);
const cx = w / 2;
const cy = h / 2;
const r = Math.min(cx, cy) - 20;
// Group: top components individually (up to 5), rest lumped, discarded
const maxSlices = 5;
const showN = Math.min(nComponents, maxSlices);
const slices = [];
const colors = ['#5b8def', '#4a7de0', '#3a6dd0', '#2a5dc0', '#1a4db0'];
let usedVar = 0;
for (let i = 0; i < showN; i++) {
slices.push({ label: `PC${i + 1}`, value: explainedVar[i], color: colors[i % colors.length] });
usedVar += explainedVar[i];
}
if (nComponents > maxSlices) {
let rest = 0;
for (let i = maxSlices; i < nComponents; i++) rest += explainedVar[i];
slices.push({ label: `PC${maxSlices + 1}-${nComponents}`, value: rest, color: '#2a4a7a' });
usedVar += rest;
}
const discarded = Math.max(0, 1 - usedVar);
if (discarded > 0.001) {
slices.push({ label: 'Discarded', value: discarded, color: '#332222' });
}
let angle = -Math.PI / 2;
for (const slice of slices) {
const sliceAngle = slice.value * Math.PI * 2;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, r, angle, angle + sliceAngle);
ctx.closePath();
ctx.fillStyle = slice.color;
ctx.fill();
ctx.strokeStyle = '#0f0f0f';
ctx.lineWidth = 2;
ctx.stroke();
// Label
if (slice.value > 0.03) {
const midAngle = angle + sliceAngle / 2;
const lx = cx + Math.cos(midAngle) * r * 0.65;
const ly = cy + Math.sin(midAngle) * r * 0.65;
ctx.fillStyle = '#fff';
ctx.font = '10px system-ui';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(slice.label, lx, ly - 6);
ctx.fillStyle = '#ccc';
ctx.font = '9px system-ui';
ctx.fillText((slice.value * 100).toFixed(1) + '%', lx, ly + 6);
}
angle += sliceAngle;
}
}
function setStatus(html) {
statusEl.innerHTML = html;
}
</script>
</body>
</html>