Repository navigation
Expand file tree
/
Copy pathIO.cpp
More file actions
1928 lines (1704 loc) · 79.9 KB
/
Copy pathIO.cpp
File metadata and controls
1928 lines (1704 loc) · 79.9 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
/* sdm: simple demultiplexer
Copyright (C) 2013 Falk Hildebrand
email: Falk.Hildebrand@gmail.com
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 <condition_variable>
#include <deque>
#if defined(__linux__)
#include <sched.h>
#endif
#include "ThreadPool.h"
#include "IO.h"
#include "OutputStreamer.h"
#include "Filters.h"
#include "Benchmark.h"
#include "OutputFileStream.h"
#include "InputFileStream.h"
#include <future>
#include <utility>
void multi_read_paired_STRget(shared_ptr<InputStreamer> IS, OutputStreamer* MD, int curThread,
int tmpBlockSize, bool MIDuse, bool keepPairHd, qual_score FastqVer) {
std::unique_ptr<multi_tmp_lines> tmpLines = std::make_unique<multi_tmp_lines>(tmpBlockSize);
bool cont(true);
while (cont) {
{
Instr::ScopedTimer st(Instr::GETDNALINES);
cont = IS->getDNAlines(tmpLines.get(), tmpBlockSize, MIDuse, true);
}
multi_read_paired_STRready(tmpLines.get(), MIDuse, MD, curThread, keepPairHd, FastqVer);
}
// unique_ptr will clean up tmpLines
}
bool multi_read_paired_STRready(multi_tmp_lines* tmpLines,
bool MIDuse, OutputStreamer* MD, int curThread,
bool keepPairHd, qual_score FastqVer, uint64_t derepBlock, uint64_t outputBlock) {
MD->beginDerepBlock(derepBlock, outputBlock);
bool isOK(true);
try {
isOK = process_read_block(tmpLines, MIDuse, MD, curThread, keepPairHd, FastqVer);
}
catch (...) {
// Seal the block anyway, so later blocks are not held back behind it;
// workers waiting for this block's output to be published stop waiting.
try { MD->endDerepBlock(derepBlock); } catch (...) {}
MD->failOutputBlocks();
throw;
}
try { MD->endDerepBlock(derepBlock); }
catch (...) { MD->failOutputBlocks(); throw; }
// Publish this block's output, in input order with a block number (no-op
// unless per-worker batching is active).
MD->finishOutputBlock(curThread, outputBlock);
return isOK;
}
bool process_read_block(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
Instr::ScopedTimer st_multi(Instr::MULTI_READ_READY);
// measure async lag if submit_ts set
if (tmpLines->submit_ts != 0) {
long long lag = Instr::now_us() - tmpLines->submit_ts;
Instr::add_us(Instr::ASYNC_LAG, lag);
tmpLines->submit_ts = 0;
}
bool isOK(true);
vector<shared_ptr<DNA>> ret(3, nullptr);
// Copy each record into worker-local strings before handing them to DNA.
// The reader's block buffers then keep their capacity (no allocation on the
// reader thread), and every string is allocated and freed by this worker
// instead of bouncing between malloc arenas.
thread_local vector<string> record;
auto convert = [&](vector<string>& lines, int readpos) {
Instr::ScopedTimer st(Instr::STR2DNA);
record = lines;
return str2DNA(std::move(record), keepPairHd, FastqVer, readpos);
};
for (size_t k = 0; k < tmpLines->size(); k++) {
ret[0].reset();
ret[1].reset();
ret[2].reset();
//cdbg("rpS");
ret[0] = convert(tmpLines->tmp[k][0], 0);
ret[1] = convert(tmpLines->tmp[k][1], 1);
if (MIDuse) {
ret[2] = convert(tmpLines->tmp[k][2], 2);
}
if (ret[0] == nullptr) {
continue;
//let's just make sure that there are not trailing objects..
}
//GoldenAxe requires some extra rounds of checking DNA
if (MD->getFilters(curThread)->isGoldAxe()) {
vector<shared_ptr<DNA>> multDNA = MD->getFilters(curThread)->GoldenAxe(ret);
if (multDNA.empty()) {
// No usable sub-amplicons (too short, no barcode, amplicon count
// out of range): count the read as processed and rejected, as
// process_DNA would, instead of dropping it from the statistics.
Filters* gaFilter = MD->getFilters(curThread);
ret[0]->failed();
gaFilter->sTotalPlus(0);
gaFilter->preFilterSeqStat(ret[0], 0);
int gaStream = 100;
MD->saveForWrite(ret[0], 1, curThread, gaStream, false);
continue;
}
int iniBCsGA(-2);
if (multDNA.size()) {
iniBCsGA = multDNA[0]->getBCnumber();
}
vector<shared_ptr<DNA>> ret2(3, nullptr);
for (size_t xi = 0; xi < multDNA.size(); xi++) {
ret2[1].reset();
ret2[2].reset();
ret2[0] = multDNA[xi];
isOK=process_DNA(ret2, MIDuse, MD, curThread);
if (ret2[0]->getBCnumber() != iniBCsGA) {//DEBUG
int BCnewWrong = ret2[0]->getBCnumber();
cerr << "Problem in GA read \n" << tmpLines->tmp[k][0][0]<<"\n"<< tmpLines->tmp[k][0][1] << "\n:Different BCs detected\n";
}
}
} else {
isOK = process_DNA(ret, MIDuse, MD, curThread);
}
//if (!isOK) {break;}
}
//delete tmpLines;
//no longer needed..
return isOK;
}
//is called from a while loop, that reads the DNA pairs
bool process_DNA(vector< shared_ptr<DNA>>& tdn,
bool MIDuse, OutputStreamer* MD, int curThread) {
auto& read1 = tdn[0];
auto& read2 = tdn[1];
auto& midRead = tdn[2];
if (read1 == nullptr) {
return false;
} //|| tdn->length()==0
Instr::ScopedTimer st_proc(Instr::PROCESS_DNA);
//DNA objects as they should be??
if (MIDuse && midRead == nullptr) {
//cerr << "Missing MID read pair.\n"; exit(4);
throw std::runtime_error("Missing MID read pair.");
}
const bool read2notNull = read2 != nullptr;
if (!read2notNull && MD->isPEseq() == 2) {
//cerr << "Second provided file has not the same number of entries as first file.\n";exit(5);
throw std::runtime_error("Second provided file has not the same number of entries as first file.");
}
//MD->checkFastqHeadVersion(tdn[0]);
//testreadpair.lock();
//cdbg("process_DNA"+ tdn[0]->getId()+"\n");
Filters* curFil = MD->getFilters(curThread);
const int mdPeSeq = MD->isPEseq();
const int pairedRd = curFil->isPaired();
const bool doBCsAtAll = curFil->doBarcodes();
const bool dualBCs = curFil->doubleBarcodes();
const int BCoffs = curFil->getBCoffset();
//register read at all with stat counter:
curFil->sTotalPlus(0);
if (read2notNull || pairedRd == 2) {
curFil->sTotalPlus(1);
}
//collect some info on general run parameters
curFil->preFilterSeqStat(read1, 0);
curFil->preFilterSeqStat(read2, 1);
//prep some variables
bool checkSwitchedRdPairs = curFil->checkSwitchedRdPairs();
(void)checkSwitchedRdPairs;
//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 && midRead != nullptr) {
tagIdx = curFil->findTag(midRead, presentBC, c_err, true,0,true,false);
read1->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 = false;
if (pairedRd == 2) {
wasReversed= curFil->swapReverseDNApairs(tdn);
} else if (!read2notNull) {
wasReversed = curFil->isReversedAmplicon(read1);
}
(void)wasReversed;
/*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(read1, -1, 0, tagIdx, curThread);
//tdn[0]->matchSeqRev
const bool ch1 = read1->isGreenQual();
bool ch2(false);
//if ( ch1 ) { cerr << cnt << " \n"; }
//normal case for check 2nd read
if (read2notNull) { //ch1&&
//dnaTemp2->setBCnumber(tdn[0]->getBCnumber());
if (doBCsAtAll && !dualBCs) { //only check in read1 for BC, if not dual BCing!!
tagIdx2 = read1->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;
}
}
else if (!curFil->doFilterAtAll() && !dualBCs && tagIdx >= 0) {
// Without filtering, only a sample index marks a read as passed. With no
// barcodes (e.g. no map), read 2 inherits read 1's index, so complete
// pairs are written as pairs instead of two singleton files.
tagIdx2 = tagIdx;
}
//if (isReversed) { tdn[1]->reverse_compliment(); }
if (!dualBCs && !read2->sampleBarcode().empty()) {
tagIdx2 = curFil->detectCutBC(read2, true);
}
MD->analyzeDNA(read2, -1, 1, tagIdx2, curThread);
ch2 = read2->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, read1, read2);
c_err = -1;
//check a second time that barcode was correctly identified, just to be double sure...
if ( tagIdx != tagIdx2 || read1->getBCnumber() != read2->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);
throw std::runtime_error("Unequal BC numbers:" + itos(tagIdx) + " : " + itos(tagIdx2) + "; in object: " + itos(read1->getBCnumber()) + " : " + itos(read2->getBCnumber()) + "\nIn read:" + read1->getId());
}
}
if (tagIdx == -1 || tagIdx2 == -1) {
read1->setBarcodeDetected(false);
if (read2notNull) {
read2->setBarcodeDetected(false);
}
} else {
curFil->setBCdna(tagIdx, read1);
if (ch2) { curFil->setBCdna(tagIdx, read2); }
if (MIDuse && ch1) {
curFil->BCintoHead(tagIdx, read1, presentBC, c_err, true);
if (ch2) { curFil->BCintoHead(tagIdx, read2, presentBC, c_err, true); }
}
}
int idx1 = 1; int idx2 = 2;
if (mdPeSeq == 2 ) {
if (read2notNull &&
(read1->isGreenYellowQual() && read2->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);
throw std::runtime_error("Error: invalid paired read pair headers:\n read1 head: " + tdn[0]->getShortId() + "\n read2 head: " + tdn[1]->getShortId());
}
}
if (MD->isPEseq() == 2 && ( MD->mergeReads() || MD->doDerepMrgSrch()) && 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->doWriteNonBCrds()) {
MD->writeNonBCReads(tdn[0], tdn[1], curThread);
}
//save for later .. and collect stats (also prepares the records for writing)
int Cstr1(100), Cstr2(100);
bool owr1;
bool owr2;
{
Instr::ScopedTimer st_out(Instr::OUTPUT_WRITE);
owr1 = MD->saveForWrite(read1, idx1, curThread, Cstr1,false);
owr2 = MD->saveForWrite(read2, idx2, curThread, Cstr2,false);
}
// Dereplication decides whether this set is counted. A set bound for the
// mid-quality tier is withheld here and written by the dereplicator only if
// it does not count it, so back-mapping that tier cannot count it twice.
bool withheld = false;
if (MD->doDeriplicate()) {
withheld = MD->dereplicateDNA(tdn[0], tdn[1], curThread, idx1, idx2);
}
if (!withheld) {
Instr::ScopedTimer st_out(Instr::OUTPUT_WRITE);
//writing of pairs needs to be mutex locked; read pairs stay together
MD->writeForWrite(read1,idx1,Cstr1,read2,idx2,Cstr2, curThread);
}
if (!owr1 || (!owr2 && read2notNull)) {
return false;
}
return true;
}
// Block buffers whose processing finished, in completion order. Lets the reader
// reuse whichever buffer is free first instead of waiting for one fixed slot.
struct CompletedBlocks {
std::mutex mutex;
std::condition_variable ready;
std::deque<size_t> done;
void push(size_t slot) {
// Notify under the lock: the reader may destroy this object as soon as
// it has seen the last completion.
std::lock_guard<std::mutex> lock(mutex);
done.push_back(slot);
ready.notify_one();
}
size_t pop() {
std::unique_lock<std::mutex> lock(mutex);
ready.wait(lock, [this] { return !done.empty(); });
const size_t slot = done.front();
done.pop_front();
return slot;
}
};
// The CPUs this process may run on: its affinity (a SLURM job's cpuset, taskset's)
// where the system tells it, else the online CPUs.
static size_t availableCpus() {
#if defined(__linux__)
cpu_set_t set;
CPU_ZERO(&set);
if (sched_getaffinity(0, sizeof(set), &set) == 0 && CPU_COUNT(&set) > 0) {
return static_cast<size_t>(CPU_COUNT(&set));
}
#endif
const unsigned n = std::thread::hardware_concurrency();
return n > 0 ? n : 1;
}
bool read_sequences(OutputStreamer* MD,
shared_ptr<InputStreamer> IS, int Nthreads) {
OptContainer* cmdArgs = getGlobalOptContainer();
if (cmdArgs == nullptr) {
throw std::runtime_error("Global option container is not initialized.");
}
const OptContainer::RuntimeOptions& runtimeOpts = cmdArgs->runtime();
if (Nthreads < 1) {
Nthreads = 1;
}
DNAmap oldMIDs;
bool MIDuse = IS->hasMIDseqs();
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 ;
bool doMC(false);
if (Nthreads > 1) {
doMC = true;
}
ThreadPool* pool = doMC ? &ThreadPool::instance() : nullptr;
// Per-worker filters, mergers and output batches are indexed by pool worker.
// If the pool was created with another size, fall back to one buffer per
// index so that a slot index identifies the per-thread state instead.
const bool workerIndexed = pool && pool->size() == static_cast<size_t>(Nthreads);
// Twice as many block buffers as workers: the reader fills the next blocks
// while every worker is busy.
const size_t slotCount = !doMC ? 1 : static_cast<size_t>(Nthreads) * (workerIndexed ? 2 : 1);
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 = runtimeOpts.iniBlockSize;
qual_score fastqVer = IS->fastQscore();
// Probe one block first and adapt batch size for short reads to reduce task scheduling overhead.
// This keeps behavior unchanged for longer reads while increasing reads/task when records are tiny.
int taskBatchMultiplier = 1;
string empty(""); empty.reserve(151);
{
cdbg("task batch size probe");
multi_tmp_lines probe(tmpBlockSize);
bool probeCont = IS->getDNAlines(&probe, tmpBlockSize, MIDuse, true);
// The offset is auto-detected from the whole probe block when no single
// record was conclusive; workers convert with the settled value.
IS->finalizeFastqVersion();
fastqVer = IS->fastQscore();
if (probeCont && probe.size() > 0 && probe.tmp[0].size() > 0 && probe.tmp[0][0].size() > 1) {
const size_t probeReadLen = probe.tmp[0][0][1].size();
if (probeReadLen > 0) {
if (probeReadLen <= 60) {
taskBatchMultiplier = 32;
}
else if (probeReadLen <= 110) {
taskBatchMultiplier = 16;
}
else if (probeReadLen <= 160) {
taskBatchMultiplier = 8;
}
else if (probeReadLen <= 350) {
taskBatchMultiplier = 4;
}
}
empty.reserve(probeReadLen + 1);
fastqVer = IS->fastQscore();
cdbg("FASTQversion: " + to_string(fastqVer) + ". ");
}
// Inputs smaller than one block end the probe with probeCont == false;
// they still need the paired header-format check.
if (fqHeadVer && probe.size() > 0 && probe.tmp[0].size() > 0 && probe.tmp[0][0].size() > 1) {
shared_ptr<DNA> tmp = str2DNA(probe.tmp[0][0], keepPairedHD, fastqVer, 0);
if (tmp) { MD->checkFastqHeadVersion(tmp); }
fqHeadVer = false;
}
IS->allStreamReset();
cdbg( " is " + to_string(taskBatchMultiplier) + ". ");
}
if (taskBatchMultiplier > 1 && tmpBlockSize <= (INT_MAX / taskBatchMultiplier)) {
tmpBlockSize *= taskBatchMultiplier;
}
cdbg("read_seq check3 ");
vector<unique_ptr<multi_tmp_lines>> tmpStrHolders(slotCount);
vector<string>tmpLines2(4, empty);
vector<vector<string>> tmpLines(3, tmpLines2);
for (size_t ii = 0; ii < slotCount; ii++) {
tmpStrHolders[ii] = make_unique<multi_tmp_lines>();
tmpStrHolders[ii]->tmp.resize(tmpBlockSize, tmpLines);
}
// Blocks are published in input order, so the outputs do not depend on -threads.
// At most one finished block per worker, and per CPU this process may run on,
// is held back: with more threads than CPUs, a descheduled worker's block
// otherwise held back one block per thread, published in bursts, and on 16
// threads of 6 CPUs the peak memory grew with the input (+47 MB on apong,
// +87 MB on 4x apong; capped: +16/+22 MB; 2026-10-16).
const size_t cpus = availableCpus();
MD->beginWriteBatching(std::max<size_t>(1, std::min(static_cast<size_t>(Nthreads), cpus)));
CompletedBlocks completed;
vector<size_t> freeSlots;
for (size_t ii = slotCount; ii-- > 0;) { freeSlots.push_back(ii); }
vector<std::exception_ptr> slotErrors(slotCount);
size_t outstanding = 0;
auto reclaim = [&]() {
const size_t slot = completed.pop();
--outstanding;
freeSlots.push_back(slot);
if (slotErrors[slot]) {
std::exception_ptr error = slotErrors[slot];
slotErrors[slot] = nullptr;
std::rethrow_exception(error);
}
};
//object holding converted DNA.. not longer used
//vector<shared_ptr<DNA>> tdn(3, nullptr);
cdbg("read_seq check4 ");
//doMC = false;//DEBUG
std::exception_ptr failure;
try {
while ( cont ) {
//decide on MC or single core submission route
if (doMC) { // multithreading
// step 0: take a free block buffer, or wait for the first worker to finish one
if (freeSlots.empty()) { reclaim(); }
const size_t slot = freeSlots.back();
freeSlots.pop_back();
multi_tmp_lines* block = tmpStrHolders[slot].get();
//step 1: read block from input into tmp buffer
{
Instr::ScopedTimer st(Instr::GETDNALINES);
cont = IS->getDNAlines(block, tmpBlockSize, MIDuse);
}
// If we read any records into the tmp buffer, submit them for processing.
// If cont==false but buffer contains data (partial final block), still process it.
if (block->size() > 0) {
// record submit timestamp and measure async creation cost
block->submit_ts = Instr::now_us();
Instr::ScopedTimer st_async(Instr::ASYNC_SUBMIT);
++outstanding;
try {
// Numbered here, in input order, so dereplication can apply
// blocks in that order however they are scheduled.
const uint64_t derepBlock = MD->reserveDerepBlock();
const uint64_t outputBlock = MD->reserveOutputBlock();
(void)pool->submit([&, block, slot, derepBlock, outputBlock]() {
try {
const int worker = workerIndexed ? pool->worker_index_of_current_thread() : static_cast<int>(slot);
if (worker < 0 || worker >= Nthreads) {
throw std::logic_error("Block processed outside the processing pool");
}
multi_read_paired_STRready(block, MIDuse, MD, worker, keepPairedHD, fastqVer, derepBlock, outputBlock);
}
catch (...) {
slotErrors[slot] = std::current_exception();
}
completed.push(slot);
});
}
catch (...) {
--outstanding;
freeSlots.push_back(slot);
throw;
}
} else {
freeSlots.push_back(slot);
}
// If no data was read and cont is false, EOF reached without data -> stop.
if (!cont) { break; }
} else {//single thread
cont = IS->getDNAlines(tmpStrHolders[0].get(), tmpBlockSize, MIDuse);
// If we read any records into the tmp buffer, process them even if cont==false (partial final block).
if (tmpStrHolders[0]->size() > 0) {
//fastqVer = IS->fastQscore();
// Numbered blocks as with several threads, so the outputs are the same.
const uint64_t derepBlock = MD->reserveDerepBlock();
const uint64_t outputBlock = MD->reserveOutputBlock();
bool cont2 = multi_read_paired_STRready(tmpStrHolders[0].get(), MIDuse,
MD, 0, keepPairedHD, fastqVer, derepBlock, outputBlock);
}
if (!cont && tmpStrHolders[0]->size() == 0) { break; }
//if (tdn[0]->isConstellationPairRev()) { revConstellation++; }
//}
}
}
}
catch (...) {
failure = std::current_exception();
}
// Keep the input buffers and OutputStreamer alive until every submitted
// block has finished, even when input parsing, submission, or another
// worker has already failed.
while (outstanding > 0) {
try {
reclaim();
}
catch (...) {
if (!failure) { failure = std::current_exception(); }
}
}
if (failure) { std::rethrow_exception(failure); }
//close shop
// Queued dereplication entries may still publish withheld mid-quality
// sets: apply them before the streams close.
MD->flushDereplication();
MD->closeOutStreams();
cdbg("read_seq check6 ");
// Print instrumentation results
Instr::printResults(std::cerr);
return true;
}
bool readCmdArgs(int argc, char* argv[]){
OptContainer* cmdArgs = getGlobalOptContainer();
if (cmdArgs == nullptr) {
throw std::runtime_error("Global option container is not initialized.");
}
if (argc%2!=1){
// cerr<<"It seems command line arguments were not passed in pairs. Aborting.\n";exit(666);
throw std::runtime_error("It seems command line arguments were not passed in pairs. Aborting.");
}
auto setDefault = [&](const string& key, const string& value) {
cmdArgs->setDefault(key, value);
};
for (int i=1; i<argc; i+=2){ //parsing of cmdline args
string theNxtSt = string(argv[i+1]);
// Arguments are key/value pairs; retain negative numeric values such as -1.
cmdArgs->set(string(argv[i]), theNxtSt);
}
setDefault("-illuminaClip", "0");
setDefault("-logLvsQ", "");
setDefault("-GoldenAxe", "0");
setDefault("-GoldenAxeMinAmpli", "0");
setDefault("-GoldenAxeMaxAmpli", "0");
setDefault("-DNAseedSelectionClassic", "0");
setDefault("-i_MID_fastq", "");
setDefault("-cramRef", "");
setDefault("-htsBarcode", "inline");
if ((*cmdArgs)["-htsBarcode"] != "inline" && (*cmdArgs)["-htsBarcode"] != "BC")
throw std::runtime_error("-htsBarcode must be inline or BC");
//set to default (empty)
setDefault("-OTU_fallback", "");
setDefault("-otu_matrix", "");
setDefault("-seedSubclusters", "0");
if ((*cmdArgs)["-seedSubclusters"] != "0" && (*cmdArgs)["-seedSubclusters"] != "1") {
throw invalid_argument("-seedSubclusters must be 0 or 1");
}
setDefault("-derepPerSR", "0");
setDefault("-ucAdditionalCounts", "");
setDefault("-ucAdditionalCounts1", "");
setDefault("-ucAdditionalCounts_refclust", "");
setDefault("-optimalRead2Cluster_ref", "");
//just for debuggin purposes: write out all seqs, where no BC can be detected..
setDefault("-o_fastq_noBC", "");
setDefault("-ucAdditionalCounts_refclust1", "");
setDefault("-XfirstReadsWritten", "");
setDefault("-XfirstReadsRead", "");
setDefault("-iniBlockSize", "120");
//filter sequence file for a specific subset of sequences
//these arguments can only occur together
if (cmdArgs->find("-specificReads") == cmdArgs->end()) {
cmdArgs->set("-specificReads", "");
} else if (cmdArgs->find("-excludeFile") == cmdArgs->end()) {
cmdArgs->set("-excludeFile", "");
}
setDefault("-onlyPair", "");
setDefault("-onlyCanonicalNTs", "0");
setDefault("-strictPositiveQualsOut", "0");
setDefault("-pairedDemulti", "0"); // by default: do not only report proper pairs
setDefault("-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") {
// Previously fell through to a misleading "Fasta not supplied" error.
throw std::runtime_error("Input empty: no sequences found in " + (*cmdArgs)["-i"]);
}
(*cmdArgs)[fmt] = (*cmdArgs)["-i"];
}
for (const string key : {"-i_sam", "-i_bam", "-i_cram"}) {
if (cmdArgs->contains(key)) {
if (cmdArgs->contains("-i_fastq") || cmdArgs->contains("-i_fna"))
throw std::runtime_error("Specify only one input format");
cmdArgs->set("-i_fastq", cmdArgs->get(key));
}
}
if (cmdArgs->find("-i_fastq") == cmdArgs->end()){ // fasta + quality format
if (cmdArgs->find("-i_fna") == cmdArgs->end()){
//cerr<<"Fasta not supplied. \nPlease give the path to your fasta file as command line argument:\n -i_fna <yourFastaFile>\n";exit(2);
throw std::runtime_error("Fasta not supplied. \nPlease give the path to your fasta file as command line argument:\n -i_fna <yourFastaFile>");
}
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"] != "")) {
newQ = "";
} 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);
throw std::runtime_error("Please give an output file (\"-o_fna\" || \"-o_fastq\") if you use sdm \"-i_path\" option.\n Aborting..");
}
}
/* if (cmdArgs->find("-map") == cmdArgs->end()){
cerr<<"You did not supply a mapping file. \nPlease give the path to your mapping file as command line argument:\n -map <PathToMappingFile>\n";
exit(2);
} */
if (cmdArgs->find("-o_qual") == cmdArgs->end()){
cmdArgs->set("-o_qual", "");
} else {
if (cmdArgs->find("-o_fastq") != cmdArgs->end()){
cerr<<"\"-o_qual\" was over-writen by \"-o_fastq\"\n";
(*cmdArgs)["-o_qual"] = "";
}
}
setDefault("-options", string("sdm_options.txt"));
setDefault("-threads", "1");
setDefault("-threadIO", "1");
// Strip an extension only when the last dot is part of the file name,
// so "./out" or "../dir/out" keep their directory part.
auto stripExtension = [](string& f) {
const size_t dot = f.find_last_of('.');
const size_t sep = f.find_last_of("/\\");
if (dot != string::npos && (sep == string::npos || dot > sep)) { f.erase(dot); }
};
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
stripExtension(ofile1);
if (tvec.size()==2){
ofile1+= "_" + getFileNoPath(tvec[1]);
stripExtension(ofile1);
}
(*cmdArgs)["-log"] = ofile1 + string(".log");
}
string ofile1 = (*cmdArgs)["-log"];
//ofile1.find_last_of(".log");
stripExtension(ofile1);
if (cmdArgs->find("-length_hist") == cmdArgs->end()){
cmdArgs->set("-length_hist", ofile1 + string("_lenHist.txt"));
}
if (cmdArgs->find("-qual_hist") == cmdArgs->end()) {
cmdArgs->set("-qual_hist", ofile1 + string("_qualHist.txt"));
}
// Position reports are optional: collect only when an output is requested.
setDefault("-merg_readpos", "");
setDefault("-qual_readpos", "");
//-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);
throw std::runtime_error("Invalid sample separator (empty).\nAborting..");
}
// .gzi block indexes next to gzip outputs are opt-in: sdm reads BGZF in
// parallel without them, and they clutter per-sample output directories.
setDefault("-o_gzi", "0");
if ((*cmdArgs)["-o_gzi"] != "0" && (*cmdArgs)["-o_gzi"] != "1") {
throw std::runtime_error("-o_gzi must be 0 or 1");
}
setBgzfIndexOutput((*cmdArgs)["-o_gzi"] == "1");
setDefault("-o_qual_offset", DEFAULT_output_qual_offset);
setDefault("-pairedRD_HD_out", DEFAULT_pairedRD_HD_out);
setDefault("-5PR1cut", DEFAULT_5PR1cut);
setDefault("-5PR2cut", DEFAULT_5PR2cut);
if (cmdArgs->find("-ignore_IO_errors") == cmdArgs->end()) {
cmdArgs->set("-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);
throw std::runtime_error("Argument \"ignore_IO_errors\" can only be \"1\" or \"0\". Instead it has value: " + (*cmdArgs)["-ignore_IO_errors"]);
}
setDefault("-o_dereplicate", "");
setDefault("-derep_map", "");
//if (cmdArgs->count("-i_fna")==0){}
setDNAseedSelectionClassic((*cmdArgs)["-DNAseedSelectionClassic"] == "1");
return true;
}
//manages read in of several input files and associated primers / tags to each file
void separateByFile(Filters* mainFilter, Benchmark* sdm_benchmark){
OptContainer* cmdArgs = getGlobalOptContainer();
if (cmdArgs == nullptr) {
throw std::runtime_error("Global option container is not initialized.");
}
#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
unique_ptr<UClinks> ucl; // Own seed state through every exit path.
shared_ptr<ReadSubset> RDSset (nullptr); //read subset filtered out?
shared_ptr<Dereplicate> dereplicator (nullptr); //dereplication of b_derep_as_fasta_ input?
ucl.reset(mainFilter->ini_SeedsReadsDerep(nullptr, 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
uint64_t maxReadsWr = mainFilter->getXreadsWr(); // should program stop after having written a certain amount of reads?
uint64_t maxReadsRd = mainFilter->getXreadsRd();
uint64_t totalReadsRead(0);
uint64_t totalReadsWrite(0);
auto printConvertedSummary = [&]() {
if ((*cmdArgs)["-o_fna"] != "") {
cerr << "Converted sequences written: " << totalReadsWrite << "\n";
}
};
uint64_t accumBPwrite(0), accumBPwriteMerg(0);
vector<string> lastSRblock (1,""); //set up SequencingRun blocks to track
string lastProcessedSRblock = "";
const OptContainer::RuntimeOptions& runtimeOpts = cmdArgs->runtime();
//---------------------------------
// Multithreading setup
//------------------------------------
bool multithreading = true;
//ThreadPool *pool = nullptr;
int threads = 1;
if (multithreading) {
threads = runtimeOpts.threads;
if (threads < 1) {
threads = 1;
}
ThreadPool::configure(static_cast<size_t>(threads));
/*if ( threads > 1) {
pool = DBG_NEW ThreadPool(threads);
}*/
cerr << "Run with " << threads << " cores.\n";
}
if (maxReadsWr > 0) {
cerr << "Only printing " << maxReadsWr << " first reads from file(s).\n";
}
if (maxReadsRd > 0) {
cerr << "Only reading " << maxReadsRd << " first reads from file(s).\n";
}
//set up a read merger for each thread..
const bool detailedMergeStats = !(*cmdArgs)["-merg_readpos"].empty() || !(*cmdArgs)["-qual_readpos"].empty();
ReadMerger positionStats;
auto printPositionStats = [&] {
if (!(*cmdArgs)["-merg_readpos"].empty()) { positionStats.printMergeHisto((*cmdArgs)["-merg_readpos"]); }
if (!(*cmdArgs)["-qual_readpos"].empty()) { positionStats.printQualHisto((*cmdArgs)["-qual_readpos"]); }
};