-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsm_sim.html
More file actions
1770 lines (1531 loc) · 73.2 KB
/
Copy pathsm_sim.html
File metadata and controls
1770 lines (1531 loc) · 73.2 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>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-J23ES8WVTN"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-J23ES8WVTN');
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-Photon Imaging Simulator</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
color: #e0e0e0;
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
h1 {
text-align: center;
color: #00d4ff;
margin-bottom: 10px;
font-size: 2em;
}
.subtitle {
text-align: center;
color: #888;
margin-bottom: 30px;
font-size: 0.9em;
}
.main-grid {
display: grid;
grid-template-columns: 600px 1fr 400px;
gap: 20px;
margin-bottom: 20px;
}
.middle-panel {
display: flex;
flex-direction: column;
gap: 20px;
}
.kymograph-panel {
background: rgba(255, 255, 255, 0.05);
border-radius: 12px;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
display: none;
}
.kymograph-panel.active {
display: block;
}
.kymograph-panel h3 {
color: #00d4ff;
margin-bottom: 15px;
}
.image-upload-section {
margin-bottom: 15px;
padding: 15px;
background: rgba(255, 255, 255, 0.03);
border-radius: 8px;
}
.image-upload-section label {
display: block;
margin-bottom: 10px;
color: #aaa;
}
.image-preset-buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.preset-btn {
padding: 8px 12px;
font-size: 0.85em;
background: rgba(255, 255, 255, 0.1);
}
.preset-btn.active {
background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%);
}
.imaging-panel {
background: rgba(255, 255, 255, 0.05);
border-radius: 12px;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.canvas-container {
position: relative;
background: #000;
border-radius: 8px;
margin-bottom: 15px;
box-shadow: 0 0 20px rgba(0, 212, 255, 0.3);
}
canvas {
display: block;
border-radius: 8px;
cursor: crosshair;
}
.controls-panel {
background: rgba(255, 255, 255, 0.05);
border-radius: 12px;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.control-section {
margin-bottom: 25px;
padding-bottom: 20px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.control-section:last-child {
border-bottom: none;
}
.control-section h3 {
color: #00d4ff;
margin-bottom: 15px;
font-size: 1.1em;
}
.scan-mode-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 15px;
}
button {
background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%);
color: white;
border: none;
padding: 12px 20px;
border-radius: 6px;
cursor: pointer;
font-size: 0.95em;
font-weight: 600;
transition: all 0.3s ease;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 212, 255, 0.4);
}
button.active {
background: linear-gradient(135deg, #ff6b6b 0%, #cc5555 100%);
}
button:disabled {
background: #333;
cursor: not-allowed;
transform: none;
}
.slider-group {
margin-bottom: 15px;
}
.slider-group label {
display: block;
margin-bottom: 8px;
color: #aaa;
font-size: 0.9em;
}
.slider-group input[type="range"] {
width: 100%;
height: 6px;
background: rgba(255, 255, 255, 0.1);
border-radius: 3px;
outline: none;
}
.slider-group input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 16px;
height: 16px;
background: #00d4ff;
cursor: pointer;
border-radius: 50%;
}
.slider-value {
display: inline-block;
float: right;
color: #00d4ff;
font-weight: 600;
}
.stimulus-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.info-box {
background: rgba(0, 212, 255, 0.1);
border-left: 3px solid #00d4ff;
padding: 15px;
margin-top: 15px;
border-radius: 4px;
font-size: 0.85em;
line-height: 1.6;
}
.trace-display {
background: rgba(255, 255, 255, 0.05);
border-radius: 12px;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.trace-display h3 {
color: #00d4ff;
margin-bottom: 15px;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 15px;
}
.stat-box {
background: rgba(255, 255, 255, 0.05);
padding: 10px;
border-radius: 6px;
text-align: center;
}
.stat-label {
color: #888;
font-size: 0.8em;
margin-bottom: 5px;
}
.stat-value {
color: #00d4ff;
font-size: 1.3em;
font-weight: 600;
}
.legend {
display: flex;
justify-content: center;
gap: 20px;
margin-top: 15px;
font-size: 0.85em;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
}
.legend-color {
width: 20px;
height: 20px;
border-radius: 3px;
}
@media (max-width: 1200px) {
.main-grid {
grid-template-columns: 1fr;
}
}
</style>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-light bg-white shadow-sm mb-3">
<div class="container">
<a class="navbar-brand fw-bold" href="index.html">SignalLab</a>
<span class="navbar-text d-none d-md-inline">
Interactive experiments in cell and neural signalling
</span>
</div>
</nav>
<div class="container">
<h1>2-Photon Imaging Simulator</h1>
<p class="subtitle">Explore how scanning patterns affect neural signal detection</p>
<div class="main-grid">
<div class="imaging-panel">
<div class="image-upload-section">
<label>Select Image:</label>
<div class="image-preset-buttons">
<button id="dendritesBtn" class="preset-btn active">Dendrites</button>
<button id="axonsBtn" class="preset-btn">Axons</button>
<button id="widefieldBtn" class="preset-btn">Wide Field</button>
</div>
</div>
<div class="canvas-container">
<canvas id="imagingCanvas" width="600" height="600"></canvas>
</div>
<div class="control-section" style="margin-top: 15px; padding: 15px; background: rgba(255, 255, 255, 0.05); border-radius: 8px;">
<h3>Trigger Neural Activity</h3>
<div class="stimulus-buttons">
<button id="apBtn">Single AP</button>
<button id="burstBtn">AP Burst</button>
<button id="waveBtn">Ca²⁺ Wave</button>
<button id="clearBtn">Clear Activity</button>
</div>
</div>
<div class="legend">
<div class="legend-item">
<div class="legend-color" style="background: #000;"></div>
<span>Background (low photons)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #0ff;"></div>
<span>Neural structure (high photons)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #f0f;"></div>
<span>Active region</span>
</div>
</div>
</div>
<div class="middle-panel">
<div class="trace-display">
<h3>Fluorescence Signal Trace</h3>
<canvas id="traceCanvas" width="500" height="200"></canvas>
</div>
<div class="kymograph-panel" id="kymographPanel">
<h3>Line Scan Kymograph</h3>
<canvas id="kymographCanvas" width="500" height="300"></canvas>
<div class="info-box" style="margin-top: 10px; font-size: 0.8em;">
<span id="kymographInfo">Time flows left to right. Each vertical line is one scan. Multiple line scans are stacked vertically with labels.</span>
</div>
</div>
</div>
<div class="controls-panel">
<div class="control-section">
<h3>Scan Mode</h3>
<div class="scan-mode-buttons">
<button id="rasterBtn" class="active">Raster Scan</button>
<button id="lineBtn">Line Scan</button>
</div>
<div class="info-box" id="modeInfo">
<strong>Raster Scan:</strong> Scans entire field of view. Best for spatial mapping and slow signals. Click to start scanning.
</div>
</div>
<div class="control-section">
<h3>Scan Parameters</h3>
<div class="slider-group">
<label>
<span id="speedLabel">Lines per Second</span>
<span class="slider-value" id="speedValue">10</span>
</label>
<input type="range" id="speedSlider" min="1" max="100" value="10">
</div>
<div class="slider-group" id="lineWidthControl" style="display:none;">
<label>
Line Width (pixels)
<span class="slider-value" id="widthValue">5</span>
</label>
<input type="range" id="widthSlider" min="1" max="20" value="5">
</div>
<button id="clearLinesBtn" style="display:none; width: 100%; margin-top: 10px;">Clear Lines</button>
</div>
<div class="control-section">
<h3>Statistics</h3>
<div class="stats">
<div class="stat-box">
<div class="stat-label">Frame Time</div>
<div class="stat-value" id="tempResValue">0 ms</div>
</div>
<div class="stat-box">
<div class="stat-label">Spatial Coverage</div>
<div class="stat-value" id="spatialValue">100%</div>
</div>
<div class="stat-box">
<div class="stat-label">Total Photons</div>
<div class="stat-value" id="photonValue">0</div>
</div>
<div class="stat-box">
<div class="stat-label">SNR</div>
<div class="stat-value" id="snrValue">0</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
/*
====================================================================
IMAGE LOADING INSTRUCTIONS
====================================================================
To load real 2-photon microscopy images instead of synthetic structures:
1. SUPPORTED FILE TYPES:
- PNG (.png) - Recommended, widely supported
- JPEG (.jpg, .jpeg) - Good for photos
- GIF (.gif) - Supported
- BMP (.bmp) - Supported
- WebP (.webp) - Modern format
- SVG (.svg) - Vector graphics
Note: TIFF (.tif, .tiff) is NOT directly supported by browsers.
You'll need to convert TIFF to PNG first.
2. GRID SIZE AND PERFORMANCE:
The gridSize variable (currently 100) controls resolution:
- 60x60 = 3,600 pixels (faster, lower resolution)
- 100x100 = 10,000 pixels (balanced - current default)
- 120x120 = 14,400 pixels (slower, higher resolution)
- 200x200 = 40,000 pixels (slowest, very high resolution)
Modern browsers can handle 100x100 easily. Increase if you want
better spatial resolution. Change line ~490: const gridSize = 100;
3. ACTIVITY MASKING (WHERE SIGNALS OCCUR):
Option A - Automatic Detection (Default):
When you load an image, bright regions (intensity > 100) are
automatically detected and used as activity locations.
Option B - Load Separate Mask File:
Create a binary mask image (white = activity regions, black = ignore)
and load it with:
loadImageFromPath('my_image.png');
loadMaskImage('my_mask.png'); // Optional mask file
The mask should have white pixels where you want signals to occur.
4. HOW TO ADD YOUR IMAGES:
Option A - Local files in same directory:
Uncomment the loadImageFromPath() line and use:
loadImageFromPath('dendrites.png');
Option B - Images in a subfolder:
loadImageFromPath('images/dendrites.png');
Option C - External URL:
loadImageFromPath('https://example.com/images/dendrites.png');
Option D - With separate mask:
loadImageFromPath('images/neurons.png');
loadMaskImage('images/neurons_mask.png');
5. IMAGE REQUIREMENTS:
- Images will be automatically scaled to gridSize × gridSize
- Converted to grayscale (R+G+B)/3
- Intensity mapped to photon counts (10-150)
- Higher pixel intensity = higher photon counts
- Bright regions automatically become activity sites
6. EXAMPLE USAGE:
Find the preset button handlers below (lines ~1350+)
Uncomment the loadImageFromPath() line and provide your path:
document.getElementById('dendritesBtn').addEventListener('click', () => {
currentImageType = 'dendrites';
loadImageFromPath('my_dendrite_image.png');
// Optional: loadMaskImage('dendrite_mask.png');
...
});
====================================================================
*/
// Canvas setup
const canvas = document.getElementById('imagingCanvas');
const ctx = canvas.getContext('2d');
const traceCanvas = document.getElementById('traceCanvas');
const traceCtx = traceCanvas.getContext('2d');
const kymographCanvas = document.getElementById('kymographCanvas');
const kymographCtx = kymographCanvas.getContext('2d');
// Simulation parameters
const gridSize = 100; // Increased from 60 - can be adjusted (60, 80, 100, 120, etc.)
const pixelSize = canvas.width / gridSize;
let photonCounts = Array(gridSize).fill(0).map(() => Array(gridSize).fill(0));
let basePhotonCounts = Array(gridSize).fill(0).map(() => Array(gridSize).fill(0));
let structures = [];
let scanMode = 'raster';
let isScanning = false;
let scanPosition = { x: 0, y: 0 };
let lineScanStart = null;
let lineScanEnd = null;
let lineScanWidth = 5;
let scanSpeed = 10; // lines per second
let lastFrameTime = 0;
// ROI for raster scan
let rasterROI = null;
let isSelectingROI = false;
let roiStart = null;
// Line scan selection
let isSelectingLine = false;
let multipleLineScans = []; // Array of {start: {x, y}, end: {x, y}}
let currentLinePreview = null; // Currently drawing line
// Signal recording
let signalTrace = [];
let traceTimeStamps = []; // Time in ms for each trace point
let lineTraces = []; // Separate trace for each line: [{lineIndex: 0, time: ..., value: ...}, ...]
let maxTracePoints = 500;
let activityMap = Array(gridSize).fill(0).map(() => Array(gridSize).fill(0));
// Frame accumulation for raster scans
let currentFrameSum = 0;
let currentFramePixels = 0;
// Activity events for rug plot
let activityEvents = []; // Store timestamps of activity triggers in ms
let scanStartTime = 0; // When scanning started (timestamp)
let maxTraceTimeWindow = 30000; // Show last 30 seconds
// Kymograph data
let kymographData = [];
let maxKymographLines = 300;
// Image upload
let uploadedImage = null;
let useUploadedImage = false;
let currentImageType = 'dendrites'; // 'dendrites', 'axons', or 'widefield'
// Initialize structures (dendrites/axons)
function initializeStructures() {
structures = [];
if (currentImageType === 'dendrites') {
// Create some dendrites
for (let i = 0; i < 5; i++) {
const startX = Math.random() * gridSize;
const startY = Math.random() * gridSize;
const angle = Math.random() * Math.PI * 2;
const length = 20 + Math.random() * 30;
const thickness = 1 + Math.random() * 2;
structures.push({
type: 'dendrite',
startX, startY, angle, length, thickness
});
}
} else if (currentImageType === 'axons') {
// Create more axons - thinner, longer
for (let i = 0; i < 8; i++) {
const startX = Math.random() * gridSize;
const startY = Math.random() * gridSize;
const angle = Math.random() * Math.PI * 2;
const length = 30 + Math.random() * 40;
structures.push({
type: 'axon',
startX, startY, angle, length, thickness: 0.8
});
}
} else if (currentImageType === 'widefield') {
// Create a field with many small structures
for (let i = 0; i < 30; i++) {
const startX = Math.random() * gridSize;
const startY = Math.random() * gridSize;
const angle = Math.random() * Math.PI * 2;
const length = 5 + Math.random() * 15;
const thickness = 0.5 + Math.random() * 1;
structures.push({
type: 'dendrite',
startX, startY, angle, length, thickness
});
}
}
createBasePhotonCounts();
}
function createBasePhotonCounts() {
// Reset to baseline
for (let y = 0; y < gridSize; y++) {
for (let x = 0; x < gridSize; x++) {
basePhotonCounts[y][x] = 10 + Math.random() * 5; // Background
}
}
// Add structure signal
structures.forEach(struct => {
const steps = Math.floor(struct.length * 2);
for (let i = 0; i < steps; i++) {
const t = i / steps;
const x = Math.floor(struct.startX + Math.cos(struct.angle) * struct.length * t);
const y = Math.floor(struct.startY + Math.sin(struct.angle) * struct.length * t);
if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) {
const baseSignal = struct.type === 'dendrite' ? 100 : 80;
basePhotonCounts[y][x] = baseSignal;
// Add thickness
const thickness = Math.floor(struct.thickness);
for (let dy = -thickness; dy <= thickness; dy++) {
for (let dx = -thickness; dx <= thickness; dx++) {
const nx = x + dx;
const ny = y + dy;
if (nx >= 0 && nx < gridSize && ny >= 0 && ny < gridSize) {
if (basePhotonCounts[ny][nx] < baseSignal) {
basePhotonCounts[ny][nx] = baseSignal;
}
}
}
}
}
}
});
updatePhotonCounts();
}
function updatePhotonCounts() {
// Reset to baseline
for (let y = 0; y < gridSize; y++) {
for (let x = 0; x < gridSize; x++) {
photonCounts[y][x] = basePhotonCounts[y][x];
}
}
// Add activity
for (let y = 0; y < gridSize; y++) {
for (let x = 0; x < gridSize; x++) {
const activity = (activityMap[y] && activityMap[y][x]) ? activityMap[y][x] : 0;
photonCounts[y][x] += activity;
}
}
}
function initializeFromImage(img) {
const tempCanvas = document.createElement('canvas');
tempCanvas.width = gridSize;
tempCanvas.height = gridSize;
const tempCtx = tempCanvas.getContext('2d');
// Draw and scale image
tempCtx.drawImage(img, 0, 0, gridSize, gridSize);
const imageData = tempCtx.getImageData(0, 0, gridSize, gridSize);
// Convert to photon counts based on intensity
structures = []; // Clear synthetic structures
const brightnessThreshold = 100; // Detect bright regions
for (let y = 0; y < gridSize; y++) {
for (let x = 0; x < gridSize; x++) {
const idx = (y * gridSize + x) * 4;
const r = imageData.data[idx];
const g = imageData.data[idx + 1];
const b = imageData.data[idx + 2];
// Convert to grayscale and map to photon counts (10-150 range)
const intensity = (r + g + b) / 3;
basePhotonCounts[y][x] = 10 + (intensity / 255) * 140;
// Detect bright regions for activity (every 10th pixel to avoid too many)
if (intensity > brightnessThreshold && x % 10 === 0 && y % 10 === 0) {
structures.push({
type: 'detected',
startX: x,
startY: y,
angle: 0,
length: 5,
thickness: 2
});
}
}
}
console.log(`Detected ${structures.length} activity regions in image`);
updatePhotonCounts();
}
function loadMaskImage(maskPath) {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
const tempCanvas = document.createElement('canvas');
tempCanvas.width = gridSize;
tempCanvas.height = gridSize;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(img, 0, 0, gridSize, gridSize);
const imageData = tempCtx.getImageData(0, 0, gridSize, gridSize);
structures = [];
// Extract structures from mask (bright pixels = activity locations)
const sampleInterval = 5; // Sample every 5 pixels
const threshold = 100; // Brightness threshold
for (let y = 0; y < gridSize; y += sampleInterval) {
for (let x = 0; x < gridSize; x += sampleInterval) {
const idx = (y * gridSize + x) * 4;
const intensity = (imageData.data[idx] + imageData.data[idx + 1] + imageData.data[idx + 2]) / 3;
if (intensity > threshold) {
structures.push({
type: 'masked',
startX: x,
startY: y,
thickness: 3
});
}
}
}
console.log(`Loaded ${structures.length} activity regions from mask`);
console.log(`Sample region: x=${structures[0]?.startX}, y=${structures[0]?.startY}`);
console.log(`Mask threshold: ${threshold}, Sample interval: ${sampleInterval} pixels`);
if (structures.length === 0) {
console.warn('Mask loaded but no bright regions found. Check mask brightness.');
}
};
img.onerror = () => {
console.error('Failed to load mask from:', maskPath);
alert(`Failed to load mask: ${maskPath}`);
};
img.src = maskPath;
}
function drawImaging() {
// Draw photon count map
for (let y = 0; y < gridSize; y++) {
for (let x = 0; x < gridSize; x++) {
const value = photonCounts[y][x] || 0;
const activity = (activityMap[y] && activityMap[y][x]) ? activityMap[y][x] : 0;
const intensity = Math.min(255, value * 1.5);
if (activity > 0) {
// Active regions in magenta
ctx.fillStyle = `rgb(${intensity}, ${intensity * 0.3}, ${intensity})`;
} else if (value > 50) {
// Structures in cyan
ctx.fillStyle = `rgb(${intensity * 0.3}, ${intensity}, ${intensity})`;
} else {
// Background
ctx.fillStyle = `rgb(${intensity * 0.3}, ${intensity * 0.3}, ${intensity * 0.3})`;
}
ctx.fillRect(x * pixelSize, y * pixelSize, pixelSize, pixelSize);
}
}
// Draw ROI selection for raster scan
if (scanMode === 'raster' && rasterROI) {
ctx.strokeStyle = 'rgba(255, 255, 0, 0.8)';
ctx.lineWidth = 3;
ctx.strokeRect(
rasterROI.x * pixelSize,
rasterROI.y * pixelSize,
rasterROI.width * pixelSize,
rasterROI.height * pixelSize
);
// Draw current scan line within ROI
if (isScanning) {
const y = (rasterROI.y + scanPosition.y) * pixelSize;
ctx.strokeStyle = 'rgba(255, 255, 0, 1)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(rasterROI.x * pixelSize, y);
ctx.lineTo((rasterROI.x + rasterROI.width) * pixelSize, y);
ctx.stroke();
}
}
// Draw line scan
if (scanMode === 'line') {
// Draw all finalized line scans
multipleLineScans.forEach((lineScan, index) => {
ctx.strokeStyle = isScanning ? 'rgba(255, 255, 0, 0.8)' : 'rgba(255, 255, 0, 0.5)';
ctx.lineWidth = lineScanWidth * pixelSize;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(lineScan.start.x * pixelSize, lineScan.start.y * pixelSize);
ctx.lineTo(lineScan.end.x * pixelSize, lineScan.end.y * pixelSize);
ctx.stroke();
// Draw direction arrow for each line
const angle = Math.atan2(
lineScan.end.y - lineScan.start.y,
lineScan.end.x - lineScan.start.x
);
const arrowSize = 10;
ctx.fillStyle = isScanning ? 'rgba(255, 255, 0, 0.8)' : 'rgba(255, 255, 0, 0.5)';
ctx.beginPath();
ctx.moveTo(lineScan.end.x * pixelSize, lineScan.end.y * pixelSize);
ctx.lineTo(
lineScan.end.x * pixelSize - arrowSize * Math.cos(angle - Math.PI / 6),
lineScan.end.y * pixelSize - arrowSize * Math.sin(angle - Math.PI / 6)
);
ctx.lineTo(
lineScan.end.x * pixelSize - arrowSize * Math.cos(angle + Math.PI / 6),
lineScan.end.y * pixelSize - arrowSize * Math.sin(angle + Math.PI / 6)
);
ctx.closePath();
ctx.fill();
// Draw line number
ctx.fillStyle = 'rgba(255, 255, 0, 0.9)';
ctx.font = '14px sans-serif';
const midX = (lineScan.start.x + lineScan.end.x) / 2 * pixelSize;
const midY = (lineScan.start.y + lineScan.end.y) / 2 * pixelSize;
ctx.fillText(`${index + 1}`, midX - 5, midY - 5);
});
// Draw current line being drawn
if (currentLinePreview && roiStart) {
ctx.strokeStyle = 'rgba(255, 255, 0, 0.3)';
ctx.lineWidth = lineScanWidth * pixelSize;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(roiStart.x, roiStart.y);
ctx.lineTo(roiStart.currentX || roiStart.x, roiStart.currentY || roiStart.y);
ctx.stroke();
}
}
// Draw ROI selection in progress
if (isSelectingROI && roiStart && scanMode === 'raster') {
ctx.strokeStyle = 'rgba(255, 255, 0, 0.5)';
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
const mouseX = roiStart.currentX || roiStart.x;
const mouseY = roiStart.currentY || roiStart.y;
ctx.strokeRect(
roiStart.x,
roiStart.y,
mouseX - roiStart.x,
mouseY - roiStart.y
);
ctx.setLineDash([]);
}
}
function updateScan(timestamp) {
if (!isScanning) return;
const frameTime = 1000 / scanSpeed; // ms per line
if (timestamp - lastFrameTime < frameTime) {
return;
}
lastFrameTime = timestamp;
if (scanMode === 'raster' && rasterROI) {
// Raster scan within ROI
const actualY = rasterROI.y + scanPosition.y;
// Accumulate signal from this line
for (let x = rasterROI.x; x < rasterROI.x + rasterROI.width; x++) {
if (actualY >= 0 && actualY < gridSize && x >= 0 && x < gridSize) {
currentFrameSum += photonCounts[actualY][x] || 0;
currentFramePixels++;
}
}
// Move to next line
scanPosition.y = (scanPosition.y + 1) % rasterROI.height;
// If we completed a full frame (returned to top), record the frame sum
if (scanPosition.y === 0) {
const currentTime = timestamp - scanStartTime;
signalTrace.push(currentFrameSum);
traceTimeStamps.push(currentTime);
currentFrameSum = 0;
currentFramePixels = 0;
}
} else if (scanMode === 'line' && multipleLineScans.length > 0) {
// Multi-line scan - sample all lines sequentially
const lineIndex = scanPosition.x % multipleLineScans.length;
const currentLine = multipleLineScans[lineIndex];
const dx = currentLine.end.x - currentLine.start.x;
const dy = currentLine.end.y - currentLine.start.y;
const length = Math.sqrt(dx * dx + dy * dy);
const steps = Math.ceil(length);
let lineData = [];
let lineSum = 0;
// Sample along the line
for (let i = 0; i < steps; i++) {
const t = i / steps;
const x = Math.floor(currentLine.start.x + dx * t);
const y = Math.floor(currentLine.start.y + dy * t);
// Sample perpendicular to line for width
const perpAngle = Math.atan2(dy, dx) + Math.PI / 2;
const halfWidth = Math.floor(lineScanWidth / 2);
let pixelSum = 0;
let pixelCount = 0;
for (let w = -halfWidth; w <= halfWidth; w++) {
const px = Math.floor(x + Math.cos(perpAngle) * w);
const py = Math.floor(y + Math.sin(perpAngle) * w);
if (px >= 0 && px < gridSize && py >= 0 && py < gridSize) {
pixelSum += photonCounts[py][px] || 0;
pixelCount++;
}
}
if (pixelCount > 0) {
const pixelValue = pixelSum / pixelCount;
lineData.push(pixelValue);
lineSum += pixelValue;
}
}
// Record the total sum with timestamp and line index
const currentTime = timestamp - scanStartTime;
signalTrace.push(lineSum);
traceTimeStamps.push(currentTime);
lineTraces.push({
lineIndex: lineIndex,
time: currentTime,
value: lineSum
});
// Add to kymograph with line index
kymographData.push({
lineIndex: lineIndex,
data: lineData,
time: currentTime
});
if (kymographData.length > maxKymographLines) {
kymographData.shift();
}
// Move to next line
scanPosition.x = (scanPosition.x + 1) % multipleLineScans.length;
}
// Trim old data outside time window
while (traceTimeStamps.length > 0 &&
traceTimeStamps[traceTimeStamps.length - 1] - traceTimeStamps[0] > maxTraceTimeWindow) {
signalTrace.shift();
traceTimeStamps.shift();
if (lineTraces.length > 0) {
lineTraces.shift();
}
}
// Remove old activity events outside time window
const currentTime = timestamp - scanStartTime;
activityEvents = activityEvents.filter(t => currentTime - t < maxTraceTimeWindow);
updateStats();
}
function drawKymograph() {
if (scanMode !== 'line' || kymographData.length === 0) return;