-
Notifications
You must be signed in to change notification settings - Fork 5
/
IO.cpp
1405 lines (1175 loc) · 52.2 KB
/
IO.cpp
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
/* sdm: simple demultiplexer
Copyright (C) 2013 Falk Hildebrand
email: [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <queue>
#include <mutex>
#include <thread>
#include "IO.h"
#include "Benchmark.h"
#include <future>
//#include "IOMultithreaded.h"
/*void read_single(OptContainer& cmdArgs, shared_ptr<OutputStreamer> MD,
shared_ptr<InputStreamer> IS, int Nthreads){
cdbg("Read single routine\n");
Filters* curFil = MD->getFilters();
curFil->singReadBC2();
int chkDerep(0);
bool checkReversedRead = curFil->checkRevRd();
bool cont(true); //bool sync(false);
while (cont){
vector<shared_ptr<DNA>> tdn = IS->getDNAMC();
if (tdn[0] == nullptr) {
#ifdef DEBUG
cerr << "NULL read returned" << endl;
#endif
cont = false;
break;
}
//collect some info on general run parameters
curFil->preFilterSeqStat(tdn[0], 0); // statistics preFilter
curFil->sTotalPlus(0);//mutex update total counts
//thread starts here
int tagIdx(-2);
if (true && checkReversedRead ) {
string presentBC(""); int c_err(0);
int chkRev(1);
tagIdx = curFil->findTag(tdn[0], presentBC, c_err, true, chkRev);
/* if (tagIdx < 0) { //check if on reversed_ read
dnaTemp1->reverse_compliment();
tagIdx = curFil->findTag(dnaTemp1, presentBC, c_err, true);
}
if (chkRev==0) {//no? undo revTranscr
tdn[0]->reverse_compliment();
}
}
tagIdx = -2;
int curThread = -1;
MD->analyzeDNA(tdn[0], -1, -1, tagIdx,curThread);
//thread ends here
//here BC has to be correctly set within DNA object
MD->dereplicateDNA(tdn[0], nullptr);//run in extra thread?
MD->write2Demulti(tdn[0], 0, curFil->getBCoffset());
//first save read in mem, then write if enough reads accumulate in mem
//extra thread for multithreading??
// This is a quality collecting step
if (!MD->saveForWrite(tdn[0],1, curThread)) {
cont = false;
break;
}
if (tdn[0]->isGreenQual()) {
chkDerep++;
}
//if (tdn!=NULL && ch1 != tdn->isGreenQual()){cerr<<"isGreenQual is != ch1! Aborting..\n";exit(12);}
}
MD->closeOutStreams();
}
*/
//converts str to DNA
void multi_read_paired_STRget(shared_ptr<InputStreamer> IS, OutputStreamer* MD, int curThread,
int tmpBlockSize, bool MIDuse, bool keepPairHd, qual_score FastqVer) {
multi_tmp_lines* tmpLines = new multi_tmp_lines(tmpBlockSize);
bool cont(true);
while (cont) {
cont = IS->getDNAlines(tmpLines, tmpBlockSize, MIDuse, true);
multi_read_paired_STRready(tmpLines, MIDuse, MD, curThread, keepPairHd, FastqVer);
}
delete tmpLines;
}
bool multi_read_paired_STRready(multi_tmp_lines* tmpLines,
bool MIDuse, OutputStreamer* MD, int curThread,
bool keepPairHd, qual_score FastqVer) {
//for loop over tmplines, each entry is a read pair
bool isOK(true);
for (size_t k = 0; k < tmpLines->size(); k++) {
vector<shared_ptr<DNA>> ret(3, nullptr);
//cdbg("rpS");
ret[0] = str2DNA(tmpLines->tmp[k][0], keepPairHd, FastqVer, 0);
ret[1] = str2DNA(tmpLines->tmp[k][1], keepPairHd, FastqVer, 1);
if (MIDuse) {
ret[2] = str2DNA(tmpLines->tmp[k][2], keepPairHd, FastqVer, 2);
}
//GoldenAxe requires some extra rounds of checking DNA
if (ret[0] != nullptr && MD->getFilters(curThread)->isGoldAxe()) {
vector<shared_ptr<DNA>> multDNA = MD->getFilters(curThread)->GoldenAxe(ret);
vector<shared_ptr<DNA>> ret2(3, nullptr);
for (size_t xi = 0; xi < multDNA.size(); xi++) {
ret2[0] = multDNA[xi];
isOK=read_paired_DNAready(ret2, MIDuse, MD, curThread);
}
} else {
isOK = read_paired_DNAready(ret, MIDuse, MD, curThread);
}
if (!isOK) {
break;
}
}
//delete tmpLines;
//no longer needed..
return isOK;
}
/*
bool read_paired_STRready(vector< vector< string>> tmpLines,
bool MIDuse, OutputStreamer* MD, int curThread,
bool keepPairHd, qual_score FastqVer) {
vector<shared_ptr<DNA>> ret(3, nullptr);
//cdbg("rpS");
ret[0] = str2DNA(tmpLines[0], keepPairHd, FastqVer, 0);
ret[1] = str2DNA(tmpLines[1], keepPairHd, FastqVer, 1);
if (MIDuse) {
ret[2] = str2DNA(tmpLines[2], keepPairHd, FastqVer, 2);
}
return read_paired_DNAready(ret, MIDuse, MD, curThread);
}
*/
//is called from a while loop, that reads the DNA pairs
bool read_paired_DNAready(vector< shared_ptr<DNA>> tdn,
bool MIDuse, OutputStreamer* MD, int curThread) {
if (tdn[0] == nullptr) {
return false;
} //|| tdn->length()==0
//DNA objects as they should be??
if (MIDuse && tdn[2] == nullptr) {
cerr << "Missing MID read pair.\n";
exit(4);
}
if (tdn[1] == nullptr && tdn[0] != nullptr && MD->isPEseq() == 2) {
cerr << "Second provided file has not the same number of entries as first file.\n";
exit(5);
}
//MD->checkFastqHeadVersion(tdn[0]);
//testreadpair.lock();
//cdbg("read_paired_DNAready"+ tdn[0]->getId()+"\n");
Filters* curFil = MD->getFilters(curThread);
//register read at all with stat counter:
curFil->sTotalPlus(0); curFil->sTotalPlus(1);
//collect some info on general run parameters
curFil->preFilterSeqStat(tdn[0], 0);
curFil->preFilterSeqStat(tdn[1], 1);
//prep some variables
int BCoffs = curFil->getBCoffset();
bool checkSwitchedRdPairs = curFil->checkSwitchedRdPairs();
bool dualBCs = curFil->doubleBarcodes();
bool doBCsAtAll = curFil->doBarcodes();
int pairedRd = curFil->isPaired();
//bool checkReversedRead = curFil->checkRevRd();
int tagIdx(-2); int tagIdx2(-2);
string presentBC(""); int c_err(0);
//bool isReversed(false);//was a reversion detected?
if (MIDuse && tdn[2] != nullptr) {
tagIdx = curFil->detectCutBC(tdn[2], presentBC, c_err, true);
tdn[0]->setBCnumber(tagIdx, BCoffs);
}
//routine checks, and reverses/swaps DNA objects
//bool reversedDNA = curFil->swapReverseDNApairs(tdn);
//now split up into multiple PB reads, if GoldenAxe (or Kinnect)
//manage reversed / swapped reads by detecting where the fwd primer is
bool wasReversed;
if (pairedRd == 2) {
wasReversed= curFil->swapReverseDNApairs(tdn);
} else if (tdn[1] == nullptr) {
wasReversed = curFil->isReversedAmplicon(tdn[0]);
}
/*if (checkBC2ndRd) {
if (!dualBCs) {
//use this routine to set the BC inside the DNA object
bool revT = false;
bool Pr1 = curFil->findPrimer(tdn[0], 0, false, 0);
bool Pr2 = curFil->findPrimer(tdn[1], 0, false, 0);
//int chkRev1(-1), chkRev2(-1);
tagIdx = curFil->findTag(tdn[0], presentBC, c_err, true, -1);
tagIdx2 = curFil->findTag(tdn[1], presentBC, c_err, true, -1);
if ((tagIdx2 >= 0 && tagIdx < 0 && !Pr1) || (Pr2 && !Pr1)) { //swap first & second read
swap(tdn[0], tdn[1]);
tdn[0]->constellationPairRev(true); tdn[1]->constellationPairRev(true);
//revConstellation++;
}
//else if (tagIdx2 < 0 && tagIdx < 0) {
// int x = 0;
//}
if (revT) {
tdn[0]->reverse_compliment(); tdn[1]->reverse_compliment();
}
}
tagIdx2 = -2; tagIdx = -2;
tdn[1]->setpairREV(); tdn[0]->setpairFWD();
}
*/
//tdn[0]->reverse_compliment();
//actually important routine
MD->analyzeDNA(tdn[0], -1, 0, tagIdx, curThread);
//tdn[0]->matchSeqRev
bool ch1(false); if (tdn[0] != NULL) { ch1 = tdn[0]->isGreenQual(); }
bool ch2(false); bool ch2n(false);
//if ( ch1 ) { cerr << cnt << " \n"; }
//normal case for check 2nd read
if (!ch2 && tdn[1] != nullptr) { //ch1&&
//dnaTemp2->setBCnumber(tdn[0]->getBCnumber());
if (doBCsAtAll && !dualBCs) { //only check in read1 for BC, if not dual BCing!!
tagIdx2 = tdn[0]->getBCnumber(); // no 2nd BC, thus no BC search in 2nd read
if (tagIdx2 >= 0) {
tagIdx2 -= BCoffs;
}else if (tagIdx2 < -1) {//something wrong with BCoffs
cerr << "tagidx2 wrongly truncated to " << tagIdx2 << endl;
}
}
//if (isReversed) { tdn[1]->reverse_compliment(); }
MD->analyzeDNA(tdn[1], -1, 1, tagIdx2, curThread);
ch2 = tdn[1]->isGreenQual();
}
//set up BC in DNA header
//remember that dual BCs are only valid after this step!
if (dualBCs && pairedRd == 2) {
//in case of single reads (PB) with double BCs
//if (dualBCs && tagIdx2 < 0 && pairedRd == 1) {
// tagIdx2 = curFil->findTag2(tdn[0], presentBC, c_err, false, -1);
//}
curFil->dblBCeval(tagIdx, tagIdx2, presentBC, tdn[0], tdn[1]);
c_err = -1;
//check a second time that barcode was correctly identified, just to be double sure...
if ( tagIdx != tagIdx2 || tdn[0]->getBCnumber() != tdn[1]->getBCnumber()) {
cerr << "Unequal BC numbers:" << tagIdx << " : " << tagIdx2 << "; in object: " << tdn[0]->getBCnumber() << " : " << tdn[1]->getBCnumber() << endl;
cerr << "In read:" << tdn[0]->getId() << endl;
exit(835);
}
}
if (tagIdx == -1 || tagIdx2 == -1) {
tdn[0]->setBarcodeDetected(false);
if (tdn[1] != nullptr) {
tdn[1]->setBarcodeDetected(false);
}
} else {
curFil->setBCdna(tagIdx, tdn[0]);
if (ch2) { curFil->setBCdna(tagIdx, tdn[1]); }
if (MIDuse && ch1) {
curFil->BCintoHead(tagIdx, tdn[0], presentBC, c_err, true);
if (ch2) { curFil->BCintoHead(tagIdx, tdn[1], presentBC, c_err, true); }
}
}
int idx1 = 1; int idx2 = 2;
bool read2notNull = tdn[1] != nullptr;
if (MD->isPEseq() == 2 ) {
if (read2notNull && tdn[0] != nullptr &&
(tdn[0]->isGreenYellowQual() && tdn[1]->isGreenYellowQual()) ) {
//only this case allows for paired reads out
idx1 = 1; idx2 = 2;
}
else {
idx1 = 3; idx2 = 4;
}
/*if (ch1 && !ch2) {
idx1 = 3; idx2 = 4;
//if (tdn[1] != NULL) { tdn[1]->failed(); }
// delete dnaTemp2;
}
else if (ch2 && !ch1) {
idx2 = 4; idx1 = 3;
//if (tdn[0] != NULL) { tdn[0]->failed(); }
// delete tdn[0];
}
/*else if (!ch1 && !ch2) { //nothing passes
if (tdn[0] != NULL) { tdn[0]->failed(); }
if (tdn[1] != NULL) { tdn[1]->failed(); }
// delete tdn[0]; delete dnaTemp2;
}*/
}
//pre-merge step
//if ( MD->mergeReads()) {MD->findSeedForMerge(tdn[0], tdn[1],curThread); }
//needed to eval qual of seed
if (read2notNull) {//check that this is really correct read pair
if (!tdn[0]->sameHeadPosFree(tdn[1])) {
cerr << "Error: invalid paired read pair headers:\n read1 head: " << tdn[0]->getShortId() << "\n read2 head: " << tdn[1]->getShortId()<<endl;
exit(152);
}
}
if (MD->mergeReads() && read2notNull) {
MD->findSeedForMerge(tdn[0], tdn[1], curThread);
}
//demultiplex write? do this first before DNA is deleted..
//at this point the tagIDX *MUST* be correctly set + BCoffset (in the DNA object, tagIDX doesn;t matter)
//cdbg("w2D ");
if (MD->Demulti2Fls()) {
MD->write2Demulti(tdn[0], tdn[1], curFil->getBCoffset(), curThread);
}
if (MD->doDeriplicate()) {
MD->dereplicateDNA(tdn[0], tdn[1]);
}
if (MD->doWriteNonBCrds()) {
MD->writeNonBCReads(tdn[0], tdn[1]);
}
// Test
/*if (OutStreamer->b_merge_pairs_derep_ && tdn[0]->merge_seed_pos_ > 0) {
auto dna_merged = ReadMerger::merge(tdn[0], tdn[1]);
}*/
//testreadpair.unlock();
//save for later .. and collect stats
//writing of pairs needs to be mutex locked
int Cstr1(100), Cstr2(100);
//cdbg("sFW\n");
bool owr1 = MD->saveForWrite(tdn[0], idx1, curThread, Cstr1,false);
bool owr2 = MD->saveForWrite(tdn[1], idx2, curThread, Cstr2,false);
//mutex version to ensure read pairs together..
MD->writeForWrite(tdn[0],idx1,Cstr1,tdn[1],idx2,Cstr2);
if (!owr1 || (!owr2 && read2notNull)) {
return false;
}
return true;
}
bool read_paired2(OptContainer* cmdArgs, OutputStreamer* MD,
shared_ptr<InputStreamer> IS, bool MIDuse, int Nthreads) {
DNAmap oldMIDs;
bool fqHeadVer(true);
cdbg("Paired reads routine v2\n");
//multithreading setup
//int Nthrds = atoi((*cmdArgs)["-threads"].c_str()) -1 ;
vector<std::thread> slots;
int DNAinMem(0);
bool cont(true), cont2(true), cont3(true);
bool keepPairedHD = IS->keepPairedHD();
int tmpBlockSize = atoi((*cmdArgs)["-iniBlockSize"].c_str());
//find out the fastqVer, fix across fastq's
qual_score fastqVer;
multi_tmp_lines* tmpO = new multi_tmp_lines(tmpBlockSize);
cont = IS->getDNAlines(tmpO, tmpBlockSize, MIDuse,true);
fastqVer = IS->fastQscore();
shared_ptr<DNA> tmp = str2DNA(tmpO->tmp[0][0], keepPairedHD, fastqVer, 0);
MD->checkFastqHeadVersion(tmp); fqHeadVer = false;
delete tmpO;
IS->allStreamReset();
for (int i = 0; i < Nthreads; ++i) {
// Each thread adds two numbers
slots.emplace_back(multi_read_paired_STRget,
IS, MD, i, tmpBlockSize, MIDuse, keepPairedHD, fastqVer);
}
for (auto& thread : slots) {
thread.join();
}
//close shop
//MD->revConstellationCnts(revConstellation);
MD->closeOutStreams();
return true;
}
struct job2 {
bool inUse = false;
future<bool> job;
//thread job;
};
bool read_paired(OptContainer* cmdArgs, OutputStreamer* MD,
shared_ptr<InputStreamer> IS, bool MIDuse, int Nthreads) {
DNAmap oldMIDs;
bool fqHeadVer(true);
cdbg( "Read paired routine\n");
/*if (sync2pair && MIDuse) {
cout << "Can not sync read pairs, while explicit MID sequences are being used! (not supported, sorry)\n";
sync2pair = false;
} */
//bool syncedMID = false;
//multithreading setup
//int Nthrds = atoi((*cmdArgs)["-threads"].c_str()) -1 ;
vector<job2> slots(Nthreads);
int thrCnt = 0;
bool doMC(false);
if (Nthreads > 1) {
doMC = true;
}
int DNAinMem(0);
bool cont(true),cont2(true),cont3(true);
bool keepPairedHD = IS->keepPairedHD();
//int revConstellation(0);
//int cnt(0);
//bool switching(true); // important to keep track of this, to fix swapped read pairs
//vector<string>tmpLines2(4, "");
//vector<vector<string>> tmpLines(3, tmpLines2);
//ini blocks of empty strings for later reuse..
int tmpBlockSize = atoi((*cmdArgs)["-iniBlockSize"].c_str());
vector<multi_tmp_lines*> tmpStrHolders(Nthreads, nullptr);
string empty(""); empty.reserve(151);
vector<string>tmpLines2(4, empty);
vector<vector<string>> tmpLines(3, tmpLines2);
for (size_t ii = 0; ii < Nthreads; ii++) {
multi_tmp_lines* tmpO = DBG_NEW multi_tmp_lines(); // will be deleted inside multi_read_paired_STRready function
tmpO->tmp.resize(tmpBlockSize, tmpLines);
tmpStrHolders[ii] = tmpO;
}
//object holding converted DNA.. not longer used
//vector<shared_ptr<DNA>> tdn(3, nullptr);
qual_score fastqVer;
while ( cont ) {
//bool sync = false;
//tests of different ways to read files..
//cnt++;
//decide on MC or single core submission route
if (true && doMC) { // multithreading
//step 0: threadpool checks
bool notSubm(true);
if (slots[thrCnt].inUse == true){
//&& slots[thrCnt].job.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {
bool cont2 = slots[thrCnt].job.get();
slots[thrCnt].inUse = false;
}
//now thread X is empty.. and eventual reads in it as well
//step 1: read 4 lines from .fq
cont = IS->getDNAlines(tmpStrHolders[thrCnt], tmpBlockSize, MIDuse);
//step 1b: set fq version (if not done already)
fastqVer = IS->fastQscore();
if (fqHeadVer) { //some things just need to be done
if (tmpStrHolders[thrCnt]->tmp[0][0].size() < 0) {cerr << "Error: empty fastq object. Please check that your input fastq contains sequences?"; exit(623);}
shared_ptr<DNA> tmp = str2DNA(tmpStrHolders[thrCnt]->tmp[0][0], keepPairedHD, fastqVer, 0);
MD->checkFastqHeadVersion(tmp); fqHeadVer = false;
}
//step 2: convert string, process, discard
if (slots[thrCnt].inUse == false) {
slots[thrCnt].job = async(std::launch::async, multi_read_paired_STRready,
tmpStrHolders[thrCnt], MIDuse, MD, thrCnt, keepPairedHD, fastqVer);
slots[thrCnt].inUse = true;
notSubm = false;
}
thrCnt++;
if (thrCnt >= Nthreads) { thrCnt = 0; }
if (!cont) { break; }
} else {//single thread
cont = IS->getDNAlines(tmpStrHolders[thrCnt], tmpBlockSize, MIDuse); fastqVer = IS->fastQscore();
if (fqHeadVer ) { //some things just need to be done
if (tmpStrHolders[thrCnt]->tmp[0][0].size() < 0) { cerr << "Error: empty fastq object. Please check that your input fastq contains sequences?"; exit(623); }
shared_ptr<DNA> tmp = str2DNA(tmpStrHolders[thrCnt]->tmp[0][0], keepPairedHD, fastqVer, 0);
MD->checkFastqHeadVersion(tmp); fqHeadVer = false;
}
bool cont2 = multi_read_paired_STRready(tmpStrHolders[thrCnt], MIDuse, MD, 0, keepPairedHD, fastqVer);
//if (tdn[0]->isConstellationPairRev()) { revConstellation++; }
//}
}
}
//get all slots
for (int x = thrCnt; x < slots.size(); x++) {//better load balancing
if (slots[x].inUse == true) {//&& slots[x].job.wait_for(std::chrono::milliseconds(1)) == std::future_status::ready) {
cont = slots[x].job.get();
slots[x].inUse = false;
}
}
for (int x = 0; x < slots.size(); x++){
if (slots[x].inUse == true){//&& slots[x].job.wait_for(std::chrono::milliseconds(1)) == std::future_status::ready) {
cont = slots[x].job.get();
slots[x].inUse = false;
}
}
//close shop
//MD->revConstellationCnts(revConstellation);
MD->closeOutStreams();
for (size_t ii = 0; ii < Nthreads; ii++) {
delete tmpStrHolders[ii];
}
return true;
}
bool readCmdArgs(int argc, char* argv[],OptContainer* cmdArgs){
if (argc%2!=1){
cerr<<"It seems command line arguments were not passed in pairs. Aborting.\n";
exit(666);
}
for (int i=1; i<argc; i+=2){ //parsing of cmdline args
string theNxtSt = string(argv[i+1]);
if (theNxtSt[0] != '-'){
(*cmdArgs)[string(argv[i])] = theNxtSt;
} else {
(*cmdArgs)[string(argv[i])] = "T";
}
}
if (cmdArgs->find("-illuminaClip") == cmdArgs->end()) {
(*cmdArgs)["-illuminaClip"] = "0";
}
if (cmdArgs->find("-logLvsQ") == cmdArgs->end()) {
(*cmdArgs)["-logLvsQ"] = "";
}
if (cmdArgs->find("-GoldenAxe") == cmdArgs->end()) {
(*cmdArgs)["-GoldenAxe"] = "0";
}
if (cmdArgs->find("-i_MID_fastq") == cmdArgs->end()) {
(*cmdArgs)["-i_MID_fastq"] = "";
}
//set to default (empty)
if (cmdArgs->find("-OTU_fallback") == cmdArgs->end()){
(*cmdArgs)["-OTU_fallback"] = "";
}
if (cmdArgs->find("-otu_matrix") == cmdArgs->end()) {
(*cmdArgs)["-otu_matrix"] = "";
}
if (cmdArgs->find("-derepPerSR") == cmdArgs->end()) {
(*cmdArgs)["-derepPerSR"] = "0";
}
if (cmdArgs->find("-ucAdditionalCounts") == cmdArgs->end()) {//.ADD
(*cmdArgs)["-ucAdditionalCounts"] = "";
}
if (cmdArgs->find("-ucAdditionalCounts1") == cmdArgs->end()) {//.REST
(*cmdArgs)["-ucAdditionalCounts1"] = "";
}
if (cmdArgs->find("-ucAdditionalCounts_refclust") == cmdArgs->end()) {//.ADDREF
(*cmdArgs)["-ucAdditionalCounts_refclust"] = "";
}
if (cmdArgs->find("-optimalRead2Cluster_ref") == cmdArgs->end()) {//.ADDREF
(*cmdArgs)["-optimalRead2Cluster_ref"] = "";
}
//just for debuggin purposes: write out all seqs, where no BC can be detected..
if (cmdArgs->find("-o_fastq_noBC") == cmdArgs->end()) {
(*cmdArgs)["-o_fastq_noBC"] = "";
}
if (cmdArgs->find("-ucAdditionalCounts_refclust1") == cmdArgs->end()) {//.RESTREF
(*cmdArgs)["-ucAdditionalCounts_refclust1"] = "";
}
if (cmdArgs->find("-ucAdditionalCounts_refclust1") == cmdArgs->end()) {//.RESTREF
(*cmdArgs)["-ucAdditionalCounts_refclust1"] = "";
}
if (cmdArgs->find("-XfirstReads") == cmdArgs->end()) {
(*cmdArgs)["-XfirstReads"] = "";
}
if (cmdArgs->find("-iniBlockSize") == cmdArgs->end()) {
(*cmdArgs)["-iniBlockSize"] = "100";
}
//filter sequence file for a specific subset of sequences
//these arguments can only occur together
if (cmdArgs->find("-specificReads") == cmdArgs->end()) {
(*cmdArgs)["-specificReads"] = "";
} else if (cmdArgs->find("-excludeFile") == cmdArgs->end()) {
(*cmdArgs)["-excludeFile"] = "";
}
if (cmdArgs->find("-onlyPair") == cmdArgs->end()) {
(*cmdArgs)["-onlyPair"] = "";
}
if (cmdArgs->find("-pairedDemulti") == cmdArgs->end()) {
(*cmdArgs)["-pairedDemulti"] = "0"; // by default: do not only report proper pairs
}
if (cmdArgs->find("-uparseVer") == cmdArgs->end()) {
(*cmdArgs)["-uparseVer"] = "";
}
if (cmdArgs->find("-i_path") == cmdArgs->end()){ //ok files are not given in mapping file
//check if dna and qual_ are passed
if (cmdArgs->find("-i") != cmdArgs->end()) {
string fmt = detectSeqFmt((*cmdArgs)["-i"]);
if (fmt == "empty") {
//exit(0);
cerr << "Only empty input files\n";
}
(*cmdArgs)[fmt] = (*cmdArgs)["-i"];
}
if (cmdArgs->find("-i_fastq") == cmdArgs->end()){ // fasta + quality format
if (cmdArgs->find("-i_fna") == cmdArgs->end()){
cerr<<"You did not supply a fasta file. \nPlease give the path to your fasta file as command line argument:\n -i_fna <yourFastaFile>\n";
exit(2);
}
if (cmdArgs->find("-i_qual") == cmdArgs->end()){
string newQ = (*cmdArgs)["-i_fna"];
int pos = (int)newQ.find_last_of(".");
newQ = newQ.substr(0,pos);
newQ += string(".qual_");
fstream fin;
fin.open(newQ.c_str(),ios::in);
if( fin.is_open() ) {
cerr<<"Using quality file: "<<newQ <<endl;
} else if ((cmdArgs->find("-number")!= cmdArgs->end() && (*cmdArgs)["-number"] =="T")||
((*cmdArgs)["-specificReads"] != "")) {
(*cmdArgs)["-i_qual"] = "";
} else {
cerr<<"You did not supply a quality file. \nPlease give the path to your quality file as command line argument:\n -i_qual <PathToQualityFile>\n";
newQ = "";
//fin.close(); exit(2);
}
fin.close();
(*cmdArgs)["-i_qual"] = newQ;
}
}
//auto create output file name
if (cmdArgs->find("-o_fna") == cmdArgs->end()){
if (cmdArgs->find("-o_fastq") == cmdArgs->end()){
//(*cmdArgs)["-o_fna"] = (*cmdArgs)["-i_fna"]+string(".sdm");
//cerr<<"Writing output fasta into "<<(*cmdArgs)["-o_fna"]<<endl;
cerr << "No output file will be written\n";
}
} else {
if (cmdArgs->find("-o_fastq") != cmdArgs->end()){
cerr<<"\"-o_fna\" was over-writen by \"-o_fastq\"\n";
(*cmdArgs)["-o_fna"] = "";
}
}
} else {
if (cmdArgs->find("-o_fna") == cmdArgs->end() && cmdArgs->find("-o_fastq") == cmdArgs->end()){
cerr<<"Please give an output file (\"-o_fna\" || \"-o_fastq\") if you use sdm \"-i_path\" option.\n Aborting..\n";
exit(2);
}
}
/* if (cmdArgs->find("-base_map") == cmdArgs->end()){
cerr<<"You did not supply a mapping file. \nPlease give the path to your mapping file as command line argument:\n -base_map <PathToMappingFile>\n";
exit(2);
} */
if (cmdArgs->find("-o_qual") == cmdArgs->end()){
(*cmdArgs)["-o_qual"] = "";
} else {
if (cmdArgs->find("-o_fastq") != cmdArgs->end()){
cerr<<"\"-o_qual\" was over-writen by \"-o_fastq\"\n";
(*cmdArgs)["-o_qual"] = "";
}
}
if (cmdArgs->find("-options") == cmdArgs->end()){
(*cmdArgs)["-options"] = string("sdm_options.txt");
}
if (cmdArgs->find("-threads") == cmdArgs->end()) {
(*cmdArgs)["-threads"] = "1";
}
if (cmdArgs->find("-threadIO") == cmdArgs->end()) {
(*cmdArgs)["-threadIO"] = "1";
}
if (cmdArgs->find("-log") == cmdArgs->end()){
string ofile1 = (*cmdArgs)["-o_fna"];
if (ofile1==""){ofile1 = (*cmdArgs)["-o_fastq"];}
vector<string> tvec = splitByComma(ofile1,false);
ofile1 = tvec[0];
//remove file ending
size_t pos = ofile1.find_last_of(".");
if (pos != string::npos){ofile1 = ofile1.substr(0,pos); }
if (tvec.size()==2){
ofile1+= "_" + getFileNoPath(tvec[1]);
pos = ofile1.find_last_of(".");
if (pos != string::npos){ofile1 = ofile1.substr(0,pos); }
}
(*cmdArgs)["-log"] = ofile1 + string(".log");
}
string ofile1 = (*cmdArgs)["-log"];
//ofile1.find_last_of(".log");
size_t logPos = ofile1.find_last_of(".");
if (logPos != std::string::npos){
ofile1 = ofile1.substr(0,logPos);
}
if (cmdArgs->find("-length_hist") == cmdArgs->end()){
(*cmdArgs)["-length_hist"] = ofile1 + string("_lenHist.txt");
}
if (cmdArgs->find("-qual_hist") == cmdArgs->end()) {
(*cmdArgs)["-qual_hist"] = ofile1 + string("_qualHist.txt");
}
if (cmdArgs->find("-merg_readpos") == cmdArgs->end()) {
(*cmdArgs)["-merg_readpos"] = ofile1 + string("_mergRpos.txt");
}
if (cmdArgs->find("- qual_readpos") == cmdArgs->end()) {
(*cmdArgs)["-qual_readpos"] = ofile1 + string("_qualRpos.txt");
}
//-length_hist -qual_hist
if (cmdArgs->find("-sample_sep") == cmdArgs->end()){
(*cmdArgs)["-sample_sep"] = DEFAULT_BarcodeNameSep;
} else if ((*cmdArgs)["-sample_sep"]==""){
cerr<<"Invalid sample separator (empty).\nAborting..\n";exit(82);
}
if (cmdArgs->find("-o_qual_offset") == cmdArgs->end()) {
(*cmdArgs)["-o_qual_offset"] = DEFAULT_output_qual_offset;
}
if (cmdArgs->find("-pairedRD_HD_out") == cmdArgs->end()) {
(*cmdArgs)["-pairedRD_HD_out"] = DEFAULT_pairedRD_HD_out;
}
if (cmdArgs->find("-5PR1cut") == cmdArgs->end()) {
(*cmdArgs)["-5PR1cut"] = DEFAULT_5PR1cut;
}
if (cmdArgs->find("-5PR2cut") == cmdArgs->end()) {
(*cmdArgs)["-5PR2cut"] = DEFAULT_5PR2cut;
}
if (cmdArgs->find("-ignore_IO_errors") == cmdArgs->end()) {
(*cmdArgs)["-ignore_IO_errors"] = DEFAULT_ignore_IO_errors;
} else if ((*cmdArgs)["-ignore_IO_errors"] != "0" && (*cmdArgs)["-ignore_IO_errors"] != "1") {
cerr << "Argument \"ignore_IO_errors\" can only be \"1\" or \"0\". Instead it has value: " << (*cmdArgs)["-ignore_IO_errors"] << endl;
exit(323);
}
if (cmdArgs->find("-o_dereplicate") == cmdArgs->end()) {
(*cmdArgs)["-o_dereplicate"] = "";
}
if (cmdArgs->find("-derep_map") == cmdArgs->end()) {
(*cmdArgs)["-derep_map"] = "";
}
//if (cmdArgs->count("-i_fna")==0){}
return true;
}
//manages read in of several input files and associated primers / tags to each file
void separateByFile(Filters* mainFilter, OptContainer* cmdArgs, Benchmark* sdm_benchmark){
#ifdef DEBUG
cerr << "separateByFile"<<endl;
#endif
// mainFilter->ini_filestruct(cmdArgs);
//setup once at start
//vector<ReadMerger*> merger(0);
//contains info on input files, format, order etc
filesStr files;
//handles testing for input files, resorting them, input file format..
mainFilter->FileEssentials(files, cmdArgs);
// mainFile for processing
string mainFile = "";
string outFile = (*cmdArgs)["-o_fna"];
//special sdm functions ini
UClinks *ucl = nullptr; // Seed extension ?
shared_ptr<ReadSubset> RDSset (nullptr); //read subset filtered out?
shared_ptr<Dereplicate> dereplicator (nullptr); //dereplication of b_derep_as_fasta_ input?
ucl = mainFilter->ini_SeedsReadsDerep(ucl, RDSset, dereplicator); // actual prep
//needs to attach to existing file sometimes
std::ios_base::openmode writeStatus = ios_base::out;
bool shortStats = false;
string shrtLog = "";
// main loop that goes over different files
int maxReads = mainFilter->getXreads(); // should program stop after having written a certain amount of reads?
int totalReadsRead(0);
uint accumBPwrite(0), accumBPwriteMerg(0);
vector<string> lastSRblock (1,""); //set up SequencingRun blocks to track
//---------------------------------
// Multithreading setup
//------------------------------------
bool multithreading = true;
//ThreadPool *pool = nullptr;
int threads = 1;
if (multithreading) {
if (cmdArgs->find("-threads") != cmdArgs->end()) {
threads = stoi((*cmdArgs)["-threads"]);
}
/*if ( threads > 1) {
pool = DBG_NEW ThreadPool(threads);
}*/
cerr << "Run with " << threads << " cores.";
}
//set up a read merger for each thread..
bool detailedMergeStats(false);
//---------------------------------
//files.uniqueFastxFiles: unique input fastx's, can be demultiplexed fastas,
// or un-demultiplexed (several) fastx /loop that goes over several input fxs
// Should be brought in right order (SRblock)
//------------------------------------
// for (unsigned int i = 0; i < files.uniqueFastxFiles.size(); i++ ) {
for (auto &uFX : files.uniqFxFls) {
uint i = uFX.second;
cdbg("Unique file " + uFX.first + "(" + itos(i) + ")\n");
if (maxReads > 0 && maxReads - totalReadsRead <= 0) { break; }
if (files.idx[i].size() == 0) { cerr << "fastXtar vector for " << uFX.first << " is empty" << endl; exit(10); }
//create subset of BCs for the currently processed fastq's (only relevant BCs)
cdbg("new filter in round " + itos(i) + "\n");
Filters* filter = mainFilter->newFilterPerBCgroup(files.idx[i]);
cdbg("Setting up threads\n");
//filter->setThreads(threads);
int tarID = files.idx[i][0];//just points to one file in uFX group..
//initialize object to handle all input file combinations
//main input of fastx, handles input IO
cdbg("Ini InputStream");
shared_ptr<InputStreamer> IS = make_shared<InputStreamer>(
!files.isFastq, mainFilter->getuserReqFastqVer(),(*cmdArgs)["-ignore_IO_errors"],
(*cmdArgs)["-pairedRD_HD_out"], threads);
if ((*cmdArgs)["-threadIO"] == "1") { IS->setTIO(true); }
if ((*cmdArgs)["-threadIO"] == "0") { IS->setTIO(false); }
// there is an entry in tar for each barcode for this file. If files.idx[i].size() is 1 there is only one barcode
if (files.idx[i].size() == 1 && files.uniqueFastxFiles.size() > 1) {
IS->atFileYofX(i + 1, (unsigned int)files.uniqueFastxFiles.size(), 1);
}
// check first if derep block will change
if (totalReadsRead>0 && mainFilter->doDereplicate() && dereplicator->DerepPerSR()
&& lastSRblock.back() != mainFilter->SequencingRun[tarID]) {
//sanity check
for (uint ii = 0; ii < (lastSRblock.size()-1); ii++) {
if (lastSRblock[ii] == lastSRblock.back()) {
cerr << "\n\nWrong block order!!\n" << lastSRblock[ii] << ":" << lastSRblock.back() << endl;
}
}
string deLogLocal = dereplicator->writeDereplDNA(mainFilter, lastSRblock.back());
if (dereplicator->DerepPerSR()) {
files.deLog += "Dereplication of SequencingRun " + lastSRblock.back() + ":\n";
}
files.deLog += deLogLocal;
dereplicator->printMergeStats(subfile((*cmdArgs)["-merg_readpos"], lastSRblock.back()),
subfile((*cmdArgs)["-qual_readpos"], lastSRblock.back()));
//continue?
dereplicator->reset();//and reset..
accumBPwrite = 0; accumBPwriteMerg = 0;
//OutStreamer->resetDemultiBPperSR();
}
if (mainFilter->SequencingRun[tarID] != lastSRblock.back()) {
lastSRblock.push_back(mainFilter->SequencingRun[tarID]);
}
string mainFileShort;
mainFile = IS->setupInput(files.path, tarID, uFX.first, files, filter->setPaired(),
(*cmdArgs)["-onlyPair"], mainFileShort, false);
if (!IS->qualityPresent()) {
filter->deactivateQualFilter();
cerr << "\n*********\nWarning:: Quality file is not present.\nRecommended to abort demultiplexing.\n*********\n\n";
}
filter->BarcodePreStats();filter->checkDoubleBarcode();filter->checkDoubleSampleIDHead();
if (mainFilter->doOptimalClusterSeq()) {
ucl->findSeq2UCinstruction(IS, files.isFastq, mainFilter);
delete filter;
continue;// after this is only qual_ filter, not required from this point on
}
cdbg("Setting up output\n");
//OutputStreamer OutStreamer = OutputStreamer(&filter, cmdArgs, writeStatus, RDSset);
//OutputStreamer also contains subfilters for MC processing and logging of reads
OutputStreamer* OutStreamer = DBG_NEW OutputStreamer(filter, cmdArgs,
writeStatus, RDSset, threads,"");
OutStreamer->attachDereplicator(dereplicator);OutStreamer->activateReadMerger(threads);
OutStreamer->setBPwrittenInSR(accumBPwrite);OutStreamer->setBPwrittenInSRmerg(accumBPwriteMerg);
OutStreamer->attachBenchmark(sdm_benchmark);filter->setMultiDNA(OutStreamer);
if (maxReads > 0) {
OutStreamer->setReadLimit(maxReads - totalReadsRead);
}
writeStatus = ofstream::app;
//prepare for BC checking (rev/fwd)
if (filter->doDemultiplex()) {
OutStreamer->setBCfixed(false, true);
if (OutStreamer->isPEseq() == 2) {
OutStreamer->setBCfixed(false, false);
}
}
//only pull out a subset of sequences
if (mainFilter->doSubselReads()) {
if (cmdArgs->find("-mocatFix") != cmdArgs->end()) {
cerr << "MOCAT fix appplies\n";
RDSset->findMatches(IS, OutStreamer, true);
} else {
RDSset->findMatches(IS, OutStreamer, false);
}
//delete OutStreamer;
delete filter;
continue;