-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcontainers.cpp
More file actions
2047 lines (1847 loc) · 61.5 KB
/
containers.cpp
File metadata and controls
2047 lines (1847 loc) · 61.5 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 <algorithm>
#include <mutex>
#include "Common.h"
#include "containers.h"
#include "Filters.h"
#include "OutputStreamer.h"
using namespace std;
// trim and is_digits are provided by Common.cpp
//
ReadSubset::ReadSubset(const string inf, const string default_outfile):
RemainderStrPos(-1), newHD(0), outFiles(0), outFilesIdx(0) {
string line;
ifstream in(inf.c_str());
if (!in){
cerr << "Could not find " << inf << " read subset file. Exiting.\n"; exit(90);
}
int ini_ColPerRow(0), cnt(0), skips(0);
//check read subset format
while (!safeGetline(in, line).eof()) {
if (line.substr(0, 1) == "#"){ skips++; continue; }
string segments;
int ColsPerRow = 0; // Initialize counter.
stringstream ss;
ss << line;
while (getline(ss, segments, '\t')) {
ColsPerRow++;
}
if (cnt == 0){
ini_ColPerRow = ColsPerRow;
}
else {
if (ColsPerRow != ini_ColPerRow){
cerr << "Number of columns in read subset file on line " << cnt + skips << " is " << ColsPerRow << ". Expected " << ini_ColPerRow << " columns.\n";
exit(91);
}
if (cnt > 1000){
break;
}
}
cnt++;
}
if (ini_ColPerRow == 0){
cerr << "Read Subset File exists, but appears to be badly formated (0 columns detected). Exiting\n"; exit(92);
}
if (cnt == 0){
cerr << "Read Subset File exists, but appears to be badly formated (0 lines detected). Exiting\n"; exit(92);
}
in.clear();
in.seekg(0, ios::beg);
//extract read subset content
cnt = 0;
map<string, int> tmpFiles;
map<string, int>::iterator tmpFilIT;
unordered_map <string, int>::iterator TarIT;
//parameters were set for in matrix, now read line by line
while (!safeGetline(in, line).eof()) {
// while(getline(in,line,'\n')) {
if (cnt != 0 && line.substr(0, 1) == "#"){ continue; }
if (line.length() < 5){ continue; }
stringstream ss; string segments; int cnt2 = 0;
ss << line;
while (getline(ss, segments, '\t')) {
if (cnt2 == 0){
//free target RD from paired end info
remove_paired_info(segments);
TarIT = Targets.find(segments);
if (TarIT == Targets.end()){
Targets[segments] = cnt;
} else {
break;
}
}
else if (cnt2 == 1){
newHD.push_back(segments);
}
else if (cnt2 == 2){
uint Idx(0);
//1: test if outfile already exists
tmpFilIT = tmpFiles.find(segments);
if (tmpFilIT != tmpFiles.end()){
Idx = (*tmpFilIT).second;
}
else {//create new key
Idx = (uint) outFiles.size();
outFiles.push_back(segments);
tmpFiles[segments] = Idx;
}
//2: add the index to outfile to this position
outFilesIdx.push_back(Idx);
}
cnt2++;
}
if (cnt2 == 1) {//no specific header
newHD.push_back("");
tmpFilIT = tmpFiles.find("Default");
uint Idx(0);
if (tmpFilIT != tmpFiles.end()) {
Idx = (*tmpFilIT).second;
} else {//create new key
Idx = (uint)outFiles.size();
outFiles.push_back("Default");
tmpFiles["Default"] = Idx;
}
outFilesIdx.push_back(Idx);
}
if (cnt2>0) { cnt++; }
}
//is extra file info in read subset file?
if (ini_ColPerRow < 3){
outFilesIdx.resize(Targets.size(), 0);
outFiles.resize(1, default_outfile);
}
}
void ReadSubset::findMatches(shared_ptr<InputStreamer> IS, OutputStreamer* MD, bool mocatFix) {
vector<shared_ptr<DNA>> match; //shared_ptr<DNA> match2(NULL);
bool cont(true), cont2(true);
int idx(0);
int pairs = IS->pairNum();
unordered_map <string, int>::iterator SEEK;
bool b_doHD = newHD.size() > 0;
//bool sync(false);//meaningless placeholder
while (cont) {
match = IS->getDNApairs();
if (match[0] == NULL) { cont = false; break; }
//if (pairs > 1) { match2 = IS->getDNA(cont2, 1); }
string curID = match[0]->getPositionFreeId();
if (mocatFix && curID.length()>5 ) {
curID = header_stem(curID);
//cerr << curID << endl;
//exit(0);
}
//cerr << curID << endl;
SEEK = Targets.find(curID);
if (SEEK == Targets.end()) {//no hit
if (RemainderStrPos != -1) {
MD->writeSelectiveStream(match[0], 0, RemainderStrPos);
if (pairs > 1) {
MD->writeSelectiveStream(match[1], 1, RemainderStrPos);
}
} else {// nothing written, but still need to delete
// delete match; if (pairs > 1) {delete match2;}
}
continue;
}
//serious work
//cerr << "H";
idx = SEEK->second;
if (b_doHD && newHD[idx] != "" && pairs>1) {
match[0]->setHeader(newHD[idx] + "#1:0");
match[1]->setHeader(newHD[idx] + "#2:0");
}
MD->writeSelectiveStream(match[0], 0, outFilesIdx[idx]);
if (pairs > 1) {
MD->writeSelectiveStream(match[1], 1, outFilesIdx[idx]);
}
//finished, clean up to reduce search space (faster??)
Targets.erase(SEEK);
if (Targets.size() == 0 && RemainderStrPos==-1) {
return;
}
}
cerr << Targets.size() << " seqs remaining (not found in current file)\n";
}
//*******************************************
//* DEREPLICATE OBJECT
//*******************************************
Dereplicate::Dereplicate(OptContainer* cmdArgs, Filters* mf):
barcode_number_to_sample_id_(0), b_usearch_fmt(true), b_singleLine(true), b_pairedInput(false),
minCopies(1,0), minCopiesStr("0"), //default minCopies accepts every derep
minCopiesSiz(1),
tmpCnt(0), curBCoffset(0), b_derep_as_fasta_(true), b_derepPerSR(false),
b_wroteMapHD(false), b_merge_pairs_derep_(false),merger(nullptr),
mapF(""), outHQf(""), outHQf_p2(""), outRest(""),
mainFilter(mf), searchWithMerg(true)
{
outfile = (*cmdArgs)["-o_dereplicate"];
if ((*cmdArgs).find("-noSearchWithMerge") != (*cmdArgs).end()) {
searchWithMerg = false;
}
string baseOF = outfile.substr(0, outfile.find_last_of('.'));
mapF = baseOF + ".map";
outHQf = baseOF + ".1.hq.fq";
outHQf_p2 = baseOF + ".2.hq.fq";
outRest = outfile + ".rest";
//clean up eventually existing files
remove(mapF.c_str()); remove(outHQf.c_str());
remove(outHQf_p2.c_str()); remove(outRest.c_str());
// Reserve hash map capacity to avoid costly rehashing during heavy dereplication.
// Allow user to override via -derep_reserve; default to 1M slots.
try {
size_t reserveSize = 1024 * 512; // 500k
if (cmdArgs->find("-derep_reserve") != cmdArgs->end()) {
reserveSize = std::stoull((*cmdArgs)["-derep_reserve"]);
}
size_t perShard = reserveSize / Dereplicate::kDerepShardCount;
if (perShard == 0) {
perShard = 1;
}
for (size_t si = 0; si < Dereplicate::kDerepShardCount; ++si) {
tracker_shards_[si].reserve(perShard);
}
} catch (...) {
// ignore parse errors and continue without reserving
}
if (cmdArgs->find("-dere_size_fmt") != cmdArgs->end() && (*cmdArgs)["-dere_size_fmt"] == "1") {
b_usearch_fmt = false;
}
if ((*cmdArgs)["-derepPerSR"] == "1") {
b_derepPerSR = true;
}
if (cmdArgs->find("-min_derep_copies") != cmdArgs->end()) {
minCopies[0] = -1;//in this case reset to -1 the first entry..
minCopiesStr = (*cmdArgs)["-min_derep_copies"];
string x = (*cmdArgs)["-min_derep_copies"];
vector<string> xs = splitByCommas(x, ',');
for (size_t i = 0; i < xs.size(); i++) {
vector<string> tmp = splitByComma(xs[i], false, ':');
if (tmp.size() > 2) {
cerr << "Derep string " << xs[i] << " has to be two integers seqparated by \":\"\n"; exit(623);
}
int pos = 1; int cnt = -1;
if (tmp.size() == 1) {//this is the 1 sample position, if not set
cnt = atoi(tmp[0].c_str());
}else{
pos = atoi(tmp[1].c_str());//number of samples
cnt = atoi(tmp[0].c_str());//16s copy numbers
}
if (pos <= 0) { cerr << "wrong derplicate position (<=0):" << xs[i] << endl; exit(312); }
if (pos > 3000) { cerr << "too large derplicate position (>3000):" << xs[i] << endl; exit(313); }
if (minCopies.size() < (size_t)pos) {
minCopies.resize(pos, -1);
}
minCopies[pos-1] = cnt;
}
minCopiesSiz = minCopies.size();
//minCopies = atoi((*cmdArgs)["-min_derep_copies"].c_str());
}
else {
minCopiesSiz = minCopies.size();
}
// set up output format of dereplication:
if (cmdArgs->find("-derep_format") != cmdArgs->end()) {
auto res = (*cmdArgs)["-derep_format"];
if (strcmp(res.c_str(), "fa") == 0) {
b_derep_as_fasta_ = true;
}
else if (strcmp(res.c_str(), "fq") == 0) {
b_derep_as_fasta_ = false;
}
else {
std::cerr << "Invalid input for option -derep_format. If specified, -derep_format can take either \"fa\" for derep_as_fasta_ and \"fq\" for fastq. ";
exit(77);
}
}
// Flag for merging paired end fsatq reads
if (cmdArgs->find("-merge_pairs_derep") != cmdArgs->end() &&
(*cmdArgs)["-merge_pairs_derep"] == "1") {
b_merge_pairs_derep_ = true;
}
}
bool Dereplicate::addDNA(shared_ptr<DNA> dna, shared_ptr<DNA> dna2) {
struct ActiveAddGuard {
Dereplicate* owner;
explicit ActiveAddGuard(Dereplicate* d) : owner(d) {}
~ActiveAddGuard() {
if (owner->active_adddna_.fetch_sub(1, std::memory_order_acq_rel) == 1 &&
owner->lifecycle_pause_.load(std::memory_order_acquire)) {
std::lock_guard<std::mutex> lk(owner->lifecycle_wait_mtx_);
owner->lifecycle_wait_cv_.notify_all();
}
}
};
for (;;) {
if (lifecycle_pause_.load(std::memory_order_acquire)) {
std::unique_lock<std::mutex> waitLock(lifecycle_wait_mtx_);
lifecycle_wait_cv_.wait(waitLock, [this]() {
return !lifecycle_pause_.load(std::memory_order_acquire);
});
continue;
}
active_adddna_.fetch_add(1, std::memory_order_acq_rel);
if (!lifecycle_pause_.load(std::memory_order_acquire)) {
break;
}
if (active_adddna_.fetch_sub(1, std::memory_order_acq_rel) == 1 &&
lifecycle_pause_.load(std::memory_order_acquire)) {
std::lock_guard<std::mutex> lk(lifecycle_wait_mtx_);
lifecycle_wait_cv_.notify_all();
}
}
ActiveAddGuard activeGuard(this);
//1st build hash of DNA
if (!dna->getBarcodeDetected()) {
return false;
}
// Get copy of sequence (might have already been modified)
//string seq = dna->getSeqPseudo();
int sample_id = dna->getBCnumber();
bool pass = dna->isGreenQual();
//deactivate this for now..
int MrgPos1 = dna->merge_seed_pos_;
//int MrgPos1 = -1;
shared_ptr<DNA> dna_merged = nullptr;
const string* srchSeqPtr = nullptr;
thread_local string srchSeqBuffer;
/*
* findSeedForMerge requires own thread..
if (searchWithMerg && merger != nullptr && dna->merge_seed_pos_ == -1) {
MrgPos1 = merger->findSeedForMerge(dna, dna2);
}*/
// Only attempt to merge if a merger has been activated and pair is present
if (searchWithMerg && dna2 != nullptr && dna->merge_seed_pos_ != -1 && merger != nullptr) {
//MrgPos1 = dna2->merge_seed_pos_;
dna_merged = merger->merge(dna, dna2);
}
if (dna_merged){
// use merged sequence for searching but keep the merged object alive
const string& mergedSeq = dna_merged->getSequence();
size_t searchLen = std::min(static_cast<size_t>(dna->length()), mergedSeq.size());
if (searchLen == mergedSeq.size()) {
srchSeqPtr = &mergedSeq;
}
else {
srchSeqBuffer.assign(mergedSeq.data(), searchLen);
srchSeqPtr = &srchSeqBuffer;
}
//merge can be a lot shorter, potentially leading to problems searching this seq
/* if (false && srchSeq.length() != dna->length()) {
//int y = 1;
srchSeq = dna->getSeqPseudo();
}*/
}
else {
const string& seq = dna->getSequence();
size_t searchLen = std::min(static_cast<size_t>(dna->length()), seq.size());
if (searchLen == seq.size()) {
srchSeqPtr = &seq;
}
else {
srchSeqBuffer.assign(seq.data(), searchLen);
srchSeqPtr = &srchSeqBuffer;
}
}
const string& srchSeq = *srchSeqPtr;
// Lock because were accessing the base_map
// See if DNA object is present
// auto dna_unique = Tracker.find(new_dna_unique);
bool new_insert(true);
map<int, shared_ptr<DNAunique>>::iterator dna_unique;
const size_t shardIdx = shard_index_for(srchSeq);
HashDNA& shard = tracker_shards_[shardIdx];
std::shared_mutex& shardMtx = drpMTX_shards_[shardIdx];
{
std::shared_lock<std::shared_mutex> shardReadLock(shardMtx); // lock for hash shard
auto dna_unique1 = shard.find(srchSeq);
if (dna_unique1 != shard.end()) {// found something
new_insert = false;
// lock the DNAuniqSet for this sequence
unique_ptr<DNAuniqSet>& dnuSet = dna_unique1->second;
std::lock_guard<std::mutex> setLock(dnuSet->lockMTX);
dna_unique = dnuSet->find(MrgPos1);
// truly dereplicated? at least overlap should fit..
if (dna_unique == dnuSet->end()) {
dnuSet->addNewDNAuniq(dna, dna2, dna_merged, MrgPos1, sample_id);
}
else { // compare to existing DNA
dna_unique->second->matchedDNA(dna, dna2, dna_merged, sample_id, b_derep_as_fasta_);
}
}
}
if (new_insert && pass) {
// create/find entry under exclusive lock and acquire set lock before releasing
// to avoid races with container rehash/reference invalidation.
std::unique_lock<std::shared_mutex> shardWriteLock(shardMtx);
auto& entry = shard[srchSeq];
bool freshEntry = !entry;
if (freshEntry) {
entry = std::make_unique<DNAuniqSet>();
}
std::lock_guard<std::mutex> setLock(entry->lockMTX);
shardWriteLock.unlock();
if (!freshEntry) {
// Another thread inserted the same srchSeq between our shared unlock
// and exclusive lock. Match against existing entries instead of
// blindly adding a duplicate.
auto dna_unique_it = entry->find(MrgPos1);
if (dna_unique_it != entry->end()) {
dna_unique_it->second->matchedDNA(dna, dna2, dna_merged, sample_id, b_derep_as_fasta_);
}
else {
entry->addNewDNAuniq(dna, dna2, dna_merged, MrgPos1, sample_id);
}
}
else {
entry->addNewDNAuniq(dna, dna2, dna_merged, MrgPos1, sample_id);
}
}
//drpMTX.unlock();
return new_insert;//didn't do a thing..
}
void Dereplicate::BCnamesAdding(Filters* fil) {
vector<string> refSID = fil->SampleID;
for (size_t i = 0; i < refSID.size(); i++) {
barcode_number_to_sample_id_.push_back(refSID[i]);
}
//this will in the end be used to synchronize the different barcodes between samples
curBCoffset = (int)barcode_number_to_sample_id_.size();
//cerr << curBCoffset << " Added BC list\n";
}
void Dereplicate::reset() {
lifecycle_pause_.store(true, std::memory_order_release);
{
std::unique_lock<std::mutex> lk(lifecycle_wait_mtx_);
lifecycle_wait_cv_.wait(lk, [this]() {
return active_adddna_.load(std::memory_order_acquire) == 0;
});
}
// for (size_t i = 0; i < Dnas.size(); i++) { delete Dnas[i]; }
// Dnas.resize(0);
//passedSize = 0;
tmpCnt = 0;
//barcode_number_to_sample_id_.resize(0);
for (size_t si = 0; si < Dereplicate::kDerepShardCount; ++si) {
std::unique_lock<std::shared_mutex> lk(drpMTX_shards_[si]);
tracker_shards_[si].clear();
}
lifecycle_pause_.store(false, std::memory_order_release);
lifecycle_wait_cv_.notify_all();
}
bool DNAuPointerCompare(shared_ptr<DNAunique> l, shared_ptr<DNAunique> r) {
return l->totalSum() > r->totalSum();
}
void Dereplicate::finishMap() {
lifecycle_pause_.store(true, std::memory_order_release);
{
std::unique_lock<std::mutex> lk(lifecycle_wait_mtx_);
lifecycle_wait_cv_.wait(lk, [this]() {
return active_adddna_.load(std::memory_order_acquire) == 0;
});
}
//at this point we can onl be sure that barcode_number_to_sample_id_ is finished
//hence now it the point to add this to map
//passedSize = 0;
tmpCnt = 0;
for (size_t si = 0; si < Dereplicate::kDerepShardCount; ++si) {
std::unique_lock<std::shared_mutex> lk(drpMTX_shards_[si]);
tracker_shards_[si].clear();
}
std::ifstream inputFile(mapF.c_str(),ios::in);
std::ofstream outputFile((mapF+"t").c_str(), ios::out);
outputFile << "#SMPLS";
bool bCombiSmpl = mainFilter->combineSamples();
vector<int> smplId2comb(0, 0);
unordered_map<string, int> & combiMapCollectGrp = mainFilter->combiMapCollectGrp;
if (!bCombiSmpl) {
for (size_t i = 0; i < barcode_number_to_sample_id_.size(); i++) {
outputFile << "\t" + std::to_string((int)i) + ":" + barcode_number_to_sample_id_[i];
}
}
else {
smplId2comb = mainFilter->combiSmplConvergeVec(barcode_number_to_sample_id_);
if (barcode_number_to_sample_id_.size() != smplId2comb.size()) {
cerr << "FATAL: barcode_number_to_sample_id_ != smplId2comb\n"; exit(234);
}
for (auto IT = combiMapCollectGrp.begin(); IT != combiMapCollectGrp.end(); IT++) {
outputFile << "\t" << std::to_string(IT->second) + ":" + IT->first;
}
}
outputFile << "\n";
b_wroteMapHD = true;
outputFile << inputFile.rdbuf();
inputFile.close();
outputFile.close();
std::remove(mapF.c_str());
int x = std::rename((mapF + "t").c_str(), mapF.c_str());
lifecycle_pause_.store(false, std::memory_order_release);
lifecycle_wait_cv_.notify_all();
return;
}
string Dereplicate::writeDereplDNA(Filters* mf, string SRblock) {
ofstream of, omaps, of2, ofRest, of2p2, of_merged;
cerr << "\nEvaluating and writing dereplicated reads..\n";
int fastqVer = mf->getuserReqFastqOutVer();
//set the correct file names for dereplication output files
string baseOF = outfile.substr(0, outfile.find_last_of('.'));
string baseOF2 = baseOF;
if (b_derepPerSR && SRblock != "") {//if writing out per SRblock, needs different filename for map and
baseOF2 += "." + SRblock;
}
string fileSuff = outfile.substr(outfile.find_last_of('.'));
string outfile2 = baseOF2 + fileSuff;
string outfile_merged = baseOF2 + ".merg" + fileSuff;
// OPEN OUTPUT FILE STREAMS
omaps.open(mapF.c_str(), ios::app);//| ios::binary
//actual dereplicated reads as required by clustering algo (uparse, cdhit, dada2,...)
of.open(outfile2.c_str(), ios::out);
//reads that did not pass dereplication min number
ofRest.open(outRest.c_str(), ios::app);
//copy of high quality read pairs -> needed for Seed extension step
of2.open(outHQf.c_str(), ios::app);
const bool can_merge_derep = b_merge_pairs_derep_ && (merger != nullptr);
if (b_merge_pairs_derep_ && merger == nullptr) {
cerr << "Warning: -merge_pairs_derep enabled but merger not initialized; continuing without merge for derep output.\n";
}
if (can_merge_derep) {
of_merged.open(outfile_merged.c_str(), ios::out);
}
if (b_pairedInput) {
of2p2.open(outHQf_p2, ios::app);
}
//sample specific derep filter
bool dereplicate_sample_specific(false);
vector<int> dereplicate_sample_specific_indices = mf->getDrerepSampleSpecifity();
if (!dereplicate_sample_specific_indices.empty()) { dereplicate_sample_specific = true; }
//combiner relevant vars
bool bCombiSmpl = mf->combineSamples();
vector<int> smplId2comb(0,0);
unordered_map<string, int> & combiMapCollectGrp = mf->combiMapCollectGrp;
if (bCombiSmpl) {
smplId2comb = mf->combiSmplConvergeVec(barcode_number_to_sample_id_);
}
//vector<string> refSID = mf->SampleID;
if (false && !b_wroteMapHD) {
omaps << "#SMPLS";
if (!bCombiSmpl) {
for (size_t i = 0; i < barcode_number_to_sample_id_.size(); i++) {
omaps << "\t" + itos((int)i) + ":" + barcode_number_to_sample_id_[i];
}
}
else {
if (barcode_number_to_sample_id_.size() != smplId2comb.size()) {
cerr << "FATAL: barcode_number_to_sample_id_ != smplId2comb\n"; exit(234);
}
for (auto IT = combiMapCollectGrp.begin(); IT != combiMapCollectGrp.end(); IT++) {
omaps << "\t" << std::to_string(IT->second) + ":" + IT->first;
}
}
omaps << "\n";
b_wroteMapHD = true;
}
//convert to vector, that can than be written out
vector<shared_ptr<DNAunique>> dereplicated_dnas;
dereplicated_dnas.reserve(tracker_size_total());
for (size_t si = 0; si < Dereplicate::kDerepShardCount; ++si) {
std::shared_lock<std::shared_mutex> lk(drpMTX_shards_[si]);
for (auto dd = tracker_shards_[si].begin(); dd != tracker_shards_[si].end(); ++dd) {
if (!dd->second) {
continue;
}
dereplicated_dnas.push_back(dd->second->best(true));
}
}
// bool DNAuPointerCompare(shared_ptr<DNAunique> l, shared_ptr<DNAunique> r) { return l->getCount() < r->getCount();}
sort(dereplicated_dnas.begin(), dereplicated_dnas.end() , DNAuPointerCompare);
size_t passedSize = 0; size_t notPassedSize = 0; size_t passed_hits(0);
size_t passedMerge(0);
//bool thrHit = false;
//sanity check
vector<int> counts_per_sample(barcode_number_to_sample_id_.size(), 0);
int total_count(0);
int passed_count(0);
ofstream* derepNowOut;
//print unique DNAs
for (size_t i = 0; i < dereplicated_dnas.size(); i++) {
shared_ptr<DNAunique> dna = dereplicated_dnas[i];;
total_count ++;
dna->Count2Head(b_usearch_fmt);
shared_ptr<DNA> dna_merged = nullptr;
if ((dereplicate_sample_specific &&
dna->pass_deprep_smplSpc(dereplicate_sample_specific_indices)) ||
pass_deprep_conditions(dna) ) {
//we do have a real derep that needs to be clustered..
passed_hits++;
passedSize += dna->totalSum();
//only do merge here, because these are known good dereps already
if (can_merge_derep && dna->merge_seed_pos_ >= 0) {
dna_merged = merger->merge(dna, dna->getPair());
}
derepNowOut = &of;
if (dna->getMergeLength() > 0) {
passedMerge++;
}
} else {
notPassedSize += dna->totalSum();
//dna->writeSeq(ofRest, b_singleLine);
derepNowOut = &ofRest;
}
if (b_derep_as_fasta_)
if (dna_merged) {//either or mechanic
dna_merged->writeSeq(of_merged, b_singleLine);
} else {
dna->writeSeq((*derepNowOut), b_singleLine);
}
else {
if (dna_merged) {
dna_merged->prepareWrite(fastqVer);
dna_merged->writeFastQ(of_merged);
} else {
dna->prepareDerepQualities(fastqVer);
dna->writeDerepFastQ((*derepNowOut));
}
}
//map is written no matter what
dna->writeMap(omaps, dna->getId(), counts_per_sample, smplId2comb);
//write out full seq + fastq
dna->resetTruncation();
dna->prepareWrite(fastqVer);
dna->writeFastQ(of2);
if (b_pairedInput) {
shared_ptr<DNAunique> oD = dna->getPair();
if (oD != nullptr) {
oD->resetTruncation();
oD->prepareWrite(fastqVer);
oD->writeFastQ(of2p2);
} else {
shared_ptr<DNA> tmp = make_shared< DNA>("", dna->getId());
tmp->writeFastQEmpty(of2p2);
}
}
}
// if (tmpCnt != passedSize) {
// cerr << "Counting failed\n" << tmpCnt << " " << passedSize<<endl;
// }
of.close(); omaps.close(); ofRest.close();
float avgSize = passed_hits > 0 ? (float)passedSize / (float)(passed_hits) : 0.f;
string report = "";
string N_notPassed = intwithcommas(int(dereplicated_dnas.size() - passed_hits));
string N_total = intwithcommas(int(dereplicated_dnas.size()));
string N_passed = intwithcommas((int)passed_hits);
report += "Dereplication: " + N_passed + " unique sequences (avg size ";
report += intwithcommas((int)avgSize) + "; " + intwithcommas((int)passedSize) + " counts, ";
report += intwithcommas(passedMerge) + " merged)\n";
if (passed_hits > 0) {
report += N_notPassed + "/" + N_total + " not passing derep conditions (" + intwithcommas((int)notPassedSize) + " counts; "+ minCopiesStr;
if (dereplicate_sample_specific) { report += " & sample specific restrictions"; }
report += ")";
}
cerr << report << endl << endl;
if (this->b_derepPerSR) {
return report;
}
int uneqCnts(0);
//check counts_per_sample vector
vector<string> SampleID = mf->SampleID;
for (unsigned int i = 0; i<SampleID.size(); i++) {
size_t j(0); bool detected = false;
for (; j < barcode_number_to_sample_id_.size(); j++) {
if (SampleID[i] == barcode_number_to_sample_id_[j]) { detected = true; break; }
}
if (detected && mf->collectStatistics[0]->BarcodeDetected[i] != counts_per_sample[j] && mf->collectStatistics[0]->BarcodeDetected[i] != -1) {
//cerr << "ERROR: Unequal counts for " << SampleID[i] << ": " << mf->collectStatistics.BarcodeDetected[i] << " vs " << counts_per_sample[j] << endl;
uneqCnts++;
} else if (!detected) {
// j is past-the-end here; print the missing SampleID instead of indexing barcode_number_to_sample_id_
cerr << "Could not detect sample_id_ " << SampleID[i] << " in ref set (check that mapping file is correctly formatted?).\n"; exit(87);
}
}
#ifdef DEBUG
cerr << "Derep Fin" << endl;
#endif
if (b_pairedInput) {
of2p2.close();
}
of2.close();
if (can_merge_derep) {
of_merged.close();
}
if (uneqCnts>0) {
cerr << "Unequal counts in " << uneqCnts << " cases. \n";
//exit(66);
}
return report;
}
bool Dereplicate::pass_deprep_conditions(shared_ptr<DNAunique> d) {
vector<int> x = d->getDerepMapSort(minCopiesSiz);
int cumSum(0);
for (size_t i = 0; i < x.size(); i++) {
cumSum += x[i];
//if (minCopies[i] == -1) { continue; }
size_t yy(minCopiesSiz);
if (yy > i) { yy = i+1; }//if checking for 1 smpl copy, don't need to check for 2 samlpe allowed copy number..
for (size_t j = 0; j < yy; j++) {
if (minCopies[j] == -1) { continue; }
//if (i > minCopiesSiz) { break; }
if (cumSum >= minCopies[j]) { return true; }
}
}
return false;
}
void writeLog(string& logf) {
ofstream of;
of.open(logf.c_str());
of.close();
}
string additionalFileName(const string& in){
if (in.find(",") == std::string::npos){
return additionalFileName2(in);
}
else {
vector<string> vi = splitByCommas(in);
string out = additionalFileName2(vi[0]);
for (uint i = 1; i < vi.size(); i++){
out += "," + additionalFileName2(vi[i]);
}
return out;
}
}
string additionalFileName2(const string& in){
size_t point = in.find_last_of('.');
if (point == (size_t)-1){ return in + ".add"; }
return in.substr(0, point) + ".add." + in.substr(point + 1);
}
string subfile(string x, string y) {
if (y == "") { return x; }
size_t pos = x.find_last_of(".");
string s = "";
if (pos != string::npos) {
s= x.substr(0, pos) + "." + y + x.substr(pos);
}
else {
s = x + "." + y;
}
return s;
}
//////////// UCLINKS ///////////////
UClinks::~UClinks(){
ucf.close();
mapdere.close();
if (merger != nullptr) {
delete merger;
merger = nullptr;
}
}
UClinks::UClinks( OptContainer* cmdArgs):
CurSetPair(-1),//maxOldDNAvec(20000),
derepMapFile(""),
bestDNA(0, NULL), oriKey(0),
mapLines(0),
clusCnt(0), uclines(0),
SEP(""),
UCread(false), pairsMerge(false), MAPread(false),
b_derepAvailable(false),
UPARSE8up(false), UPARSE9up(false), UPARSE11up(false),
UpUcFnd(false), cdhit(false), vsearch(false),
ucispaf(false),
otuTerm("OTU"), otuOUTterm("OTU_"),
RefDBmode(false), RefDBotuStart(-1),
SeedsAreWritten(false),
OTUmat(0), unregistered_samples(false),
doChimeraCnt(false), OTUnumFixed(true),
totalDerepCnt(0),
qCovThr(0.8f), perIDmatch(97.f),
b_merge_pairs_optiSeed_(false),merger(nullptr)
{
//read in UC file and assign clusters
SEP = (*cmdArgs)["-sample_sep"];
string str = (*cmdArgs)["-optimalRead2Cluster"];
if (str.find(".paf") != string::npos) {
ucispaf = true; UpUcFnd = true;
}
ucf.open(str.c_str(),ios::in);
if (!ucf){
UCread = true;
cerr<<"Could not open uc file\n"<< str<<endl; exit(46);
}
if (cmdArgs->find("-derep_map") != cmdArgs->end()) {
derepMapFile = (*cmdArgs)["-derep_map"];
}
if (cmdArgs->find("-minQueryCov") != cmdArgs->end()) {
qCovThr = (float) atof((*cmdArgs)["-minQueryCov"].c_str());
}
if (cmdArgs->find("-id") != cmdArgs->end()) {
perIDmatch =(float) atof((*cmdArgs)["-id"].c_str());
}
if (cmdArgs->find("-count_chimeras") != cmdArgs->end() &&
(*cmdArgs)["-count_chimeras"] == "T") {
doChimeraCnt = true;
}
if (cmdArgs->find("-merge_pairs_seed") != cmdArgs->end() &&
(*cmdArgs)["-merge_pairs_seed"] == "1") {
b_merge_pairs_optiSeed_ = true;
}
//set version of mapping/clustering
if ((*cmdArgs)["-uparseVer"] != "") {
if ((*cmdArgs)["-uparseVer"] == "N11") {//UNOISE v11
UPARSE8up = true;
otuTerm = "Zot";
otuOUTterm = "Zotu";
}
else if ((*cmdArgs)["-uparseVer"] == "cdhit") {
cdhit = true; UpUcFnd = true; UPARSE8up = true;
} else if ((*cmdArgs)["-uparseVer"] == "vsearch") {
UpUcFnd = true; vsearch = true;
} else {
int upVer = atoi((*cmdArgs)["-uparseVer"].c_str());
if (upVer >= 8 && upVer < 9) {
UPARSE8up = true; UpUcFnd = true;
}
else if (upVer >= 9 && upVer < 11) {
UPARSE8up = true; UPARSE9up = true; UpUcFnd = true;
}
else if (upVer == 9966) {//cdhit code
cdhit = true; UpUcFnd = true;
}
else if (upVer >= 11) {
UPARSE8up = true; UPARSE9up = true; UPARSE11up = true; UpUcFnd = true;
otuTerm = "otu";
}
}
}
}
void UClinks::readDerepInfo(const string dereM) {
mapdere.open(dereM.c_str(), ios::in);
if (!mapdere) {
cerr << "Can't open " << dereM << ". \nAborting\n"; exit(54);
}
int cnt(0);
totalDerepCnt = 0;
b_derepAvailable = true;
string line("");
//only read header
while (!safeGetline(mapdere, line).eof()) {
// while(getline(in,line,'\n')) {
if (line.length() < 3) { continue; }
string segments;
stringstream ss;
ss << line;
int tbcnt = -1;
//(*cmdArgs)["-i_MID_fastq"]
while (getline(ss, segments, '\t')) {
tbcnt++;
if (cnt == 0) { //search for header
if (tbcnt == 0) {
if (segments != "#SMPLS") { cerr << "First line in dereplicate map has to start with #SMPLS, corrupted file.\n" << dereM << endl; exit(98); }
continue;
}
vector<string> spl = header_string_split(segments, ":");
int ccnt = stoi(spl[0]);
SmplIDs[spl[1]] = ccnt;
} else {//actual derep info per sorted line
cerr << "wrong mapping reading\n"; exit(64);
}
}
if (cnt == 0) {
OTUmat.resize(SmplIDs.size(), vector<matrixUnit>(clusCnt + 1, 0));
}
break;
}
cout << "Found " << SmplIDs.size() << " samples in derep.map\n";
}
//read in dereplicated info from derep.map and derep.hq.fq (in IS) -> they are in the same order
int UClinks::oneDerepLine(shared_ptr<DNAunique> d) {
if (MAPread){
return 0;
}
string line("");
int cnt(0);
while (!safeGetline(mapdere, line).eof()) {
//if (line.length() < 3) { continue; }
if (line[0] == '#') {continue;}
string segments;
//stringstream ss;
//string head("");
//ss << line;
int tbcnt = -1;
long curCnt(0),curCnt2(0);
size_t strpos(line.find_first_of('\t')), lastpos(0);
while (strpos != string::npos){
//while (getline(ss, segments, '\t')) {
segments = line.substr(lastpos, strpos - lastpos);
lastpos = strpos+1;
strpos = line.find_first_of('\t', lastpos);
tbcnt++;
if (tbcnt == 0) {
if (!d->sameHead(segments)) {
cerr << segments << " is not " << d->getId() << endl;
//this is actually a fatal error and currently not covered
//derep.map and fq [which one??] need to have reads in the same order..
exit(738);
}
size_t idx = segments.find(";size=");
if (idx != string::npos) {
curCnt = atoi(segments.substr(idx + 6, segments.find(";", idx + 5) - (idx + 6)).c_str());
//curCnt
}
continue;
}
size_t spl = segments.find(":"); int occur = stoi(segments.substr(spl+1));