-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
3281 lines (2785 loc) · 152 KB
/
index.html
File metadata and controls
3281 lines (2785 loc) · 152 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-VNXC3S1LH2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-VNXC3S1LH2');
</script>
<!-- Google Tag Manager -->
<script>(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-N5RW3TB3');</script>
<!-- End Google Tag Manager -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snipe SRA Exploration Dashboard</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
<script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lz-string/1.4.4/lz-string.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.js"></script>
<!-- Driver.js CSS and JS -->
<script src="https://cdn.jsdelivr.net/npm/driver.js@1.0.1/dist/driver.js.iife.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/driver.js@1.0.1/dist/driver.css" />
<link rel="stylesheet" href="styles/styles.css">
<script src="scripts/snipe-explore.js"></script>
</head>
<!-- Help Modal -->
<div id="help-modal" class="modal">
<div class="modal-content">
<span id="close-modal" class="close-button">×</span>
<h2>Snipe metrics description</h2>
<div id="modal-column-definitions">
<!-- Column definitions will be inserted here -->
</div>
</div>
</div>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-N5RW3TB3" height="0" width="0"
style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
<div class="container">
<!-- Brand/Logo -->
<a class="navbar-brand" href="#">
<img src="assets/scatter-plot.png" alt="Snipe Logo" width="40" height="40"
class="d-inline-block align-top">
Snipe Explore Dashboard
</a>
<!-- Toggler for Mobile View -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar Links -->
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<!-- Navigation Links -->
<li class="nav-item">
<a class="nav-link" href="https://snipe-bio.github.io/" target="_blank">Homepage</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://github.com/snipe-bio/snipe" target="_blank">snipe CLI</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://github.com/orgs/snipe-bio/discussions"
target="_blank">Discussions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://github.com/snipe-bio/explore/issues/new" target="_blank">File
issue</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Updated Species and Reference Selection with Amplicon -->
<div class="container">
<div id="data-selection-container" class="species-selection">
<div class="control-group">
<label for="species-select">Species:</label>
<select id="species-select">
<option value="">Select Species</option>
<!-- Options will be populated dynamically -->
</select>
</div>
<div class="control-group">
<label for="reference-select">Reference Genome:</label>
<select id="reference-select" disabled>
<option value="">Select Reference Genome</option>
<!-- Options will be populated dynamically -->
</select>
</div>
<div class="control-group">
<label for="amplicon-select">Amplicon:</label>
<select id="amplicon-select" disabled>
<option value="">Select Amplicon (Optional)</option>
<!-- Options will be populated dynamically -->
</select>
</div>
<div class="control-group">
<button id="load-data-button" disabled>Load Data</button>
</div>
<div id="log-info" class="log-info" style="display: none;">
<!-- Log information will be displayed here -->
</div>
</div>
<!-- Tabbed Plot Container -->
<div class="tabs-container">
<ul class="nav nav-tabs" id="plot-tabs">
<!-- Tabs will be added here dynamically -->
<li class="nav-item">
<button class="new-tab-button" id="new-tab-button">
<i class="fa fa-plus"></i>
<span class="tab-button-text">Add First Plot</span>
</button>
</li>
</ul>
<div class="tab-content" id="plots-container">
<!-- Plot content will be added here dynamically -->
</div>
</div>
<div id="add-view-container" style="display: none;">
<button id="add-view" class="add-view-button">
<i class="fa fa-plus-circle"></i> Add View
</button>
</div>
<div id="data-selection-section">
<div id="table-container" class="table-container">
<!-- Table will be inserted here -->
</div>
</div>
</div>
<div class="floating-buttons">
<button id="clear-selections" class="floating-button">
<i class="fa fa-eraser"></i>
<span>Clear Selections</span>
</button>
<button id="export-table" class="floating-button">
<i class="fa fa-file-export"></i>
<span>Export Table (TSV)</span>
</button>
<button id="export-pdf" class="floating-button">
<i class="fa fa-file-pdf"></i>
<span>Export Snipe Report</span>
</button>
<button id="scroll-to-table" class="floating-button">
<i class="fa fa-arrow-down"></i>
<span>Scroll to Table</span>
</button>
<button id="help-button" class="floating-button">
<i class="fa-solid fa-circle-question"></i>
<span>Snipe metrics definitions</span>
</button>
<!-- driverJS -->
<button id="start-tour" class="floating-button">
<i class="fa fa-book"></i>
<span>Start Tour</span>
</button>
<!-- New Import/Export Session Buttons -->
<button id="export-session" class="floating-button">
<i class="fa fa-download"></i>
<span>Export Session</span>
</button>
<button id="import-session" class="floating-button">
<i class="fa fa-upload"></i>
<span>Import Session</span>
</button>
<button id="export-session-url" class="floating-button">
<i class="fa fa-link"></i>
<span>Export Session to URL</span>
</button>
<button id="upload-data" class="floating-button">
<i class="fa fa-upload"></i>
<span>Upload Data</span>
</button>
</div>
<script>
let data = [];
let currentPlotData = [];
let selectedPoints = [];
let plotsContainer, tableContainer, exportTableButton, clearSelectionsButton, addViewButton;
let plotCounter = 0;
let snipe_metadata = {};
let uploadStats = {
totalNewExperiments: 0,
totalUpdatedExperiments: 0,
lastUploadTimestamp: null
};
const species_genome_amplicon_path = {
'Canine': {
'CanFam3.1': {
'Exome': 'https://raw.githubusercontent.com/snipe-bio/dbs/refs/heads/main/qc_tables/Dog/canfam31_ychr_exome_rna_gtdb.tsv'
}
},
'Cattle': {
'ARS-UCD2.0': {
'Exome': 'https://raw.githubusercontent.com/snipe-bio/dbs/refs/heads/main/qc_tables/Cattle/cattle_arsucd20_exome_rna_gtdb.tsv'
}
},
'Human': {
'CHM13v2': {
'Exome': 'https://raw.githubusercontent.com/snipe-bio/dbs/refs/heads/main/qc_tables/Human/human_chm13v2_exome_rna_gtdb.tsv'
}
},
"Mouse": {
"GRCm39": {
"Exome": "https://raw.githubusercontent.com/snipe-bio/dbs/refs/heads/main/qc_tables/Mouse/mouse_grcm39_exome_rna_gtdb.tsv"
},
},
"Arabidopsis": {
"TAIR10.1": {
"Exome": "https://raw.githubusercontent.com/snipe-bio/dbs/refs/heads/main/qc_tables/Arabidopsis/arabidopsis_snipe_TAIR10.1_exome_rna_gtdb.tsv"
}
},
};
document.addEventListener('DOMContentLoaded', function () {
// Get references to the elements
const speciesSelect = document.getElementById('species-select');
const referenceSelect = document.getElementById('reference-select');
const ampliconSelect = document.getElementById('amplicon-select');
const loadDataButton = document.getElementById('load-data-button');
const dataSelectionContainer = document.getElementById('data-selection-container');
plotsContainer = document.getElementById('plots-container');
tableContainer = document.getElementById('table-container');
exportTableButton = document.getElementById('export-table');
clearSelectionsButton = document.getElementById('clear-selections');
addViewButton = document.getElementById('add-view');
// Initialize the tabs container
initTabsContainer();
exportTableButton.addEventListener('click', exportTableToTSV);
clearSelectionsButton.addEventListener('click', clearSelections);
addViewButton.addEventListener('click', addNewPlot);
document.getElementById('export-pdf').addEventListener('click', exportAllDataAsPDF);
document.getElementById('scroll-to-table').addEventListener('click', scrollToTable);
// Populate species options
for (const species in species_genome_amplicon_path) {
const option = document.createElement('option');
option.value = species;
option.textContent = species;
speciesSelect.appendChild(option);
}
// Set default selected species
speciesSelect.value = 'Canine';
// Event listener for species select
speciesSelect.addEventListener('change', function () {
const selectedSpecies = speciesSelect.value;
// Clear previous reference options
referenceSelect.innerHTML = '<option value="">Select Reference Genome</option>';
referenceSelect.disabled = true;
// Clear amplicon options
ampliconSelect.innerHTML = '<option value="">Select Amplicon (Optional)</option>';
ampliconSelect.disabled = true;
loadDataButton.disabled = true;
// Clear data and plots
clearAllData();
if (selectedSpecies) {
const references = species_genome_amplicon_path[selectedSpecies];
for (const reference in references) {
const option = document.createElement('option');
option.value = reference;
option.textContent = reference;
referenceSelect.appendChild(option);
}
referenceSelect.disabled = false;
// Set default selected reference
referenceSelect.value = 'CanFam3.1';
// Trigger change event to populate amplicon
referenceSelect.dispatchEvent(new Event('change'));
}
});
// Add the new tab button event listener
document.getElementById('new-tab-button').addEventListener('click', function () {
// Create new plot using the addNewPlot function from snipe-explore.js
const plotId = addNewPlot();
// Make sure to activate the newly created tab
if (plotId) {
activateTab(plotId);
}
});
// Event listener for reference select
referenceSelect.addEventListener('change', function () {
const selectedSpecies = speciesSelect.value;
const selectedReference = referenceSelect.value;
// Clear previous amplicon options
ampliconSelect.innerHTML = '<option value="">Select Amplicon (Optional)</option>';
ampliconSelect.disabled = true;
loadDataButton.disabled = true;
// Clear data and plots
clearAllData();
if (selectedReference) {
const amplicons = species_genome_amplicon_path[selectedSpecies][selectedReference];
for (const amplicon in amplicons) {
const option = document.createElement('option');
option.value = amplicon;
option.textContent = amplicon === '' ? 'No Amplicon' : amplicon;
ampliconSelect.appendChild(option);
}
ampliconSelect.disabled = false;
// Set default selected amplicon
ampliconSelect.value = 'Amplicon';
// Trigger change event to enable load data button
ampliconSelect.dispatchEvent(new Event('change'));
}
});
// Event listener for amplicon select
ampliconSelect.addEventListener('change', function () {
const selectedSpecies = speciesSelect.value;
const selectedReference = referenceSelect.value;
const selectedAmplicon = ampliconSelect.value;
const dataFilePath = species_genome_amplicon_path[selectedSpecies][selectedReference][selectedAmplicon];
// Clear data and plots
clearAllData();
if (dataFilePath) {
loadDataButton.disabled = false;
} else {
loadDataButton.disabled = true;
}
});
// Event listener for load data button
loadDataButton.addEventListener('click', function () {
const selectedSpecies = speciesSelect.value;
const selectedReference = referenceSelect.value;
const selectedAmplicon = ampliconSelect.value;
const dataFilePath = species_genome_amplicon_path[selectedSpecies][selectedReference][selectedAmplicon];
if (dataFilePath) {
loadData(dataFilePath);
loadDataButton.disabled = true;
} else {
alert('Data not available for selected species, reference genome, and amplicon.');
}
});
// Event listeners for the new buttons
document.getElementById('export-session').addEventListener('click', exportSession);
// Event listener for the Export Session to URL button
document.getElementById('export-session-url').addEventListener('click', exportSessionToURL);
// Check if there's session data or user data in the URL
const urlParams = new URLSearchParams(window.location.search);
const sessionDataEncoded = urlParams.get('session');
const dataEncoded = urlParams.get('data');
let userData = null;
if (dataEncoded) {
const dataJSON = LZString.decompressFromEncodedURIComponent(dataEncoded);
if (dataJSON) {
userData = JSON.parse(dataJSON);
} else {
alert('Failed to load data from URL.');
}
}
if (sessionDataEncoded) {
// Case 1 or 3: Session URL present
const sessionDataJSON = LZString.decompressFromEncodedURIComponent(sessionDataEncoded);
if (sessionDataJSON) {
importSession(sessionDataJSON, userData);
if (userData) {
// Hide data selection since user data is provided
dataSelectionContainer.style.display = 'none';
}
} else {
alert('Failed to load session from URL.');
}
} else if (userData) {
// Case 2: Only data URL present
dataSelectionContainer.style.display = 'none'; // Hide data selection
loadUserData(userData);
} else {
speciesSelect.dispatchEvent(new Event('change'));
}
// Attach event listener to the "Start Tour" button
const startTourButton = document.getElementById('start-tour');
startTourButton.addEventListener('click', function () {
startTour();
});
const helpButton = document.getElementById('help-button');
const helpModal = document.getElementById('help-modal');
const closeModalButton = document.getElementById('close-modal');
helpButton.addEventListener('click', function () {
helpModal.style.display = 'flex'; // Show the modal using flex layout
});
closeModalButton.addEventListener('click', function () {
helpModal.style.display = 'none'; // Hide the modal
});
window.addEventListener('click', function (event) {
if (event.target === helpModal) {
helpModal.style.display = 'none'; // Hide modal when clicking outside the content
}
});
// Event listener for the Import Session button
document.getElementById('import-session').addEventListener('click', function () {
const importSessionModal = document.getElementById('import-session-modal');
importSessionModal.style.display = 'flex';
});
// Event listener for the close button in the modal
document.getElementById('import-session-close').addEventListener('click', function () {
const importSessionModal = document.getElementById('import-session-modal');
importSessionModal.style.display = 'none';
});
// Event listener for the Import Session confirm button
document.getElementById('import-session-confirm').addEventListener('click', function () {
const fileInput = document.getElementById('session-file-input');
const textarea = document.getElementById('session-textarea');
if (fileInput.files.length > 0) {
// Read the file
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const jsonData = e.target.result;
importSession(jsonData);
// Close the modal
document.getElementById('import-session-modal').style.display = 'none';
// Show notification
showNotification('Session imported successfully.');
};
reader.readAsText(file);
} else if (textarea.value.trim() !== '') {
// Use the pasted data
const jsonData = textarea.value.trim();
importSession(jsonData);
// Close the modal
document.getElementById('import-session-modal').style.display = 'none';
// Show notification
showNotification('Session imported successfully.');
} else {
alert('Please upload a session file or paste session data.');
}
});
// Close modal when clicking outside of it
window.addEventListener('click', function (event) {
const importSessionModal = document.getElementById('import-session-modal');
if (event.target === importSessionModal) {
importSessionModal.style.display = 'none';
}
});
// Event listener for the Export Session to URL button
document.getElementById('export-session-url').addEventListener('click', exportSessionToURL);
// Event listener for the close button in the modal
document.getElementById('export-session-url-close').addEventListener('click', function () {
const exportSessionUrlModal = document.getElementById('export-session-url-modal');
exportSessionUrlModal.style.display = 'none';
});
// Event listener for the copy to clipboard button
document.getElementById('copy-session-url').addEventListener('click', function () {
const sessionUrlInput = document.getElementById('session-url-input');
sessionUrlInput.select();
sessionUrlInput.setSelectionRange(0, 99999);
document.execCommand('copy');
// Show a notification
showNotification('Session URL copied to clipboard.');
});
// Close modal when clicking outside of it
window.addEventListener('click', function (event) {
const exportSessionUrlModal = document.getElementById('export-session-url-modal');
if (event.target === exportSessionUrlModal) {
exportSessionUrlModal.style.display = 'none';
}
});
// Event listener for the Upload Data button
document.getElementById('upload-data').addEventListener('click', function () {
const uploadDataModal = document.getElementById('upload-data-modal');
uploadDataModal.style.display = 'flex';
});
// Event listener for the close button in the upload data modal
document.getElementById('upload-data-close').addEventListener('click', function () {
const uploadDataModal = document.getElementById('upload-data-modal');
uploadDataModal.style.display = 'none';
});
// Close modal when clicking outside of it
window.addEventListener('click', function (event) {
const uploadDataModal = document.getElementById('upload-data-modal');
if (event.target === uploadDataModal) {
uploadDataModal.style.display = 'none';
}
});
// Event listener for the Upload Data confirm button
document.getElementById('upload-data-confirm').addEventListener('click', function () {
const fileInput = document.getElementById('upload-data-file-input');
const uploadMode = document.querySelector('input[name="upload-data-mode"]:checked').value;
if (fileInput.files.length > 0) {
// Read the file
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const tsvData = e.target.result;
parseAndLoadUserData(tsvData, uploadMode);
document.getElementById('upload-data-modal').style.display = 'none';
};
reader.readAsText(file);
} else {
alert('Please select a TSV file to upload.');
}
});
// Close modal when clicking outside of it
window.addEventListener('click', function (event) {
const uploadDataModal = document.getElementById('upload-data-modal');
if (event.target === uploadDataModal) {
uploadDataModal.style.display = 'none';
}
});
tableContainer.addEventListener('click', function (event) {
event.preventDefault(); // Prevent default link behavior
// Show Depth per Chromosome
if (event.target && event.target.classList.contains('show-depth')) {
const uniqueId = event.target.getAttribute('data-unique-id');
const selectedData = data.find(row => row._uniqueId === uniqueId);
if (selectedData) {
plot_depth_per_chromosome(selectedData);
} else {
alert('Data not found for the selected Experiment.');
}
}
// Purge Experiment
if (event.target && event.target.classList.contains('purge-experiment')) {
const uniqueId = event.target.getAttribute('data-unique-id');
purgeExperiment(uniqueId);
}
// Purge BioProject
if (event.target && event.target.classList.contains('purge-bioproject')) {
const bioProject = event.target.getAttribute('data-bioproject');
purgeBioProject(bioProject);
}
// Purge BioSample
if (event.target && event.target.classList.contains('purge-biosample')) {
const bioSample = event.target.getAttribute('data-biosample');
purgeBioSample(bioSample);
}
if (event.target && event.target.classList.contains('view-sra')) {
const uniqueId = event.target.getAttribute('data-unique-id');
const selectedData = data.find(row => row._uniqueId === uniqueId);
if (selectedData && selectedData['Experiment ID']) {
const sraUrl = `https://www.ncbi.nlm.nih.gov/sra/${selectedData['Experiment ID']}`;
window.open(sraUrl, '_blank', 'noopener,noreferrer');
} else {
alert('Experiment ID not found for the selected Experiment.');
}
}
});
// Event listeners to search for experiments by URL
// Check for sra-exp, bioproject, biosample, and species in URL
const sraExp = urlParams.get('sra-exp');
const bioproject = urlParams.get('bioproject');
const biosample = urlParams.get('biosample');
const speciesParam = urlParams.get('species');
if ((sraExp || bioproject || biosample) && speciesParam) {
// Set speciesSelect to speciesParam
speciesSelect.value = speciesParam;
speciesSelect.dispatchEvent(new Event('change'));
setTimeout(() => {
const selectedSpecies = speciesSelect.value;
const references = species_genome_amplicon_path[selectedSpecies];
const defaultReference = Object.keys(references)[0];
referenceSelect.value = defaultReference;
referenceSelect.dispatchEvent(new Event('change'));
setTimeout(() => {
const selectedReference = referenceSelect.value;
const amplicons = species_genome_amplicon_path[selectedSpecies][selectedReference];
const defaultAmplicon = Object.keys(amplicons)[0];
ampliconSelect.value = defaultAmplicon;
ampliconSelect.dispatchEvent(new Event('change'));
setTimeout(() => {
const dataFilePath = species_genome_amplicon_path[selectedSpecies][selectedReference][defaultAmplicon];
if (dataFilePath) {
loadData(dataFilePath, function () {
// Data is loaded, now search for the Experiment ID, BioProject, or BioSample
let searchTerm = null;
let searchField = null;
if (sraExp) {
searchTerm = sraExp;
searchField = 'Experiment ID';
} else if (bioproject) {
searchTerm = bioproject;
searchField = 'BioProject';
} else if (biosample) {
searchTerm = biosample;
searchField = 'BioSample';
}
// Perform case-insensitive search
const matchingData = data.filter(row => row[searchField] && row[searchField].toLowerCase() === searchTerm.toLowerCase());
const pointType = searchField === 'Experiment ID' ? 'Experiment' : searchField === 'BioProject' ? 'BioProject' : 'BioSample';
if (matchingData.length > 0) {
// Found matching data
selectedPoints = selectedPoints.concat(matchingData);
updateTable();
highlightSelectedPoints();
showModal(`${pointType} Found`, `${pointType} ${searchTerm} found and highlighted in the table. Create a new plot to visualize the data.`);
} else {
showModal(`${pointType} Not Found`, `${pointType} ${searchTerm} not found in the data.`);
}
});
loadDataButton.disabled = true;
} else {
alert('Data not available for selected species, reference genome, and amplicon.');
}
}, 500);
}, 500);
}, 500);
}
});
function parseAndLoadUserData(tsvData, uploadMode) {
// Parse the TSV data using PapaParse
const results = Papa.parse(tsvData, {
header: true,
delimiter: "\t",
});
const userDataArray = results.data.filter(row => Object.values(row).some(value => value !== null && value !== ''));
// Update the last upload timestamp
const currentTimestamp = new Date().toISOString();
if (uploadMode === 'replace') {
// Reset cumulative stats on replace
uploadStats = {
totalNewExperiments: 0,
totalUpdatedExperiments: 0,
lastUploadTimestamp: currentTimestamp
};
clearAllData();
loadUserData(userDataArray);
uploadStats.totalNewExperiments += userDataArray.length;
showNotification(`Successfully loaded ${uploadStats.totalNewExperiments} experiments.`, 'success');
} else if (uploadMode === 'append') {
// Update the last upload timestamp
uploadStats.lastUploadTimestamp = currentTimestamp;
// Ensure existing data is present
if (!data || data.length === 0) {
showNotification('Error: No existing data found to append to.', 'error');
return;
}
const existingColumns = new Set(Object.keys(data[0] || {}));
const newColumns = new Set(Object.keys(userDataArray[0] || {}));
const allColumns = new Set([...existingColumns, ...newColumns]);
// Initialize missing columns in both datasets with default value null
data.forEach(row => {
newColumns.forEach(col => {
if (!row.hasOwnProperty(col) && col !== 'Experiment ID') {
row[col] = null;
}
});
});
userDataArray.forEach(row => {
existingColumns.forEach(col => {
if (!row.hasOwnProperty(col) && col !== 'Experiment ID') {
row[col] = null;
}
});
});
// Integrate user data with existing data and get the list of new experiments
console.log('Upload Stats Before Integration:', uploadStats);
const newExperiments = integrateUserData(userDataArray);
console.log('Upload Stats After Integration:', uploadStats);
// Add newExperiments to selectedPoints
if (newExperiments.length > 0) {
{ {/* selectedPoints = selectedPoints.concat(newExperiments); */ } }
operationsLog.push(`Added ${newExperiments.length} new experiments to selected points.`);
console.log('Selected Points after append:', selectedPoints);
} else {
console.log('No new experiments to add to selected points.');
}
// Update plots and table
for (let i = 1; i <= plotCounter; i++) {
const plotId = `plot-${i}`;
updatePlot(plotId);
}
/*
UNCOMMENT TO AUTO-HIGHLIGHT NEW POINTS
updateTable();
highlightSelectedPoints();
*/
// Show notification with cumulative upload statistics
displayDataStatistics();
showNotification(
`Data integrated successfully: ${uploadStats.totalNewExperiments} new experiments added, ${uploadStats.totalUpdatedExperiments} existing experiments updated.`,
'success'
);
}
}
function displayDataStatistics() {
const logInfoDiv = document.getElementById('log-info');
if (!logInfoDiv) return;
// Show the log info box
logInfoDiv.style.display = 'block';
const totalPoints = data.length;
const assayTypes = [...new Set(data.map(row => row["Assay type"] || 'Unknown').filter(type => type))];
const assayTypeCounts = assayTypes.map(type => {
const count = data.filter(row => row["Assay type"] === type).length;
return `\t- ${type}: ${count}`;
}).join('\n');
const uniqueBioProjects = new Set(data.map(row => row["BioProject"])).size;
const uniqueExperiments = new Set(data.map(row => row["Experiment ID"])).size;
// Prepare cumulative upload statistics
let uploadStatsSection = '';
if (uploadStats.lastUploadTimestamp) {
const timestamp = new Date(uploadStats.lastUploadTimestamp).toLocaleString();
uploadStatsSection = `
<details style="margin-top: 0px;">
<summary><strong>Last Upload Statistics</strong> (${timestamp})</summary>
<pre>
- New experiments added: ${uploadStats.totalNewExperiments}
- Existing experiments updated: ${uploadStats.totalUpdatedExperiments}
- Total experiments affected: ${uploadStats.totalNewExperiments + uploadStats.totalUpdatedExperiments}</pre>
</details>`;
}
// Prepare metadata information
let metadataInfo = '';
if (snipe_metadata && Object.keys(snipe_metadata).length > 0) {
metadataInfo = `<details style="margin-top: 0px;">
<summary><strong>Metadata (click to expand)</strong></summary>
<pre>${JSON.stringify(snipe_metadata.metadata, null, 2)}</pre></details>
`;
}
// Prepare the main stats as plain text within a <div>
const logContent = `
- Total Data Points: ${totalPoints}
- BioProjects: ${uniqueBioProjects}
- Experiments: ${uniqueExperiments}
<details style="margin-top: 0px;">
<summary>Assay types (click to expand)</summary>
<pre>${assayTypeCounts}</pre>
</details>${uploadStatsSection}${metadataInfo}`;
logInfoDiv.innerHTML = `
Data Statistics: ${logContent}
`.trim();
}
function scrollToTable() {
const tableSection = document.getElementById('data-selection-section');
tableSection.scrollIntoView({ behavior: 'smooth' });
}
// Function to clear plots and data
function clearAllData() {
data = null;
currentPlotData = null;
selectedPoints = [];
plotsContainer.innerHTML = '';
tableContainer.innerHTML = '';
plotCounter = 0;
document.getElementById('add-view-container').style.display = 'none';
}
function purgeExperiment(uniqueId) {
if (!confirm('Are you sure you want to purge this Experiment? This action cannot be undone.')) {
return;
}
data = data.filter(row => row._uniqueId !== uniqueId);
selectedPoints = selectedPoints.filter(point => point._uniqueId !== uniqueId);
updateTable();
showNotification('Experiment purged successfully.', 'success');
}
function purgeBioProject(bioProject) {
if (!confirm(`Are you sure you want to purge all Experiments under BioProject "${bioProject}"? This action cannot be undone.`)) {
return;
}
data = data.filter(row => row['BioProject'] !== bioProject);
selectedPoints = selectedPoints.filter(point => point['BioProject'] !== bioProject);
updateTable();
showNotification(`All Experiments under BioProject "${bioProject}" have been purged successfully.`, 'success');
}
function purgeBioSample(bioSample) {
if (!confirm(`Are you sure you want to purge all Experiments under BioSample "${bioSample}"? This action cannot be undone.`)) {
return;
}
data = data.filter(row => row['BioSample'] !== bioSample);
selectedPoints = selectedPoints.filter(point => point['BioSample'] !== bioSample);
updateTable();
showNotification(`All Experiments under BioSample "${bioSample}" have been purged successfully.`, 'success');
}
function parseMetadata(headerLine) {
try {
const parsedHeader = JSON.parse(headerLine);
const decompressedMetadata = decompressMetadata(parsedHeader.metadata);
const metadataObject = JSON.parse(decompressedMetadata);
return {
snipe_version: parsedHeader["snipe-version"],
metadata: metadataObject
};
} catch (e) {
showNotification('Error parsing metadata. Please check the console for more details.', 'error');
console.error('Error parsing metadata:', e);
return {};
}
}
function decompressMetadata(base64String) {
return LZString.decompressFromBase64(base64String);
}
function loadData(filePath, callback, addInitialPlot = true) {
const skip_columns = ["scale", "filename", "ksize"];
dataFilePath = filePath; // Set the global dataFilePath
// Show loading modal
document.getElementById('loading-modal').style.display = 'flex';
Papa.parse(dataFilePath, {
download: true,
header: false, // Disable header parsing to handle it manually
delimiter: "\t",
skipEmptyLines: true, // Skip empty lines
complete: function (results) {
let dataRows = results.data;
// Check if the first row is a metadata comment
if (dataRows.length > 0 && typeof dataRows[0][0] === 'string' && dataRows[0][0].startsWith('#')) {
const metadataLine = dataRows[0][0].slice(1); // Remove the leading '#'
snipe_metadata = parseMetadata(metadataLine);
console.log('Metadata:', snipe_metadata);
dataRows.shift(); // Remove the metadata row from data
}
if (dataRows.length > 0) {
const headers = dataRows.shift(); // Extract headers from the second row
// Convert data rows into objects using the headers
const parsedData = dataRows.map(row => {
const obj = {};
headers.forEach((header, index) => {
// Exclude skipped columns
if (!skip_columns.includes(header)) {
obj[header] = row[index];
}
});
return obj;
});
// Filter out any empty rows
const newData = parsedData.filter(row => Object.values(row).some(value => value !== null && value !== ''));
// Assign a unique ID to each data point based on a unique field
newData.forEach(row => {
row._uniqueId = row['Experiment ID']; // Use a unique field
});
if (data) {
data = data.concat(newData);
} else {
data = newData;
}
}
// Populate column definitions in the modal
populateModalColumnDefinitions();
// Now that data is loaded, set up the rest of the UI
plotsContainer = document.getElementById('plots-container');
tableContainer = document.getElementById('table-container');
exportTableButton = document.getElementById('export-table');
clearSelectionsButton = document.getElementById('clear-selections');
addViewButton = document.getElementById('add-view');
exportTableButton.addEventListener('click', exportTableToTSV);
clearSelectionsButton.addEventListener('click', clearSelections);
addViewButton.addEventListener('click', addNewPlot);
document.getElementById('export-pdf').addEventListener('click', exportAllDataAsPDF);
document.getElementById('scroll-to-table').addEventListener('click', scrollToTable);
// Initialize variables
plotCounter = 0;
// Show the add-view button
document.getElementById('add-view-container').style.display = 'block';
// Initialize and start the tour after data is loaded
initOnboardingTour();