-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSequenceImportPanel.js
More file actions
2768 lines (2544 loc) · 125 KB
/
SequenceImportPanel.js
File metadata and controls
2768 lines (2544 loc) · 125 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
/*
* Copyright (c) 2012 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
Ext4.define('SequenceAnalysis.panel.SequenceImportPanel', {
extend: 'SequenceAnalysis.panel.BaseSequencePanel',
alias: 'widget.sequenceanalysis-sequenceimportpanel',
jobType: 'readsetImport',
initComponent: function(){
Ext4.override(Ext4.data.validations, {
presenceMessage: 'Field is required'
});
this.fileGroupStore = Ext4.create('Ext.data.ArrayStore', {
model: Ext4.define('SequenceAnalysis.model.FileSetModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'fileGroupId'}
]
})
});
this.readsetStore = Ext4.create('Ext.data.ArrayStore', {
validateAll: function(){
this.each(function(r){
r.validate();
})
},
model: Ext4.define('SequenceAnalysis.model.ReadsetModel', {
sequenceImportPanel: this,
extend: 'Ext.data.Model',
fields: [
{name: 'fileGroupId', allowBlank: false, sortType: SequenceAnalysis.Utils.getNaturalSortValue},
{name: 'readset', allowBlank: false, sortType: SequenceAnalysis.Utils.getNaturalSortValue},
{name: 'readsetname', useNull: true},
{name: 'importType', useNull: true},
{name: 'barcode5', useNull: true},
{name: 'barcode3', useNull: true},
{name: 'platform', allowBlank: false},
{name: 'application', allowBlank: false},
{name: 'chemistry', allowBlank: false},
{name: 'concentration', type: 'float', useNull: true},
{name: 'fragmentSize', type: 'float', useNull: true},
{name: 'librarytype', useNull: true},
{name: 'sampletype', useNull: true},
{name: 'subjectid', useNull: true},
{name: 'sampledate', type: 'date'},
{name: 'comments', useNull: true},
{name: 'sampleid', useNull: true},
{name: 'instrument_run_id', type: 'int', useNull: true}
],
validations: [
{type: 'presence', field: 'fileGroupId'},
{type: 'presence', field: 'readsetname'},
{type: 'presence', field: 'platform'},
{type: 'presence', field: 'application'}
],
getFileId: function(){
return [this.get('fileGroupId'), this.get('barcode5'), this.get('barcode3')].join('||');
},
validate: function(options) {
var errors = this.callParent(arguments);
var id = this.getFileId();
var name = this.get('readsetname');
var doDemultiplex = this.sequenceImportPanel.down('#doDemultiplex').getValue();
if (doDemultiplex && !this.get('barcode5') && !this.get('barcode3')){
var msg = 'Demultiplexing was selected, must enter at least one barcode.';
errors.add({
field: 'barcode5',
message: msg
});
errors.add({
field: 'barcode3',
message: msg
});
}
if (this.store){
this.store.each(function(r){
if (r !== this && r.getFileId() === id){
var msg = 'Only one readset may use each file group, unless barcoding is used.';
errors.add({
field: 'fileGroupId',
message: msg
});
errors.add({
field: 'barcode5',
message: msg
});
errors.add({
field: 'barcode3',
message: msg
});
}
if (r !== this && r.get('readsetname') === name){
errors.add({
field: 'readsetname',
message: 'All names must be unique'
});
}
}, this);
if (this.sequenceImportPanel.down('#importReadsetIds').getValue()){
if (!this.get('readset')){
errors.add({
field: 'readset',
message: 'This field is required.'
});
}
}
}
return errors;
},
hasMany: {model: 'SequenceAnalysis.model.ReadsetDataModel', name: 'files'}
})
});
this.readDataStore = Ext4.create('Ext.data.ArrayStore', {
groupField: 'fileGroupId',
model: Ext4.define('SequenceAnalysis.model.ReadsetDataModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', sortType: SequenceAnalysis.Utils.getNaturalSortValue},
{name: 'fileGroupId', allowBlank: false, sortType: SequenceAnalysis.Utils.getNaturalSortValue},
{name: 'fileRecord1'},
{name: 'fileRecord2'},
{name: 'platformUnit'},
{name: 'centerName'},
{name: 'comments'}
],
validations: [
{type: 'presence', field: 'fileGroupId'},
{type: 'presence', field: 'fileRecord1'}
],
validate: function(options) {
var errors = this.callParent(arguments);
var file1 = this.get('fileRecord1');
var file2 = this.get('fileRecord2');
if (file1 === file2){
errors.add({
field: 'fileRecord1',
message: 'The forward and reverse reads cannot use the same file'
});
}
if (this.store){
var otherFiles = [];
this.store.each(function(r) {
if (r !== this) {
if (r.get('fileRecord1')){
otherFiles.push(r.get('fileRecord1'));
}
if (r.get('fileRecord2')){
otherFiles.push(r.get('fileRecord2'));
}
}
}, this);
otherFiles = Ext4.unique(otherFiles);
if (file1 && otherFiles.indexOf(file1) !== -1){
errors.add({
field: 'fileRecord1',
message: 'This file is being used by another group'
});
}
if (file2 && otherFiles.indexOf(file2) !== -1){
errors.add({
field: 'fileRecord2',
message: 'This file is being used by another group'
});
}
}
return errors;
},
belongsTo: 'SequenceAnalysis.model.ReadsetModel'
})
});
Ext4.apply(this, {
configDefaults: {},
buttonAlign: 'left',
buttons: [{
text: 'Import Data',
itemId: 'startAnalysis',
handler: this.onSubmit,
scope: this
}]
});
Ext4.QuickTips.init();
this.callParent(arguments);
this.add([{
xtype: 'panel',
width: '100%',
title: 'Instructions',
defaults: {
border: false
},
items: [{
style: 'padding-bottom:10px;',
html: 'The purpose of this import process is to normalize the sequence data into a common format (FASTQ), create one file per sample, and capture sample metadata (name, sample type, subject name, etc). Reads are organized into readsets. ' +
'Each readset is roughly equals to one input file (or 2 for pair-end data), and it connects the sequences in this file with sample attributes, such as subject name, sample type, platform, etc.'
},{
html: '<h4><a href="https://bimberlab.github.io/DiscvrLabKeyModules/discvr-seq/management.html" target="_blank">Click here for more detailed instructions</a></h4>'
}]
}, this.getRunInfoCfg(), this.getFilePanelCfg(),{
xtype:'panel',
border: true,
title: 'Step 1: General Options',
itemId: 'sampleInformation',
bodyStyle: 'padding:5px;',
width: '100%',
defaults: {
border: false,
width: '100%'
},
items :[{
width: '700',
html: 'Note: all input files will be automatically converted to FASTQ (ASCII offset 33) if not already.',
style: 'padding-bottom:10px;',
border: false
},SequenceAnalysis.panel.SequenceImportPanel.getInputFileTreatmentField({itemId: 'originalFileTreatment', name: 'inputFileTreatment'}),{
xtype: 'checkbox',
name: 'deleteIntermediateFiles',
fieldLabel: 'Delete Intermediate Files',
checked: true,
helpPopup: 'If selected, all intermediate sequence files will be deleted. These files are usually only needed for debugging purposes, and it is selected by default to save space.'
},{
fieldLabel: 'Run FastQC',
helpPopup: 'Use this option to automatically run and cache a FastQC report. For large input files, FastQC can take a long time to run. Pre-caching this information may be useful later.',
name: 'inputfile.runFastqc',
xtype:'checkbox',
itemId: 'runFastqc',
checked: true
},{
xtype: 'checkbox',
name: 'inputfile.flagLowReads',
inputValue: true,
fieldLabel: 'Flag Readsets With Low Reads',
helpPopup: 'If checked, readsets with fewer than the provided number of reads will be automatically flagged with the specified status.',
scope: this,
handler: function(btn, val){
btn.up('form').down('#lowReadThresholdOptions').setVisible(btn.checked);
}
},{
xtype: 'fieldset',
style: 'padding:5px;',
hidden: true,
hideMode: 'offsets',
width: 'auto',
itemId: 'lowReadThresholdOptions',
fieldDefaults: {
width: 350
},
items: [{
xtype: 'ldk-numberfield',
fieldLabel: 'Read Threshold',
helpPopup: 'Readsets with fewer than this many reads will be flagged',
minValue: 0,
name: 'inputfile.lowReadThreshold',
value: 1000
},{
xtype: 'ldk-simplelabkeycombo',
fieldLabel: 'Status',
schemaName: 'sequenceanalysis',
queryName: 'readset_status',
sortField: 'status',
valueField: 'status',
value: 'Failed',
displayField: 'status',
plugins: ['ldk-usereditablecombo'],
name: 'inputfile.lowReadStatusLabel'
}]
}]
},this.getReadDataSection(), this.getReadsetSection(), {
xtype: 'panel',
style: 'padding-bottom: 0px;',
width: '100%',
border: false,
items: [{
border: false,
width: '100%',
style: 'text-align: center',
html: 'Powered By DISCVR-Seq. <a href="https://bimberlab.github.io/DiscvrLabKeyModules/discvr-seq/overview.html">Click here to learn more.</a>'
}]
}]);
this.on('afterrender', this.updateColWidth, this, {single: true});
this.down('#readsetGrid').on('columnresize', this.updateColWidth, this);
this.on('midchange', this.onMidChange, this);
this.mon(this.readDataStore, 'update', this.onReadDataUpdate, this, {buffer: 200, delay: 200});
},
onReadDataUpdate: function(){
//NOTE: if actively editing, dont update the grid. defer until either edit or cancel
var readDataGrid = this.down('#readDataGrid');
if (readDataGrid.editingPlugin.editing){
var callback = function(){
this.mun(readDataGrid.editingPlugin, 'edit', callback, this);
this.mun(readDataGrid.editingPlugin, 'canceledit', callback, this);
this.onReadDataUpdate();
};
this.mon(readDataGrid.editingPlugin, 'edit', callback, this, {single: true, delay: 100});
this.mon(readDataGrid.editingPlugin, 'canceledit', callback, this, {single: true, delay: 100});
return;
}
this.down('#readsetGrid').getView().refresh();
//update fileGroupIds
var distinctGroups = [];
this.readDataStore.each(function(r){
if (r.get('fileGroupId')){
distinctGroups.push(r.get('fileGroupId'));
}
}, this);
distinctGroups = Ext4.unique(distinctGroups).sort(SequenceAnalysis.Utils.naturalSortFn);
var found = [];
Ext4.Array.forEach(this.fileGroupStore.getRange(), function(fg){
if (fg.get('fileGroupId')) {
if (distinctGroups.indexOf(fg.get('fileGroupId')) === -1) {
this.fileGroupStore.remove(fg);
}
else {
found.push(fg.get('fileGroupId'));
}
}
}, this);
Ext4.Array.forEach(distinctGroups, function(name){
if (found.indexOf(name) === -1){
this.fileGroupStore.add(this.fileGroupStore.createModel({
fileGroupId: name
}));
}
}, this);
this.readsetStore.each(function(r){
if (distinctGroups.indexOf(r.get('fileGroupId')) === -1){
r.set('fileGroupId', null);
}
}, this);
},
statics: {
getInputFileTreatmentField: function(config){
return Ext4.apply({
fieldLabel: 'Treatment of Input Files',
xtype: 'combo',
helpPopup: 'This determines how the input files are handled. By default, files are normalized to FASTQ and the originals deleted to save space. However, you can choose to keep the original (compressed), or leave the originals alone.',
width: 600,
forceSelection: true,
displayField: 'display',
valueField: 'value',
value: 'delete',
store: {
type: 'array',
fields: ['display', 'value'],
data: [
['Copy, delete originals', 'delete'],
['Move originals and compress', 'compress'],
['Copy, leave originals in place', 'none'],
['Leave in place', 'leaveInPlace']
]
}
}, config || {});
},
getRenderer: function (colName) {
var column;
return function (value, cellMetaData, record, rowIndex, colIndex, store) {
var errors = record.validate();
if (!errors.isValid()) {
var msgs = errors.getByField(colName);
if (msgs.length) {
var texts = [];
Ext4.Array.forEach(msgs, function (m) {
texts.push(m.message);
}, this);
texts = Ext4.unique(texts);
cellMetaData.tdCls = cellMetaData.tdCls ? cellMetaData.tdCls + ' ' : '';
cellMetaData.tdCls += 'labkey-grid-cell-invalid';
cellMetaData.tdAttr = cellMetaData.tdAttr || '';
cellMetaData.tdAttr += " data-qtip=\"" + Ext4.util.Format.htmlEncode(texts.join('<br>')) + "\"";
}
}
return value;
}
}
},
//<sample name>_<barcode sequence>_L<lane (0-padded to 3 digits)>_R<read number>_<set number (0-padded to 3 digits>.fastq.gz
ILLUMINA_REGEX: /^(.+)_L(.+)_(R){0,1}([0-9])(_[0-9]+){0,1}(\.f(ast){0,1}q)(\.gz)?$/i,
//Example from NextSeq: RNA160915BB_34A_22436_Gag120_Clone-10_S10_R1_001.fastq.gz
//OR: 210304_NS500556_0465_AHHVNKAFX2.OSPHL00042_old_cdna_2.R2.fq.gz
//This should also allow simple pairs, like: file1_1.fq.gz and file1_2.fq.gz
ILLUMINA_REGEX_NO_LANE: /^(.+)[\._](R){0,1}([0-9])(_[0-9]+){0,1}(\.f(ast){0,1}q)(\.gz)?$/i,
//example: 214-3-6-GEX_1_S29_L002_R1_001.fastq.gz
//<sample name>_<barcode sequence>_L<lane (0-padded to 3 digits)>_R<read number>_<set number (0-padded to 3 digits>.fastq.gz
TENX_REGEX: /^(.+?)(_[0-9]+){0,1}_S(.+)_L(.+)_(R){0,1}([0-9])(_[0-9]+){0,1}(\.f(ast){0,1}q)(\.gz)?$/i,
populateSamples: function(orderType, isPaired){
this.fileNameStore.sort([{
sorterFn: function(o1, o2){
o1 = o1.get('displayName');
o2 = o2.get('displayName');
return o1 = SequenceAnalysis.Utils.naturalSortFn(o1, o2);
}
}]);
this.readDataStore.removeAll();
var errorMsgs = [];
if (!orderType || orderType === 'illumina' || orderType === '10x'){
var map = {};
this.fileNameStore.each(function(rec, i) {
if (rec.get('readgroup'))
{
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
m.set('fileRecord1', rec.get('id'));
m.set('platformUnit', rec.get('readgroup').platformUnit);
m.set('fileGroupId', rec.get('readgroup').sample);
m.set('centerName', rec.get('readgroup').centerName);
map[rec.get('readgroup').sample] = map[rec.get('readgroup').sample] || [];
map[rec.get('readgroup').sample].push(m);
}
else if (orderType === '10x' && this.TENX_REGEX.test(rec.get('fileName'))){
var match = this.TENX_REGEX.exec(rec.get('fileName'));
var sample = match[1];
var platformUnit = match[1]; //force concat
var setNo = match[7];
var setId = platformUnit + '_' + setNo;
var direction = match[6];
this.processIlluminaMatch(sample, platformUnit, setNo, setId, direction, rec, map, errorMsgs);
}
else if (this.ILLUMINA_REGEX.test(rec.get('fileName'))){
var match = this.ILLUMINA_REGEX.exec(rec.get('fileName'));
var sample = match[1];
var platformUnit = match[1] + '_L' + match[2];
var setNo = match[5];
var setId = platformUnit + '_' + setNo;
var direction = match[4];
this.processIlluminaMatch(sample, platformUnit, setNo, setId, direction, rec, map, errorMsgs);
}
else if (this.ILLUMINA_REGEX_NO_LANE.test(rec.get('fileName'))){
var match = this.ILLUMINA_REGEX_NO_LANE.exec(rec.get('fileName'));
var setNo = match[4] ? match[4].replace(/^_/, '') : null;
var sample = match[1];
var platformUnit = match[1];
var setId = match[1] + (setNo ? '-' + setNo : '');
var direction = match[3];
this.processIlluminaMatch(sample, platformUnit, null, setId, direction, rec, map, errorMsgs);
}
else {
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
m.set('fileRecord1', rec.get('id'));
var fileArr = rec.get('fileName').replace(/\.gz$/, '').split('.');
fileArr.pop();
var fileGroupId = fileArr.length === 1 ? fileArr[0] : fileArr.join('.');
m.set('fileGroupId', fileGroupId);
//m.set('platformUnit', fileGroupId);
map[rec.get('fileName')] = map[rec.get('fileName')] || [];
map[rec.get('fileName')].push(m);
}
}, this);
var keys = Ext4.Object.getKeys(map).sort(SequenceAnalysis.Utils.naturalSortFn);
Ext4.Array.forEach(keys, function(key){
if (Ext4.isArray(map[key])){
Ext4.Array.forEach(map[key], function(r){
this.readDataStore.add(r);
}, this);
}
else {
Ext4.Array.forEach(Ext4.Object.getKeys(map[key]), function(pu, idx){
this.readDataStore.add(map[key][pu]);
}, this);
}
}, this);
}
else if (orderType === 'row'){
this.fileNameStore.each(function(rec, i) {
if (isPaired){
if (i % 2 === 0){
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
var fileArr = rec.get('fileName').replace(/\.gz$/, '').split('.');
fileArr.pop();
m.set('fileRecord1', rec.get('id'));
var fileGroupId = fileArr.length === 1 ? fileArr[0] : fileArr.join('.');
m.set('fileGroupId', fileGroupId);
this.readDataStore.add(m);
}
else
{
this.readDataStore.getAt(this.readDataStore.getCount() - 1).set('fileRecord2', rec.get('id'));
}
}
else {
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
var fileArr = rec.get('fileName').replace(/\.gz$/, '').split('.');
fileArr.pop();
m.set('fileRecord1', rec.get('id'));
var fileGroupId = fileArr.length === 1 ? fileArr[0] : fileArr.join('.');
m.set('fileGroupId', fileGroupId);
this.readDataStore.add(m);
}
}, this);
}
else if (orderType === 'column') {
if (isPaired){
var colSize = Math.ceil(this.fileNameStore.getCount() / 2);
this.fileNameStore.each(function (rec, i){
if (i < colSize) {
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
var fileArr = rec.get('fileName').replace(/\.gz$/, '').split('.');
fileArr.pop();
m.set('fileRecord1', rec.get('id'));
var fileGroupId = fileArr.length === 1 ? fileArr[0] : fileArr.join('.');
m.set('fileGroupId', fileGroupId);
this.readDataStore.add(m);
}
else {
this.readDataStore.getAt(i - colSize).set('fileRecord2', rec.get('id'));
}
}, this);
}
else {
//this should never get called. column/paired is the same thing as row/paired
this.fileNameStore.each(function (rec, i){
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
var fileArr = rec.get('fileName').replace(/\.gz$/, '').split('.');
fileArr.pop();
m.set('fileRecord1', rec.get('id'));
var fileGroupId = fileArr.length === 1 ? fileArr[0] : fileArr.join('.');
m.set('fileGroupId', fileGroupId);
this.readDataStore.add(m);
}, this);
}
}
this.readDataStore.sort('fileGroupId');
this.down('#readDataGrid').getView().refresh();
//populate readsets
var distinctNames = [];
this.readDataStore.each(function(r){
distinctNames.push(r.get('fileGroupId'));
}, this);
distinctNames = Ext4.unique(distinctNames).sort(SequenceAnalysis.Utils.naturalSortFn);
//update fileGroupIds
Ext4.Array.forEach(distinctNames, function(name){
this.fileGroupStore.add(this.fileGroupStore.createModel({
fileGroupId: name
}));
}, this);
Ext4.Array.forEach(distinctNames, function(name){
if (this.readsetStore.findExact('fileGroupId', name) === -1) {
this.readsetStore.add(this.readsetStore.createModel({
fileGroupId: name
}));
}
}, this);
Ext4.Array.forEach(this.readsetStore.getRange(), function(r){
if (distinctNames.indexOf(r.get('fileGroupId')) === -1){
this.readsetStore.remove(r);
}
}, this);
if (this.readDataStore.getCount() === 0 && this.fileNameStore.getCount() !== 0){
var msg = 'Possible error parsing file groups on SequenceImportPanel. Names were:\n';
this.fileNameStore.each(function(f){
msg += '[' + f.get('fileName') + ']\n';
}, this);
}
return errorMsgs;
},
processIlluminaMatch: function(sample, platformUnit, lane, setId, readSet, rec, map, errorMsgs){
map[sample] = map[sample] || {};
map[sample][setId] = map[sample][setId] || [];
//NOTE: this likely will be a string
if (readSet == 1){
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
m.set('fileRecord1', rec.get('id'));
m.set('fileGroupId', sample);
m.set('platformUnit', platformUnit);
map[sample][setId].push(m);
}
else {
var arr = map[sample][setId];
if (!arr.length){
var msg = 'Possible error parsing file groups on SequenceImportPanel. Encountered reverse reads prior to forward for file: [' + setId + ']. Names were:\n';
this.fileNameStore.each(function(f){
msg += '[' + f.get('fileName') + ']\n';
}, this);
errorMsgs.push('Possible error: Encountered reverse reads prior to forward reads for ' + setId + ', which can indicate files are out of alphabetical order, one file from a pair is missing, or a problem parsing the filenames. Please check over the file groups carefully.');
var m = Ext4.create('SequenceAnalysis.model.ReadsetDataModel', {});
m.set('fileRecord2', rec.get('id'));
m.set('fileGroupId', sample);
m.set('platformUnit', platformUnit);
map[sample][setId].push(m);
}
else {
arr[arr.length - 1].set('fileRecord2', rec.get('id'));
}
}
},
getJsonParams: function(config){
var values = this.callParent(arguments);
if (!values) {
return;
}
//make sure input files are valid
var totalErrors = 0;
values.inputFiles = [];
this.fileNameStore.clearFilter();
this.fileNameStore.each(function(rec){
if (rec.get('error'))
totalErrors++;
else {
if (!rec.get('dataId'))
values.inputFiles.push({
fileName: rec.get('fileName'),
relPath: rec.get('relPath')
});
else
values.inputFiles.push({dataId: rec.get('dataId')});
}
}, this);
if (totalErrors){
Ext4.Msg.alert('Error', 'Some of the sequence files had errors and cannot be used. Please hover over the red cells near the top of the page to see more detail on these errors');
return;
}
if (this.getReadsetParams(values) === false){
return false;
}
return values;
},
getReadsetParams: function(values){
var barcodes = {};
var doDemultiplex = this.down('#doDemultiplex').getValue();
var showBarcodes = this.down('#showBarcodes').getValue();
var errors = Ext4.create('Ext.data.Errors');
this.readDataStore.each(function(r, sampleIdx) {
var recErrors = r.validate();
if (recErrors.getCount()){
errors.add(recErrors.getRange());
}
}, this);
this.fileNameStore.clearFilter();
this.barcodeStore.clearFilter();
var fileGroupMap = {};
this.readDataStore.each(function(r, idx){
var recErrors = r.validate();
if (recErrors.getCount()){
errors.add(recErrors.getRange());
}
var i = 1;
var readData = {
fileGroupId: r.get('fileGroupId'),
centerName: r.get('centerName'),
platformUnit: r.get('platformUnit')
};
while (i <= 2){
if (r.get('fileRecord' + i)){
var fileDataRecIdx = this.fileNameStore.findExact('id', r.get('fileRecord' + i));
var fileDataRec = this.fileNameStore.getAt(fileDataRecIdx);
if (fileDataRec){
readData['file' + i] = {
fileName: fileDataRec.get('fileName'),
relPath: fileDataRec.get('relPath'),
dataId: fileDataRec.get('dataId')
}
}
}
i++;
}
fileGroupMap[r.get('fileGroupId')] = fileGroupMap[r.get('fileGroupId')] || [];
fileGroupMap[r.get('fileGroupId')].push(readData);
}, this);
var fileIdx = 1;
for (var group in fileGroupMap){
values['fileGroup_' + fileIdx] = {
name: group,
files: fileGroupMap[group]
};
fileIdx++;
}
if (Ext4.Object.isEmpty(fileGroupMap)){
Ext4.Msg.alert('Error', 'There are no file groups. You must complete the section showing how your files are grouped into lanes/groups');
return false;
}
if (!this.readsetStore.getCount()){
Ext4.Msg.alert('Error', 'There are no readsets defined. Please fill out the readset grid');
return false;
}
this.readsetStore.each(function(r, sampleIdx){
var recErrors = r.validate();
if (recErrors.getCount()){
errors.add(recErrors.getRange());
}
var key = [r.get('fileRecord1')];
key.push(r.get('fileRecord2'));
if (!doDemultiplex && !showBarcodes){
delete r.data['barcode5'];
delete r.data['barcode3'];
}
else {
key.push(r.data['barcode5']);
key.push(r.data['barcode3']);
}
key = key.join("||");
//handle barcodes
var rec;
if (doDemultiplex && r.get('barcode5')){
rec = this.barcodeStore.getAt(this.barcodeStore.find('tag_name', r.get('barcode5')));
if (!barcodes[r.get('barcode5')]){
barcodes[r.get('barcode5')] = [r.get('barcode5'), rec.get('sequence')];
}
}
if (doDemultiplex && r.get('barcode3')){
rec = this.barcodeStore.getAt(this.barcodeStore.find('tag_name', r.get('barcode3')));
if (rec && !barcodes[r.get('barcode3')]){
barcodes[r.get('barcode3')] = [r.get('barcode3'), rec.get('sequence')];
}
}
if (doDemultiplex && (!r.get('barcode5') && !r.get('barcode3'))){
Ext4.Msg.alert('Error', 'One or more readsets are missing barcodes. Please either enter these or uncheck the option to demultiplex.');
return false;
}
var sampleDate = r.get('sampledate');
if (sampleDate){
sampleDate = Ext4.Date.format(sampleDate, 'Y-m-d');
}
values['readset_' + sampleIdx] = {
barcode5: r.get('barcode5'),
barcode3: r.get('barcode3'),
readset: r.get('readset'),
readsetname: r.get('readsetname'),
importType: r.get('importType'),
platform: r.get('platform'),
application: r.get('application'),
chemistry: r.get('chemistry'),
concentration: r.get('concentration'),
fragmentSize: r.get('fragmentSize'),
librarytype: r.get('librarytype'),
sampletype: r.get('sampletype'),
subjectid: r.get('subjectid'),
sampledate: sampleDate,
comments: r.get('comments'),
sampleid: r.get('sampleid'),
instrument_run_id: r.get('instrument_run_id'),
fileGroupId: r.get('fileGroupId')
};
}, this);
for (var i in barcodes){
values['barcode_'+i] = barcodes[i];
}
console.log(values);
if (errors.getCount()){
Ext4.Msg.alert('Error', 'There are ' + errors.getCount() + ' errors. Please review the cells highlighted in red. Note: you can hover over the cell for more information on the issue.');
return false;
}
},
onSubmit: function(){
var ret = this.getJsonParams();
if (!ret)
return;
this.startAnalysis(ret);
},
getFilePanelCfg: function(){
return {
xtype:'panel',
border: true,
title: 'Selected Files',
itemId: 'files',
width: 'auto',
defaults: {
border: false,
style: 'padding: 5px;'
},
items: [{
xtype: 'dataview',
itemId: 'fileListView',
store: this.fileNameStoreCopy,
itemSelector:'tr.file_list',
tpl: [
'<table class="fileNames"><tr class="fileNames"><td>Id</td><td>Filename</td><td>Read Group (BAMs Only)</td><td>Folder</td><td></td></tr>',
'<tpl for=".">',
'<tr class="file_list">',
'<td><a href="{[LABKEY.ActionURL.buildURL("experiment", "showData", values.containerPath, {rowId: values.dataId})]}" target="_blank">{dataId}</a></td>',
'<td ',
'<tpl if="error">style="background: red;" data-qtip="{error}"</tpl>',
'><a href="{[LABKEY.ActionURL.buildURL("experiment", "showData", values.containerPath, {rowId: values.dataId})]}" target="_blank">{fileName:htmlEncode}</a></td>',
'<td>{[values.readgroup ? values.readgroup.platformUnit : ""]}</td>',
'<td><a href="{[LABKEY.ActionURL.buildURL("project", "start", null, {})]}" target="_blank">{containerPath:htmlEncode}</a></td>',
'<tpl if="dataId">',
'<td><a href="{[LABKEY.ActionURL.buildURL("sequenceanalysis", "fastqcReport", values["container/path"], {dataIds: values.dataId, cacheResults: false})]}" target="_blank">View FASTQC Report</a></td>',
'</tpl>',
'<tpl if="!dataId">',
'<td><a href="{[LABKEY.ActionURL.buildURL("sequenceanalysis", "fastqcReport", values["container/path"], {filenames: values.fileName, cacheResults: false})]}" target="_blank">View FASTQC Report</a></td>',
'</tpl>',
'</tr>',
'</tpl>',
'</table>'
]
},{
html: '',
itemId: 'totalFiles',
border: false,
style: 'padding-left: 5px;padding-top: 10px;'
}]
}
},
getRunInfoCfg: function(){
return {
xtype:'form',
border: true,
bodyBorder: false,
title: 'Run Information',
name: 'protocols',
width: 'auto',
defaults: Ext4.Object.merge({}, this.fieldDefaults, {bodyStyle: 'padding:5px;'}),
defaultType: 'textfield',
items :[{
fieldLabel: 'Job Name',
width: 600,
helpPopup: 'This is the name assigned to this job, which must be unique. Results will be moved into a folder with this name.',
name: 'jobName',
itemId: 'jobName',
allowBlank:false,
value: 'SequenceImport_'+ Ext4.Date.format(new Date(), 'Ymd'),
maskRe: new RegExp('[A-Za-z0-9_]'),
validator: function(val){
return (this.isValidProtocol === false ? 'Job Name Already In Use' : true);
}
},{
fieldLabel: 'Run Description',
xtype: 'textarea',
width: 600,
height: 100,
helpPopup: 'Description for this protocol (optional)',
itemId: 'runDescription',
name: 'runDescription',
allowBlank:true
}, {
xtype: 'ldk-linkbutton',
style: 'margin-left: ' + (this.fieldDefaults.labelWidth + 4) + 'px;',
width: null,
hidden: !LABKEY.Security.currentUser.isAdmin,
text: 'Set Page Defaults',
itemId: 'copyPrevious',
linkCls: 'labkey-text-link',
scope: this,
handler: function (btn) {
Ext4.create('Ext.window.Window', {
title: 'Set Page Defaults',
items: [{
xtype: 'sequenceanalysis-sequenceimportsettingspanel',
border: false,
hidePageLoadWarning: false,
hideButtons: true
}],
buttons: SequenceAnalysis.panel.SequenceImportSettingsPanel.getButtons().concat([{
text: 'Cancel',
handler: function (btn) {
btn.up('window').close();
}
}])
}).show();
}
}]
}
},
initFiles: function(){
this.fileNameStore = Ext4.create('Ext.data.Store', {
fields: ['id', 'displayName', 'fileName', 'filePath', 'relPath', 'basename', 'container', 'containerPath', 'dataId', 'readgroup', 'error', 'uses', 'info']
});
this.fileNameStoreCopy = Ext4.create('Ext.data.Store', {
model: this.fileNameStore.model
});
this.fileNames.sort(SequenceAnalysis.Utils.naturalSortFn);
Ext4.Msg.wait('Loading...');
var multi = new LABKEY.MultiRequest();
multi.add(LABKEY.Ajax.request, {
method: 'POST',
url: LABKEY.ActionURL.buildURL('sequenceanalysis', 'validateReadsetFiles'),
params: {
path: LABKEY.ActionURL.getParameter('path'),
fileNames: this.fileNames,
fileIds: this.fileIds
},
scope: this,
success: this.onFileLoad,
failure: LDK.Utils.getErrorCallback()
});
multi.add(LABKEY.Ajax.request, {
method: 'POST',
url: LABKEY.ActionURL.buildURL('sequenceanalysis', 'getSequenceImportDefaults'),
scope: this,
success: function(response){
LDK.Utils.decodeHttpResponseJson(response);
if (response.responseJSON){
this.configDefaults = response.responseJSON;
for (var name in this.configDefaults){
var item = this.down('component[name=' + name + ']');
LDK.Assert.assertNotEmpty('Unable to find SequenceImportField with name: ' + name, item);
if (item){
item.setValue(this.configDefaults[name]);
}
}
}
},
failure: LDK.Utils.getErrorCallback()
});
multi.add(LABKEY.Ajax.request, {
method: 'POST',
url: LABKEY.ActionURL.buildURL('sequenceanalysis', 'getResourceSettingsJson'),
scope: this,
success: function(response){
LDK.Utils.decodeHttpResponseJson(response);
if (response.responseJSON){
var json = response.responseJSON;
var cfg = this.getJobResourcesCfg(response.responseJSON);
if (cfg) {
cfg.title = 'Step 4: Job Resources (optional)';
var idx = this.items.length - 1;
this.insert(idx, cfg);