-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspinEvolution.html
More file actions
1376 lines (1202 loc) · 58 KB
/
spinEvolution.html
File metadata and controls
1376 lines (1202 loc) · 58 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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Spin Evolution Animation</title>
<style>
body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
display: flex;
gap: 20px;
flex-direction: row;
}
.left-panel {
width: 350px;
flex-shrink: 0;
}
.right-panel {
flex: 1;
min-width: 0;
}
/* Mobile styles */
@media (max-width: 768px) {
body {
padding: 10px;
}
.container {
flex-direction: column;
gap: 15px;
padding: 15px;
border-radius: 5px;
}
.left-panel {
width: 100%;
order: 2;
}
.right-panel {
order: 1;
}
.control-row {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.control-row button {
margin-bottom: 0;
flex: 1;
margin-right: 5px;
}
.control-row button:last-child {
margin-right: 0;
}
}
.controls {
margin-bottom: 20px;
display: flex;
flex-direction: column;
gap: 15px;
}
.control-row {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
#canvas3d {
border: 1px solid #ddd;
border-radius: 5px;
background: linear-gradient(135deg, #fafafa 0%, #f0f0f0 100%);
width: 100%;
height: 70vh;
cursor: grab;
user-select: none;
/* min-height: 400px;
max-height: 1200px; */
}
#canvas3d:active {
cursor: grabbing;
}
#signalChart {
border-radius: 5px;
margin-top: 20px;
width: 100%;
height: 25vh;
}
/* Mobile canvas adjustments */
@media (max-width: 768px) {
#canvas3d {
height: 30vh;
min-height: 200px;
max-height: 300px;
}
#signalChart {
height: 15vh;
margin-top: 15px;
}
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
min-height: 44px; /* Touch-friendly minimum size */
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
select {
padding: 8px;
border-radius: 5px;
border: 1px solid #ddd;
width: 100%;
min-height: 44px; /* Touch-friendly minimum size */
font-size: 16px; /* Prevents zoom on iOS */
}
/* Mobile button and input adjustments */
@media (max-width: 768px) {
button {
padding: 12px 20px;
font-size: 16px;
width: 100%;
margin-bottom: 8px;
}
select {
padding: 12px;
font-size: 16px;
}
}
.info {
margin-top: 20px;
padding: 15px;
background-color: #f9f9f9;
border-radius: 5px;
border-left: 4px solid #4CAF50;
}
.status {
margin: 10px 0;
font-weight: bold;
color: #333;
}
.view-controls {
margin: 10px 0;
padding: 10px;
background-color: #f5f5f5;
border-radius: 5px;
}
.view-controls label {
margin-right: 15px;
display: block;
margin-bottom: 5px;
}
/* Mobile info and controls adjustments */
@media (max-width: 768px) {
.info {
margin-top: 15px;
padding: 10px;
}
.info h3 {
font-size: 16px;
margin-bottom: 8px;
}
.info p {
font-size: 14px;
margin: 5px 0;
}
.view-controls {
margin: 8px 0;
padding: 8px;
}
.view-controls label {
font-size: 14px;
margin-bottom: 8px;
}
h1 {
font-size: 24px;
margin-bottom: 15px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="left-panel">
<h1>MRI Spin Evolution</h1>
<div class="controls">
<div class="control-row">
<select id="sequenceSelect">
<option value="hahn">Hahn Echo</option>
<option value="hahn_wide">Hahn Echo (Wide Dispersion)</option>
<option value="spinecho">Spin Echo</option>
<option value="spinecho_wide">Spin Echo (Wide Dispersion)</option>
<option value="stimulated">Stimulated Echo</option>
</select>
</div>
<div class="control-row">
<button id="playBtn">Play</button>
<button id="pauseBtn" disabled>Pause</button>
<button id="resetBtn">Reset</button>
</div>
<div class="view-controls">
<label>Speed: <input type="range" id="speedSlider" min="0.1" max="2" step="0.1" value="1" style="width: 100%;"></label>
</div>
<div class="view-controls">
<label>Time: <input type="range" id="timelineSlider" min="0" max="100" value="0" step="0.1" style="width: 100%;"> </label>
</div>
<div class="view-controls">
<label>Zoom: <input type="range" id="zoomSlider" min="20" max="500" value="300" style="width: 100%;"></label>
</div>
</div>
<div class="status" id="status">Loading simulation...</div>
<div class="info">
<h3>Current Sequence: <span id="currentSequence">Hahn Echo</span></h3>
<p id="sequenceInfo">90° pulse along x-axis, followed by 90° pulse along x-axis</p>
<p><strong>Time:</strong> <span id="currentTime">0.00</span> s | <strong>Frame:</strong> <span id="currentFrame">0</span></p>
</div>
</div>
<div class="right-panel">
<canvas id="canvas3d"></canvas>
<canvas id="signalChart"></canvas>
</div>
</div>
<script>
// Utility functions for rotation matrices
function rotx(theta) {
const th2 = theta * Math.PI / 180;
return [
[1, 0, 0],
[0, Math.cos(th2), Math.sin(th2)],
[0, -Math.sin(th2), Math.cos(th2)]
];
}
function roty(theta) {
const th2 = theta * Math.PI / 180;
return [
[Math.cos(th2), 0, -Math.sin(th2)],
[0, 1, 0],
[Math.sin(th2), 0, Math.cos(th2)]
];
}
function rotz(theta) {
const th2 = theta * Math.PI / 180;
return [
[Math.cos(th2), Math.sin(th2), 0],
[-Math.sin(th2), Math.cos(th2), 0],
[0, 0, 1]
];
}
// Vector matrix multiplication
function matrixVectorMultiply(matrix, vector) {
const result = [0, 0, 0];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
result[i] += matrix[i][j] * vector[j];
}
}
return result;
}
// Linear space
function linspace(start, stop, num) {
const arr = [];
const step = (stop - start) / (num - 1);
for (let i = 0; i < num; i++) {
arr.push(start + step * i);
}
return arr;
}
// Mean calculation
function mean(arr) {
return arr.reduce((a, b) => a + b, 0) / arr.length;
}
// Enhanced 3D to 2D projection with interactive viewing
function project3D(x, y, z, azimuth = 37.5, elevation = 30) {
const azRad = (azimuth - 90) * Math.PI / 180;
const elRad = elevation * Math.PI / 180;
// Rotation matrices
const cosAz = Math.cos(azRad);
const sinAz = Math.sin(azRad);
const cosEl = Math.cos(elRad);
const sinEl = Math.sin(elRad);
// Apply rotations
const x1 = x * cosAz - y * sinAz;
const y1 = x * sinAz + y * cosAz;
const z1 = z;
const x2 = x1;
const y2 = y1 * cosEl - z1 * sinEl;
const z2 = y1 * sinEl + z1 * cosEl;
return { x: x2, y: y2, z: z2 };
}
// Sequence configurations
const sequences = {
hahn: {
name: "Hahn Echo",
angles: [90, 90],
flipTimes: [0, 1],
rotFuncs: ['rotx', 'rotx'],
timeRange: [-0.05, 2],
timePoints: 201,
zMax: 0.5,
noSpins: 150,
flipImages: 25,
info: "90° pulse along x-axis, followed by 90° pulse along x-axis"
},
spinecho: {
name: "Spin Echo",
angles: [90, 180],
flipTimes: [0, 1],
rotFuncs: ['rotx', 'roty'],
timeRange: [-0.05, 3.5],
timePoints: 201,
zMax: 0.5,
noSpins: 200,
flipImages: 25,
info: "90° pulse along x-axis, followed by 180° pulse along y-axis"
},
stimulated: {
name: "Stimulated Echo",
angles: [90, 90, 90],
flipTimes: [0, 0.5, 1.5],
rotFuncs: ['rotx', 'rotx', 'rotx'],
timeRange: [-0.05, 3.5],
timePoints: 501,
zMax: 5,
noSpins: 500,
flipImages: 25,
info: "Three 90° pulses along x-axis at different time points"
},
hahn_wide: {
name: "Hahn Echo (Wide Dispersion)",
angles: [90, 90],
flipTimes: [0, 1],
rotFuncs: ['rotx', 'rotx'],
timeRange: [-0.05, 3.5],
timePoints: 501,
zMax: 5,
noSpins: 1500,
flipImages: 25,
info: "90° pulse along x-axis, followed by 90° pulse along x-axis (wide frequency dispersion)"
},
spinecho_wide: {
name: "Spin Echo (Wide Dispersion)",
angles: [90, 180],
flipTimes: [0, 1],
rotFuncs: ['rotx', 'roty'],
timeRange: [-0.05, 3.5],
timePoints: 201,
zMax: 5,
noSpins: 500,
flipImages: 25,
info: "90° pulse along x-axis, followed by 180° pulse along y-axis (wide frequency dispersion)"
}
};
class SpinEvolution {
constructor(opts) {
this.angles = opts.angles;
this.flipTimes = opts.flipTimes;
this.rotFuncs = opts.rotFuncs;
this.t = linspace(opts.timeRange[0], opts.timeRange[1], opts.timePoints);
this.zMax = opts.zMax;
this.zMin = -opts.zMax;
this.noSpins = opts.noSpins;
this.flipImages = opts.flipImages;
this.deltaT = this.t[1] - this.t[0];
this.zPerSec = linspace(this.zMin, this.zMax, this.noSpins);
this.noFlips = this.flipTimes.length;
this.simulate();
}
simulate() {
// Initialize magnetization vectors
this.M = [];
for (let dt = 0; dt < this.t.length; dt++) {
this.M[dt] = [];
for (let i = 0; i < this.noSpins; i++) {
if (dt === 0) {
this.M[dt][i] = [0, 0, 1]; // Initial magnetization along z
} else {
this.M[dt][i] = [0, 0, 0];
}
}
}
// Simulate evolution
for (let dt = 1; dt < this.t.length; dt++) {
for (let i = 0; i < this.noSpins; i++) {
// Apply rotation around z-axis (free precession)
const Rz = rotz(this.zPerSec[i] * 360 * this.deltaT);
this.M[dt][i] = matrixVectorMultiply(Rz, this.M[dt-1][i]);
// Check for RF pulses
for (let flipIdx = 0; flipIdx < this.noFlips; flipIdx++) {
if (Math.abs(this.t[dt] - this.flipTimes[flipIdx]) < this.deltaT / 2) {
const rotFunc = this.rotFuncs[flipIdx];
let R;
switch (rotFunc) {
case 'rotx':
R = rotx(this.angles[flipIdx]);
break;
case 'roty':
R = roty(this.angles[flipIdx]);
break;
case 'rotz':
R = rotz(this.angles[flipIdx]);
break;
}
this.M[dt][i] = matrixVectorMultiply(R, this.M[dt][i]);
}
}
// Normalize to maintain unit length
const mag = Math.sqrt(
this.M[dt][i][0] * this.M[dt][i][0] +
this.M[dt][i][1] * this.M[dt][i][1] +
this.M[dt][i][2] * this.M[dt][i][2]
);
if (mag > 0) {
this.M[dt][i] = this.M[dt][i].map(v => v / mag);
}
}
}
this.createExpandedArrays();
this.calculateSignals();
}
createExpandedArrays() {
this.newM = JSON.parse(JSON.stringify(this.M));
this.newTimeI = [...Array(this.t.length).keys()];
this.rfTracking = new Array(this.t.length).fill(0);
let addedFrames = 0;
for (let dt = 0; dt < this.t.length; dt++) {
for (let flipIdx = 0; flipIdx < this.noFlips; flipIdx++) {
if (Math.abs(this.t[dt] - this.flipTimes[flipIdx]) < this.deltaT / 2) {
const insertIndex = dt + addedFrames;
// Create gradual rotation frames
const rotFunc = this.rotFuncs[flipIdx];
const angleStep = this.angles[flipIdx] / this.flipImages;
let rotID = 0;
switch (rotFunc) {
case 'rotx': rotID = 1; break;
case 'roty': rotID = 2; break;
case 'rotz': rotID = 3; break;
}
// Get the magnetization state BEFORE the RF pulse (from previous time step)
// This is the state after free precession but before RF pulse application
let prePulseMagnetization;
if (dt > 0) {
// Simulate the free precession for this time step without RF pulse
prePulseMagnetization = [];
for (let i = 0; i < this.noSpins; i++) {
const Rz = rotz(this.zPerSec[i] * 360 * this.deltaT);
prePulseMagnetization[i] = matrixVectorMultiply(Rz, this.M[dt-1][i]);
}
} else {
// For dt=0, use the initial magnetization
prePulseMagnetization = JSON.parse(JSON.stringify(this.M[dt]));
}
// Replace the original frame and add gradual rotation frames
for (let j = 0; j < this.flipImages; j++) {
let R;
const currentAngle = angleStep * (j + 1); // Progressive angle
switch (rotFunc) {
case 'rotx':
R = rotx(currentAngle);
break;
case 'roty':
R = roty(currentAngle);
break;
case 'rotz':
R = rotz(currentAngle);
break;
}
// Create new frame with progressive rotation from pre-pulse state
const newFrame = [];
for (let i = 0; i < this.noSpins; i++) {
newFrame[i] = matrixVectorMultiply(R, prePulseMagnetization[i]);
}
if (j === 0) {
// Replace the original frame
this.newM[insertIndex] = newFrame;
this.rfTracking[insertIndex] = rotID;
} else {
// Insert additional frames
this.newM.splice(insertIndex + j, 0, newFrame);
this.newTimeI.splice(insertIndex + j, 0, dt);
this.rfTracking.splice(insertIndex + j, 0, rotID);
}
}
addedFrames += this.flipImages - 1; // -1 because we replaced one frame instead of inserting
break;
}
}
}
}
calculateSignals() {
this.meanSignalY = [];
this.meanSignalX = [];
for (let dt = 0; dt < this.M.length; dt++) {
const yValues = this.M[dt].map(m => m[1]);
const xValues = this.M[dt].map(m => m[0]);
this.meanSignalY.push(mean(yValues));
this.meanSignalX.push(mean(xValues));
}
}
}
class EnhancedCanvas3DRenderer {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.updateSize();
this.scale = 300;
this.azimuth = -25;
this.elevation = -40;
// Mouse/touch interaction variables
this.isDragging = false;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.onViewChange = null; // Callback for when view changes
this.setupInteraction();
}
setupInteraction() {
// Mouse events
this.canvas.addEventListener('mousedown', (e) => {
this.isDragging = true;
this.lastMouseX = e.clientX;
this.lastMouseY = e.clientY;
this.canvas.style.cursor = 'grabbing';
e.preventDefault();
});
this.canvas.addEventListener('mousemove', (e) => {
if (!this.isDragging) return;
const deltaX = e.clientX - this.lastMouseX;
const deltaY = e.clientY - this.lastMouseY;
// Update azimuth and elevation based on mouse movement
this.azimuth += deltaX * 0.5; // Horizontal movement controls azimuth
this.elevation += deltaY * 0.5; // Vertical movement controls elevation
// Keep azimuth in 0-360 range
this.azimuth = ((this.azimuth % 360) + 360) % 360;
// Clamp elevation to -90 to 90 range
this.elevation = Math.max(-90, Math.min(90, this.elevation));
this.lastMouseX = e.clientX;
this.lastMouseY = e.clientY;
// Notify about view change
if (this.onViewChange) {
this.onViewChange(this.azimuth, this.elevation);
}
e.preventDefault();
});
this.canvas.addEventListener('mouseup', () => {
this.isDragging = false;
this.canvas.style.cursor = 'grab';
});
this.canvas.addEventListener('mouseleave', () => {
this.isDragging = false;
this.canvas.style.cursor = 'grab';
});
// Touch events for mobile
this.canvas.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
this.isDragging = true;
this.lastMouseX = e.touches[0].clientX;
this.lastMouseY = e.touches[0].clientY;
e.preventDefault();
}
});
this.canvas.addEventListener('touchmove', (e) => {
if (!this.isDragging || e.touches.length !== 1) return;
const deltaX = e.touches[0].clientX - this.lastMouseX;
const deltaY = e.touches[0].clientY - this.lastMouseY;
// Update azimuth and elevation based on touch movement
this.azimuth += deltaX * 0.5;
this.elevation += deltaY * 0.5;
// Keep azimuth in 0-360 range
this.azimuth = ((this.azimuth % 360) + 360) % 360;
// Clamp elevation to -90 to 90 range
this.elevation = Math.max(-90, Math.min(90, this.elevation));
this.lastMouseX = e.touches[0].clientX;
this.lastMouseY = e.touches[0].clientY;
// Notify about view change
if (this.onViewChange) {
this.onViewChange(this.azimuth, this.elevation);
}
e.preventDefault();
});
this.canvas.addEventListener('touchend', () => {
this.isDragging = false;
});
// Set initial cursor
this.canvas.style.cursor = 'grab';
}
updateSize() {
// Get the display size of the canvas
const rect = this.canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
// Set the canvas size in memory (actual resolution)
this.canvas.width = rect.width * dpr;
this.canvas.height = rect.height * dpr;
// Scale the context to match device pixel ratio
this.ctx.scale(dpr, dpr);
// Set the display size
this.canvas.style.width = rect.width + 'px';
this.canvas.style.height = rect.height + 'px';
this.width = rect.width;
this.height = rect.height;
this.centerX = this.width / 2;
this.centerY = this.height / 2;
}
setViewParameters(azimuth, elevation, scale) {
this.azimuth = azimuth;
this.elevation = elevation;
this.scale = scale;
}
clear() {
this.ctx.clearRect(0, 0, this.width, this.height);
// Create a subtle gradient background
const gradient = this.ctx.createLinearGradient(0, 0, this.width, this.height);
gradient.addColorStop(0, '#fafafa');
gradient.addColorStop(1, '#f0f0f0');
this.ctx.fillStyle = gradient;
this.ctx.fillRect(0, 0, this.width, this.height);
}
drawAxes() {
// X axis (black)
const xEnd = project3D(1.2, 0, 0, this.azimuth, this.elevation);
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 3;
this.ctx.beginPath();
this.ctx.moveTo(this.centerX, this.centerY);
this.ctx.lineTo(this.centerX + xEnd.x * this.scale, this.centerY - xEnd.y * this.scale);
this.ctx.stroke();
// Arrow for X axis
this.drawArrowHead(this.centerX + xEnd.x * this.scale, this.centerY - xEnd.y * this.scale,
Math.atan2(-xEnd.y, xEnd.x), '#000000');
// Y axis (black)
const yEnd = project3D(0, 1.2, 0, this.azimuth, this.elevation);
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 3;
this.ctx.beginPath();
this.ctx.moveTo(this.centerX, this.centerY);
this.ctx.lineTo(this.centerX + yEnd.x * this.scale, this.centerY - yEnd.y * this.scale);
this.ctx.stroke();
this.drawArrowHead(this.centerX + yEnd.x * this.scale, this.centerY - yEnd.y * this.scale,
Math.atan2(-yEnd.y, yEnd.x), '#000000');
// Z axis (black)
const zEnd = project3D(0, 0, 1.2, this.azimuth, this.elevation);
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 3;
this.ctx.beginPath();
this.ctx.moveTo(this.centerX, this.centerY);
this.ctx.lineTo(this.centerX + zEnd.x * this.scale, this.centerY - zEnd.y * this.scale);
this.ctx.stroke();
this.drawArrowHead(this.centerX + zEnd.x * this.scale, this.centerY - zEnd.y * this.scale,
Math.atan2(-zEnd.y, zEnd.x), '#000000');
// Labels
this.ctx.fillStyle = '#333';
this.ctx.font = 'bold 16px Arial';
this.ctx.fillText('X', this.centerX + xEnd.x * this.scale + 15, this.centerY - xEnd.y * this.scale + 5);
this.ctx.fillText('Y', this.centerX + yEnd.x * this.scale + 15, this.centerY - yEnd.y * this.scale + 5);
this.ctx.fillText('Z', this.centerX + zEnd.x * this.scale + 15, this.centerY - zEnd.y * this.scale + 5);
}
drawArrowHead(x, y, angle, color) {
this.ctx.fillStyle = color;
this.ctx.beginPath();
this.ctx.moveTo(x, y);
this.ctx.lineTo(x - 10 * Math.cos(angle - 0.3), y - 10 * Math.sin(angle - 0.3));
this.ctx.lineTo(x - 10 * Math.cos(angle + 0.3), y - 10 * Math.sin(angle + 0.3));
this.ctx.closePath();
this.ctx.fill();
}
drawSpins(spins, rfTracking, zPerSec) {
// Calculate min and max frequencies for normalization
const minFreq = Math.min(...zPerSec);
const maxFreq = Math.max(...zPerSec);
const freqRange = maxFreq - minFreq;
// Create surface patches first (behind the arrows)
this.drawSpinSurface(spins, zPerSec, minFreq, maxFreq, freqRange);
// Sort spins by z-depth for proper rendering of arrows
const spinData = [];
for (let i = 0; i < spins.length; i += 3) { // Draw every 3rd spin for better performance
const spin = spins[i];
const proj = project3D(spin[0], spin[1], spin[2], this.azimuth, this.elevation);
spinData.push({ spin, proj, index: i });
}
// Sort by z-depth (render back to front)
spinData.sort((a, b) => a.proj.z - b.proj.z);
// Draw spin vectors as lines with arrows
spinData.forEach(({ spin, proj, index }) => {
// Color based on precession frequency (faster = red, slower = blue)
if (index < zPerSec.length && freqRange > 0) {
const normalizedFreq = (zPerSec[index] - minFreq) / freqRange;
// Red for fast (high frequency), Blue for slow (low frequency)
const red = Math.round(255 * normalizedFreq);
const blue = Math.round(255 * (1 - normalizedFreq));
// Vary lightness based on depth for better 3D effect
const lightnessFactor = 0.7 + (proj.z + 1) * 0.15; // Range from 0.7 to 1.0
const adjustedRed = Math.round(red * lightnessFactor);
const adjustedBlue = Math.round(blue * lightnessFactor);
this.ctx.strokeStyle = `rgb(${adjustedRed}, 0, ${adjustedBlue})`;
} else {
// Fallback to a purple color if frequency data is unavailable
this.ctx.strokeStyle = '#8844cc';
}
this.ctx.lineWidth = 2;
this.ctx.beginPath();
this.ctx.moveTo(this.centerX, this.centerY);
this.ctx.lineTo(
this.centerX + proj.x * this.scale,
this.centerY - proj.y * this.scale
);
this.ctx.stroke();
// Draw arrowhead
const endX = this.centerX + proj.x * this.scale;
const endY = this.centerY - proj.y * this.scale;
const angle = Math.atan2(-proj.y, proj.x);
this.ctx.fillStyle = this.ctx.strokeStyle;
this.ctx.beginPath();
this.ctx.moveTo(endX, endY);
this.ctx.lineTo(endX - 8 * Math.cos(angle - 0.3), endY - 8 * Math.sin(angle - 0.3));
this.ctx.lineTo(endX - 8 * Math.cos(angle + 0.3), endY - 8 * Math.sin(angle + 0.3));
this.ctx.closePath();
this.ctx.fill();
});
// Draw RF pulse indicator
if (rfTracking > 0) {
let arrowPos, arrowColor, axisName;
switch (rfTracking) {
case 1: // X-axis
arrowPos = project3D(1, 0, 0, this.azimuth, this.elevation);
arrowColor = '#ff0000';
axisName = 'X';
break;
case 2: // Y-axis
arrowPos = project3D(0, 1, 0, this.azimuth, this.elevation);
arrowColor = '#00ff00';
axisName = 'Y';
break;
case 3: // Z-axis
arrowPos = project3D(0, 0, 1, this.azimuth, this.elevation);
arrowColor = '#0000ff';
axisName = 'Z';
break;
}
// Draw wide green RF pulse arrow
this.drawWideRFArrow(arrowPos, axisName);
// Pulsing RF indicator (smaller circle now)
const pulseIntensity = Math.sin(Date.now() * 0.01) * 0.3 + 0.7;
this.ctx.fillStyle = arrowColor;
this.ctx.globalAlpha = pulseIntensity;
this.ctx.beginPath();
this.ctx.arc(
this.centerX + arrowPos.x * this.scale * 1.4,
this.centerY - arrowPos.y * this.scale * 1.4,
15, 0, 2 * Math.PI
);
this.ctx.fill();
this.ctx.globalAlpha = 1;
this.ctx.fillStyle = 'white';
this.ctx.font = 'bold 10px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText('RF',
this.centerX + arrowPos.x * this.scale * 1.4,
this.centerY - arrowPos.y * this.scale * 1.4 + 3
);
// RF axis label
this.ctx.fillStyle = arrowColor;
this.ctx.font = 'bold 12px Arial';
this.ctx.fillText(`RF-${axisName}`,
this.centerX + arrowPos.x * this.scale * 1.4,
this.centerY - arrowPos.y * this.scale * 1.4 + 30
);
}
}
drawWideRFArrow(arrowPos, axisName) {
// Calculate arrow start and end positions
const arrowLength = this.scale * 0.8; // Make arrow shorter than axis
const startX = this.centerX + arrowPos.x * this.scale * 0.2;
const startY = this.centerY - arrowPos.y * this.scale * 0.2;
const endX = this.centerX + arrowPos.x * this.scale * 1.0;
const endY = this.centerY - arrowPos.y * this.scale * 1.0;
// Arrow shaft
this.ctx.strokeStyle = '#00AA00'; // Bright green
this.ctx.lineWidth = 12; // Wide arrow shaft
this.ctx.lineCap = 'round';
this.ctx.beginPath();
this.ctx.moveTo(startX, startY);
this.ctx.lineTo(endX - arrowPos.x * this.scale * 0.15, endY + arrowPos.y * this.scale * 0.15);
this.ctx.stroke();
// Arrow head (wide triangle)
const angle = Math.atan2(-arrowPos.y, arrowPos.x);
const headLength = 25;
const headWidth = 15;
this.ctx.fillStyle = '#00AA00'; // Same bright green
this.ctx.beginPath();
this.ctx.moveTo(endX, endY);
this.ctx.lineTo(
endX - headLength * Math.cos(angle - Math.PI/6),
endY - headLength * Math.sin(angle - Math.PI/6)
);
this.ctx.lineTo(
endX - headLength * 0.7 * Math.cos(angle),
endY - headLength * 0.7 * Math.sin(angle)
);
this.ctx.lineTo(
endX - headLength * Math.cos(angle + Math.PI/6),
endY - headLength * Math.sin(angle + Math.PI/6)
);
this.ctx.closePath();
this.ctx.fill();
// Add white outline to make it more visible
this.ctx.strokeStyle = 'white';
this.ctx.lineWidth = 2;
this.ctx.stroke();
// RF pulse label on the arrow
this.ctx.fillStyle = 'white';
this.ctx.font = 'bold 14px Arial';
this.ctx.textAlign = 'center';
this.ctx.strokeStyle = '#00AA00';
this.ctx.lineWidth = 3;
const labelX = startX + (endX - startX) * 0.5;
const labelY = startY + (endY - startY) * 0.5 - 5;
this.ctx.strokeText(`RF ${axisName}`, labelX, labelY);
this.ctx.fillText(`RF ${axisName}`, labelX, labelY);
}
drawSpinSurface(spins, zPerSec, minFreq, maxFreq, freqRange) {
// Create surface patches that follow the actual 3D spin distribution
// Similar to MATLAB's approach: create triangles from origin to consecutive spins
// Sample fewer spins for surface to improve performance
const surfaceSpins = [];
for (let i = 0; i < spins.length; i += 4) { // Every 4th spin
const spin = spins[i];
const proj = project3D(spin[0], spin[1], spin[2], this.azimuth, this.elevation);
// Calculate color based on frequency
let color;
if (i < zPerSec.length && freqRange > 0) {
const normalizedFreq = (zPerSec[i] - minFreq) / freqRange;
const red = Math.round(255 * normalizedFreq);
const blue = Math.round(255 * (1 - normalizedFreq));
const alpha = 0.3; // Semi-transparent surface
color = `rgba(${red}, 0, ${blue}, ${alpha})`;
} else {
color = 'rgba(136, 68, 204, 0.3)'; // fallback purple
}
surfaceSpins.push({
x: this.centerX + proj.x * this.scale,
y: this.centerY - proj.y * this.scale,
z: proj.z,
color: color,
originalIndex: i
});
}
// Origin point
const origin = {
x: this.centerX,
y: this.centerY,
z: 0
};
// Create triangular patches connecting consecutive spins through the origin
// This follows the MATLAB approach - no forced closure, let the surface be naturally open
for (let i = 0; i < surfaceSpins.length - 1; i++) {
const spin1 = surfaceSpins[i];
const spin2 = surfaceSpins[i + 1];
// Create triangle: origin -> spin1 -> spin2
this.ctx.beginPath();
this.ctx.moveTo(origin.x, origin.y);
this.ctx.lineTo(spin1.x, spin1.y);
this.ctx.lineTo(spin2.x, spin2.y);
this.ctx.closePath();
// Use the color from the first spin of the triangle
this.ctx.fillStyle = spin1.color;
this.ctx.fill();
}
// Note: No closure connection - let the surface remain naturally open
// This allows the surface to properly represent the frequency distribution
// without artificial connections between distant frequency spins