-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFilters.cpp
More file actions
3760 lines (3371 loc) · 113 KB
/
Filters.cpp
File metadata and controls
3760 lines (3371 loc) · 113 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
#include "Filters.h"
#include "OutputStreamer.h"
//*******************************************
//* FILTERS OBJECT
//*******************************************
Filters::Filters(OptContainer* cmdArgs1) :
PrimerL(0), PrimerR(0), PrimerL_RC(0), PrimerR_RC(0), PrimerIdx(0),
Barcode(0), revBarcode(0), Barcode2(0), revBarcode2(0),
HeadSmplID(0),
hetPrimer(2, vector<string>(0)),
collectStatistics(2), statAddition(2),
FastaF(0), QualF(0), FastqF(0), MIDfqF(0),
derepMinNum(0),
SequencingRun(0),
lMD(NULL),
tAdapter(""), tAdapterLength(0),
removeAdapter(false), bDoMultiplexing(true), bDoBarcode(true),
bDoBarcode2(false), bDoBarcode2Rd1(false),
bDoHeadSmplID(false), bBarcodeSameSize(false),
bOneFileSample(false), curBCnumber(-1), BCoffset(0),
bAdditionalOutput(false), b2ndRDBcPrimCk(false),
bRevRdCk(false), bChkRdPrs(true),
min_l(0), alt_min_l(0), min_l_p(-1.f), alt_min_l_p(-1.f),
maxReadLength(0), norm2fiveNTs(false),
max_l(10000), min_q(0.f), alt_min_q(0.f),
BcutPrimer(true), alt_BcutPrimer(true), bPrimerR(false),
BextensivePrimerChecks(false),
bRequireRevPrim(false), alt_bRequireRevPrim(false),
bRequireFwdPrim(false), alt_bRequireFwdPrim(false), BcutTag(true),
bCompletePairs(false), bShortAmplicons(false),
minBCLength1_(0), minBCLength2_(0), maxBCLength1_(0), maxBCLength2_(0), minPrimerLength_(0), maxHomonucleotide_(0), trimHomonucleotide_(0),
cut5PR1(0), cut5PR2(0),
PrimerErrs(0), alt_PrimerErrs(0), barcodeErrors_(0),
MaxAmb(-1), alt_MaxAmb(-1),
FQWwidth(0), EWwidth(0),
RevPrimSeedL(5),
b_BinFilBothPairs(false),
BinFilErr(2.5), BinFilP(-1.f),
alt_FQWthr(0), alt_EWthr(0),
PEheaderVerWr(0), TrimStartNTs(0), TruncSeq(-1),
userReqFastqVer(0), userReqFastqOutVer(33), maxAccumQP(-1),
alt_maxAccumQP(-1),
pairedSeq(-1),
//revConstellationN(0),
BCdFWDREV(2),
firstXreadsW(-1), firstXreadsR(-1),
restartSet(false), b_optiClusterSeq(false),
b_subselectionReads(false), b_doQualFilter(true),
b_doFilter(true),
bDoDereplicate(false), bDoSeedExtension(false), bDoCombiSamples(false),
maxReadsPerOFile(0), ReadsWritten(0), OFileIncre(0),
demultiBPperSR(0),
barcodeLengths1_(0), barcodeLengths2_(0),
illuPEfwd(""), illuPErev(""), illuSEuni(""), illuSEidx(""),
Bcheck4illuAdapts(false), doGoldAxe(false),
GoldAxeMinAmpli(-1), GoldAxeMaxAmpli(-1),
cmdArgs(cmdArgs1), passed_interval_reads(0)
{
//csMTX[0].unlock();
//csMTX[1].unlock();
//set up objects to collect statistics on run
collectStatistics[0] = make_shared<collectstats>();
collectStatistics[1] = make_shared<collectstats>();
statAddition[0] = make_shared<collectstats>();
statAddition[1] = make_shared<collectstats>();
GAstatistics = make_shared<GAstats>();
mergeStats = make_shared<MEstats>();
bool alt_bRequireRevPrimSet = false;
string optF("");
if (cmdArgs->find("-options") != cmdArgs->end()) {
optF = (*cmdArgs)["-options"];
}
iniSpacer = (*cmdArgs)["-sample_sep"];
//***************************************
//default options
int maxAmb(0), PrimerErrs(1), TagErrs(0);
float minQual(25);
float minL(250.f);
int maxL(1000);
int QualWinWidth = 50;
float QualWinThr = 0;
int EndWinWidth = 15;
float EndWinThr = 20;
int maxHomoNT(12); int trimHomoNT(12);
bool keepTag(false), keepPrimer(false);
bool addModConf = false;
//set up some basic objects
if ((*cmdArgs).find("-paired") != cmdArgs->end()) {
pairedSeq = atoi((*cmdArgs)["-paired"].c_str()); //fakeEssentials();
if (pairedSeq < 1 || pairedSeq>3) { cerr << "Argument \"-paired\" supplied with unknown parameter. Aborting.\n"; exit(28); }
if ((*cmdArgs)["-onlyPair"] == "1" || (*cmdArgs)["-onlyPair"] == "2") {
pairedSeq = 1;
}
}
if (cmdArgs->find("-normRdsToFiveNTs") != cmdArgs->end()) {
norm2fiveNTs = true;
cerr << "Warning: normRdsToFiveNTs is not implemented!\n";
}
if ((*cmdArgs)["-logLvsQ"].c_str() != "") {
collectStatistics[0]->setbLvsQlogsPreFilt(true);
}
if ((*cmdArgs)["-GoldenAxe"] == "1") { this->setGoldAxe(true, stoi((*cmdArgs)["-GoldenAxeMaxAmpli"]), stoi((*cmdArgs)["-GoldenAxeMinAmpli"])); }
//delimit output file size to X reads
if (cmdArgs->find("-maxReadsPerOutput") != cmdArgs->end()) {
maxReadsPerOFile = atoi((*cmdArgs)["-maxReadsPerOutput"].c_str());
}
if (cmdArgs->find("-DemultiBPperSR") != cmdArgs->end()) {
stringstream ss((*cmdArgs)["-DemultiBPperSR"]);
double d = 0;
ss >> d;
demultiBPperSR = (uint)d;
}
//important for fastq format
if (cmdArgs->find("-i_qual_offset") != cmdArgs->end()) {
if ((*cmdArgs)["-i_qual_offset"] == "auto") {
userReqFastqVer = 0;
}
else {
userReqFastqVer = atoi((*cmdArgs)["-i_qual_offset"].c_str());
}
}
cut5PR1 = atoi((*cmdArgs)["-5PR1cut"].c_str());
cut5PR2 = atoi((*cmdArgs)["-5PR2cut"].c_str());
//cerr<<(*cmdArgs)["-o_qual_offset"]<<endl;
userReqFastqOutVer = atoi((*cmdArgs)["-o_qual_offset"].c_str());
//statistic tracker
//do new SEED sequence selection?
if (cmdArgs->find("-optimalRead2Cluster") != cmdArgs->end()) {
b_optiClusterSeq = true;
}
//do selection of specific reads?
if ((*cmdArgs)["-specificReads"] != "") {
b_subselectionReads = true;
}
if (cmdArgs->find("-binomialFilterBothPairs") != cmdArgs->end() && (*cmdArgs)["-binomialFilterBothPairs"] == "1") {
b_BinFilBothPairs = true;
}
if ((*cmdArgs)["-illuminaClip"] == "1") {
Bcheck4illuAdapts = true;
}
if ((*cmdArgs)["-XfirstReadsWritten"] != "") {
firstXreadsW = atoi((*cmdArgs)["-XfirstReadsWritten"].c_str());
}
if ((*cmdArgs)["-XfirstReadsRead"] != "") {
firstXreadsR = atoi((*cmdArgs)["-XfirstReadsRead"].c_str());
}
//***************************************
//read options
ifstream opt;
opt.open(optF.c_str(), ios::in);
if (!opt || optF == "") {
cerr << "NO filtering will be done on your reads (just rewriting / log files created)." << endl;
b_doFilter = false;
return;
}
string line;
while (getline(opt, line, '\n')) {
if (line.length() <= 1 || line.substr(0, 1) == "#") {
continue;
}
bool addMod = false;
if (line.substr(0, 1) == "*") {
addMod = true;
line = line.substr(1);
}
string segs;
string segs2;
stringstream ss;
ss << line;
getline(ss, segs, '\t');
getline(ss, segs2, '\t');
if (strcmp(segs.c_str(), "minSeqLength") == 0) {
if (addMod) {
float tmp = (float)atof(segs2.c_str());
if (tmp > 1.f) {
alt_min_l = (int)tmp;
}
else {
alt_min_l = -1;
alt_min_l_p = tmp;
}
if (alt_min_l != minL) { addModConf = true; }
}
else {
minL = (float)atof(segs2.c_str());
}
}
else if (strcmp(segs.c_str(), "maxSeqLength") == 0) {
maxL = atoi(segs2.c_str());
}
else if (strcmp(segs.c_str(), "minAvgQuality") == 0) {
if (addMod) {
alt_min_q = (float)atof(segs2.c_str());
if (alt_min_q != minQual) { addModConf = true; }
}
else {
minQual = (float)atof(segs2.c_str());
}
}
else if (strcmp(segs.c_str(), "maxAmbiguousNT") == 0) {
if (addMod) {
alt_MaxAmb = atoi(segs2.c_str());
if (MaxAmb != alt_MaxAmb) { addModConf = true; }
}
else {
maxAmb = atoi(segs2.c_str());
}
}
else if (strcmp(segs.c_str(), "QualWindowThreshhold") == 0) {
if (addMod) {
alt_FQWthr = (float)atof(segs2.c_str());
if (alt_FQWthr != QualWinThr) { addModConf = true; }
}
else {
QualWinThr = (float)atof(segs2.c_str());
}
}
else if (strcmp(segs.c_str(), "QualWindowWidth") == 0) {
QualWinWidth = atoi(segs2.c_str());
}
else if (strcmp(segs.c_str(), "BinErrorModelMaxExpError") == 0) {
BinFilErr = (float)atof(segs2.c_str());
if (BinFilErr < 0) {
cerr << "BinErrorModelMaxExpError was set to <0. Set to 0 instead.\n";
BinFilErr = 0;
}
}
else if (strcmp(segs.c_str(), "BinErrorModelAlpha") == 0) {
BinFilP = (float)atof(segs2.c_str());
if (BinFilP != -1.f && (BinFilP < 0.f || BinFilP>1.f)) {
cerr << "BinErrorModelAlpha has to be between 0 and 1 (or -1 to deactivate).\nAborting..\n";
exit(542);
}
}
else if (strcmp(segs.c_str(), "TrimWindowWidth") == 0) {
EndWinWidth = atoi(segs2.c_str());
}
else if (strcmp(segs.c_str(), "TrimWindowThreshhold") == 0) {
if (addMod) {
alt_EWthr = (float)atof(segs2.c_str());
if (alt_EWthr != EndWinThr) { addModConf = true; }
}
else {
EndWinThr = (float)atof(segs2.c_str());
}
}
else if (strcmp(segs.c_str(), "maxBarcodeErrs") == 0) {
TagErrs = atoi(segs2.c_str());
}
else if (strcmp(segs.c_str(), "maxPrimerErrs") == 0) {
if (addMod) {
alt_PrimerErrs = atoi(segs2.c_str());
if (alt_PrimerErrs != PrimerErrs) { addModConf = true; }
}
else {
PrimerErrs = atoi(segs2.c_str());
}
}
else if (strcmp(segs.c_str(), "keepBarcodeSeq") == 0) {
atoi(segs2.c_str()) == 0 ? keepTag = false : keepTag = true;
}
else if (strcmp(segs.c_str(), "keepPrimerSeq") == 0) {
if (addMod) {
atoi(segs2.c_str()) == 0 ? alt_BcutPrimer = false : alt_BcutPrimer = true;
if (alt_BcutPrimer != keepPrimer) { addModConf = true; }
}
else {
atoi(segs2.c_str()) == 0 ? keepPrimer = false : keepPrimer = true;
}
}
else if (strcmp(segs.c_str(), "maxHomonucleotide") == 0) {
maxHomoNT = atoi(segs2.c_str());
}
else if (strcmp(segs.c_str(), "trimHomonucleotide") == 0) {
trimHomoNT = atoi(segs2.c_str());
}
else if (strcmp(segs.c_str(), "maxAccumulatedError") == 0) {
if (addMod) {
alt_maxAccumQP = double(atof(segs2.c_str()));
if (alt_maxAccumQP != maxAccumQP) { addModConf = true; }
}
else {
maxAccumQP = double(atof(segs2.c_str()));
}
}
else if (strcmp(segs.c_str(), "TechnicalAdapter") == 0) {
tAdapter = segs2.c_str();
transform(tAdapter.begin(), tAdapter.end(), tAdapter.begin(), ::toupper);
tAdapterLength = (int)tAdapter.length();
removeAdapter = true;
}
else if (segs == "PEheaderPairFmt") {
PEheaderVerWr = atoi(segs2.c_str());
}
else if (segs == "TrimStartNTs") {
TrimStartNTs = atoi(segs2.c_str());
}
else if (segs == "fastqVersion") {
if (segs2 == "auto") {
userReqFastqVer = 0;
}
else {
userReqFastqVer = FastqVerMod(atoi(segs2.c_str()));
}
}
else if (segs == "ExtensivePrimerChecks") {
if (segs2 == "T") {
BextensivePrimerChecks = true;
}
}
else if (segs == "RejectSeqWithoutRevPrim") {
if (addMod) {
alt_bRequireRevPrimSet = true;
if (segs2 == "T") {
alt_bRequireRevPrim = true;
}
else { alt_bRequireRevPrim = false; }
if (alt_bRequireRevPrim != bRequireRevPrim) { addModConf = true; }
}
else {
if (segs2 == "T") {
bRequireRevPrim = true;
}
else { bRequireRevPrim = false; }
}
}
else if (segs == "RejectSeqWithoutFwdPrim") {
if (addMod) {
alt_bRequireFwdPrim = true;
if (segs2 == "T") {
alt_bRequireFwdPrim = true;
}
else { alt_bRequireFwdPrim = false; }
if (alt_bRequireFwdPrim != bRequireFwdPrim) { addModConf = true; }
}
else {
if (segs2 == "T") {
bRequireFwdPrim = true;
}
else { bRequireFwdPrim = false; }
}
}
else if (segs == "TruncateSequenceLength") {
TruncSeq = atoi(segs2.c_str());
if (TruncSeq != -1 && TruncSeq < (int)minL) { minL = (float)TruncSeq; }
}
else if (segs == "AmpliconShortPE") {
if (segs2 == "T") {
bShortAmplicons = true;
}
else { bShortAmplicons = false; }
}
else if (segs == "CheckForMixedPairs") {
if (segs2 == "T") {
b2ndRDBcPrimCk = true;
}
else { b2ndRDBcPrimCk = false; }
}
else if (segs == "CheckForReversedSeqs") {
if (segs2 == "T") {
bRevRdCk = true;
}
else { bRevRdCk = false; }
}
else if (segs == "SyncReadPairs") {
if (segs2 == "T") {
bChkRdPrs = true;
}
else { bChkRdPrs = false; }
}
else if (segs == "illuminaFwd") {
illuPEfwd = segs2;
}
else if (segs == "illuminaRev") {
illuPErev = segs2;
}
else if (segs == "illuminaSngUni") {
illuSEuni = segs2;
}
else if (segs == "illuminaSngIdx") {
illuSEidx = segs2;
}
}
//report some non-std options
if (bShortAmplicons) {
cerr << "Checking for reverse primers on 1st read.\n";
}
if (b2ndRDBcPrimCk) {
cerr << "Checking for switched pairs.\n";
}
opt.close();
//set in filter object
this->setSeqLength(minL, maxL);
this->setPrimerErrs(PrimerErrs);
this->setTagErrs(TagErrs);
this->removePrimer(!keepPrimer);
this->removeTag(!keepTag);
this->setMaxAmb(maxAmb);
this->setAvgMinQual(minQual);
this->setFloatingQWin(QualWinWidth, QualWinThr);
this->setFloatingEWin(EndWinWidth, EndWinThr);
this->setMaxHomo(maxHomoNT);
this->setTrimHomo3P(trimHomoNT);
//alternative options (mid qual filtering)
if (addModConf) {
if (!alt_bRequireRevPrimSet) { alt_bRequireRevPrim = bRequireRevPrim; }
if (cmdArgs->find("-o_fna") != cmdArgs->end() && (*cmdArgs)["-o_fna"].length() > 1) {
if (cmdArgs->find("-o_fna2") == cmdArgs->end()) {
(*cmdArgs)["-o_fna2"] = additionalFileName((*cmdArgs)["-o_fna"]);
//(*cmdArgs)["-o_fna2"] = (*cmdArgs)["-o_fna"].substr(0,(*cmdArgs)["-o_fna"].length()-4)+".add.fna";
}
}
else if (cmdArgs->find("-o_fastq") != cmdArgs->end() && (*cmdArgs)["-o_fastq"].length() > 1) {
if (cmdArgs->find("-o_fastq2") == cmdArgs->end()) {
(*cmdArgs)["-o_fastq2"] = additionalFileName((*cmdArgs)["-o_fastq"]);
}
}
bAdditionalOutput = true;
}
}
void Filters::addDNAtoCStats(const shared_ptr<DNA>& d, int Pair) {
//here should be the only place to count Barcodes!
int easyPair = Pair < 3 ? Pair - 1 : Pair - 3;
//csMTX[easyPair]->lock();
collectStatistics[easyPair]->total2++;
if (d->isGreenQual() || d->isYellowQual()) {
this->DNAstatLQ(d, easyPair, d->isYellowQual());
collectStatistics[easyPair]->totalSuccess++;
if (d->isYellowQual()) {
collectStatistics[easyPair]->totalMid++;
}
}
else {
collectStatistics[easyPair]->totalRejected++;
}
//some general stats that always apply:
if (d->QualCtrl.PrimerFwdFail) {
collectStatistics[easyPair]->PrimerFail++;
}
if (d->QualCtrl.PrimerRevFail) {
collectStatistics[easyPair]->PrimerRevFail++;
}
if (d->QualCtrl.minLqualTrim) {
collectStatistics[easyPair]->minLqualTrim++;
}
if (d->QualCtrl.TagFail) {
collectStatistics[easyPair]->TagFail++;
}
if (d->QualCtrl.fail_correct_BC) {
collectStatistics[easyPair]->fail_correct_BC++;
}
if (d->QualCtrl.suc_correct_BC) {
collectStatistics[easyPair]->suc_correct_BC++;
}
if (d->QualCtrl.RevPrimFound) {
collectStatistics[easyPair]->RevPrimFound++;
}
if (d->QualCtrl.QWinTrimmed || d->QualCtrl.AccErrTrimmed) {
collectStatistics[easyPair]->Trimmed++;
}
if (d->getTA_cut()) {
collectStatistics[easyPair]->adapterRem++;
}
//exit(0);
if (d->isGreenQual() || d->isYellowQual()) {
countBCdetected(d->getBCnumber(), easyPair, d->isYellowQual());
//and register as success
}
else {
if (d->getBarcodeDetected()) {
//DNA is no longer useful
failedStats2(d, easyPair);
}
//delete d;
if (d->QualCtrl.AvgQual) {
collectStatistics[easyPair]->AvgQual++;
}
if (d->QualCtrl.minL) {
collectStatistics[easyPair]->minL++;
}
if (d->QualCtrl.maxL) {
collectStatistics[easyPair]->maxL++;
}
if (d->QualCtrl.HomoNT) {
collectStatistics[easyPair]->HomoNT++;
}
if (d->QualCtrl.HomoNTtrimmed) {
collectStatistics[easyPair]->HomoNTtrimmed++;
}
if (d->QualCtrl.MaxAmb) {
collectStatistics[easyPair]->MaxAmb++;
}
if (d->QualCtrl.BinomialErr) {
collectStatistics[easyPair]->BinomialErr++;
}
if (d->QualCtrl.QualWin) {
collectStatistics[easyPair]->QualWin++;
}
}
if (d->isDereplicated()) {
if (d->getBarcodeDetected() && !d->isGreenQual() && !d->isYellowQual()) {
this->statAddDerepBadSeq(d->getBCnumber());
}
}
//csMTX[easyPair]->unlock();
}
Filters::Filters(Filters* of, int BCnumber, bool takeAll, size_t threads)
:
PrimerL(0, ""), PrimerR(0, ""),
PrimerL_RC(0, ""), PrimerR_RC(0, ""),
PrimerIdx(of->PrimerIdx),
Barcode(0), revBarcode(0), Barcode2(0), revBarcode2(0),
HeadSmplID(0), hetPrimer(2, vector<string>(0)),
collectStatistics(2, nullptr), statAddition(2, nullptr),
FastaF(of->FastaF), QualF(of->QualF), FastqF(of->FastqF),
MIDfqF(of->MIDfqF), derepMinNum(of->derepMinNum),
lMD(of->lMD),
tAdapter(of->tAdapter), tAdapterLength(of->tAdapterLength),
removeAdapter(of->removeAdapter), bDoMultiplexing(of->bDoMultiplexing),
bDoBarcode(of->bDoBarcode), bDoBarcode2(of->bDoBarcode2), bDoBarcode2Rd1(of->bDoBarcode2Rd1),
bDoHeadSmplID(of->bDoHeadSmplID),
bBarcodeSameSize(of->bBarcodeSameSize),
bOneFileSample(of->bOneFileSample), curBCnumber(BCnumber), BCoffset(of->BCoffset),
bAdditionalOutput(of->bAdditionalOutput), b2ndRDBcPrimCk(of->b2ndRDBcPrimCk),
bRevRdCk(of->bRevRdCk), bChkRdPrs(of->bChkRdPrs),
min_l(of->min_l), alt_min_l(of->alt_min_l), min_l_p(of->min_l_p), alt_min_l_p(of->alt_min_l_p),
maxReadLength(0), norm2fiveNTs(of->norm2fiveNTs),
max_l(of->max_l), min_q(of->min_q), alt_min_q(of->alt_min_q),
BcutPrimer(of->BcutPrimer), alt_BcutPrimer(of->alt_BcutPrimer),
bPrimerR(of->bPrimerR),
bRequireRevPrim(of->bRequireRevPrim), alt_bRequireRevPrim(of->alt_bRequireRevPrim),
BextensivePrimerChecks(of->BextensivePrimerChecks),
bRequireFwdPrim(of->bRequireFwdPrim), alt_bRequireFwdPrim(of->alt_bRequireFwdPrim),
BcutTag(of->BcutTag),
bCompletePairs(of->bCompletePairs), bShortAmplicons(of->bShortAmplicons),
minBCLength1_(of->minBCLength1_), minBCLength2_(of->minBCLength2_), maxBCLength1_(of->maxBCLength1_), maxBCLength2_(of->maxBCLength2_), minPrimerLength_(of->minPrimerLength_), maxHomonucleotide_(of->maxHomonucleotide_), trimHomonucleotide_(of->trimHomonucleotide_),
cut5PR1(of->cut5PR1), cut5PR2(of->cut5PR2),
PrimerErrs(of->PrimerErrs), alt_PrimerErrs(of->alt_PrimerErrs), barcodeErrors_(of->barcodeErrors_),
MaxAmb(of->MaxAmb), alt_MaxAmb(of->alt_MaxAmb),
FQWwidth(of->FQWwidth), EWwidth(of->EWwidth),
RevPrimSeedL(of->RevPrimSeedL),
b_BinFilBothPairs(of->b_BinFilBothPairs),
BinFilErr(of->BinFilErr), BinFilP(of->BinFilP),
FQWthr(of->FQWthr), EWthr(of->EWthr),
alt_FQWthr(of->alt_FQWthr), alt_EWthr(of->alt_EWthr),
PEheaderVerWr(of->PEheaderVerWr), TrimStartNTs(of->TrimStartNTs),
TruncSeq(of->TruncSeq),
iniSpacer(of->iniSpacer), userReqFastqVer(of->userReqFastqVer),
userReqFastqOutVer(of->userReqFastqOutVer), maxAccumQP(of->maxAccumQP),
alt_maxAccumQP(of->alt_maxAccumQP),
//BChit, BCrevhit initialize to 0 - new set, new luck
pairedSeq(of->pairedSeq),
//revConstellationN(0),
BCdFWDREV(of->BCdFWDREV),
firstXreadsW(of->firstXreadsW), firstXreadsR(of->firstXreadsR),
restartSet(false),
b_optiClusterSeq(of->b_optiClusterSeq), b_subselectionReads(of->b_subselectionReads),
b_doQualFilter(of->b_doQualFilter),
b_doFilter(of->b_doFilter),
bDoDereplicate(of->bDoDereplicate),
bDoSeedExtension(of->bDoSeedExtension),
bDoCombiSamples(of->bDoCombiSamples),
maxReadsPerOFile(of->maxReadsPerOFile),
demultiBPperSR(of->demultiBPperSR),
//ReadsWritten(of->ReadsWritten), OFileIncre(of->OFileIncre),
barcodeLengths1_(0), barcodeLengths2_(0),
illuPEfwd(of->illuPEfwd), illuPErev(of->illuPErev), illuSEuni(of->illuSEuni), illuSEidx(of->illuSEidx),
Bcheck4illuAdapts(of->Bcheck4illuAdapts),
doGoldAxe(of->doGoldAxe),
GoldAxeMinAmpli(of->GoldAxeMinAmpli), GoldAxeMaxAmpli(of->GoldAxeMaxAmpli),
SequencingRun(0), cmdArgs(of->cmdArgs), passed_interval_reads(0)
{
cdbg("New Filter object from copy\n");
ReadsWritten = of->writtenReads();
OFileIncre = of->getFileIncrementor();
BCdFWDREV[0].reset(); BCdFWDREV[1].reset();
//collectStatistics.resize(2); statAddition.resize(2);
//csMTX[0] = new mutex(); csMTX[1] = new mutex();
collectStatistics[0] = make_shared<collectstats>();
collectStatistics[1] = make_shared<collectstats>();
collectStatistics[0]->setbLvsQlogsPreFilt(of->collectStatistics[0]->getbLvsQlogsPreFilt());
statAddition[0] = make_shared<collectstats>(); statAddition[1] = make_shared<collectstats>();
GAstatistics = make_shared<GAstats>();
mergeStats = make_shared<MEstats>();
cdbg("New Filter::resize collectStatistics done\n");
if (takeAll) {
this->allResize((uint)of->PrimerIdx.size());
PrimerIdxRev = of->PrimerIdxRev;
PrimerIdx = of->PrimerIdx;
Barcode = of->Barcode;
Barcode2 = of->Barcode2;
SampleID = of->SampleID;
SampleID_Combi = of->SampleID_Combi;
HeadSmplID = of->HeadSmplID;
PrimerL = of->PrimerL;
PrimerR = of->PrimerR;
PrimerL_RC = of->PrimerL_RC;
PrimerR_RC = of->PrimerR_RC;
hetPrimer = of->hetPrimer;
lMD = of->lMD;
barcodeLengths1_ = of->barcodeLengths1_;
barcodeLengths2_ = of->barcodeLengths2_;
SequencingRun = of->SequencingRun;
SequencingRun2id = of->SequencingRun2id;
BarcodePreStats();
}
}
Filters::~Filters() {
cdbg("Deleting filter .. ");
// for (size_t i = 0; i < csMTX.size(); i++){
// delete csMTX[i];
// }
// for (size_t i = 0; i < 2; i++) { delete PostFilt[i]; delete RepStatAddition[i]; }
// delete PreFiltP1; delete PreFiltP2;
//cdbg("Done\n");
}
Filters* Filters::newFilterPerBCgroup(const vector<int> idxi) {
if (idxi.size() < 1) {
return nullptr;
}
cdbg("newFilterPerBCgroup::start : " + itos(idxi[0]) + "\n");
// get filter from main filter object passing an index for mapping?!
// shared_ptr<Filters> filter = make_shared<Filters>(shared_from_this(), idxi[0]);
Filters* filter = DBG_NEW Filters(this, idxi[0]);
cdbg("newFilterPerBCgroup::star2t\n");
// number of mapping file lines associated with that unique fastx
unsigned int tarSize = (unsigned int)idxi.size();
filter->allResize(tarSize);
int tarID = -1;
bool isDoubleBarcoded = this->doubleBarcodes();
cdbg("newFilterPerBCgroup::Go over BCs\n");
// iterate over every occurence of unique fa
for (unsigned int j = 0; j < tarSize; j++) { //fill in filter
// Get id_ of file in tar
tarID = idxi[j];
if (this->PrimerIdx[tarID] > -1) {
filter->addPrimerL(this->PrimerL[this->PrimerIdx[tarID]], j);
}
if (this->doReversePrimers() && this->PrimerIdxRev[tarID] > -1) {
filter->addPrimerR(this->PrimerR[this->PrimerIdxRev[tarID]], j);
}
filter->Barcode[j] = this->Barcode[tarID];
if (isDoubleBarcoded) {
filter->Barcode2[j] = this->Barcode2[tarID];
}
filter->SampleID[j] = this->SampleID[tarID];
filter->SampleID_Combi[j] = this->SampleID_Combi[tarID];
filter->HeadSmplID[j] = this->HeadSmplID[tarID];
}
cdbg("newFilterPerBCgroup::check 4 doubles\n");
//sanity check no double barcodes..
filter->checkDoubleBarcode();
filter->singReadBC2();
return filter;
}
void Filters::miniCheckDNA(shared_ptr<DNA> d, shared_ptr<DNA> d2) {
int BCoffs = getBCoffset();
bool checkSwitchedRdPairs = this->checkSwitchedRdPairs();
bool dualBCs = this->doubleBarcodes();
bool doBCsAtAll = this->doBarcodes();
int pairedRd = this->isPaired();
//needs some basic cleanups here..
bool wasReversed;
if (pairedRd == 2) {
vector< shared_ptr<DNA>>tdn(0); tdn.push_back(d);
if (d2 != nullptr) { tdn.push_back(d2); }
else { tdn.push_back(nullptr); }
wasReversed = this->swapReverseDNApairs(tdn);
}
else if (d2 == nullptr) {
wasReversed = this->isReversedAmplicon(d);
}
//remove base pairs 3' or 5' ?
if (getcut5PR1()) { d->cutSeq(0, getcut5PR1()); }
if (getcut5PR2()) { d2->cutSeq(0, getcut5PR2()); }
if (removeAdapter) { remove_adapter(d); }
if (BcutPrimer || Bcheck4illuAdapts) {
int tagIdx = 0; //for now just set to 0.. if an experiment uses > 1 primers this would need to change
bool fwdRC = false; bool revRC = true;//if this gets changed, the read needs to be reverse complemented
cutPrimer(d, PrimerIdx[tagIdx], fwdRC, 0, BextensivePrimerChecks);
if (bShortAmplicons) {//also check other end of primer.. also use for PacBio amplicons
//case for 1) long read 2) look for both primers 3) rev required
cutPrimerRev(d, PrimerIdxRev[tagIdx], revRC, BextensivePrimerChecks);
}
if (d2 != nullptr) {//pair_ == 1, check for fwd primer in pair_ 2 (rev-compl)
bool revCheck = false;// pair == -1 || pair == 0;//1:false for RC, else always a reverse check
cutPrimerRev(d2, PrimerIdxRev[tagIdx], revCheck, false);
if (bShortAmplicons) {//also check other end of primer..
cutPrimer(d, PrimerIdx[tagIdx], revCheck, 1);
}
}
//conditions for failing read on not finding fwd primer
if (!d->getFwdPrimDetect() && bRequireFwdPrim) {
d->setYellowQual(true);
}
//conditions for failing read on not finding rev primer
if (d2 != nullptr && bRequireRevPrim && !d->getRevPrimDetect()) {//failed to find reverse primer
d->setYellowQual(true);
}
}
}
//service function to ini OTU Seed extension
UClinks* Filters::ini_SeedsReadsDerep(UClinks* ucl, shared_ptr<ReadSubset>& RDSset,
shared_ptr<Dereplicate>& Dere) {
if (this->doOptimalClusterSeq()) {
ucl = DBG_NEW UClinks(cmdArgs);
if (cmdArgs->find("-mergedPairs") != cmdArgs->end() && (*cmdArgs)["-mergedPairs"] == "1") {
ucl->pairedSeqsMerged();
this->setFloatingEWin(0, 0.f);
}
else {
this->setFloatingEWin(10, 25);
}
//are fallback fasta sequences available?
if ((*cmdArgs)["-OTU_fallback"] != "") {
shared_ptr<InputStreamer> FALL = make_shared<InputStreamer>(true,
this->getuserReqFastqVer(), (*cmdArgs)["-ignore_IO_errors"], (*cmdArgs)["-pairedRD_HD_out"], 1);
FALL->setupFna((*cmdArgs)["-OTU_fallback"]);
ucl->setupDefSeeds(FALL, SampleID);
}
ucl->activateMerger();
}
else if (this->doSubselReads()) {
//this will select a list of reads and distribute these into multiple files
RDSset = make_shared<ReadSubset>((*cmdArgs)["-specificReads"], "");
}
else if (this->doDereplicate()) {
Dere = make_shared<Dereplicate>(cmdArgs, this);
// ReadMerger* merg = DBG_NEW ReadMerger(); //create special object for these functions
Dere->activateMerger();
}
return ucl;
}
//simulates that in mapping file links to sequence file was given.
bool Filters::setcmdArgsFiles() {
if (FastqF.size() == 0 && QualF.size() == 0 && FastaF.size() > 0) {
//fasta entry but no qual entries
string path = "";
if (cmdArgs->find("-i_path") != cmdArgs->end() && (*cmdArgs)["-i_path"].length() >= 1) {
path = (*cmdArgs)["-i_path"] + string("/");
}
QualF.resize(FastaF.size());
for (unsigned int i = 0; i < FastaF.size(); i++) {
string newQ = FastaF[i];
int pos = (int)newQ.find_last_of(".");
newQ = newQ.substr(0, pos);
newQ += string(".qual_");
fstream fin;
string fullQ = path + newQ;
fin.open(fullQ.c_str(), ios::in);
if (fin.is_open()) {
cerr << "Using quality file: " << fullQ << endl;
}
else if (cmdArgs->find("-number") != cmdArgs->end() && (*cmdArgs)["-number"] == "T") {
;
}
else {
cerr << "You did not supply a quality file for" << path + FastaF[i] << ". \nPlease give the path to your quality file as command line argument:\n -i_qual <PathToQualityFile>\n";
newQ = "";
//fin.close();return false;
}
fin.close();
QualF[i] = newQ;
}
}
int fileSiz = (int)Barcode.size();
//instead of max:
if (!bDoMultiplexing) { fileSiz = 1; }
if (FastaF.size() == 0 && FastqF.size() == 0) {
//set up fasta/fastq vector specific to corresponding BC (that should be in this file)
if (cmdArgs->find("-i_fastq") == cmdArgs->end()) {
FastaF.resize(fileSiz);
QualF.resize(fileSiz);
for (unsigned int i = 0; i < FastaF.size(); i++) {
FastaF[i] = (*cmdArgs)["-i_fna"];
QualF[i] = (*cmdArgs)["-i_qual"];
}
}
else {//fastq input
vector<string> fqTmp(1, (*cmdArgs)["-i_fastq"]);
if ((*cmdArgs)["-i_fastq"].find(";") != string::npos) {//";" denotes several files
if (fileSiz == 1) {//no BC,
fqTmp = splitByCommas((*cmdArgs)["-i_fastq"], ';');
this->allResize((uint)fqTmp.size());
fileSiz = (int)fqTmp.size();
cerr << "Detected " << fileSiz << " input files (pairs)." << endl;
FastqF = fqTmp;
}
else {
cerr << "Fastq string contains symbol \";\". Not allowed in input string"; exit(32);
}
}
else {
FastqF.resize(fileSiz, (*cmdArgs)["-i_fastq"]);
}
}
}
if (MIDfqF.size() == 0)
if (cmdArgs->find("-i_MID_fastq") != cmdArgs->end()) {
MIDfqF.resize(fileSiz, "");
for (unsigned int i = 0; i < MIDfqF.size(); i++) {
MIDfqF[i] = (*cmdArgs)["-i_MID_fastq"];
}
}
if ((*cmdArgs)["-o_dereplicate"] != "") {
//check if file could exist
ofstream temp;
temp.open((*cmdArgs)["-o_dereplicate"].c_str(), ios::out);
if (!temp) { cerr << "Could not open outstream to dereplicated sequences:\n" << (*cmdArgs)["- o_dereplicate"] << endl; exit(78); }
temp.close();
bDoDereplicate = true;
}
return true;
}
//only does BC 1
void Filters::reverseTS_all_BC() {
// for (int i=0; i<Barcode.size();i++){
// reverseTS(Barcode[i]);
// }
Barcode = revBarcode;
revBarcode.resize(0);
barcodes1_.clear();
for (uint i = 0; i < Barcode.size(); i++) {
barcodes1_[Barcode[i]] = i;
barcodeLengths1_[i] = (int)Barcode[i].length();
}
}
void Filters::reverseTS_all_BC2() {
// for (int i=0; i<Barcode.size();i++){
// reverseTS(Barcode[i]);
// }
Barcode2 = revBarcode2;
revBarcode2.resize(0);
barcodes2_.clear();
for (uint i = 0; i < Barcode2.size(); i++) {
barcodes2_[Barcode2[i]] = i;
barcodeLengths2_[i] = (int)Barcode2[i].length();
}
}
bool Filters::isReversedAmplicon(shared_ptr<DNA> tdn) {
if ((!checkRevRd())) {
return false;
}
//BC should be already cut at this point..
//int tagIdx = 0;//just try
//method 1: just check if primer is found reversed, most basic and seems to work fine..
//simple check if fwd rev primer is in reverse position: then reverse transcribe
bool fwdRd1Primer = checkIfPrimerHits(tdn, 0, 0);
bool fwdRd1PrimerRev = checkIfRevPrimerHits(tdn, 0, 0);
if (fwdRd1Primer) {
return false;
}
if (fwdRd1PrimerRev) {
tdn->reverse_compliment();
collectStatistics[0]->reversedRds++;//take stats on this
return true;
}
return false;
}
vector<shared_ptr<DNA>> Filters::GoldenAxe(vector< shared_ptr<DNA>>& tdn) {
vector<shared_ptr<DNA>> retDNA(0);
if (!this->isGoldAxe() || this->isPaired() != 1) {
return retDNA;
}
if (tdn[0]->length() < 100) { return retDNA; }
int idx = tdn[0]->getBCnumber();
///first check if amplicon wrongly oriented..
isReversedAmplicon(tdn[0]);
if (idx < 0) {
//string presentBC(""); int c_err(0);
//idx = this->findTag(tdn[0], presentBC, c_err, true,0,true);
idx = detectCutBC(tdn[0], true);
if (idx < 0) {
if (isReversedAmplicon(tdn[0])) {
//string presentBC(""); int c_err(0);
//idx = this->findTag(tdn[0], presentBC, c_err, true,0,true);
idx = detectCutBC(tdn[0], true);
}
}
/*if (idx >= 0) { //this should be done within "detectCutBC"
if (this->doubleBarcodes() ) {
int tagIdx2(-2);
tagIdx2 = this->findTag2(tdn[0], presentBC, c_err, false, -1);
this->dblBCeval(idx, tagIdx2, presentBC, tdn[0], nullptr);
if (idx != tagIdx2) {
cerr << "GA Double BC eval unsuccesful!\n"; exit(828);
}
}
tdn[0]->setBCnumber(idx, getBCoffset());
}
*/
if (idx >= 0) { tdn[0]->setBCnumber(idx, getBCoffset()); }
}
if (idx < 0) {
tdn[0]->failed(); //retDNA.push_back(tdn[0]);
//this->addGAstats(tdn[0], retDNA);
GAstatistics->addBaseGAStats(tdn[0], retDNA, 0);
return retDNA;