Repository navigation
Expand file tree
/
Copy pathecm_visualizer.js
More file actions
1857 lines (1554 loc) · 77.4 KB
/
Copy pathecm_visualizer.js
File metadata and controls
1857 lines (1554 loc) · 77.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
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
class ECMVisualizer {
constructor() {
this.gridSize = 100;
this.currentMoleculeIndex = 0; // proCI by default
this.simulationRunning = false;
this.iteration = 0;
this.currentTime = 0.0; // ADDED: Missing property initialization
this.dataBuffer = null;
this.timeStep = 0.1; // Default time step for ODE integration
// For visualization range (needed for text display)
this.minValue = 0.1; // ADDED: Default values
this.maxValue = 0.9; // ADDED: Default values
this.brushSelectedCells = 0; // ADDED: Missing property
// Individual cell selection for tracking (NOT for input)
this.cellSelectionMode = false;
this.trackedCells = []; // Array of {row, col, color} objects for line plot tracking
// Publication-quality colorblind-safe palette (Wong, Nature Methods 2011)
this.cellColors = ['#0072B2', '#D55E00', '#009E73', '#CC79A7', '#E69F00', '#56B4E9', '#F0E442', '#000000'];
// Track modified values for selected cells
this.modifiedCellValues = {};
// Brush selection properties (for input molecules)
this.brushMode = false;
this.brushSize = 5; // Brush radius in cells
this.selectedCellsForInput = new Set(); // Stores "row,col" strings of selected cells
this.isMouseDown = false;
this.lastMousePos = null;
// Define molecule mappings
this.ecmMolecules = [
{name: 'proCI', index: 0},
{name: 'proCIII', index: 1},
{name: 'fibronectin', index: 2},
{name: 'periostin', index: 3},
{name: 'TNC', index: 4},
{name: 'PAI1', index: 5},
{name: 'CTGF', index: 6},
{name: 'EDAFN', index: 7},
{name: 'TIMP1', index: 8},
{name: 'TIMP2', index: 9},
{name: 'proMMP1', index: 10},
{name: 'proMMP2', index: 11},
{name: 'proMMP3', index: 12},
{name: 'proMMP8', index: 13},
{name: 'proMMP9', index: 14},
{name: 'proMMP12', index: 15},
{name: 'proMMP14', index: 16}
];
this.fbMolecules = [
{name: 'TGFBfb', index: 0},
{name: 'AngIIfb', index: 1},
{name: 'IL6fb', index: 2},
{name: 'ET1fb', index: 3},
];
this.inputMolecules = [
{name: 'AngIIin', index: 0},
{name: 'TGFBin', index: 1},
{name: 'tensionin', index: 2},
{name: 'IL6in', index: 3},
{name: 'IL1in', index: 4},
{name: 'TNFain', index: 5},
{name: 'NEin', index: 6},
{name: 'PDGFin', index: 7},
{name: 'ET1in', index: 8},
{name: 'NPin', index: 9},
{name: 'E2in', index: 10}
];
// Rate constants with defaults
this.rateConstants = {
k_input: 1.0,
k_feedback: 0.5,
k_degradation: 0.1,
k_receptor: 2.0,
k_inhibition: 0.5,
k_activation: 1.0,
k_production: 0.01,
k_diffusion: 0.2
};
// Store current input values for selected cells
this.currentInputValues = {};
this.inputMolecules.forEach(mol => {
this.currentInputValues[mol.name] = 0;
});
// Initialize data for tracking concentrations
this.concentrationData = {}; // Will store data for each tracked cell
// Store elements for later access
this.uiElements = {};
// Initialize UI
this.initUI();
this.initCanvas();
this.initLinePlot();
// Connect to WebAssembly module
this.initWasm();
}
initUI() {
// Create molecule selector
const selector = document.createElement('select');
selector.id = 'molecule-selector';
const addOptions = (groupName, molecules) => {
const group = document.createElement('optgroup');
group.label = groupName;
molecules.forEach(mol => {
const option = document.createElement('option');
option.value = mol.index;
option.textContent = mol.name;
group.appendChild(option);
});
selector.appendChild(group);
};
addOptions('ECM Molecules', this.ecmMolecules);
addOptions('Feedback Molecules', this.fbMolecules);
selector.value = this.currentMoleculeIndex;
selector.addEventListener('change', (e) => {
this.currentMoleculeIndex = parseInt(e.target.value);
this.updateVisualization();
this.updateTrackedCellsUI();
});
document.body.appendChild(selector);
// Create brush selection controls (for input molecules) - KEEP ABOVE HEATMAP
const brushContainer = document.createElement('div');
brushContainer.id = 'brush-controls';
brushContainer.style.border = '2px solid #007acc';
brushContainer.style.padding = '10px';
brushContainer.style.margin = '10px 0';
brushContainer.style.backgroundColor = '#f0f8ff';
const brushTitle = document.createElement('h3');
brushTitle.textContent = 'Brush selection tool (for input molecules)';
brushTitle.style.margin = '0 0 10px 0';
brushContainer.appendChild(brushTitle);
// Brush mode toggle
const brushToggle = document.createElement('button');
brushToggle.id = 'brush-toggle';
brushToggle.textContent = 'Enable brush mode';
brushToggle.style.marginRight = '10px';
brushToggle.addEventListener('click', () => this.toggleBrushMode());
brushContainer.appendChild(brushToggle);
// Clear selection button
const clearSelection = document.createElement('button');
clearSelection.textContent = 'Clear selection';
clearSelection.style.marginRight = '10px';
clearSelection.addEventListener('click', () => this.clearBrushSelection());
brushContainer.appendChild(clearSelection);
// Brush size control
const brushSizeContainer = document.createElement('div');
brushSizeContainer.style.display = 'inline-block';
brushSizeContainer.style.marginLeft = '10px';
const brushSizeLabel = document.createElement('label');
brushSizeLabel.textContent = 'Brush size: ';
brushSizeLabel.htmlFor = 'brush-size';
const brushSizeInput = document.createElement('input');
brushSizeInput.type = 'range';
brushSizeInput.id = 'brush-size';
brushSizeInput.min = '1';
brushSizeInput.max = '15';
brushSizeInput.value = this.brushSize.toString();
brushSizeInput.style.width = '100px';
const brushSizeDisplay = document.createElement('span');
brushSizeDisplay.textContent = this.brushSize.toString();
brushSizeDisplay.style.marginLeft = '5px';
brushSizeInput.addEventListener('input', (e) => {
this.brushSize = parseInt(e.target.value);
brushSizeDisplay.textContent = this.brushSize.toString();
});
brushSizeContainer.appendChild(brushSizeLabel);
brushSizeContainer.appendChild(brushSizeInput);
brushSizeContainer.appendChild(brushSizeDisplay);
brushContainer.appendChild(brushSizeContainer);
// Selected cells count display
const selectionInfo = document.createElement('div');
selectionInfo.id = 'selection-info';
selectionInfo.style.marginTop = '10px';
selectionInfo.style.fontStyle = 'italic';
selectionInfo.textContent = 'No cells selected';
brushContainer.appendChild(selectionInfo);
document.body.appendChild(brushContainer);
// Create input molecule controls
const inputContainer = document.createElement('div');
inputContainer.id = 'input-controls';
inputContainer.style.border = '1px solid #ccc';
inputContainer.style.padding = '10px';
inputContainer.style.margin = '10px 0';
const inputTitle = document.createElement('h3');
inputTitle.textContent = 'Input molecule concentrations (for brush-selected cells)';
inputTitle.style.margin = '0 0 10px 0';
inputContainer.appendChild(inputTitle);
const inputNote = document.createElement('div');
inputNote.textContent = 'Note: These values will be applied only to brush-selected cells. Unselected cells use default values (0).';
inputNote.style.fontSize = '12px';
inputNote.style.color = '#666';
inputNote.style.marginBottom = '10px';
inputContainer.appendChild(inputNote);
this.inputMolecules.forEach(mol => {
const div = document.createElement('div');
div.className = 'input-control';
const label = document.createElement('label');
label.textContent = mol.name;
label.htmlFor = `input-${mol.name}`;
const input = document.createElement('input');
input.type = 'range';
input.id = `input-${mol.name}`;
input.min = '0';
input.max = '1';
input.step = '0.01';
input.value = '0';
const valueDisplay = document.createElement('span');
valueDisplay.className = 'value-display';
valueDisplay.textContent = '0.00';
valueDisplay.style.marginLeft = '10px';
valueDisplay.style.width = '40px';
valueDisplay.style.display = 'inline-block';
input.addEventListener('input', (e) => {
const value = parseFloat(e.target.value);
valueDisplay.textContent = value.toFixed(2);
this.currentInputValues[mol.name] = value;
this.applyInputToSelectedCells();
});
div.appendChild(label);
div.appendChild(input);
div.appendChild(valueDisplay);
inputContainer.appendChild(div);
});
document.body.appendChild(inputContainer);
// Create ODE parameter controls
const odeContainer = document.createElement('div');
odeContainer.id = 'ode-controls';
odeContainer.innerHTML = '<h3>ODE Parameters</h3>';
// Create time step control
const timeStepDiv = document.createElement('div');
timeStepDiv.className = 'ode-param';
const timeStepLabel = document.createElement('label');
timeStepLabel.textContent = 'Time Step';
timeStepLabel.htmlFor = 'time-step';
const timeStepInput = document.createElement('input');
timeStepInput.type = 'range';
timeStepInput.id = 'time-step';
timeStepInput.min = '0.01';
timeStepInput.max = '0.5';
timeStepInput.step = '0.01';
timeStepInput.value = this.timeStep.toString();
const timeStepDisplay = document.createElement('span');
timeStepDisplay.textContent = this.timeStep.toFixed(2);
timeStepDisplay.style.marginLeft = '10px';
timeStepInput.addEventListener('input', (e) => {
this.timeStep = parseFloat(e.target.value);
timeStepDisplay.textContent = this.timeStep.toFixed(2);
if (this.wasm) {
this.wasm._setTimeStep(this.timeStep);
}
});
timeStepDiv.appendChild(timeStepLabel);
timeStepDiv.appendChild(timeStepInput);
timeStepDiv.appendChild(timeStepDisplay);
odeContainer.appendChild(timeStepDiv);
// Add rate constant controls
const rateParams = [
{ id: 'k_input', name: 'Input rate', min: 0.1, max: 5.0, default: this.rateConstants.k_input },
{ id: 'k_feedback', name: 'Feedback rate', min: 0.1, max: 5.0, default: this.rateConstants.k_feedback },
{ id: 'k_degradation', name: 'Degradation rate', min: 0.01, max: 1.0, default: this.rateConstants.k_degradation },
{ id: 'k_receptor', name: 'Receptor rate', min: 0.1, max: 5.0, default: this.rateConstants.k_receptor },
{ id: 'k_inhibition', name: 'Inhibition rate', min: 0.1, max: 5.0, default: this.rateConstants.k_inhibition },
{ id: 'k_activation', name: 'Activation rate', min: 0.1, max: 5.0, default: this.rateConstants.k_activation },
{ id: 'k_production', name: 'Production rate', min: 0.001, max: 0.1, default: this.rateConstants.k_production },
{ id: 'k_diffusion', name: 'Diffusion rate', min: 0.01, max: 1.0, default: this.rateConstants.k_diffusion }
];
rateParams.forEach(param => {
const div = document.createElement('div');
div.className = 'ode-param';
const label = document.createElement('label');
label.textContent = param.name;
label.htmlFor = param.id;
const input = document.createElement('input');
input.type = 'range';
input.id = param.id;
input.min = param.min.toString();
input.max = param.max.toString();
input.step = ((param.max - param.min) / 100).toString();
input.value = param.default.toString();
const display = document.createElement('span');
display.textContent = param.default.toFixed(4);
display.style.marginLeft = '10px';
input.addEventListener('input', (e) => {
this.rateConstants[param.id] = parseFloat(e.target.value);
display.textContent = this.rateConstants[param.id].toFixed(4);
this.updateRateConstants();
});
div.appendChild(label);
div.appendChild(input);
div.appendChild(display);
odeContainer.appendChild(div);
});
// Hide ODE controls initially
odeContainer.style.display = 'none';
// Add button to toggle ODE controls
const toggleButton = document.createElement('button');
toggleButton.textContent = 'Show ODE parameters';
toggleButton.addEventListener('click', () => {
if (odeContainer.style.display === 'none') {
odeContainer.style.display = 'block';
toggleButton.textContent = 'Hide ODE parameters';
} else {
odeContainer.style.display = 'none';
toggleButton.textContent = 'Show ODE parameters';
}
});
document.body.appendChild(toggleButton);
document.body.appendChild(odeContainer);
// Create simulation controls
const controls = document.createElement('div');
controls.id = 'simulation-controls';
const startButton = document.createElement('button');
startButton.textContent = 'Start';
startButton.addEventListener('click', () => this.startSimulation());
const stopButton = document.createElement('button');
stopButton.textContent = 'Stop';
stopButton.addEventListener('click', () => this.stopSimulation());
const stepButton = document.createElement('button');
stepButton.textContent = 'Step';
stepButton.addEventListener('click', () => this.stepSimulation());
const resetButton = document.createElement('button');
resetButton.textContent = 'Reset';
resetButton.addEventListener('click', () => this.resetSimulation());
controls.appendChild(startButton);
controls.appendChild(stopButton);
controls.appendChild(stepButton);
controls.appendChild(resetButton);
document.body.appendChild(controls);
}
// Initialize line plot canvas
initLinePlot() {
const container = document.createElement('div');
container.style.marginTop = '20px';
const plotsLabel = document.createElement('div');
plotsLabel.textContent = 'Tracked cell concentrations over time';
plotsLabel.style.fontWeight = 'bold';
plotsLabel.style.marginBottom = '10px';
// Create a flex container for canvas and buttons
const plotContainer = document.createElement('div');
plotContainer.style.display = 'flex';
plotContainer.style.alignItems = 'flex-end';
plotContainer.style.gap = '15px';
// Create canvas for line plots
this.linePlotCanvas = document.createElement('canvas');
this.linePlotCanvas.width = 700;
this.linePlotCanvas.height = 300;
this.linePlotCanvas.style.border = '1px solid #000';
this.linePlotCtx = this.linePlotCanvas.getContext('2d');
// Export buttons container (right side, bottom aligned)
const buttonContainer = document.createElement('div');
buttonContainer.style.display = 'flex';
buttonContainer.style.flexDirection = 'column';
buttonContainer.style.gap = '10px';
const exportSVGButton = document.createElement('button');
exportSVGButton.textContent = '📥 Export Plot as SVG';
exportSVGButton.style.padding = '10px 15px';
exportSVGButton.style.backgroundColor = '#FF9800';
exportSVGButton.style.color = 'white';
exportSVGButton.style.border = 'none';
exportSVGButton.style.borderRadius = '4px';
exportSVGButton.style.cursor = 'pointer';
exportSVGButton.style.fontSize = '14px';
exportSVGButton.style.fontWeight = 'bold';
exportSVGButton.addEventListener('click', () => {
this.exportLinePlotToSVG();
});
buttonContainer.appendChild(exportSVGButton);
const exportPNGButton = document.createElement('button');
exportPNGButton.textContent = '📄 Export Plot as PNG';
exportPNGButton.style.padding = '10px 15px';
exportPNGButton.style.backgroundColor = '#2196F3';
exportPNGButton.style.color = 'white';
exportPNGButton.style.border = 'none';
exportPNGButton.style.borderRadius = '4px';
exportPNGButton.style.cursor = 'pointer';
exportPNGButton.style.fontSize = '14px';
exportPNGButton.style.fontWeight = 'bold';
exportPNGButton.addEventListener('click', () => {
this.exportLinePlotToPNG();
});
buttonContainer.appendChild(exportPNGButton);
plotContainer.appendChild(this.linePlotCanvas);
plotContainer.appendChild(buttonContainer);
container.appendChild(plotsLabel);
container.appendChild(plotContainer);
document.body.appendChild(container);
}
initCanvas() {
const canvasContainer = document.createElement('div');
canvasContainer.style.display = 'flex';
canvasContainer.style.alignItems = 'flex-start';
canvasContainer.style.gap = '15px';
canvasContainer.style.marginTop = '20px';
// Create a container for the canvas and tracking controls
const leftContainer = document.createElement('div');
leftContainer.style.display = 'flex';
leftContainer.style.flexDirection = 'column';
leftContainer.style.gap = '15px';
// Canvas
this.canvas = document.createElement('canvas');
this.canvas.width = 600;
this.canvas.height = 600;
this.ctx = this.canvas.getContext('2d');
this.canvas.style.cursor = 'crosshair';
this.canvas.style.border = '1px solid #ccc';
this.canvas.style.width = '500px';
this.canvas.style.height = '500px';
this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e));
this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e));
this.canvas.addEventListener('mouseup', (e) => this.handleMouseUp(e));
this.canvas.addEventListener('mouseleave', (e) => this.handleMouseUp(e));
this.canvas.addEventListener('click', (e) => this.handleCellClick(e));
leftContainer.appendChild(this.canvas);
// NOW ADD CELL TRACKING TOOL BELOW THE HEATMAP
const trackingContainer = document.createElement('div');
trackingContainer.id = 'tracking-controls';
trackingContainer.style.border = '2px solid #ff6600';
trackingContainer.style.padding = '10px';
trackingContainer.style.margin = '10px 0';
trackingContainer.style.backgroundColor = '#fff5f0';
const trackingTitle = document.createElement('h3');
trackingTitle.textContent = 'Cell tracking tool (for line plot)';
trackingTitle.style.margin = '0 0 10px 0';
trackingContainer.appendChild(trackingTitle);
// Cell selection mode toggle
const cellSelectToggle = document.createElement('button');
cellSelectToggle.id = 'cell-select-toggle';
cellSelectToggle.textContent = 'Enable cell selection';
cellSelectToggle.style.marginRight = '10px';
cellSelectToggle.addEventListener('click', () => this.toggleCellSelectionMode());
trackingContainer.appendChild(cellSelectToggle);
// Clear tracked cells button
const clearTrackedCells = document.createElement('button');
clearTrackedCells.textContent = 'Clear tracked cells';
clearTrackedCells.style.marginRight = '10px';
clearTrackedCells.addEventListener('click', () => this.clearTrackedCells());
trackingContainer.appendChild(clearTrackedCells);
// Tracked cells info
const cellsInfo = document.createElement('div');
cellsInfo.id = 'cells-info';
cellsInfo.style.marginTop = '10px';
cellsInfo.style.fontStyle = 'italic';
cellsInfo.textContent = 'No cells selected for tracking';
trackingContainer.appendChild(cellsInfo);
// Container for tracked cell concentration controls
const trackedCellsContainer = document.createElement('div');
trackedCellsContainer.id = 'tracked-cells-container';
trackedCellsContainer.style.marginTop = '10px';
trackingContainer.appendChild(trackedCellsContainer);
leftContainer.appendChild(trackingContainer);
canvasContainer.appendChild(leftContainer);
// Export buttons container (right side)
const buttonContainer = document.createElement('div');
buttonContainer.style.display = 'flex';
buttonContainer.style.flexDirection = 'column';
buttonContainer.style.gap = '10px';
const exportSVGButton = document.createElement('button');
exportSVGButton.textContent = '📥 Export as SVG (600x600)';
exportSVGButton.style.padding = '10px 15px';
exportSVGButton.style.backgroundColor = '#FF9800';
exportSVGButton.style.color = 'white';
exportSVGButton.style.border = 'none';
exportSVGButton.style.borderRadius = '4px';
exportSVGButton.style.cursor = 'pointer';
exportSVGButton.style.fontSize = '14px';
exportSVGButton.style.fontWeight = 'bold';
exportSVGButton.addEventListener('click', () => {
console.log("SVG Export button clicked");
this.exportCanvasToSVG();
});
buttonContainer.appendChild(exportSVGButton);
const exportPNGButton = document.createElement('button');
exportPNGButton.textContent = '📄 Export as PNG (600x600)';
exportPNGButton.style.padding = '10px 15px';
exportPNGButton.style.backgroundColor = '#2196F3';
exportPNGButton.style.color = 'white';
exportPNGButton.style.border = 'none';
exportPNGButton.style.borderRadius = '4px';
exportPNGButton.style.cursor = 'pointer';
exportPNGButton.style.fontSize = '14px';
exportPNGButton.style.fontWeight = 'bold';
exportPNGButton.addEventListener('click', () => {
console.log("PNG Export button clicked");
this.exportCanvasToPNG();
});
buttonContainer.appendChild(exportPNGButton);
canvasContainer.appendChild(buttonContainer);
document.body.appendChild(canvasContainer);
}
exportCanvasToSVG() {
try {
console.log("Starting SVG export...");
// Set dimensions to 600x600
const width = 600;
const height = 600;
const gridSize = this.gridSize;
// Get current time value
const currentTime = (this.iteration * this.timeStep).toFixed(2);
// Update min/max values before export (call the updateVisualization method to set them)
this.updateMinMaxValues();
// Calculate brush selected cells count
this.brushSelectedCells = this.selectedCellsForInput.size;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", width);
svg.setAttribute("height", height);
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("version", "1.1");
// Add metadata
const metadata = document.createElementNS("http://www.w3.org/2000/svg", "metadata");
metadata.textContent = `Created by ECM Simulation - Iteration ${this.iteration}`;
svg.appendChild(metadata);
const title = document.createElementNS("http://www.w3.org/2000/svg", "title");
title.textContent = `ECMSim - Iteration ${this.iteration}`;
svg.appendChild(title);
const cellWidth = width / gridSize;
const cellHeight = height / gridSize;
// Create a group for the heatmap cells
const cellGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
cellGroup.setAttribute("class", "heatmap-cells");
// Create a temporary canvas to get color data - BUT DON'T DRAW THE LEGEND!
const tempCanvas = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
const tempCtx = tempCanvas.getContext('2d');
// Clear the temporary canvas
tempCtx.clearRect(0, 0, width, height);
// Draw ONLY the heatmap cells (not the legend) - we need to recreate the heatmap
if (this.wasm) {
try {
// Get data based on molecule type (ECM or feedback)
let dataPtr;
let isFeedback = false;
if (this.currentMoleculeIndex >= 100) {
const adjustedIndex = this.currentMoleculeIndex - 100;
dataPtr = this.wasm._getFeedbackData(adjustedIndex);
isFeedback = true;
} else {
dataPtr = this.wasm._getECMData(this.currentMoleculeIndex);
}
// Apply log scaling for better visualization
const logMin = this.minValue > 0 ? Math.log10(this.minValue) : -3;
const logMax = Math.log10(this.maxValue);
const logRange = Math.max(logMax - logMin, 0.01);
// Draw heatmap cells directly to temp canvas
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
let value = this.wasm._readDataValue(dataPtr, i, j);
// Apply log scaling for better visualization of small values
if (value > 0) {
let logVal = Math.log10(value);
value = (logVal - logMin) / logRange;
} else {
value = 0;
}
// Create heatmap color (red to yellow for ECM, blue for feedback)
let r, g, b;
if (isFeedback) {
// Blue gradient for feedback molecules
r = 0;
g = Math.min(255, value * 255);
b = Math.min(255, value * 255 * 2);
} else {
// Red-yellow gradient for ECM molecules
r = Math.min(255, value * 255 * 2);
g = Math.min(255, value * 255);
b = 0;
}
tempCtx.fillStyle = `rgb(${Math.floor(r)}, ${Math.floor(g)}, ${Math.floor(b)})`;
tempCtx.fillRect(j * cellWidth, i * cellHeight, cellWidth, cellHeight);
}
}
// Free the data memory
this.wasm._freeData(dataPtr);
} catch (error) {
console.error("Error generating heatmap for SVG:", error);
}
}
const imageData = tempCtx.getImageData(0, 0, width, height);
const pixelData = imageData.data;
// Draw heatmap cells as SVG rectangles
for (let row = 0; row < gridSize; row++) {
for (let col = 0; col < gridSize; col++) {
const x = Math.floor(col * cellWidth + cellWidth / 2);
const y = Math.floor(row * cellHeight + cellHeight / 2);
const pixelIndex = (y * width + x) * 4;
// Check if pixel index is within bounds
if (pixelIndex < 0 || pixelIndex + 3 >= pixelData.length) {
continue;
}
const r = pixelData[pixelIndex];
const g = pixelData[pixelIndex + 1];
const b = pixelData[pixelIndex + 2];
// Check if pixel is valid
if (isNaN(r) || isNaN(g) || isNaN(b)) {
continue;
}
const color = `rgb(${r},${g},${b})`;
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", col * cellWidth);
rect.setAttribute("y", row * cellHeight);
rect.setAttribute("width", Math.ceil(cellWidth));
rect.setAttribute("height", Math.ceil(cellHeight));
rect.setAttribute("fill", color);
rect.setAttribute("stroke", "none");
cellGroup.appendChild(rect);
}
}
svg.appendChild(cellGroup);
// Add brush selection overlay if there are selected cells
console.log("SVG Export - Brush selected cells:", this.selectedCellsForInput.size);
if (this.selectedCellsForInput.size > 0) {
const brushGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
brushGroup.setAttribute("class", "brush-selection");
this.selectedCellsForInput.forEach(cellKey => {
const [row, col] = cellKey.split(',').map(Number);
const x = col * cellWidth;
const y = row * cellHeight;
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", Math.ceil(cellWidth));
rect.setAttribute("height", Math.ceil(cellHeight));
// Use proper SVG opacity attributes instead of rgba()
rect.setAttribute("fill", "#FFFFFF");
rect.setAttribute("fill-opacity", "0.3");
rect.setAttribute("stroke", "#FFFFFF");
rect.setAttribute("stroke-opacity", "0.8");
rect.setAttribute("stroke-width", "0.5");
brushGroup.appendChild(rect);
});
svg.appendChild(brushGroup);
console.log("SVG Export - Added brush selection group with", this.selectedCellsForInput.size, "cells");
}
// Add tracked cells with colored borders and labels
console.log("SVG Export - Tracked cells:", this.trackedCells.length);
if (this.trackedCells.length > 0) {
const trackedGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
trackedGroup.setAttribute("class", "tracked-cells");
this.trackedCells.forEach((cell, index) => {
const x = cell.col * cellWidth;
const y = cell.row * cellHeight;
// Outer colored border
const outerRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
outerRect.setAttribute("x", x - 2);
outerRect.setAttribute("y", y - 2);
outerRect.setAttribute("width", Math.ceil(cellWidth) + 4);
outerRect.setAttribute("height", Math.ceil(cellHeight) + 4);
outerRect.setAttribute("fill", "none");
outerRect.setAttribute("stroke", cell.color);
outerRect.setAttribute("stroke-width", "4");
trackedGroup.appendChild(outerRect);
// Inner white border for contrast
const innerRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
innerRect.setAttribute("x", x);
innerRect.setAttribute("y", y);
innerRect.setAttribute("width", Math.ceil(cellWidth));
innerRect.setAttribute("height", Math.ceil(cellHeight));
innerRect.setAttribute("fill", "none");
innerRect.setAttribute("stroke", "#FFFFFF");
innerRect.setAttribute("stroke-width", "1");
trackedGroup.appendChild(innerRect);
// Cell number label with stroke for visibility
const textStroke = document.createElementNS("http://www.w3.org/2000/svg", "text");
textStroke.setAttribute("x", x + 2);
textStroke.setAttribute("y", y + 12);
textStroke.setAttribute("font-family", "Arial, sans-serif");
textStroke.setAttribute("font-size", "12");
textStroke.setAttribute("font-weight", "bold");
textStroke.setAttribute("fill", "none");
textStroke.setAttribute("stroke", "#000000");
textStroke.setAttribute("stroke-width", "3");
textStroke.textContent = `${index + 1}`;
trackedGroup.appendChild(textStroke);
// Cell number label fill
const textFill = document.createElementNS("http://www.w3.org/2000/svg", "text");
textFill.setAttribute("x", x + 2);
textFill.setAttribute("y", y + 12);
textFill.setAttribute("font-family", "Arial, sans-serif");
textFill.setAttribute("font-size", "12");
textFill.setAttribute("font-weight", "bold");
textFill.setAttribute("fill", "#FFFFFF");
textFill.textContent = `${index + 1}`;
trackedGroup.appendChild(textFill);
});
svg.appendChild(trackedGroup);
console.log("SVG Export - Added tracked cells group with", this.trackedCells.length, "cells");
}
// Add text details as SVG text (crisp and scalable)
const textGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
textGroup.setAttribute("class", "heatmap-text");
// Background rectangle for text
const textBg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
textBg.setAttribute("x", 10);
textBg.setAttribute("y", 10);
textBg.setAttribute("width", 320);
textBg.setAttribute("height", 80);
textBg.setAttribute("fill", "white");
textBg.setAttribute("fill-opacity", "0.8");
textBg.setAttribute("stroke", "#333");
textBg.setAttribute("stroke-width", "1");
textBg.setAttribute("rx", "5");
textBg.setAttribute("ry", "5");
textGroup.appendChild(textBg);
// Create text lines
const textLines = [
`Iteration: ${this.iteration} | Time: ${currentTime}`,
`Range: ${this.minValue.toExponential(2)} - ${this.maxValue.toExponential(2)}`,
`Brush selected (input): ${this.brushSelectedCells} cells`,
`Tracked cells (plot): ${this.trackedCells.length}`
];
// Add each text line
textLines.forEach((line, index) => {
const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.setAttribute("x", 20);
text.setAttribute("y", 30 + (index * 15));
text.setAttribute("font-family", "Arial, sans-serif");
text.setAttribute("font-size", "12");
text.setAttribute("fill", "#333");
text.textContent = line;
textGroup.appendChild(text);
});
svg.appendChild(textGroup);
const svgString = new XMLSerializer().serializeToString(svg);
const blob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(blob);
// Create and trigger download
const link = document.createElement("a");
link.href = url;
link.download = `ecm-heatmap-${this.iteration}-600x600.svg`;
// Append to body, click, and remove
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Revoke the object URL
setTimeout(() => {
URL.revokeObjectURL(url);
}, 100);
console.log("SVG export completed successfully");
} catch (error) {
console.error("Error exporting SVG:", error);
alert("Failed to export SVG: " + error.message);
}
}
exportCanvasToPNG() {
try {
console.log("Starting PNG export...");
// Create a temporary canvas for high-resolution PNG
const tempCanvas = document.createElement('canvas');
tempCanvas.width = 600;
tempCanvas.height = 600;
const tempCtx = tempCanvas.getContext('2d');
// Scale the original canvas content to 600x600
tempCtx.drawImage(this.canvas, 0, 0, this.canvas.width, this.canvas.height,
0, 0, 600, 600);
const dataUrl = tempCanvas.toDataURL('image/png');
// Create and trigger download
const link = document.createElement('a');
link.href = dataUrl;
link.download = `ecm-heatmap-${this.iteration}-600x600.png`;
// Append to body, click, and remove
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log("PNG export completed successfully");
} catch (error) {
console.error("Error exporting PNG:", error);
alert("Failed to export PNG: " + error.message);
}
}
exportLinePlotToPNG() {
try {
console.log("Starting Line Plot PNG export...");
const dataUrl = this.linePlotCanvas.toDataURL('image/png');
// Create and trigger download
const link = document.createElement('a');
link.href = dataUrl;
link.download = `ecm-lineplot-${this.iteration}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log("Line Plot PNG export completed successfully");
} catch (error) {
console.error("Error exporting Line Plot PNG:", error);
alert("Failed to export Line Plot PNG: " + error.message);
}
}
exportLinePlotToSVG() {
try {
console.log("Starting Line Plot SVG export...");
const width = this.linePlotCanvas.width;
const height = this.linePlotCanvas.height;
const padding = 40;
const plotWidth = width - padding * 2;
const plotHeight = height - padding * 2;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", width);
svg.setAttribute("height", height);
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
// White background
const bg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
bg.setAttribute("width", width);
bg.setAttribute("height", height);
bg.setAttribute("fill", "white");
svg.appendChild(bg);
// Draw axes
const axes = document.createElementNS("http://www.w3.org/2000/svg", "path");
axes.setAttribute("d", `M ${padding} ${padding} L ${padding} ${padding + plotHeight} L ${padding + plotWidth} ${padding + plotHeight}`);
axes.setAttribute("stroke", "#000");
axes.setAttribute("stroke-width", "1");
axes.setAttribute("fill", "none");
svg.appendChild(axes);
// Draw grid lines
for (let i = 0; i <= 10; i++) {
const y = padding + plotHeight - (i * plotHeight / 10);
const gridLine = document.createElementNS("http://www.w3.org/2000/svg", "line");
gridLine.setAttribute("x1", padding);
gridLine.setAttribute("y1", y);
gridLine.setAttribute("x2", padding + plotWidth);
gridLine.setAttribute("y2", y);
gridLine.setAttribute("stroke", "#eee");
gridLine.setAttribute("stroke-width", "0.5");
svg.appendChild(gridLine);
}
// Find max value for scaling
let maxValue = 0;
Object.values(this.concentrationData).forEach(data => {
data.forEach(v => maxValue = Math.max(maxValue, v));
});
if (maxValue <= 0) maxValue = 1;
// Draw data lines for each tracked cell
this.trackedCells.forEach((cell, cellIndex) => {
const key = `${cell.row},${cell.col}`;
const data = this.concentrationData[key];
if (data && data.length > 1) {
let pathD = '';
for (let i = 0; i < data.length; i++) {
const x = padding + (i / (data.length - 1)) * plotWidth;
const y = padding + plotHeight - (data[i] / maxValue * plotHeight);