-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmi.html
775 lines (731 loc) · 32.6 KB
/
mi.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mutual Information Playground</title>
<h2>Mutual Information Playground</h2>
<h3 style="margin-top: 0; margin-bottom: 0.2;">Author: <a href="https://maxsun.io/" target="_blank">Max Muchen Sun</a> | April, 2025</h3>
<!-- MathJax is included if needed elsewhere but not for numeric table updates -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<style>
/* Basic styling */
body {
margin: 0;
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
padding: 20px;
}
/* Container for the top table */
#topRowContainer {
width: 1120px;
/* same as 3 squares: 360×3 + 2×20 = 1120 */
margin: 0 auto;
text-align: center;
padding: 10px;
}
#expressionTable {
margin: 0 auto;
border-collapse: collapse;
font-size: 25px;
}
#expressionTable th,
#expressionTable td {
border: 1px solid #ccc;
padding: 8px 12px;
}
#expressionTable th {
background: #f7f7f7;
font-weight: bold;
}
.row {
display: flex;
justify-content: center;
gap: 20px;
width: 100%;
}
.square-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
}
.title {
font-size: 18px;
}
canvas {
border: 1px solid #ccc;
width: 360px;
height: 360px;
image-rendering: pixelated;
}
.button-row {
display: flex;
justify-content: center;
gap: 20px;
width: 100%;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#miProgress {
width: 360px;
height: 20px;
}
#miInfo {
font-size: 14px;
margin-top: 5px;
}
</style>
</head>
<body>
<!-- Top table for the expression values -->
<div id="topRowContainer">
<table id="expressionTable">
<thead>
<tr>
<th>I(x)</th>
<th>x</th>
<th>p(y=1|x)</th>
<th>H[p(s)) - H(p(s|x,y=1)]</th>
<th>p(y=0|x)</th>
<th>H[p(s)) - H(p(s|x,y=0)]</th>
</tr>
</thead>
<tbody>
<tr>
<td id="tdIx">???</td>
<td id="tdX">???</td>
<td id="tdPy1">???</td>
<td id="tdDiff1">???</td>
<td id="tdPy0">???</td>
<td id="tdDiff0">???</td>
</tr>
</tbody>
</table>
</div>
<!-- Top row of squares -->
<div class="row" id="row1">
<div class="square-container">
<div class="title">\( p(s \mid y=1) \)</div>
<canvas data-id="square1" width="360" height="360"></canvas>
</div>
<div class="square-container">
<div class="title">\( p(s \mid y=0) \)</div>
<canvas data-id="square2" width="360" height="360"></canvas>
</div>
</div>
<!-- Bottom row: density field, iterative belief, MI field -->
<div class="row" id="row2">
<div class="square-container">
<div class="title">\( p(y=1 \mid s=[0.5,0.5],\, x) \)</div>
<canvas data-id="square3" width="360" height="360"></canvas>
</div>
<div class="square-container">
<div class="title">Iterative Belief \( p(s) \)</div>
<canvas data-id="square4" width="360" height="360"></canvas>
</div>
<div class="square-container">
<div class="title">\( I(x) \)</div>
<canvas data-id="square5" width="360" height="360"></canvas>
</div>
</div>
<!-- Button row -->
<div class="button-row">
<button id="resetButton">Reset</button>
<button id="toggleTargetButton">Show Target</button>
<button id="visualizeMIButton">Visualize Mutual Information</button>
</div>
<!-- MI Progress -->
<progress id="miProgress" value="0" max="100"></progress>
<div id="miInfo">Progress: 0% | 0 iters/sec | Time left: – s</div>
<script>
/********************************************************************
* PART 1: Global Variables, Belief, and Tracker State.
********************************************************************/
const gridRes = 50;
const totalCells = gridRes * gridRes;
const miBatchSize = 20;
let beliefMatrix = null;
let beliefFieldData = null; // For visualization purposes only
let hiddenTarget = { x: Math.random() * 0.6 + 0.2, y: Math.random() * 0.6 + 0.2 };
let showHiddenTarget = false;
let miFieldData = null;
let miComputationIndex = 0;
let showMIField = false;
let miStartTime = 0;
// Table cells
const tdIx = document.getElementById("tdIx");
const tdPy1 = document.getElementById("tdPy1");
const tdDiff1 = document.getElementById("tdDiff1");
const tdPy0 = document.getElementById("tdPy0");
const tdDiff0 = document.getElementById("tdDiff0");
const tdX = document.getElementById("tdX");
// Progress elements
const miProgressBar = document.getElementById("miProgress");
const miInfo = document.getElementById("miInfo");
// Buttons
const resetButton = document.getElementById("resetButton");
const toggleTargetButton = document.getElementById("toggleTargetButton");
const visualizeMIButton = document.getElementById("visualizeMIButton");
// Tracker for mouse/touch position etc.
const dot = { pos: { x: 0, y: 0 }, target: { x: 0, y: 0 }, visible: false };
const velocityFactor = 0.15, maxVelocity = 0.05;
/********************************************************************
* PART 2: Helper Functions
********************************************************************/
// Sum-based normalization
function normalizeBySum(array) {
const sumVal = array.reduce((a, b) => a + b, 0);
if (sumVal > 0) {
for (let i = 0; i < array.length; i++) {
array[i] /= sumVal;
}
} else {
const val = 1 / array.length;
for (let i = 0; i < array.length; i++) {
array[i] = val;
}
}
}
// Create visualization image from a 1D data array.
function createVisualizationImage(dataArray) {
let minVal = Infinity, maxVal = -Infinity;
for (let i = 0; i < dataArray.length; i++) {
if (dataArray[i] < minVal) minVal = dataArray[i];
if (dataArray[i] > maxVal) maxVal = dataArray[i];
}
const range = (maxVal - minVal) > 0 ? (maxVal - minVal) : 1;
const off = document.createElement("canvas");
off.width = gridRes;
off.height = gridRes;
const ctx = off.getContext("2d");
let imgData = ctx.createImageData(gridRes, gridRes);
for (let i = 0; i < dataArray.length; i++) {
let normVal = (dataArray[i] - minVal) / range;
normVal = Math.min(Math.max(normVal, 0), 1);
const c = plasmaColor(normVal);
let idx = i * 4;
imgData.data[idx] = c.r;
imgData.data[idx + 1] = c.g;
imgData.data[idx + 2] = c.b;
imgData.data[idx + 3] = 255;
}
return imgData;
}
// Plasma colormap
function plasmaColor(t) {
const cp = [
{ t: 0.0, r: 13, g: 8, b: 135 },
{ t: 0.25, r: 84, g: 28, b: 154 },
{ t: 0.5, r: 186, g: 66, b: 124 },
{ t: 0.75, r: 249, g: 136, b: 77 },
{ t: 1.0, r: 240, g: 249, b: 33 }
];
if (t <= cp[0].t) return cp[0];
if (t >= cp[cp.length - 1].t) return cp[cp.length - 1];
for (let i = 0; i < cp.length - 1; i++) {
if (t >= cp[i].t && t <= cp[i + 1].t) {
const f = (t - cp[i].t) / (cp[i + 1].t - cp[i].t);
return {
r: Math.round(cp[i].r + f * (cp[i + 1].r - cp[i].r)),
g: Math.round(cp[i].g + f * (cp[i + 1].g - cp[i].g)),
b: Math.round(cp[i].b + f * (cp[i + 1].b - cp[i].b))
};
}
}
return cp[cp.length - 1];
}
// Compute density field for square3.
function computeDensityFieldImageData(res) {
const w = res, h = res;
const off = document.createElement("canvas");
off.width = w;
off.height = h;
const oc = off.getContext("2d");
const imageData = oc.createImageData(w, h);
const data = imageData.data;
const sX = 0.5, sY = 0.5;
for (let j = 0; j < h; j++) {
for (let i = 0; i < w; i++) {
const x = i / w;
const y = 1 - (j / h); // coordinate flip
const d = Math.hypot(x - sX, y - sY);
const f = Math.exp(-100 * ((d - 0.2) ** 2));
const c = plasmaColor(f);
const idx = (j * w + i) * 4;
data[idx + 0] = c.r;
data[idx + 1] = c.g;
data[idx + 2] = c.b;
data[idx + 3] = 255;
}
}
return imageData;
}
// Draw imageData scaled to target dimensions.
function drawScaledImageData(ctx, imageData, dw, dh) {
const off = document.createElement("canvas");
off.width = imageData.width;
off.height = imageData.height;
const oc = off.getContext("2d");
oc.putImageData(imageData, 0, 0);
ctx.drawImage(off, 0, 0, dw, dh);
}
/********************************************************************
* PART 3: Setup: Candidate Positions and Initialize Belief/Density
********************************************************************/
const candidatePositions = [];
for (let j = 0; j < gridRes; j++) {
for (let i = 0; i < gridRes; i++) {
candidatePositions.push({ x: i / gridRes, y: 1 - j / gridRes });
}
}
function initializeBelief() {
beliefMatrix = new Array(totalCells).fill(1);
normalizeBySum(beliefMatrix);
}
function measurementLikelihood(sx, sy, mx, my) {
const dist = Math.hypot(mx - sx, my - sy);
const likelihood = Math.exp(-100 * ((dist - 0.2) ** 2));
return Math.max(likelihood, 1e-6);
}
function distributionEntropy(dist) {
let e = 0;
for (let i = 0; i < dist.length; i++) {
const p = dist[i];
if (p > 0) e -= p * Math.log(p);
}
return e;
}
/********************************************************************
* PART 4: Setup Canvases and Precompute Density Field for Square3
********************************************************************/
const canvases = document.querySelectorAll("canvas");
let densityFieldData = null;
canvases.forEach(canvas => {
if (canvas.dataset.id === "square3") {
densityFieldData = computeDensityFieldImageData(gridRes);
}
if (canvas.dataset.id === "square4" && !beliefMatrix) {
initializeBelief();
}
});
// Draw a fixed white triangle marker.
function drawTriangleMarker(ctx, normX, normY, side, canvasHeight) {
const centerX = normX * ctx.canvas.width;
const centerY = canvasHeight - normY * ctx.canvas.height;
const radius = side * Math.sqrt(3) / 3;
const angleOffset = -Math.PI / 2;
const vertices = [];
for (let k = 0; k < 3; k++) {
const theta = angleOffset + k * (2 * Math.PI / 3);
vertices.push({
x: centerX + radius * Math.cos(theta),
y: centerY + radius * Math.sin(theta)
});
}
ctx.beginPath();
ctx.moveTo(vertices[0].x, vertices[0].y);
ctx.lineTo(vertices[1].x, vertices[1].y);
ctx.lineTo(vertices[2].x, vertices[2].y);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.stroke();
}
/********************************************************************
* PART 5: Button and Mouse/Touch Events
********************************************************************/
const errorMessageDiv = document.createElement("div");
errorMessageDiv.style.color = "red";
errorMessageDiv.style.fontWeight = "bold";
errorMessageDiv.style.marginTop = "5px";
document.body.insertBefore(errorMessageDiv, document.getElementById("topRowContainer"));
resetButton.addEventListener("click", () => {
hiddenTarget = { x: Math.random() * 0.6 + 0.2, y: Math.random() * 0.6 + 0.2 };
canvases.forEach(canvas => {
if (canvas.dataset.id === "square4") {
initializeBelief();
beliefFieldData = null;
}
});
});
toggleTargetButton.addEventListener("click", () => {
showHiddenTarget = !showHiddenTarget;
toggleTargetButton.textContent = showHiddenTarget ? "Hide Target" : "Show Target";
});
visualizeMIButton.addEventListener("click", () => {
miComputationIndex = 0;
showMIField = false;
miProgressBar.value = 0;
miInfo.innerText = "Progress: 0% | 0 iters/sec | Time left: – s";
miStartTime = performance.now();
const off = document.createElement("canvas");
off.width = gridRes;
off.height = gridRes;
const oc = off.getContext("2d");
miFieldData = oc.createImageData(gridRes, gridRes);
animateMI();
});
// Helper function to extract event coordinates for mouse and touch.
function getEventCoordinates(e, canvas) {
let clientX, clientY;
if (e.changedTouches) {
clientX = e.changedTouches[0].clientX;
clientY = e.changedTouches[0].clientY;
} else {
clientX = e.clientX;
clientY = e.clientY;
}
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
return {
x: (clientX - rect.left) * scaleX,
y: (clientY - rect.top) * scaleY
};
}
// Shared function for handling a tap/click on square4.
function handleBeliefTap(e, canvas) {
e.preventDefault();
const coords = getEventCoordinates(e, canvas);
const m = { x: coords.x / canvas.width, y: 1 - (coords.y / canvas.height) };
const dx_true = m.x - hiddenTarget.x;
const dy_true = m.y - hiddenTarget.y;
const d_true = Math.hypot(dx_true, dy_true);
const p_meas = Math.exp(-100 * ((d_true - 0.2) ** 2));
const outcome = (Math.random() < p_meas) ? 1 : 0;
sampledDot = { x: m.x, y: m.y, color: (outcome === 1) ? "red" : "white" };
for (let j = 0; j < gridRes; j++) {
for (let i = 0; i < gridRes; i++) {
const idx = j * gridRes + i;
const s_x = i / gridRes, s_y = 1 - (j / gridRes);
const dd = Math.hypot(m.x - s_x, m.y - s_y);
const L = Math.max(Math.exp(-100 * ((dd - 0.2) ** 2)), 1e-6);
const likelihood = (outcome === 1) ? L : Math.max(1 - L, 1e-6);
beliefMatrix[idx] *= likelihood;
}
}
normalizeBySum(beliefMatrix);
beliefFieldData = createVisualizationImage(beliefMatrix);
}
// Add mouse event listeners for hover tracking to all canvases.
canvases.forEach(canvas => {
canvas.addEventListener("mousemove", (e) => {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
dot.target.x = x / canvas.width;
dot.target.y = 1 - (y / canvas.height);
dot.visible = true;
});
canvas.addEventListener("mouseleave", () => {
dot.target.x = dot.pos.x;
dot.target.y = dot.pos.y;
dot.visible = false;
});
// Add touch event listeners to all canvases (for dragging).
canvas.addEventListener("touchstart", (e) => {
e.preventDefault();
const coords = getEventCoordinates(e, canvas);
dot.target.x = coords.x / canvas.width;
dot.target.y = 1 - (coords.y / canvas.height);
dot.visible = true;
}, false);
canvas.addEventListener("touchmove", (e) => {
e.preventDefault();
const coords = getEventCoordinates(e, canvas);
dot.target.x = coords.x / canvas.width;
dot.target.y = 1 - (coords.y / canvas.height);
}, false);
});
// For square4 add click and touchend for measurement update.
let sampledDot = null;
canvases.forEach(canvas => {
if (canvas.dataset.id === "square4") {
canvas.addEventListener("click", (e) => {
handleBeliefTap(e, canvas);
});
canvas.addEventListener("touchend", (e) => {
handleBeliefTap(e, canvas);
}, false);
}
});
/********************************************************************
* PART 6: Progressive MI Calculation
********************************************************************/
function animateMI() {
const w = gridRes, h = gridRes;
if (miComputationIndex < w * h) {
const sumBelief = beliefMatrix.reduce((a, b) => a + b, 0);
const normBelief = new Array(totalCells);
for (let i = 0; i < totalCells; i++) {
normBelief[i] = beliefMatrix[i] / sumBelief;
}
const priorEntropy = distributionEntropy(normBelief);
for (let n = 0; n < miBatchSize && miComputationIndex < w * h; n++, miComputationIndex++) {
const i = miComputationIndex % w;
const j = Math.floor(miComputationIndex / w);
const xCand = { x: i / w, y: 1 - (j / h) };
let p_y1 = 0;
for (let k = 0; k < totalCells; k++) {
const s = candidatePositions[k];
const L = Math.max(Math.exp(-100 * ((Math.hypot(xCand.x - s.x, xCand.y - s.y) - 0.2) ** 2)), 1e-6);
p_y1 += normBelief[k] * L;
}
const p_y0 = 1 - p_y1;
let postY1 = new Array(totalCells);
for (let k = 0; k < totalCells; k++) {
const s = candidatePositions[k];
const L = Math.max(Math.exp(-100 * ((Math.hypot(xCand.x - s.x, xCand.y - s.y) - 0.2) ** 2)), 1e-6);
postY1[k] = normBelief[k] * L;
}
normalizeBySum(postY1);
const H_postY1 = distributionEntropy(postY1);
let postY0 = new Array(totalCells);
for (let k = 0; k < totalCells; k++) {
const s = candidatePositions[k];
const L = Math.max(Math.exp(-100 * ((Math.hypot(xCand.x - s.x, xCand.y - s.y) - 0.2) ** 2)), 1e-6);
postY0[k] = normBelief[k] * (1 - L);
}
normalizeBySum(postY0);
const H_postY0 = distributionEntropy(postY0);
const I_x = (priorEntropy - (p_y1 * H_postY1 + p_y0 * H_postY0)) * 255.0;
const dIndex = miComputationIndex * 4;
miFieldData.data[dIndex] = I_x;
miFieldData.data[dIndex + 1] = I_x;
miFieldData.data[dIndex + 2] = I_x;
miFieldData.data[dIndex + 3] = 255;
}
const progressPercent = (miComputationIndex / (w * h)) * 100;
miProgressBar.value = progressPercent;
const elapsed = (performance.now() - miStartTime) / 1000;
const itersPerSec = miComputationIndex / elapsed;
const timeLeft = ((w * h) - miComputationIndex) / itersPerSec;
miInfo.innerText = `Progress: ${progressPercent.toFixed(1)}% | ${itersPerSec.toFixed(1)} iters/sec | Time left: ${timeLeft.toFixed(1)} s`;
requestAnimationFrame(animateMI);
} else {
const rawMI = new Array(totalCells);
for (let i = 0; i < totalCells; i++) {
rawMI[i] = miFieldData.data[i * 4];
}
miFieldData = createVisualizationImage(rawMI);
showMIField = true;
}
}
/********************************************************************
* PART 7: Real-Time Table Updates
********************************************************************/
function updateTableValues() {
if (!beliefMatrix) {
tdIx.textContent = "???";
tdPy1.textContent = "???";
tdDiff1.textContent = "???";
tdPy0.textContent = "???";
tdDiff0.textContent = "???";
tdX.textContent = "???";
return;
}
const sumBelief = beliefMatrix.reduce((a, b) => a + b, 0);
if (sumBelief <= 0) {
tdIx.textContent = "NaN";
tdPy1.textContent = "NaN";
tdDiff1.textContent = "NaN";
tdPy0.textContent = "NaN";
tdDiff0.textContent = "NaN";
tdX.textContent = "NaN";
return;
}
const normBelief = new Array(totalCells);
for (let i = 0; i < totalCells; i++) {
normBelief[i] = beliefMatrix[i] / sumBelief;
}
const mx = dot.pos.x, my = dot.pos.y;
let p_y1 = 0;
for (let i = 0; i < totalCells; i++) {
const s = candidatePositions[i];
const L = measurementLikelihood(s.x, s.y, mx, my);
p_y1 += normBelief[i] * L;
}
const p_y0 = 1 - p_y1;
const priorEntropy = distributionEntropy(normBelief);
let postY1 = new Array(totalCells);
for (let i = 0; i < totalCells; i++) {
const s = candidatePositions[i];
const L = measurementLikelihood(s.x, s.y, mx, my);
postY1[i] = normBelief[i] * L;
}
normalizeBySum(postY1);
const H_postY1 = distributionEntropy(postY1);
let postY0 = new Array(totalCells);
for (let i = 0; i < totalCells; i++) {
const s = candidatePositions[i];
const L = measurementLikelihood(s.x, s.y, mx, my);
postY0[i] = normBelief[i] * (1 - L);
}
normalizeBySum(postY0);
const H_postY0 = distributionEntropy(postY0);
const diff1 = priorEntropy - H_postY1;
const diff0 = priorEntropy - H_postY0;
const Ix = priorEntropy - (p_y1 * H_postY1 + p_y0 * H_postY0);
tdIx.textContent = Ix.toFixed(3);
tdX.textContent = `(${dot.pos.x.toFixed(2)}, ${dot.pos.y.toFixed(2)})`;
tdPy1.textContent = p_y1.toFixed(3);
tdDiff1.textContent = diff1.toFixed(3);
tdPy0.textContent = p_y0.toFixed(3);
tdDiff0.textContent = diff0.toFixed(3);
}
/********************************************************************
* PART 8: Main Animation Loop
********************************************************************/
function animate() {
updateTableValues();
canvases.forEach(canvas => {
const ctx = canvas.getContext("2d");
if (canvas.dataset.id === "square3") {
// Recompute the raw density values for each cell using f = exp(-100*((d - 0.2)**2))
const rawDensity = new Array(gridRes * gridRes);
for (let j = 0; j < gridRes; j++) {
for (let i = 0; i < gridRes; i++) {
const idx = j * gridRes + i;
const x = i / gridRes;
const y = 1 - (j / gridRes);
const d = Math.hypot(x - 0.5, y - 0.5);
const f = Math.exp(-100 * ((d - 0.2) ** 2));
rawDensity[idx] = f;
}
}
const visImg = createVisualizationImage(rawDensity);
drawScaledImageData(ctx, visImg, canvas.width, canvas.height);
drawTriangleMarker(ctx, 0.5, 0.5, 30, canvas.height);
// (Optionally, draw the tracker marker as well)
const trackerX = dot.pos.x * canvas.width;
const trackerY = canvas.height - (dot.pos.y * canvas.height);
ctx.beginPath();
ctx.arc(trackerX, trackerY, 10, 0, 2 * Math.PI);
ctx.fillStyle = "grey";
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
ctx.stroke();
} else if (canvas.dataset.id === "square4") {
if (beliefMatrix) {
const visImg = createVisualizationImage(beliefMatrix);
drawScaledImageData(ctx, visImg, canvas.width, canvas.height);
} else {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
if (showHiddenTarget) {
drawTriangleMarker(ctx, hiddenTarget.x, hiddenTarget.y, 30, canvas.height);
}
if (sampledDot) {
const sampleX = sampledDot.x * canvas.width;
const sampleY = canvas.height - (sampledDot.y * canvas.height);
ctx.beginPath();
ctx.arc(sampleX, sampleY, 10, 0, 2 * Math.PI);
ctx.fillStyle = sampledDot.color;
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
ctx.stroke();
}
// Tracker marker in square4 uses measurement color if available, else white.
const trackerX = dot.pos.x * canvas.width;
const trackerY = canvas.height - (dot.pos.y * canvas.height);
ctx.beginPath();
ctx.arc(trackerX, trackerY, 10, 0, 2 * Math.PI);
const trackerColor = sampledDot ? sampledDot.color : "white";
ctx.fillStyle = trackerColor;
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
ctx.stroke();
} else if (canvas.dataset.id === "square5") {
if (showMIField && miFieldData) {
const rawMI = new Array(totalCells);
for (let i = 0; i < totalCells; i++) {
rawMI[i] = miFieldData.data[i * 4];
}
const visImg = createVisualizationImage(rawMI);
drawScaledImageData(ctx, visImg, canvas.width, canvas.height);
} else {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// Tracker marker in square5 (always grey)
const trackerX = dot.pos.x * canvas.width;
const trackerY = canvas.height - (dot.pos.y * canvas.height);
ctx.beginPath();
ctx.arc(trackerX, trackerY, 10, 0, 2 * Math.PI);
ctx.fillStyle = "grey";
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
ctx.stroke();
}
// Top row squares (square1 and square2)
if (canvas.dataset.id === "square1" || canvas.dataset.id === "square2") {
let hypoBelief = new Array(totalCells).fill(0);
let maxValHypo = -Infinity;
for (let j = 0; j < gridRes; j++) {
for (let i = 0; i < gridRes; i++) {
const idx = j * gridRes + i;
const s_x = i / gridRes;
const s_y = 1 - (j / gridRes);
const dist = Math.hypot(dot.pos.x - s_x, dot.pos.y - s_y);
let L;
if (canvas.dataset.id === "square1") {
L = Math.max(Math.exp(-100 * ((dist - 0.2) ** 2)), 1e-6);
} else {
L = Math.max(1 - Math.exp(-100 * ((dist - 0.2) ** 2)), 1e-6);
}
const prior = beliefMatrix ? beliefMatrix[idx] : 1;
hypoBelief[idx] = prior * L;
if (hypoBelief[idx] > maxValHypo) maxValHypo = hypoBelief[idx];
}
}
normalizeBySum(hypoBelief);
const visImg = createVisualizationImage(hypoBelief);
drawScaledImageData(ctx, visImg, canvas.width, canvas.height);
const trackerX = dot.pos.x * canvas.width;
const trackerY = canvas.height - (dot.pos.y * canvas.height);
ctx.beginPath();
ctx.arc(trackerX, trackerY, 10, 0, 2 * Math.PI);
ctx.fillStyle = (canvas.dataset.id === "square1") ? "red" : "white";
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
ctx.stroke();
}
});
// Update tracker position (smooth movement).
const diffX = dot.target.x - dot.pos.x;
const diffY = dot.target.y - dot.pos.y;
let vx = diffX * velocityFactor, vy = diffY * velocityFactor;
const speed = Math.sqrt(vx * vx + vy * vy);
if (speed > maxVelocity) {
const scale = maxVelocity / speed;
vx *= scale;
vy *= scale;
}
dot.pos.x += vx;
dot.pos.y += vy;
requestAnimationFrame(animate);
}
/********************************************************************
* PART 9: Start the Main Loop
********************************************************************/
animate();
</script>
</body>
</html>