-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathfiles.html
1214 lines (1130 loc) · 53 KB
/
files.html
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
<div id="file-panel" class="container-fluid">
<div id="file-table" class="container">
<p id="warning-prompt" class="text-muted"> If you're having a problem with MicrobeTrace, please
<a target="_blank" href="https://github.com/CDCgov/MicrobeTrace/wiki/Troubleshooting---Caching" style="font-weight: bold;text-decoration:underline">troubleshoot caching</a>.
</p>
<p id="file-prompt" class="text-muted">Drag-and-Drop Files here, or click "Add File(s)" to load data.</p>
</div>
</div>
<div id="file-footer">
<div class="container" style="padding: 15px">
<div class="row">
<div class="col">
<input type="file" id="data-files" class="d-none" multiple="true">
<label for="data-files" class="btn btn-primary btn-nr floater mb-0">Add File(s)</label>
<button type="button" id="sequenceControlsButton" class="btn btn-default btn-nr floater" data-toggle="modal" data-target="#sequence-controls-modal">Sequence Controls</button>
</div>
<div class="col text-right">
<button id="launch" class="btn btn-success" title="Please select a Network CSV or FASTA File" disabled>Launch</button>
</div>
</div>
</div>
</div>
<div class="view-controls">
<button type="button" id="file-settings-toggle" class="btn btn-light btn-sm" data-toggle="button" title="Toggle File Settings">
<span class="oi oi-cog"></span>
</button>
</div>
<div id="file-settings-pane" class="left-pane">
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="files-tab" data-toggle="tab" href="#file-settings" role="tab" aria-controls="file-settings" aria-selected="true">Files</a>
</li>
<li class="nav-item">
<a class="nav-link" id="experimental-tab" data-toggle="tab" href="#experimental-settings" role="tab" aria-controls="experimental-settings" aria-selected="false">Experimental</a>
</li>
</ul>
<div class="tab-content">
<div id="file-settings" class="tab-pane fade active show" role="tabpanel">
<div class="form-group row">
<div class="col-5">
<label for="default-distance-metric" class="mr-2" title="Which Genetic Distance Metric should Microbe use to first construct the network?">
Distance Metric
</label>
</div>
<div class="col-7">
<select id="default-distance-metric" class="form-control form-control-sm mr-5">
<option value="tn93" selected>TN93</option>
<option value="snps">SNPs</option>
</select>
</div>
</div>
<div id="ambiguities-row" class="form-group row">
<div class="col-5">
<label for="ambiguity-resolution-strategy" class="mr-2" title="What Strategy should MicrobeTrace use to handle ambiguities?">
Ambiguities
</label>
</div>
<div class="col-7">
<select id="ambiguity-resolution-strategy" class="form-control form-control-sm mr-5">
<option value="AVERAGE">Average</option>
<option value="RESOLVE">Resolve</option>
<option value="SKIP">Skip</option>
<option value="GAPMM">GapMM</option>
<option value="HIVTRACE-G">HIV-TRACE -g</option>
</select>
</div>
</div>
<div id="ambiguity-threshold-row" class="form-group row">
<div class="col-5">
<label for="ambiguity-threshold" class="mr-2" title="What's the maximum genetic distance you wish to consider linked? Please note that this can be changed later.">
Ambiguity Threshold
</label>
</div>
<div class="col-7">
<input type="number" id="ambiguity-threshold" class="form-control form-control-sm" min="0" value="0.015" step="0.001">
</div>
</div>
<div class="form-group row">
<div class="col-5">
<label for="default-distance-threshold" class="mr-2" title="What's the maximum genetic distance you wish to consider linked? Please note that this can be changed later.">
Link Threshold
</label>
</div>
<div class="col-7">
<input type="number" id="default-distance-threshold" class="form-control form-control-sm" min="0" value="0.015" step="0.001">
</div>
</div>
<div class="form-group row">
<div class="col-5">
<label for="default-view">View to Launch</label>
</div>
<div class="col-7">
<select id="default-view" class="form-control form-control-sm" title="Which view should MicrobeTrace render first, once it has successfully processed the data?">
<option value="2d_network" selected>2D Network</option>
<option value="pixi">Pixi</option>
<option value="3d_network">3D Network</option>
<option value="bubbles">Bubbles</option>
<option value="table">Table</option>
</select>
</div>
</div>
</div>
<div id="experimental-settings" class="tab-pane fade" role="tabpanel">
<div class="form-group row">
<div class="col-12">
<div class="alert alert-warning alert-dismissible" role="alert">
<p>The following settings are experimental! Use at your own risk!</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
<div class="form-group row" title="Would you like to generate a network based on random data?">
<div class="col-4">Generate</div>
<div class="col">
<input id="generate-number" type="number" class="form-control form-control-sm" min="1" max="2000" step="1" value="100">
</div>
<div class="col">
<button id="generate-sequences" class="btn btn-light btn-sm col">Sequences</button>
</div>
</div>
<div class="form-group row" title="Would you like to attempt to infer the direction of your links?">
<div class="col-4">Directionality</div>
<div class="col-8">
<div class="btn-group btn-group-toggle btn-group-sm w-100" data-toggle="buttons">
<label class="btn btn-light active col" title="Do Not infer transmission directionality.">
<input type="radio" name="infer-directionality" id="infer-directionality-false" autocomplete="off" checked> Off
</label>
<label class="btn btn-light col" title="Attempt to infer transmission directionality?">
<input type="radio" name="infer-directionality" id="infer-directionality" autocomplete="off"> Inferred
</label>
</div>
</div>
</div>
<!-- <div class="form-group row" title="Would you like to attempt to triangulate missing values in your distance matrices?">
<div class="col-4">Triangulation</div>
<div class="col-8">
<div class="btn-group btn-group-toggle btn-group-sm w-100" data-toggle="buttons">
<label class="btn btn-light col active" title="Do Not Triangulate missing cells in Distance Matrices.">
<input type="radio" name="triangulate" id="triangulate-false" autocomplete="off" checked> Off
</label>
<label class="btn btn-light col" title="Attempt to Triangulate missing cells in Distance Matrices.">
<input type="radio" name="triangulate" id="triangulate" autocomplete="off"> On
</label>
</div>
</div>
</div> -->
<div class="form-group row"
title="Should MicrobeTrace automatically stash your session so if your computer crashes you can recover your session?
Please note that this causes MicrobeTrace to store data on your computer's hard drive, which may have implications for PII.">
<div class="col-4">Autostashing</div>
<div class="col-8">
<div class="btn-group btn-group-toggle btn-group-sm w-100" data-toggle="buttons">
<label class="btn btn-light active col" title="Do Not Automatically Stash Sessions">
<input type="radio" name="stash-auto" id="stash-auto-no" autocomplete="off" checked> Off
</label>
<label class="btn btn-light col" title="Automatically Stash Sessions">
<input type="radio" name="stash-auto" id="stash-auto-yes" autocomplete="off"> On
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="sequence-controls-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="#sequence-controls-title" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 id="sequence-controls-title" class="modal-title">Sequence Settings</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul class="nav nav-tabs" id="sequence-controls-tab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="sequence-alignment-tab" data-toggle="tab" href="#sequence-alignment" role="tab" aria-controls="sequence-alignment" aria-selected="true">Alignment</a>
</li>
<li class="nav-item">
<a class="nav-link" id="sequence-auditor-tab" data-toggle="tab" href="#sequence-auditor" role="tab" aria-controls="sequence-auditor" aria-selected="false">Audit</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="sequence-alignment" role="tabpanel" aria-labelledby="sequence-alignment-tab">
<div class="form-group row">
<div class="col-12">
<div class="alert alert-warning alert-dismissible" role="alert">
<p>
MicrobeTrace is not intended to be an alignment program (although it can be used in that way).
For best results, please align your sequences using
<a href="https://en.wikipedia.org/wiki/List_of_sequence_alignment_software" target="_blank" rel="noreferrer noopener">an external tool</a>
before loading them into MicrobeTrace.
<a href="https://github.com/CDCgov/MicrobeTrace/wiki/Alignment" class="ifOnline" target="_blank" rel="noreferrer noopener">Click here for additional information.</a>
</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-2" title="Should MicrobeTrace align your sequences?">Align</div>
<div class="col-10">
<div class="btn-group btn-group-toggle btn-group-sm w-100" data-toggle="buttons">
<label class="btn btn-light active col" title="Do Not Align Sequences">
<input type="radio" name="shouldAlign" id="align-none" data-aligner="none" autocomplete="off" checked>
None
</label>
<label class="btn btn-light col" title="Align Sequences using Smith-Waterman aligner">
<input type="radio" name="shouldAlign" id="align-sw" data-aligner="sw" autocomplete="off">
Smith-Waterman
</label>
</div>
</div>
</div>
<div class="form-group row alignConfigRow">
<div class="col-2" title="What should MicrobeTrace use as a reference to align your sequences?">Reference Source</div>
<div class="col-10">
<div class="btn-group btn-group-toggle btn-group-sm w-100" data-toggle="buttons">
<label class="btn btn-light active col" title="Load Reference from FASTA">
<input type="radio" name="reference-source" id="reference-source-file" autocomplete="off" checked>
Load From FASTA
</label>
<label class="btn btn-light col" title="Use First Sequence as Reference">
<input type="radio" name="reference-source" id="reference-source-first" autocomplete="off">
First Sequence
</label>
<label class="btn btn-light col" title="Generate a Consensus Sequence to use as a Reference">
<input type="radio" name="reference-source" id="reference-source-consensus" autocomplete="off">
Consensus
</label>
</div>
</div>
</div>
<div class="form-group row" id="reference-file-row">
<div class="col-2" title="Against what sequence should MicrobeTrace align your sequences?">Reference</div>
<div class="col-5">
<div class="custom-file">
<input type="file" class="custom-file-input" id="refSeqFileLoad">
<label class="custom-file-label" for="refSeqFileLoad" style="overflow:hidden">HXB2</label>
</div>
</div>
<div class="col-5">
<select id="refSeqID" class="form-control"></select>
</div>
</div>
<div class="row alignConfigRow">
<div class="form-group col offset-2" title="How much should MicrobeTrace reward matching bases?">
<label for="alignerMatch">Match Reward</label>
<input type="number" id="alignerMatch" class="form-control" value="1" min="0">
</div>
<div class="form-group col" title="How much should MicrobeTrace penalize non-matching bases?">
<label for="alignerMismatch">Mismatch Cost</label>
<input type="number" id="alignerMismatch" class="form-control" value="1" min="0">
</div>
</div>
<div class="row alignConfigRow">
<div class="form-group col offset-2" title="How much should MicrobeTrace Penalize opening a gap?">
<label for="alignerGapO">Gap Opening Cost</label>
<input type="number" id="alignerGapO" class="form-control" value="5" min="0">
</div>
<div class="form-group col" title="How much should MicrobeTrace Penalize extending a gap?">
<label for="alignerGapE">Gap Extension Cost</label>
<input type="number" id="alignerGapE" class="form-control" value="2" min="0">
</div>
</div>
<div class="row alignPreviewRow">
<div class="w-100 text-center" id="alignment-preview"></div>
</div>
</div>
<div class="tab-pane fade" id="sequence-auditor" role="tabpanel" aria-labelledby="sequence-auditor-tab">
<div class="row mb-3">
<div class="form-check col" title="Checks to see if a Sequence is empty.">
<input class="form-check-input" type="checkbox" id="audit-empty" checked>
<label class="form-check-label" for="audit-empty">
Empty
</label>
</div>
<div class="form-check col" title="Checks to see if a Sequence is all gaps.">
<input class="form-check-input" type="checkbox" id="audit-gaps" checked>
<label class="form-check-label" for="audit-gaps">
Gaps
</label>
</div>
<div class="form-check col" title="Check to see if sequence contains any characters that are RNA instead of DNA.">
<input class="form-check-input" type="checkbox" id="audit-RNA" checked>
<label class="form-check-label" for="audit-RNA">
RNA
</label>
</div>
<div class="form-check col" title="Check to see if Sequence contains any characters that represent Amino Acids.">
<input class="form-check-input" type="checkbox" id="audit-amino-acids" checked>
<label class="form-check-label" for="audit-amino-acids">
Amino Acids
</label>
</div>
<div class="form-check col" title="Check to see if Sequence contains any characters describing an alignment.">
<input class="form-check-input" type="checkbox" id="audit-CIGAR" checked>
<label class="form-check-label" for="audit-CIGAR">
CIGAR
</label>
</div>
<div class="form-check col" title="Check to see if Sequence contains any characters that are illegal in any genomic or proteomic alphabet.">
<input class="form-check-input" type="checkbox" id="audit-malformed" checked>
<label class="form-check-label" for="audit-malformed">
Malformed
</label>
</div>
<div class="col">
<button type="button" class="btn btn-primary btn-sm w-100" id="audit-launcher">Run</button>
</div>
</div>
<div class="row" id="audited-sequences"></div>
<div class="row flex-row-reverse" style="padding-right: 21px">
<button class="btn btn-danger btn-sm" id="audit-toggle-all">Toggle All</button>
</div>
</div>
</div>
</div>
<div class="modal-footer clearfix">
<button type="submit" class="btn btn-success pull-right" data-dismiss="modal"
title="Confirm Load Settings are All Properly Set">Confirm</button>
</div>
</div>
</div>
</div>
<script>
(function () {
ga('set', 'page', '/files');
ga('set', 'title', 'Files View');
ga('send', 'pageview');
'use strict';
$('#file-panel').parent().css('z-index', 1000);
$('#file-settings-toggle').on('click', function () {
const pane = $('#file-settings-pane');
if ($(this).hasClass('active')) {
pane.animate({ left: '-400px' }, () => pane.hide());
} else {
pane.show(0, () => pane.animate({ left: '0px' }));
}
});
if (session.files.length > 0) {
$('#file-prompt, #warning-prompt').remove();
session.files.forEach(addToTable);
}
$('#data-files').on('change', function () {
processFiles(this.files);
});
$('#file-panel').on('dragover', evt => {
evt.stopPropagation();
evt.preventDefault();
evt.originalEvent.dataTransfer.dropEffect = 'copy';
}).on('drop', evt => {
evt.stopPropagation();
evt.preventDefault();
processFiles(evt.originalEvent.dataTransfer.files);
});
function processFiles(files){
const n = files.length;
$('#file-prompt, #warning-prompt').remove();
for (let i = 0; i < n; i++) processFile(files[i]);
$('#launch').prop('disabled', false).focus();
}
function processFile(rawfile) {
const extension = rawfile.name.split('.').pop().toLowerCase();
if (extension == 'zip') {
let new_zip = new JSZip();
new_zip
.loadAsync(rawfile)
.then(zip => {
zip.forEach((relativePath, zipEntry) => {
zipEntry.async("string").then(c => {
MT.processJSON(c, zipEntry.name.split('.').pop())
});
});
});
return;
}
if (extension == 'microbetrace' || extension == 'hivtrace') {
let reader = new FileReader();
reader.onloadend = out => MT.processJSON(out.target.result, extension);
reader.readAsText(rawfile, 'UTF-8');
return;
}
if (extension == 'svg') {
let reader = new FileReader();
reader.onloadend = out => MT.processSVG(out.target.result);
reader.readAsText(rawfile, 'UTF-8');
return;
}
fileto.promise(rawfile, (extension == 'xlsx' || extension == 'xls') ? 'ArrayBuffer' : 'Text').then(file => {
file.name = filterXSS(file.name);
file.extension = file.name.split('.').pop().toLowerCase();
session.files.push(file);
addToTable(file);
});
}
function addToTable(file) {
const extension = file.extension ? file.extension : filterXSS(file.name).split('.').pop().toLowerCase();
//#291 restore to previous filetype selection if available
const isFasta = 'fasta' == file.format || extension.indexOf('fas') > -1;
const isNewick = 'newick' == file.format ||extension.indexOf('nwk') > -1 || extension.indexOf('newick') > -1;
const isXL = (extension == 'xlsx' || extension == 'xls');
const isNode = 'node' == file.format || file.name.toLowerCase().includes('node');
if (isXL) {
let workbook = XLSX.read(file.contents, { type: 'array' });
let data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {raw: false, dateNF: 'yyyy-mm-dd'});
let headers = [];
data.forEach(row => {
Object.keys(row).forEach(key => {
const safeKey = filterXSS(key);
if (!headers.includes(safeKey)) headers.push(safeKey);
});
});
addTableTile(headers);
} else {
Papa.parse(file.contents, {
delimiter: ",",
// newline: "\r\n",
header: true,
preview: 1,
complete: output => addTableTile(output.meta.fields.map(filterXSS))
});
}
//For the love of all that's good...
//TODO: Rewrite this as a [Web Component](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) or [something](https://reactjs.org/docs/react-component.html) or something.
function addTableTile(headers) {
let root = $('<div class="file-table-row"></div>').data('filename', file.name);
let fnamerow = $('<div class="row w-100"></div>');
$('<div class="file-name col"></div>')
.append($('<a href="#" class="oi oi-circle-x align-middle p-1" title="Remove this file"></a>').on('click', () => {
session.files.splice(session.files.findIndex(f => f.name == file.name), 1);
root.slideUp(() => root.remove());
}))
.append($('<a href="#" class="oi oi-data-transfer-download align-middle p-1" title="Resave this file"></a>').on('click', () => {
saveAs(new Blob([file.contents], { type: file.type | 'text' }), file.name);
}))
.append('<span class="p-1">' + file.name + '</span>')
.append(`
<div class="btn-group btn-group-toggle btn-group-sm float-right" data-toggle="buttons">
<label class="btn btn-light${!isFasta & !isNewick & !isNode ? ' active' : ''}">
<input type="radio" name="options-${file.name}" data-type="link" autocomplete="off"${!isFasta & !isNewick & !isNode ? ' checked' : ''}>Link
</label>
<label class="btn btn-light${!isFasta & !isNewick & isNode ? ' active' : ''}">
<input type="radio" name="options-${file.name}" data-type="node" autocomplete="off"${!isFasta & !isNewick & isNode ? ' checked' : ''}>Node
</label>
<label class="btn btn-light">
<input type="radio" name="options-${file.name}" data-type="matrix" autocomplete="off">Matrix
</label>
<label class="btn btn-light${isFasta ? ' active' : ''}">
<input type="radio" name="options-${file.name}" data-type="fasta" autocomplete="off"${isFasta ? ' checked' : ''}>FASTA
</label>
<label class="btn btn-light${isNewick ? ' active' : ''}">
<input type="radio" name="options-${file.name}" data-type="newick" autocomplete="off"${isNewick ? ' checked' : ''}>Newick
</label>
</div>
`).appendTo(fnamerow);
fnamerow.appendTo(root);
let optionsrow = $('<div class="row w-100"></div>');
let options = '<option>None</option>' + headers.map(h => `<option value="${h}">${MT.titleize(h)}</option>`).join('\n');
optionsrow.append(`
<div class='col-4 '${isFasta || isNewick ? ' style="display: none;"' : ''} data-file='${file.name}'>
<label for="file-${file.name}-field-1">${isNode ? 'ID' : 'Source'}</label>
<select id="file-${file.name}-field-1" class="form-control form-control-sm">${options}</select>
</div>
<div class='col-4 '${isFasta || isNewick ? ' style="display: none;"' : ''} data-file='${file.name}'>
<label for="file-${file.name}-field-2">${isNode ? 'Sequence' : 'Target'}</label>
<select id="file-${file.name}-field-2" class="form-control form-control-sm">${options}</select>
</div>
<div class='col-4 '${isFasta || isNewick ? ' style="display: none;"' : ''} data-file='${file.name}'>
<label for="file-${file.name}-field-3">Distance</label>
<select id="file-${file.name}-field-3" class="form-control form-control-sm">${options}</select>
</div>
`);
optionsrow.appendTo(root);
function matchHeaders(type) {
const these = $(`[data-file='${file.name}'] select`);
if(file.field1) {
//#291 restore to previous variable selection if available
$(these.get(0)).val(file.field1);
$(these.get(1)).val(file.field2);
$(these.get(2)).val(file.field3);
} else {
const a = type == 'node' ? ['ID', 'Id', 'id'] : ['SOURCE', 'Source', 'source'],
b = type == 'node' ? ['SEQUENCE', 'SEQ', 'SEQS', 'Sequence', 'Seqs', 'sequence', 'seq', 'seqs'] : ['TARGET', 'Target', 'target'],
c = ['length', 'Length', 'distance', 'Distance', 'snps', 'SNPs', 'tn93', 'TN93'];
[a, b, c].forEach((list, i) => {
$(these.get(i)).val("None");
list.forEach(title => {
if (headers.includes(title)) $(these.get(i)).val(title);
});
if ($(these.get(i)).val() == 'None' &&
!(i == 1 && type == 'node') && //If Node Sequence...
!(i == 2 && type == 'link')) { //...or Link distance...
//...don't match to a variable in the dataset, leave them as "None".
$(these.get(i)).val(headers[i]);
//Everything else, just guess the next ordinal column.
}
});
}
}
root.appendTo('#file-table');
matchHeaders($(`[name="options-${file.name}"]:checked`).data('type'));
function refit(e) {
const type = $(e ? e.target : `[name="options-${file.name}"]:checked`).data('type'),
these = $(`[data-file='${file.name}']`),
first = $(these.get(0)),
second = $(these.get(1)),
third = $(these.get(2));
if (type == 'node') {
first.slideDown().find('label').text('ID');
second.slideDown().find('label').text('Sequence');
third.slideUp();
matchHeaders(type);
} else if (type == 'link') {
first.slideDown().find('label').text('Source');
second.slideDown().find('label').text('Target');
third.slideDown();
matchHeaders(type);
} else {
these.slideUp();
}
updateMetadata(file);
}
// $(`#file-${file.name}-field-1`).change(() => updateMetadata(file));
// $(`#file-${file.name}-field-2`).change(() => updateMetadata(file));
// $(`#file-${file.name}-field-3`).change(() => updateMetadata(file));
document.getElementById(`file-${file.name}-field-1`).addEventListener('change', (event) => {
updateMetadata(file);
$('#launch').prop('disabled', false);
});
document.getElementById(`file-${file.name}-field-2`).addEventListener('change', (event) => {
updateMetadata(file);
$('#launch').prop('disabled', false);
});
document.getElementById(`file-${file.name}-field-3`).addEventListener('change', (event) => {
updateMetadata(file);
$('#launch').prop('disabled', false);
});
$(`[name="options-${file.name}"]`).change(() => {
refit();
$('#launch').prop('disabled', false);
});
refit();
}
}
function updateMetadata(file){
$('#file-panel .file-table-row').each((i, el) => {
const $el = $(el);
const fname = $el.data('filename');
const selects = $el.find('select');
const f = session.files.find(file => file.name == fname);
f.format = $el.find('input[type="radio"]:checked').data('type');
f.field1 = selects.get(0).value;
f.field2 = selects.get(1).value;
f.field3 = selects.get(2).value;
});
}
async function readFastas() {
const fastas = session.files.filter(f => f.extension.includes('fas'));
const nodeCSVsWithSeqs = session.files.filter(f => f.format == "node" && f.field2 != "None" && f.field2 != "");
if (fastas.length == 0 && nodeCSVsWithSeqs.length == 0) return [];
let data = [];
for(let i = 0; i < fastas.length; i++){
let fasta = fastas[i];
let nodes = await MT.parseFASTA(fasta.contents);
data = data.concat(nodes);
}
// TODO: Cannot presently preview sequences in Node CSV/XLSX tables.
// for(let j = 0; j < nodeCSVsWithSeqs.length; j++){
// let csv = nodeCSVsWithSeqs[j];
// await MT.parseNodeCSV(csv.contents).then(nodes => {
// data = data.concat(nodes);
// });
// }
return data;
}
async function updatePreview(data) {
$('#alignment-preview').empty().append('<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>');
if ($('#align-sw').is(':checked')) {
data = await MT.align({
nodes: data,
reference: session.data.reference,
match: [parseFloat($('#alignerMatch').val()), -parseFloat($('#alignerMismatch').val())],
gap: [-parseFloat($('#alignerGapO').val()), -parseFloat($('#alignerGapE').val())]
})
}
alignmentViewer(data, { showID: false })
.then(canvas => $('#alignment-preview').empty().append(canvas));
}
$('.alignConfigRow').hide();
$('#align-sw').parent().on('click', () => {
session.style.widgets['align-sw'] = true;
session.style.widgets['align-none'] = false;
$('.alignConfigRow, #reference-file-row').slideDown();
$('#alignment-preview').slideUp(function() {
$(this).empty().show();
});
});
$('#align-none').parent().on('click', () => {
session.style.widgets['align-sw'] = false;
session.style.widgets['align-none'] = true;
$('.alignConfigRow, #reference-file-row').slideUp();
$('#alignment-preview').slideUp(function () {
$(this).empty().show();
});
});
$('#reference-source-file').parent().on('click', () => {
session.style.widgets['reference-source-file'] = true;
session.style.widgets['reference-source-first'] = false;
session.style.widgets['reference-source-consensus'] = false;
session.data.reference = $('#refSeqID').val();
if(!session.style.widgets['align-none']) $('#reference-file-row').slideDown();
});
$('#reference-source-first').parent().on('click', () => {
session.style.widgets['reference-source-file'] = false;
session.style.widgets['reference-source-first'] = true;
session.style.widgets['reference-source-consensus'] = false;
$('#reference-file-row').slideUp();
});
$('#reference-source-consensus').parent().on('click', () => {
session.style.widgets['reference-source-file'] = false;
session.style.widgets['reference-source-first'] = false;
session.style.widgets['reference-source-consensus'] = true;
$('#reference-file-row').slideUp();
});
$('#reference-file-row').hide();
$('#refSeqFileLoad').on('change', function () {
const file = this.files[0];
let reader = new FileReader();
reader.onloadend = e => {
if (e.target.readyState == FileReader.DONE) {
MT.parseFASTA(e.target.result).then(nodes => {
$('#refSeqID')
.html(nodes.map((d, i) => `
<option value="${filterXSS(d.seq)}" ${i == 0 ? "selected" : ""}>${filterXSS(d.id)}</option>
`))
.trigger('change');
});
$('label[for="refSeqFileLoad"]').text(filterXSS(file.name));
}
};
reader.readAsText(file);
});
$('#refSeqID').html(`
<option value="${MT.HXB2.substr(2000, 2100)}" selected>Pol</option>
<option value="${MT.HXB2}">Complete</option>
`).on('change', function(){ session.data.reference = this.value; });
$('#sequenceControlsButton, #alignment-preview').on('click', () => {
readFastas().then(data => {
if(session.style.widgets['reference-source-first']){
session.data.reference = nodes[0].seq;
}
if(session.style.widgets['reference-source-consensus']){
MT.computeConsensus().then(consensus => session.data.reference = consensus);
}
updatePreview(data);
});
});
let auditBlock = $('#audited-sequences');
const logAudit = (id, type) => {
let match = auditBlock.find(`[data-id="${id}"]`);
let button = $(`<button class="btn btn-warning btn-sm audit-exclude" data-id="${id}">Exclude</button>`).on('click', function(){
let thi$ = $(this);
const id = thi$.data('id');
if(thi$.text() == 'Exclude'){
session.data.nodeExclusions.push(id);
thi$.removeClass('btn-warning').addClass('btn-success').text('Include');
} else {
session.data.nodeExclusions.splice(session.data.nodeExclusions.indexOf(id), 1);
thi$.removeClass('btn-success').addClass('btn-warning').text('Exclude');
}
});
let row = $(`<div class="alert alert-warning w-100 d-flex justify-content-between" role="alert"><span>${id} appears to be ${type}.</span></div>`);
row.append(button);
auditBlock.append(row);
};
$('#audit-launcher').on('click', () => {
readFastas().then(data => {
const start = Date.now();
const isGaps = /^-+$/;
const isRNA = /^[ACGURYMKWSBDHVN-]+$/;
const isAA = /^[ARNDCQEGHILKMFPSTWYVBZN]+$/;
const isDNA = /^[ACGTRYMKWSBDHVN-]+$/;
const isCIGAR = /^[0-9MIDNSHP=X]+$/;
const isMalformed = /[^ACGTURYMKWSBDHVNQEILFPZX0-9-]+/;
const checkEmpty = $('#audit-empty').is(':checked');
const checkGaps = $('#audit-gaps').is(':checked');
const checkRNA = $('#audit-RNA').is(':checked');
const checkAA = $('#audit-amino-acids').is(':checked');
const checkCIGAR = $('#audit-CIGAR').is(':checked');
const checkMalformed = $('#audit-malformed').is(':checked');
let any = false;
data.forEach(d => {
const seq = d.seq, id = d.id;
if(checkEmpty && seq == '') logAudit(id, 'empty');
if(checkGaps && isGaps.test(seq)) logAudit(id, 'all gaps')
if(checkRNA && isRNA.test(seq) && !isGaps.test(seq)) logAudit(id, 'RNA');
if(checkAA && isAA.test(seq) && !isDNA.test(seq)) logAudit(id, 'amino acids');
if(checkCIGAR && isCIGAR.test(seq)) logAudit(id, 'a CIGAR');
if(checkMalformed && isMalformed.test(seq)) logAudit(id, 'malformed');
});
console.log('Sequence Auditing time:', (Date.now() - start).toLocaleString(), 'ms');
});
});
$('#audit-toggle-all').on('click', () => {
$('.audit-exclude').trigger('click');
});
$('#default-distance-metric').change(function () {
ga('send', 'event', 'default-distance-metric', 'update', this.value);
const lsv = this.value;
localforage.setItem('default-distance-metric', lsv);
$('#default-distance-metric').val(lsv);
if (lsv == 'snps') {
$('#ambiguities-row').slideUp();
$('#default-distance-threshold, #link-threshold')
.attr('step', 1)
.val(16);
session.style.widgets["link-threshold"] = 16;
} else {
$('#ambiguities-row').slideDown();
$('#default-distance-threshold, #link-threshold')
.attr('step', 0.001)
.val(0.015);
session.style.widgets["link-threshold"] = 0.015;
}
session.style.widgets['default-distance-metric'] = lsv;
});
$('#default-distance-threshold').change(function () {
session.style.widgets["link-threshold"] = this.value;
});
localforage.getItem('default-distance-metric').then(cachedLSV => {
if (cachedLSV) {
$('#default-distance-metric').val(cachedLSV).trigger('change');
}
});
$('#ambiguity-resolution-strategy').on('change', function () {
const v = this.value;
session.style.widgets['ambiguity-resolution-strategy'] = v;
if(v == 'HIVTRACE-G'){
$('#ambiguity-threshold-row').slideDown();
} else {
$('#ambiguity-threshold-row').slideUp();
}
}).change();
$('#ambiguity-threshold').on('change', function(){
const v = this.value;
session.style.widgets['ambiguity-threshold'] = v;
});
localforage.getItem('default-view').then(cachedView => {
$('#default-view')
.on('change', function () {
const v = this.value;
localforage.setItem('default-view', v);
session.style.widgets['default-view'] = v;
session.layout.content[0].type = v;
})
.val(cachedView ? cachedView : session.style.widgets['default-view'])
.trigger('change');
});
$('#generate-sequences').on('click', () => {
$('#file-prompt, #warning-prompt').remove();
$('#launch').prop('disabled', false).focus();
processFile(new File([Papa.unparse(MT.generateSeqs('gen-' + session.meta.readyTime + '-', parseFloat($('#generate-number').val()), 20))], 'generatedNodes.csv'));
});
$('#infer-directionality-false').parent().on('click', () => {
session.style.widgets['infer-directionality-false'] = true;
});
$('#infer-directionality').parent().on('click', () => {
session.style.widgets['infer-directionality-false'] = false;
});
$('#triangulate-false').parent().on('click', () => {
session.style.widgets['triangulate-false'] = true;
});
$('#triangulate').parent().on('click', () => {
session.style.widgets['triangulate-false'] = false;
});
$('#stash-auto-yes').parent().on('click', () => {
localforage.setItem('stash-auto', 'true');
});
localforage.getItem('stash-auto').then(autostash => {
if (autostash == 'true') {
$('#stash-auto-yes').parent().trigger('click');
}
});
$('#stash-auto-no').parent().on('click', () => {
if (temp.autostash) clearInterval(temp.autostash.interval);
localforage.setItem('stash-auto', 'false');
});
function message(msg) {
session.messages.push(msg);
$('#loading-information').html(session.messages.join('<br>'));
}
$('#launch').on('click', () => {
session.meta.startTime = Date.now();
$('#launch').prop('disabled', true);
document.getElementById('loading-information').innerHTML="<p>Processing file(s)...</p>";
new Promise(function(resolve, reject) {
$('#loading-information-modal').on('shown.bs.modal', function (e) {
session.messages = [];
$('#loading-information').html('');
resolve("done");
});
$('#loading-information-modal').modal({
backdrop: false,
keyboard: false
});
setTimeout(() => reject(new Error("Problem loading information modal!")), 5000);
}).then(
result => launch(), //
error => {alert(error); launch(); } // informational modal doesn't load
);
})
const launch = async () => {
temp.messageTimeout = setTimeout(() => {
$('#loadCancelButton').slideDown();
alertify.warning('If you stare long enough, you can reverse the DNA Molecule\'s spin direction');
}, 20000);
const nFiles = session.files.length - 1;
const check = nFiles > 0;
const hierarchy = ['newick', 'matrix', 'link', 'node', 'fasta'];
session.files.sort((a, b) => hierarchy.indexOf(a.format) - hierarchy.indexOf(b.format));
session.meta.anySequences = session.files.some(file => (file.format == "fasta") || (file.format == "node" && file.field2 !== "None"));
session.files.forEach((file, fileNum) => {
const start = Date.now();
const origin = [file.name];
if (file.format == 'fasta') {
message(`Parsing ${file.name} as FASTA...`);
let newNodes = 0;
MT.parseFASTA(file.contents).then(seqs => {
const n = seqs.length;
for (let i = 0; i < n; i++) {
let node = seqs[i];
if (!node) continue;
newNodes += MT.addNode({
_id: filterXSS(node.id),
seq: filterXSS(node.seq),
origin: origin
}, check);
}
console.log('FASTA Merge time:', (Date.now() - start).toLocaleString(), 'ms');
message(` - Parsed ${newNodes} New, ${seqs.length} Total Nodes from FASTA.`);
if (fileNum == nFiles) processSequences();
});
} else if (file.format == 'link') {
message(`Parsing ${file.name} as Link List...`);
let l = 0;
let forEachLink = link => {
const keys = Object.keys(link);
const n = keys.length;
let safeLink = {};
for (let i = 0; i < n; i++) {
let key = filterXSS(keys[i]);
safeLink[key] = (typeof link[key] === 'string') ? filterXSS(link[key]) : link[key]; // #195
if (!session.data.linkFields.includes(key)) {
session.data.linkFields.push(key);
}
}
l += MT.addLink(Object.assign({
source: '' + safeLink[file.field1],
target: '' + safeLink[file.field2],
origin: origin,
visible: true,
distance: file.field3 == 'None' ? 0 : parseFloat(safeLink[file.field3])
}, safeLink), check);
};
if (file.extension == 'xls' || file.extension == 'xlsx') {
let workbook = XLSX.read(file.contents, { type: 'array' });
let data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {raw: false, dateNF: 'yyyy-mm-dd'});
data.map(forEachLink);
message(` - Parsed ${l} New, ${data.length} Total Links from Link Excel Table.`);
let n = 0, t = 0;
let nodeIDs = [];
const k = data.length;
for (let i = 0; i < k; i++) {
const l = data[i];
const f1 = l[file.field1];
if (nodeIDs.indexOf(f1) == -1) {
t++;
nodeIDs.push(f1);
n += MT.addNode({
_id: '' + f1,
origin: origin
}, true);
}
const f2 = l[file.field2];
if (nodeIDs.indexOf(f2) == -1) {
t++;
nodeIDs.push(f2);
n += MT.addNode({
_id: '' + f2,
origin: origin
}, true);
}
}
console.log('Link Excel Parse time:', (Date.now() - start).toLocaleString(), 'ms');
message(` - Parsed ${n} New, ${t} Total Nodes from Link Excel Table.`);
if (fileNum == nFiles) processSequences();
} else {
Papa.parse(file.contents, {
delimiter: ",",
// newline: "\r\n",
header: true,
dynamicTyping: true,
skipEmptyLines: true,
complete: results => {
let data = results.data;
data.map(forEachLink);
message(` - Parsed ${l} New, ${data.length} Total Links from Link CSV.`);
results.meta.fields.forEach(key => {
const safeKey = filterXSS(key);
if (!session.data.linkFields.includes(safeKey)) {
session.data.linkFields.push(safeKey);
}
});
let newNodes = 0, totalNodes = 0;
const n = data.length;
let nodeIDs = [];
for (let i = 0; i < n; i++) {
const l = data[i];
const f1 = l[file.field1];
if (nodeIDs.indexOf(f1) == -1) {
totalNodes++;
newNodes += MT.addNode({
_id: '' + f1,
origin: origin
}, true);
}
const f2 = l[file.field2];
if (nodeIDs.indexOf(f2) == -1) {
totalNodes++;
newNodes += MT.addNode({