-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadam_slow.html
More file actions
693 lines (626 loc) · 26.7 KB
/
Copy pathadam_slow.html
File metadata and controls
693 lines (626 loc) · 26.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Adam Optimizer · 3D Interactive Visualization</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: 'Segoe UI', 'PingFang SC', Roboto, sans-serif;
background-color: #0a0a18;
color: #fff;
}
#info {
position: absolute;
top: 20px;
left: 20px;
z-index: 10;
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(8px);
padding: 14px 22px;
border-radius: 12px;
border-left: 4px solid #ff6b6b;
pointer-events: none;
user-select: none;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
}
#info h1 { margin: 0; font-size: 20px; font-weight: 600; letter-spacing: 0.5px; }
#info p { margin: 4px 0 0 0; font-size: 13px; opacity: 0.8; }
#info .highlight { color: #ffd93d; }
/* Control Panel */
#controls {
position: absolute;
top: 20px;
right: 20px;
z-index: 20;
background: rgba(10, 10, 25, 0.85);
backdrop-filter: blur(12px);
padding: 20px 24px;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.7);
width: 260px;
user-select: none;
font-size: 13px;
pointer-events: auto;
max-height: calc(100vh - 120px);
overflow-y: auto;
}
#controls::-webkit-scrollbar { width: 4px; }
#controls::-webkit-scrollbar-thumb { background: #444; border-radius: 8px; }
#controls .title {
font-weight: 600;
font-size: 15px;
margin-bottom: 16px;
color: #fff;
letter-spacing: 0.5px;
border-bottom: 1px solid rgba(255,255,255,0.06);
padding-bottom: 10px;
}
.control-group {
margin-bottom: 14px;
}
.control-group label {
display: flex;
justify-content: space-between;
font-size: 12px;
color: #aaa;
margin-bottom: 4px;
letter-spacing: 0.3px;
}
.control-group label .val {
color: #ffd93d;
font-family: 'Courier New', monospace;
font-weight: 600;
}
.control-group input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 4px;
background: #2a2a4a;
border-radius: 4px;
outline: none;
transition: background 0.2s;
}
.control-group input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: #4ecdc4;
cursor: pointer;
box-shadow: 0 0 12px #4ecdc488;
border: 2px solid #0a0a18;
}
.control-group input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background: #4ecdc4;
cursor: pointer;
border: 2px solid #0a0a18;
}
.hint {
font-size: 11px;
color: #777;
margin-top: 2px;
line-height: 1.4;
padding-left: 2px;
}
.hint strong { color: #aaa; }
.btn-restart {
width: 100%;
padding: 10px 0;
margin-top: 8px;
background: linear-gradient(135deg, #4ecdc4, #44a8b3);
border: none;
border-radius: 8px;
color: #0a0a18;
font-weight: 700;
font-size: 14px;
cursor: pointer;
transition: all 0.2s ease;
letter-spacing: 0.8px;
box-shadow: 0 4px 16px rgba(78, 205, 196, 0.3);
}
.btn-restart:hover {
transform: scale(1.02);
filter: brightness(1.15);
box-shadow: 0 6px 24px rgba(78, 205, 196, 0.5);
}
.btn-restart:active { transform: scale(0.98); }
#legend {
position: absolute;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
z-index: 10;
background: rgba(10, 10, 20, 0.8);
backdrop-filter: blur(6px);
padding: 10px 24px;
border-radius: 40px;
display: flex;
gap: 28px;
font-size: 13px;
border: 1px solid rgba(255, 255, 255, 0.06);
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
pointer-events: none;
user-select: none;
flex-wrap: wrap;
justify-content: center;
}
#legend .item { display: flex; align-items: center; gap: 8px; }
#legend .dot {
width: 12px;
height: 12px;
border-radius: 50%;
display: inline-block;
}
#legend .dot.traj { background: #ff6b6b; box-shadow: 0 0 12px #ff6b6b88; }
#legend .dot.momentum { background: #4ecdc4; box-shadow: 0 0 12px #4ecdc488; }
#legend .dot.scale { background: #ffe66d; box-shadow: 0 0 12px #ffe66d88; }
#legend .dot.grad { background: #a29bfe; box-shadow: 0 0 12px #a29bfe88; }
#status {
position: absolute;
bottom: 100px;
right: 30px;
z-index: 10;
background: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(4px);
padding: 12px 18px;
border-radius: 10px;
font-size: 13px;
font-family: 'Courier New', monospace;
border: 1px solid rgba(255, 255, 255, 0.06);
pointer-events: none;
user-select: none;
text-align: right;
line-height: 1.6;
min-width: 120px;
}
#status .label { opacity: 0.4; font-size: 10px; text-transform: uppercase; letter-spacing: 1px; }
#status .value { color: #ffd93d; }
@media (max-width: 820px) {
#controls { width: 200px; padding: 16px; top: 12px; right: 12px; }
#controls .title { font-size: 13px; }
#legend { font-size: 11px; gap: 14px; padding: 8px 16px; bottom: 16px; width: 90%; flex-wrap: wrap; }
#status { display: none; }
}
@media (max-width: 600px) {
#info { top: 10px; left: 10px; padding: 10px 14px; }
#info h1 { font-size: 15px; }
#controls { width: 160px; padding: 12px; font-size: 11px; top: 80px; right: 8px; }
.control-group { margin-bottom: 10px; }
.btn-restart { font-size: 12px; padding: 8px 0; }
}
</style>
</head>
<body>
<div id="info">
<h1>🧠 Adam Optimization · 3D Core Math</h1>
<p>Loss surface · Parameter trajectory · <span class="highlight">1st moment</span> (momentum) · <span class="highlight">2nd moment</span> (adaptive scale)</p>
</div>
<!-- Control Panel -->
<div id="controls">
<div class="title">⚙️ Hyperparameters</div>
<div class="control-group">
<label>Learning Rate (η) <span class="val" id="lrVal">0.12</span></label>
<input type="range" id="lrSlider" min="0.001" max="0.5" step="0.001" value="0.12" />
<div class="hint"><strong>Step size.</strong> Too high → divergence. Too low → slow convergence.</div>
</div>
<div class="control-group">
<label>Beta 1 (β₁) <span class="val" id="b1Val">0.900</span></label>
<input type="range" id="b1Slider" min="0.5" max="0.999" step="0.001" value="0.9" />
<div class="hint"><strong>Momentum decay.</strong> Controls the exponential moving average of the gradient. Default 0.9.</div>
</div>
<div class="control-group">
<label>Beta 2 (β₂) <span class="val" id="b2Val">0.999</span></label>
<input type="range" id="b2Slider" min="0.9" max="0.9999" step="0.0001" value="0.999" />
<div class="hint"><strong>Adaptive scale decay.</strong> Controls the moving average of squared gradients. Default 0.999.</div>
</div>
<div class="control-group">
<label>Animation Speed <span class="val" id="speedVal">200 ms</span></label>
<input type="range" id="speedSlider" min="50" max="800" step="10" value="200" />
<div class="hint"><strong>Step interval.</strong> Higher = slower, easier to observe.</div>
</div>
<button class="btn-restart" id="restartBtn">⟳ Apply & Restart</button>
</div>
<div id="legend">
<span class="item"><span class="dot traj"></span> Trajectory</span>
<span class="item"><span class="dot momentum"></span> Momentum (1st moment m)</span>
<span class="item"><span class="dot scale"></span> Adaptive scale (√v)</span>
<span class="item"><span class="dot grad"></span> Gradient ∇f</span>
</div>
<div id="status">
<div class="label">Iteration</div>
<div class="value" id="stepDisplay">0 / 60</div>
<div class="label" style="margin-top:6px;">Current η</div>
<div class="value" id="lrDisplay">0.12</div>
</div>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.128.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.128.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
// ======================== CORE MATH ========================
// Loss: f(x,y) = 0.5*(x²+y²) + 0.3*sin(3x)*cos(3y) + 0.2*(x+y)
function loss(x, y) {
return 0.5 * (x * x + y * y) + 0.3 * Math.sin(3 * x) * Math.cos(3 * y) + 0.2 * (x + y);
}
function grad(x, y) {
return [x - 0.9 * Math.sin(3 * x) * Math.cos(3 * y) + 0.2,
y + 0.9 * Math.cos(3 * x) * Math.sin(3 * y) + 0.2];
}
// ======================== THREE.JS SETUP ========================
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0a18);
const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 30);
camera.position.set(5.5, 4.5, 6.5);
camera.lookAt(0, 0.2, 0);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.2;
document.body.appendChild(renderer.domElement);
const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = '0px';
labelRenderer.domElement.style.left = '0px';
labelRenderer.domElement.style.pointerEvents = 'none';
document.body.appendChild(labelRenderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.target.set(0, 0.2, 0);
controls.maxPolarAngle = Math.PI / 2.1;
controls.minDistance = 2.5;
controls.maxDistance = 16;
// Lighting
const ambient = new THREE.AmbientLight(0x404060, 0.5);
scene.add(ambient);
const dirLight = new THREE.DirectionalLight(0xffeedd, 1.0);
dirLight.position.set(3, 8, 5);
dirLight.castShadow = true;
scene.add(dirLight);
scene.add(new THREE.DirectionalLight(0x4488ff, 0.4).position.set(-4, 2, -3));
scene.add(new THREE.DirectionalLight(0xffaa66, 0.3).position.set(-2, 1, -5));
const gridHelper = new THREE.GridHelper(8, 20, 0x8888ff, 0x334466);
gridHelper.position.y = -0.1;
scene.add(gridHelper);
// ======================== SURFACE ========================
const range = 3.2,
res = 80;
const vertices = [],
indices = [],
colors = [];
const heightMap = [];
let minZ = Infinity,
maxZ = -Infinity;
for (let j = 0; j <= res; j++) {
const row = [];
const y = -range + (j / res) * 2 * range;
for (let i = 0; i <= res; i++) {
const x = -range + (i / res) * 2 * range;
const z = loss(x, y);
row.push(z);
if (z < minZ) minZ = z;
if (z > maxZ) maxZ = z;
}
heightMap.push(row);
}
const rangeZ = maxZ - minZ || 0.001;
for (let j = 0; j <= res; j++) {
const y = -range + (j / res) * 2 * range;
for (let i = 0; i <= res; i++) {
const x = -range + (i / res) * 2 * range;
const z = heightMap[j][i];
vertices.push(x, z, y);
const t = (z - minZ) / rangeZ;
colors.push(Math.min(1, t * 1.2), Math.min(1, 0.4 + t * 0.8), Math.max(0, 1.0 - t * 0.9));
}
}
for (let j = 0; j < res; j++) {
for (let i = 0; i < res; i++) {
const a = i + j * (res + 1),
b = i + 1 + j * (res + 1),
c = i + (j + 1) * (res + 1),
d = i + 1 + (j + 1) * (res + 1);
indices.push(a, b, c, b, d, c);
}
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
geo.setIndex(indices);
geo.computeVertexNormals();
const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
vertexColors: true,
side: THREE.DoubleSide,
roughness: 0.4,
metalness: 0.1,
transparent: true,
opacity: 0.85,
}));
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
const wire = new THREE.Mesh(geo.clone(), new THREE.MeshBasicMaterial({
color: 0x88ccff,
wireframe: true,
transparent: true,
opacity: 0.06,
}));
scene.add(wire);
// ======================== TRAIL & ARROWS ========================
const MAX_TRAIL = 60;
const trailGeo = new THREE.BufferGeometry();
const trailPos = new Float32Array(MAX_TRAIL * 3);
trailGeo.setAttribute('position', new THREE.BufferAttribute(trailPos, 3));
trailGeo.setDrawRange(0, 0);
const trailLine = new THREE.Line(trailGeo, new THREE.LineBasicMaterial({ color: 0xff6b6b, transparent: true,
opacity: 0.9 }));
scene.add(trailLine);
const sphereMat = new THREE.MeshStandardMaterial({ color: 0xff6b6b, emissive: 0xff3333, emissiveIntensity: 0.6,
roughness: 0.2 });
const sphere = new THREE.Mesh(new THREE.SphereGeometry(0.12, 16, 16), sphereMat);
sphere.castShadow = true;
scene.add(sphere);
const glow = new THREE.Mesh(new THREE.SphereGeometry(0.22, 12, 12), new THREE.MeshBasicMaterial({ color: 0xff6b6b,
transparent: true, opacity: 0.2 }));
scene.add(glow);
// Arrows
const arrowGroup = new THREE.Group();
scene.add(arrowGroup);
const mArrow = new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), 0.01, 0x4ecdc4, 0.25,
0.12);
const vArrow = new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), 0.01, 0xffe66d, 0.25,
0.12);
const gArrow = new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), 0.01, 0xa29bfe, 0.25,
0.12);
arrowGroup.add(mArrow);
arrowGroup.add(vArrow);
arrowGroup.add(gArrow);
function makeLabel(text, color) {
const div = document.createElement('div');
div.textContent = text;
div.style.color = color;
div.style.fontSize = '13px';
div.style.fontWeight = '600';
div.style.textShadow = '0 0 12px rgba(0,0,0,0.9)';
div.style.fontFamily = 'monospace';
div.style.background = 'rgba(0,0,0,0.5)';
div.style.padding = '2px 10px';
div.style.borderRadius = '12px';
div.style.backdropFilter = 'blur(4px)';
div.style.border = '1px solid rgba(255,255,255,0.1)';
div.style.pointerEvents = 'none';
return new CSS2DObject(div);
}
const labelM = makeLabel('momentum m', '#4ecdc4');
const labelV = makeLabel('√v scale', '#ffe66d');
const labelG = makeLabel('gradient ∇f', '#a29bfe');
scene.add(labelM);
scene.add(labelV);
scene.add(labelG);
// ======================== SIMULATION STATE ========================
let theta = new THREE.Vector3(2.2, 0, -1.8);
theta.y = loss(theta.x, theta.z);
let m = new THREE.Vector3(0, 0, 0);
let v = new THREE.Vector3(0, 0, 0);
let t = 0;
const history = [];
let allStates = [];
let animIndex = 0;
let lastStepTime = 0;
// UI Elements
const lrSlider = document.getElementById('lrSlider');
const b1Slider = document.getElementById('b1Slider');
const b2Slider = document.getElementById('b2Slider');
const speedSlider = document.getElementById('speedSlider');
const lrVal = document.getElementById('lrVal');
const b1Val = document.getElementById('b1Val');
const b2Val = document.getElementById('b2Val');
const speedVal = document.getElementById('speedVal');
const stepDisplay = document.getElementById('stepDisplay');
const lrDisplay = document.getElementById('lrDisplay');
// ======================== SIMULATION ENGINE ========================
function runSimulation(lr, beta1, beta2, steps = 60) {
const eps = 1e-8;
let th = new THREE.Vector3(2.2, 0, -1.8);
th.y = loss(th.x, th.z);
let mm = new THREE.Vector3(0, 0, 0);
let vv = new THREE.Vector3(0, 0, 0);
let tt = 0;
const states = [];
for (let i = 0; i < steps; i++) {
const [gx, gz] = grad(th.x, th.z);
const g = new THREE.Vector3(gx, 0, gz);
tt += 1;
mm.x = beta1 * mm.x + (1 - beta1) * g.x;
mm.z = beta1 * mm.z + (1 - beta1) * g.z;
vv.x = beta2 * vv.x + (1 - beta2) * g.x * g.x;
vv.z = beta2 * vv.z + (1 - beta2) * g.z * g.z;
const mHatX = mm.x / (1 - Math.pow(beta1, tt));
const mHatZ = mm.z / (1 - Math.pow(beta1, tt));
const vHatX = vv.x / (1 - Math.pow(beta2, tt));
const vHatZ = vv.z / (1 - Math.pow(beta2, tt));
th.x -= lr * mHatX / (Math.sqrt(vHatX) + eps);
th.z -= lr * mHatZ / (Math.sqrt(vHatZ) + eps);
th.y = loss(th.x, th.z);
states.push({
theta: th.clone(),
m: mm.clone(),
v: vv.clone(),
g: g.clone(),
step: tt
});
}
return states;
}
function resetSimulation() {
const lr = parseFloat(lrSlider.value);
const beta1 = parseFloat(b1Slider.value);
const beta2 = parseFloat(b2Slider.value);
lrVal.textContent = lr.toFixed(3);
b1Val.textContent = beta1.toFixed(3);
b2Val.textContent = beta2.toFixed(3);
lrDisplay.textContent = lr.toFixed(3);
allStates = runSimulation(lr, beta1, beta2, 60);
// Reset state
theta.set(2.2, 0, -1.8);
theta.y = loss(theta.x, theta.z);
m.set(0, 0, 0);
v.set(0, 0, 0);
t = 0;
history.length = 0;
history.push(theta.clone());
animIndex = 0;
lastStepTime = performance.now();
// Update trail
const posAttr = trailLine.geometry.attributes.position;
const array = posAttr.array;
for (let i = 0; i < MAX_TRAIL; i++) {
array[i * 3] = 0;
array[i * 3 + 1] = -999;
array[i * 3 + 2] = 0;
}
posAttr.needsUpdate = true;
trailLine.geometry.setDrawRange(0, 1);
sphere.position.copy(theta);
sphere.position.y += 0.02;
glow.position.copy(sphere.position);
stepDisplay.textContent = `0 / 60`;
// Hide arrows initially
mArrow.visible = false;
vArrow.visible = false;
gArrow.visible = false;
labelM.visible = false;
labelV.visible = false;
labelG.visible = false;
}
// ======================== UPDATE VISUALIZATION ========================
function applyState(state) {
theta.copy(state.theta);
m.copy(state.m);
v.copy(state.v);
t = state.step;
history.push(theta.clone());
if (history.length > MAX_TRAIL) history.shift();
// Trail
const posAttr = trailLine.geometry.attributes.position;
const array = posAttr.array;
const count = history.length;
for (let i = 0; i < count; i++) {
const p = history[i];
array[i * 3] = p.x;
array[i * 3 + 1] = p.y + 0.02;
array[i * 3 + 2] = p.z;
}
posAttr.needsUpdate = true;
trailLine.geometry.setDrawRange(0, count);
sphere.position.copy(theta);
sphere.position.y += 0.02;
glow.position.copy(sphere.position);
// Gradient for arrows
const [gx, gz] = grad(theta.x, theta.z);
const g = new THREE.Vector3(gx, 0, gz);
const origin = theta.clone();
origin.y += 0.15;
// Momentum (m)
const mVec = new THREE.Vector3(m.x, 0, m.z);
const mLen = mVec.length();
if (mLen > 0.001) {
const mDir = mVec.clone().normalize();
const mScale = Math.min(mLen * 0.6, 1.2);
mArrow.setDirection(mDir);
mArrow.setLength(mScale, 0.25, 0.12);
mArrow.position.copy(origin);
mArrow.visible = true;
labelM.position.copy(origin.clone().add(mDir.clone().multiplyScalar(mScale + 0.3)));
labelM.visible = true;
} else { mArrow.visible = false;
labelM.visible = false; }
// Adaptive scale (sqrt(v)) - direction follows gradient
const sqrtV = new THREE.Vector3(Math.sqrt(v.x), 0, Math.sqrt(v.z));
const sLen = sqrtV.length();
if (sLen > 0.001) {
const gLen = g.length();
let sDir = gLen > 0.001 ? g.clone().normalize() : new THREE.Vector3(1, 0, 0);
const sScale = Math.min(sLen * 0.4, 1.5);
vArrow.setDirection(sDir);
vArrow.setLength(sScale, 0.25, 0.12);
vArrow.position.copy(origin);
vArrow.visible = true;
labelV.position.copy(origin.clone().add(sDir.clone().multiplyScalar(sScale + 0.3)));
labelV.visible = true;
} else { vArrow.visible = false;
labelV.visible = false; }
// Gradient
const gLen2 = g.length();
if (gLen2 > 0.001) {
const gDir = g.clone().normalize();
const gScale = Math.min(gLen2 * 0.5, 1.0);
gArrow.setDirection(gDir);
gArrow.setLength(gScale, 0.25, 0.12);
gArrow.position.copy(origin);
gArrow.visible = true;
labelG.position.copy(origin.clone().add(gDir.clone().multiplyScalar(gScale + 0.3)));
labelG.visible = true;
} else { gArrow.visible = false;
labelG.visible = false; }
stepDisplay.textContent = `${Math.min(t, 60)} / 60`;
}
// ======================== ANIMATION LOOP ========================
function animate() {
requestAnimationFrame(animate);
const speed = parseInt(speedSlider.value);
const now = performance.now();
if (animIndex < allStates.length && (now - lastStepTime >= speed)) {
const state = allStates[animIndex];
applyState(state);
animIndex++;
lastStepTime = now;
}
controls.update();
renderer.render(scene, camera);
labelRenderer.render(scene, camera);
}
// ======================== UI EVENTS ========================
document.getElementById('restartBtn').addEventListener('click', () => {
resetSimulation();
});
// Update displayed values on slider change
lrSlider.addEventListener('input', () => { lrVal.textContent = parseFloat(lrSlider.value).toFixed(3); });
b1Slider.addEventListener('input', () => { b1Val.textContent = parseFloat(b1Slider.value).toFixed(3); });
b2Slider.addEventListener('input', () => { b2Val.textContent = parseFloat(b2Slider.value).toFixed(4); });
speedSlider.addEventListener('input', () => { speedVal.textContent = `${speedSlider.value} ms`; });
// ======================== INIT ========================
speedVal.textContent = `${speedSlider.value} ms`;
resetSimulation();
animate();
// ======================== RESIZE ========================
window.addEventListener('resize', () => {
const w = window.innerWidth,
h = window.innerHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
labelRenderer.setSize(w, h);
});
console.log('Adam 3D Visualization ready. Adjust hyperparameters and click "Apply & Restart".');
</script>
</body>
</html>