Repository navigation
Expand file tree
/
Copy pathcontainers.cpp
More file actions
3824 lines (3580 loc) · 153 KB
/
Copy pathcontainers.cpp
File metadata and controls
3824 lines (3580 loc) · 153 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 <cassert>
#include <cmath>
#include <deque>
#include <future>
#include <limits>
#include <filesystem>
#include <sstream>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include "OutputFileStream.h"
#include <mutex>
#include "Common.h"
#include "containers.h"
#include "PartitionWorkPool.h"
#include "ThreadPool.h"
#include "CoarseDereplication.h"
#include "Filters.h"
#include "OutputStreamer.h"
using namespace std;
namespace {
OptContainer* g_opt_container = nullptr;
// Runs task(0 .. count-1) on the pool and waits for all of them; the first
// failure is rethrown once every submitted task has finished. Never call this
// from one of the pool's own workers.
template <class Task>
void runOnPool(ThreadPool& pool, size_t count, const Task& task) {
std::vector<std::future<void>> done;
done.reserve(count);
std::exception_ptr failure;
try {
for (size_t i = 0; i < count; ++i) { done.push_back(pool.submit([&task, i]() { task(i); })); }
} catch (...) { failure = std::current_exception(); }
for (auto& future : done) {
try { future.get(); } catch (...) { if (!failure) { failure = std::current_exception(); } }
}
if (failure) { std::rethrow_exception(failure); }
}
// Sorts `items` in place by `less`. With a pool and enough items, every
// segment is split at its median (std::nth_element), all segments of a level
// in parallel, until there is one segment per worker; the segments are then
// sorted in parallel. Needs no memory per item. `less` must be a strict total
// order (no equivalent items), so the result is exactly std::sort's.
template <class T, class Less>
void sortOnPool(std::vector<T>& items, const Less& less, ThreadPool* pool) {
constexpr size_t kSegment = 16384;
if (!pool || items.size() < 2 * kSegment) { std::sort(items.begin(), items.end(), less); return; }
std::vector<size_t> bounds{0, items.size()};
while (bounds.size() - 1 < pool->size() && items.size() / (bounds.size() - 1) >= 2 * kSegment) {
const size_t segments = bounds.size() - 1;
std::vector<size_t> next(2 * segments + 1);
for (size_t s = 0; s < segments; ++s) {
next[2 * s] = bounds[s];
next[2 * s + 1] = bounds[s] + (bounds[s + 1] - bounds[s]) / 2;
}
next[2 * segments] = items.size();
runOnPool(*pool, segments, [&](size_t s) {
std::nth_element(items.begin() + next[2 * s], items.begin() + next[2 * s + 1], items.begin() + next[2 * s + 2], less);
});
bounds.swap(next);
}
runOnPool(*pool, bounds.size() - 1, [&](size_t s) { std::sort(items.begin() + bounds[s], items.begin() + bounds[s + 1], less); });
}
// Formatted output of one dereplication output chunk, kept in fixed-size
// segments taken from a shared pool. Growing and freeing a string per
// chunk on many threads leaves large freed buffers in each worker's malloc
// arena; recycled segments keep the memory at what is actually in flight.
class SegmentPool {
public:
static constexpr size_t kSegmentSize = size_t(1) << 20;
using Segment = std::unique_ptr<char[]>;
Segment take() {
std::lock_guard<std::mutex> lock(mutex_);
if (free_.empty()) { return Segment(new char[kSegmentSize]); }
Segment segment = std::move(free_.back());
free_.pop_back();
return segment;
}
void give(Segment segment) {
std::lock_guard<std::mutex> lock(mutex_);
free_.push_back(std::move(segment));
}
private:
std::mutex mutex_;
std::vector<Segment> free_;
};
class SegmentBuffer final : public std::streambuf {
public:
explicit SegmentBuffer(SegmentPool& pool) : pool_(pool) {}
SegmentBuffer(const SegmentBuffer&) = delete;
SegmentBuffer& operator=(const SegmentBuffer&) = delete;
~SegmentBuffer() override { release(); }
// Writes the buffered bytes and returns the segments to the pool.
void writeTo(std::ostream& out) {
for (size_t i = 0; i < segments_.size(); ++i) {
const size_t used = i + 1 == segments_.size() ? static_cast<size_t>(pptr() - pbase()) : SegmentPool::kSegmentSize;
out.write(segments_[i].get(), static_cast<std::streamsize>(used));
}
release();
}
protected:
int_type overflow(int_type ch) override {
if (traits_type::eq_int_type(ch, traits_type::eof())) { return traits_type::not_eof(ch); }
grow();
*pptr() = traits_type::to_char_type(ch);
pbump(1);
return ch;
}
std::streamsize xsputn(const char* data, std::streamsize count) override {
std::streamsize written = 0;
while (written < count) {
if (pptr() == epptr()) { grow(); }
const std::streamsize amount = std::min<std::streamsize>(epptr() - pptr(), count - written);
std::memcpy(pptr(), data + written, static_cast<size_t>(amount));
pbump(static_cast<int>(amount));
written += amount;
}
return written;
}
private:
void grow() {
segments_.push_back(pool_.take());
char* begin = segments_.back().get();
setp(begin, begin + SegmentPool::kSegmentSize);
}
void release() {
for (auto& segment : segments_) { pool_.give(std::move(segment)); }
segments_.clear();
setp(nullptr, nullptr);
}
SegmentPool& pool_;
std::vector<SegmentPool::Segment> segments_;
};
struct SegmentStream {
explicit SegmentStream(SegmentPool& pool) : buffer(pool), stream(&buffer) {}
SegmentBuffer buffer;
std::ostream stream;
};
}
void setGlobalOptContainer(OptContainer* options) {
g_opt_container = options;
}
OptContainer* getGlobalOptContainer() {
return g_opt_container;
}
OptContainer& globalOptContainer() {
if (g_opt_container == nullptr) {
throw std::runtime_error("Global option container is not initialized.");
}
return *g_opt_container;
}
// 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()) {
// Same rows as the parser below reads: it skips comments and lines under 5 characters.
if (line.substr(0, 1) == "#" || line.length() < 5){ 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 + 1 << " is " << ColsPerRow << ". Expected " << ini_ColPerRow << " columns.\n";
exit(91);
}
// Every row is checked: a short row after the first 1000 misaligned
// the header and output-file columns (out-of-bounds outFilesIdx).
}
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 (line.substr(0, 1) == "#"){ continue; } // comment/header, as in the format check above
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");
}
else if (b_doHD && newHD[idx] != "") {
match[0]->setHeader(newHD[idx]); // single-end subsets were never renamed
}
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::ThreadLocalBatch& Dereplicate::get_or_create_thread_batch() {
// The registry owns pending work even after a producer exits. The weak
// cache detects destruction/address reuse without a reference-count RMW per read.
thread_local std::weak_ptr<ThreadLocalBatch> cache;
thread_local ThreadLocalBatch* cachedBatch = nullptr;
if (cache.expired() || cachedBatch->owner != this) {
auto batch = std::make_shared<ThreadLocalBatch>();
batch->owner = this;
batch->pending.reserve(kThreadBatchFlushThreshold);
std::lock_guard<std::mutex> guard(batch_registry_mtx_);
batch_registry_.push_back(batch);
cache = batch;
cachedBatch = batch.get();
}
return *cachedBatch;
}
size_t Dereplicate::tracker_size_total() const {
size_t size = 0;
for (const auto& shard : shards_) { size += shard->coarse ? (shard->coarse->outputsExact() ? shard->coarse->exactGroups().size() : shard->coarse->groups().size()) : shard->tracker.size(); }
return size;
}
bool Dereplicate::apply_pending_entry_locked(const PendingDerepEntry& pending, HashDNA& tracker, bool deferring) {
auto it = tracker.find(pending.srchSeq);
if (it == tracker.end() && !pending.pass && !deferring) { return false; }
bool fresh = it == tracker.end();
if (fresh) { it = tracker.try_emplace(pending.srchSeq, std::make_unique<DNAuniqSet>()).first; }
auto& group = it->second;
if (coarse_ && deferring && !pending.pass &&
(!coarse_->outputsExact() || coarse_->storesQualities() || coarse_->storesDiffs())) {
// Reuse the ordinary deferred-prefix table, retaining the observations
// needed for variant export as well as their counts. These reads never
// supply the output representative; outputGroups attaches their evidence
// only if a passing exact/prefix anchor exists.
auto representative = group->find(pending.mergePos);
if (representative == group->end()) {
group->addNewDNAuniq(pending.dna, coarse_->storesQualities() ? pending.dna2 : nullptr,
b_merge_pairs_derep_ ? pending.dna_merged : nullptr, pending.mergePos, -1, true, false);
if (coarse_->storesQualities() || coarse_->storesDiffs()) {
const auto& source = mergedSearchKeys_ && pending.dna_merged ? pending.dna_merged : pending.dna;
auto reference = std::make_shared<const string>(coarse_->storesQualities() ? std::string_view(source->getSequence()) : source->getSeqPseudoView());
auto mateReference = coarse_->storesQualities() && pending.dna2 ?
std::make_shared<const string>(pending.dna2->getSequence()) : nullptr;
(*group)[pending.mergePos]->attachDiffDNA(std::make_shared<diffDNA>(reference, false,
coarse_->storesQualities(), mateReference));
}
}
auto& dna = (*group)[pending.mergePos];
if (coarse_->storesQualities() && pending.dna2) { dna->recordDiffPairQuality(*pending.dna, *pending.dna2, pending.sample_id); }
else if (coarse_->storesQualities()) { dna->recordDiffQuality(*pending.dna, pending.sample_id); }
else {
const auto& source = mergedSearchKeys_ && pending.dna_merged ? pending.dna_merged : pending.dna;
dna->recordDiffDNA(source->getSeqPseudoView(), pending.sample_id);
}
return true;
}
// Deferred failures are buffered separately. They become evidence only
// if a passing anchor exists at output time; buffering is not acceptance.
const bool evidenceOnly = deferring && !pending.pass;
// Deferred failures can never supply an output representative. Keep only
// R1 evidence and, when requested for output, merged quality evidence.
// Their mates and unused merged products need not be retained in memory.
group->addObservation(pending.dna, evidenceOnly ? nullptr : pending.dna2,
evidenceOnly && !b_merge_pairs_derep_ ? nullptr : pending.dna_merged,
pending.mergePos, pending.sample_id, b_derep_as_fasta_, b_merge_pairs_derep_, !evidenceOnly);
return true;
}
void Dereplicate::apply_pending_entry(const PendingDerepEntry& pending, Shard& shard,
const CoarseDereplication::Probe* probe, std::vector<CoarseDereplication::Update>* deferred) {
// Called with a shard lock or exclusive work-pool ownership. Statistics are
// finalized here, not while filtering still has this observation queued.
auto& stats = shard.admission;
stats.mergedKeys += mergedSearchKeys_ && bool(pending.dna_merged);
// A non-passing read whose key already has a passing dereplicate is counted
// right away. Otherwise a set with withheld mid-quality output is written
// instead of counted (a pipeline back-maps it; never both), while a set
// without such output is deferred: attached at output to the passing group
// of its key (prefix mode: every non-passing read), or dropped, never
// reaching .rest or the map on its own.
if (!pending.pass && defersNonPassing()) {
const bool known = exact_key_known(pending, shard);
if (pending.withheld) {
if (!known) { publish_uncounted(pending); ++stats.published; return; }
} else if (prefixMode_) {
if (deferCountsOnly_) { shard.rejectedTallies[pending.srchSeq].add(pending.sample_id); }
else { apply_pending_entry_locked(pending, shard.rejected, true); }
++stats.deferred;
return;
} else if (!known) {
bool kept;
if (retainsVariants()) {
// The reads themselves (already allocated), within a byte budget.
auto bytes = [](const shared_ptr<DNA>& d) -> uint64_t {
return d ? sizeof(DNA) + 2 * uint64_t(d->mem_length()) + 2 * d->getId().size() : 0;
};
const uint64_t size = bytes(pending.dna) + bytes(pending.dna2) + bytes(pending.dna_merged);
kept = deferredEvidenceBytes_.fetch_add(size, std::memory_order_relaxed) + size <= kDeferredEvidenceBytes;
if (kept) {
shard.deferredEvidence[deferredKeyHash(pending.srchSeq)].push_back(
DeferredEvidence{pending.dna, pending.dna2, pending.dna_merged, pending.sample_id});
}
else { deferredEvidenceBytes_.fetch_sub(size, std::memory_order_relaxed); }
}
else {
// Sample counts only, under a key hash, in a capped table.
kept = shard.deferredCounts.add(deferredKeyHash(pending.srchSeq), pending.sample_id, deferredKeyCapPerShard_);
}
if (kept) { ++stats.deferred; }
else { ++stats.unmatched; ++stats.deferredDropped; } // as 3.60: not counted
return;
}
}
bool admitted;
if (shard.coarse && (!pending.srchSeq.empty() || !shard.coarse->storageOnly())) {
const auto& source = mergedSearchKeys_ && pending.dna_merged ? pending.dna_merged : pending.dna;
admitted = shard.coarse->add(pending.srchSeq, source->getSeqPseudoView(), pending.dna, pending.dna2,
pending.dna_merged, pending.sample_id, pending.pass, searchLength,
b_derep_as_fasta_, b_merge_pairs_derep_, pending.mergePos, probe, deferred) != CoarseDereplication::npos;
} else {
admitted = apply_pending_entry_locked(pending, shard.tracker, false);
}
if (!admitted) {
if (pending.withheld) { publish_uncounted(pending); ++stats.published; }
else { ++stats.unmatched; }
}
else if (pending.pass) { ++stats.high; }
else if (pending.dna->isYellowQual()) { ++stats.mid; }
else { ++stats.failed; }
}
void Dereplicate::publish_uncounted(const PendingDerepEntry& pending) {
if (!publisher_) { throw std::logic_error("Dereplicate: a withheld record set has no publisher"); }
publisher_(pending.dna, pending.dna2, pending.route, pending.outputBlock, pending.indexInBlock);
}
void Dereplicate::flushPending() {
LifecyclePause pause(*this);
flush_all_batches();
}
bool Dereplicate::DeferredCounts::add(uint64_t key, int sample, size_t cap) {
if (sample < 0) { return true; } // no sample: nothing to count (diffDNA ignores it as well)
auto bump = [sample](std::vector<std::pair<int, uint64_t>>& counts) {
for (auto& entry : counts) { if (entry.first == sample) { ++entry.second; return; } }
counts.emplace_back(sample, 1);
};
if (auto several = multi.find(key); several != multi.end()) { bump(several->second); return true; }
auto one = single.find(key);
if (one == single.end()) {
if (size() >= cap) { return false; }
single.emplace(key, Single{sample, 1});
return true;
}
if (one->second.sample == sample && one->second.copies < std::numeric_limits<uint32_t>::max()) {
++one->second.copies;
return true;
}
std::vector<std::pair<int, uint64_t>> counts{{one->second.sample, one->second.copies}};
single.erase(one);
bump(counts);
multi.emplace(key, std::move(counts));
return true;
}
bool Dereplicate::exact_key_known(const PendingDerepEntry& pending, const Shard& shard) const {
if (shard.coarse && (!pending.srchSeq.empty() || !shard.coarse->storageOnly())) {
return shard.coarse->hasExactKey(pending.srchSeq);
}
return shard.tracker.find(pending.srchSeq) != shard.tracker.end();
}
void Dereplicate::flush_batch(ThreadLocalBatch& batch) {
if (batch.pending.empty()) { return; }
uint64_t searchBases = 0;
for (const auto& entry : batch.pending) { searchBases += entry.srchSeq.size(); }
srch_seq_total_len_.fetch_add(searchBases, std::memory_order_relaxed);
srch_seq_count_.fetch_add(batch.pending.size(), std::memory_order_relaxed);
struct ClearBatch { ThreadLocalBatch& batch; ~ClearBatch() { batch.pending.clear(); } } clear{batch};
if (parallelGlobalCoarse_) {
flush_global_coarse(batch);
return;
}
thread_local std::vector<std::vector<size_t>> grouped;
grouped.resize(shards_.size());
for (auto& indices : grouped) { indices.clear(); }
for (size_t i = 0; i < batch.pending.size(); ++i) { grouped[batch.pending[i].shard].push_back(i); }
if (coarseWorkPool_) {
std::vector<PartitionWorkPool::Work> work;
work.reserve(shards_.size());
for (size_t i = 0; i < grouped.size(); ++i) {
if (!grouped[i].empty()) { work.push_back({i, grouped[i].size()}); }
}
// Capture the submitting thread's grouping explicitly. A helper must
// not resolve the thread_local variable to its own current batch.
auto* indices = &grouped;
coarseWorkPool_->run(work, [this, &batch, &work, indices](size_t task) {
auto& shard = *shards_[work[task].partition];
// Pool ownership serializes this index, without a shard mutex wait.
for (size_t index : (*indices)[work[task].partition]) {
apply_pending_entry(batch.pending[index], shard);
}
});
return;
}
// Shards are independent: apply to every shard that is free right away and
// only then wait for the busy ones, instead of queueing behind other
// workers in a fixed shard order.
thread_local std::vector<size_t> busy;
busy.clear();
for (size_t i = 0; i < shards_.size(); ++i) {
if (grouped[i].empty()) { continue; }
auto& shard = *shards_[i];
std::unique_lock<std::mutex> guard(shard.mutex, std::try_to_lock);
if (!guard.owns_lock()) { busy.push_back(i); continue; }
for (size_t index : grouped[i]) {
apply_pending_entry(batch.pending[index], shard);
}
}
for (size_t i : busy) {
auto& shard = *shards_[i];
std::lock_guard<std::mutex> guard(shard.mutex);
for (size_t index : grouped[i]) {
apply_pending_entry(batch.pending[index], shard);
}
}
}
void Dereplicate::flush_global_coarse(ThreadLocalBatch& batch) {
auto& shard = *shards_.front();
auto& coarse = *shard.coarse;
thread_local CoarseDereplication::SearchScratch scratch;
thread_local std::vector<CoarseDereplication::Probe> probes;
thread_local std::vector<CoarseDereplication::Update> updates;
probes.assign(batch.pending.size(), CoarseDereplication::Probe{});
updates.clear();
struct ClearUpdates { ~ClearUpdates() { updates.clear(); } } clearUpdates;
{
// Phase 1: candidate searches (most of the work) against a snapshot.
std::shared_lock<std::shared_mutex> snapshot(shard.snapshot);
for (size_t i = 0; i < batch.pending.size(); ++i) {
const auto& pending = batch.pending[i];
if (prefixMode_ && !pending.pass) { continue; } // deferred prefix evidence, no search
probes[i] = coarse.probe(pending.srchSeq, pending.dna, pending.dna2, pending.pass, searchLength, scratch);
}
}
{
// Phase 2: commit in batch order. Exact keys are re-checked and only
// anchors created after each snapshot are searched again, so the
// result equals committing this batch serially at this point.
std::lock_guard<std::mutex> guard(shard.mutex);
std::unique_lock<std::shared_mutex> exclusive(shard.snapshot);
for (size_t i = 0; i < batch.pending.size(); ++i) {
apply_pending_entry(batch.pending[i], shard, &probes[i], &updates);
}
}
// Phase 3: representative, count and variant updates touch only their own
// target; updates of one target stay in batch order under its stripe.
for (const auto& update : updates) {
const size_t stripe = (reinterpret_cast<uintptr_t>(update.target) >> 6) % coarseUpdateStripes_.size();
std::lock_guard<std::mutex> guard(coarseUpdateStripes_[stripe]);
coarse.apply(update);
}
}
void Dereplicate::flush_all_batches() {
drain_sealed_blocks();
std::vector<std::shared_ptr<ThreadLocalBatch>> batches;
{ std::lock_guard<std::mutex> guard(batch_registry_mtx_); batches = batch_registry_; }
for (auto& batch : batches) {
flush_batch(*batch);
free_returned_reads(*batch);
}
}
Dereplicate::Dereplicate(OptContainer* cmdArgs, Filters* mf):
barcode_number_to_sample_id_(0), b_usearch_fmt(true), b_singleLine(true), b_pairedInput(false),
minCopyRules(1, DerepCopyRule{0, 0}), minCopiesStr("0"), //default accepts every derep
minCopiesFastFailThreshold(-1),
tmpCnt(0), curBCoffset(0), b_derep_as_fasta_(true), b_derepPerSR(false),
b_wroteMapHD(false), b_merge_pairs_derep_(false),merger(nullptr),
searchLength(150),
mapF(""), outHQf(""), outHQf_p2(""), outRest(""),
mainFilter(mf), searchWithMerg(true)
{
const uint64_t identity = CoarseDereplication::parseIdentity(cmdArgs->get("-derepIdentity", "100"));
const unsigned homopolymer = CoarseDereplication::parseHomopolymer(cmdArgs->get("-derepSeedHomopolymer", "4"));
const string diffOption = cmdArgs->get("-derepStoreDiffs", "0");
if (diffOption != "0" && diffOption != "1") { throw std::invalid_argument("-derepStoreDiffs must be 0 or 1"); }
const string subclusterOption = cmdArgs->get("-derepSubclusterFasta", "0");
if (subclusterOption != "0" && subclusterOption != "1") {
throw std::invalid_argument("-derepSubclusterFasta must be 0 or 1");
}
writeSubclusters_ = subclusterOption == "1";
if (writeSubclusters_ && diffOption != "1") {
throw std::invalid_argument("-derepSubclusterFasta 1 requires -derepStoreDiffs 1");
}
const string reassignOption = cmdArgs->get("-derepReassign", "0");
if (reassignOption != "0" && reassignOption != "1") { throw std::invalid_argument("-derepReassign must be 0 or 1"); }
const string clusterOption = cmdArgs->get("-derepCoarseClusters", "0");
if (clusterOption != "0" && clusterOption != "1") { throw std::invalid_argument("-derepCoarseClusters must be 0 or 1"); }
// Explicit final reassignment also requests coarse cluster output.
const bool exactOutput = clusterOption != "1" && reassignOption != "1";
const string qualityOption = cmdArgs->get("-derepStoreQuals", "0");
if (qualityOption != "0" && qualityOption != "1") { throw std::invalid_argument("-derepStoreQuals must be 0 or 1"); }
if (qualityOption == "1") {
if (!cmdArgs->get("-i_fna").empty() && cmdArgs->get("-i_qual").empty()) {
throw std::invalid_argument("-derepStoreQuals requires complete input qualities; FASTA alone is insufficient");
}
const auto fastaFiles = mf->getFastaFiles(), qualityFiles = mf->getQualFiles();
for (size_t i = 0; i < fastaFiles.size(); ++i) {
if (!fastaFiles[i].empty() && (i >= qualityFiles.size() || qualityFiles[i].empty())) {
throw std::invalid_argument("-derepStoreQuals requires a quality file for every FASTA input");
}
}
}
if (qualityOption == "1") {
b_pairedInput = mf->isPaired() > 1;
// Exact pair variants keep the two processed mates and their own scores.
searchWithMerg = false;
for (const auto* option : {"-merge_pairs_derep", "-merge_pairs_filter", "-merge_pairs_demulti"}) {
if (cmdArgs->get(option) == "1") { throw std::invalid_argument(std::string("-derepStoreQuals requires unmerged input; disable ") + option); }
}
}
const string globalOption = cmdArgs->get("-derepGlobal", "0");
if (globalOption != "0" && globalOption != "1") { throw std::invalid_argument("-derepGlobal must be 0 or 1"); }
const bool coarseMode = identity < CoarseDereplication::identityScale || diffOption == "1" || reassignOption == "1" || qualityOption == "1";
const string prefixOption = cmdArgs->contains("-derepPrefix") ? (*cmdArgs)["-derepPrefix"] : "auto";
if (prefixOption != "auto" && prefixOption != "0" && prefixOption != "1") {
throw std::invalid_argument("-derepPrefix must be auto, 0, or 1");
}
const OptContainer::RuntimeOptions& runtimeOpts = cmdArgs->runtime();
outfile = (*cmdArgs)["-o_dereplicate"];
if (runtimeOpts.noSearchWithMerge) {
searchWithMerg = false;
}
string baseOF = std::filesystem::path(outfile).replace_extension().string();
if (coarseMode && diffOption == "1" && outfile == baseOF + ".diff") {
throw std::invalid_argument("The dereplicate output cannot be its own .diff sidecar; choose a FASTA/FASTQ output filename");
}
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 500k slots.
size_t reserveSize = coarseMode ? 0 : runtimeOpts.derepReserve;
// Independent sequence keys can update concurrently. Keep each key in one
// shard so occurrence counts, quality evidence, and selection stay atomic.
// Approximate groups may stay independent. Exact-prefix and explicitly global
// clustering/reassignment retain one index so cross-key matching stays global.
// Explicit coarse-cluster output also needs the global index: approximate
// matches in different partitions would never be grouped, and the
// partitioned mode exists to save memory for exact-parent output.
const bool globalCoarse = runtimeOpts.threads <= 1 || globalOption == "1" ||
reassignOption == "1" || clusterOption == "1" || identity == CoarseDereplication::identityScale;
const size_t shardCount = coarseMode && globalCoarse ? 1 : 64;
shards_.reserve(shardCount);
for (size_t i = 0; i < shardCount; ++i) {
auto shard = std::make_unique<Shard>();
shard->tracker.reserve(reserveSize / shardCount + (reserveSize % shardCount != 0));
if (coarseMode) {
shard->coarse = std::make_unique<CoarseDereplication>(identity, homopolymer, diffOption == "1", reassignOption == "1", qualityOption == "1", exactOutput);
}
shards_.push_back(std::move(shard));
}
if (coarseMode) { coarse_ = shards_.front()->coarse.get(); }
if (coarseMode && shardCount > 1) { coarseWorkPool_ = std::make_unique<PartitionWorkPool>(shardCount); }
parallelGlobalCoarse_ = coarseMode && shardCount == 1 && runtimeOpts.threads > 1;
// Also on one thread: entries are then applied, and withheld sets published, at the end of each
// read block as with several, so the outputs do not depend on the number of threads.
orderedAdmission_ = true;
if (orderedAdmission_ && !coarseWorkPool_ && !parallelGlobalCoarse_) { orderedPool_ = std::make_unique<PartitionWorkPool>(shardCount); }
// Enough queued blocks to keep the committer busy while every other worker
// processes its next block; queued blocks keep their reads in memory.
commitBacklog_ = std::max<size_t>(4, 2 * size_t(runtimeOpts.threads));
// A few blocks' worth: enough for every lane to have work, small enough
// that the committer's final drain stays short.
updateBacklog_ = 256 * size_t(runtimeOpts.threads);
if (runtimeOpts.hasDereSizeFmt && runtimeOpts.disableUsearchSizeFmt) {
b_usearch_fmt = false;
}
if (runtimeOpts.derepPerSR) {
b_derepPerSR = true;
}
if (runtimeOpts.hasMinDerepCopies && runtimeOpts.minDerepCopies == "auto") {
// the rule comes from the run itself once every read is dereplicated (setAutoCopyRules in writeDereplDNA)
autoCopyRules_ = true;
minCopiesStr = "auto";
} else if (runtimeOpts.hasMinDerepCopies) {
minCopiesStr = runtimeOpts.minDerepCopies;
string x = runtimeOpts.minDerepCopies;
std::replace(x.begin(), x.end(), ';', ','); // "8:1;3:4" is accepted like "8:1,3:4"
minCopyRules.clear();
vector<string> xs = splitByCommas(x, ',');
for (size_t i = 0; i < xs.size(); i++) {
if (xs[i].empty()) { continue; }
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);
}
// A bare number counts copies across all samples; "X:Y" needs X copies in total, found in at least Y samples.
DerepCopyRule rule{ atoll(tmp[0].c_str()), 0 };
if (tmp.size() == 2) {
rule.samples = atoi(tmp[1].c_str());//number of samples
if (rule.samples <= 0) { cerr << "wrong derplicate position (<=0):" << xs[i] << endl; exit(312); }
if (rule.samples > 3000) { cerr << "too large derplicate position (>3000):" << xs[i] << endl; exit(313); }
}
minCopyRules.push_back(rule);
}
if (minCopyRules.empty()) { minCopyRules.push_back(DerepCopyRule{ 0, 0 }); }
}
setCopyRules(minCopyRules);
// set up output format of dereplication:
if (runtimeOpts.hasDerepFormat) {
auto res = runtimeOpts.derepFormat;
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 (runtimeOpts.hasMergePairsDerep && runtimeOpts.mergePairsDerep) {
b_merge_pairs_derep_ = true;
}
// A consensus key that differs from its representative's R1 (an R2 base won
// in the overlap, or the key extends into R2) would write that R1 again under
// a second key. Merged keys are therefore used only with merged output.
mergedSearchKeys_ = searchWithMerg && b_merge_pairs_derep_;
if (runtimeOpts.hasDerepSrchLen) {
const string& searchLenArg = (*cmdArgs)["-derepSrchLen"];
size_t parsedChars = 0;
long long parsedLen = 0;
try {
parsedLen = std::stoll(searchLenArg, &parsedChars);
}
catch (...) {
cerr << "Invalid search length specified for -derepSrchLen. Search length must be -1 or a positive integer. Exiting.\n";
exit(78);
}
if (parsedChars != searchLenArg.size() || parsedLen == 0 || parsedLen < -1 || parsedLen > std::numeric_limits<int>::max()) {
cerr << "Invalid search length specified for -derepSrchLen. Search length must be -1 or a positive integer. Exiting.\n";
exit(78);
}
searchLength = static_cast<int>(parsedLen);
}
const int fixedLength = mf->fixedDereplicationLength(mergedSearchKeys_);
const int clusteringCap = mf->dereplicationLengthLimit();
const bool explicitCap = mf->hasExplicitDerepSearchLength() && searchLength > 0;
prefixMode_ = (!coarse_ || coarse_->outputsExact()) && (prefixOption == "1" || (prefixOption == "auto" && !explicitCap && fixedLength == 0));
if (prefixMode_) {
searchLength = clusteringCap;
} else if (coarse_) {
if (!explicitCap) { searchLength = -1; }
if (clusteringCap > 0 && (searchLength < 0 || searchLength > clusteringCap)) { searchLength = clusteringCap; }
} else if (prefixOption == "auto") {
if (!explicitCap && fixedLength > 0) { searchLength = fixedLength; }
if (clusteringCap > 0 && (searchLength < 0 || searchLength > clusteringCap)) {
searchLength = clusteringCap;
}
}
cerr << "Dereplication matching: " << (coarse_ ? cmdArgs->get("-derepIdentity", "100") + "% streaming substitution clusters" : (prefixMode_ ? "100% prefix" : "exact length"))
<< (searchLength > 0 ? " (search cap " + to_string(searchLength) + ")" : " (full logical sequence)") << "\n";
if (coarse_) {
cerr << "Coarse dereplication: " << shards_.size() << (shards_.size() > 1 ?
" independent partitions; no final consolidation\n" : " global index\n");
if (coarseWorkPool_) { cerr << "Coarse scheduling: shared partition work pool (existing workers)\n"; }
if (parallelGlobalCoarse_) { cerr << "Coarse scheduling: concurrent snapshot searches, ordered commits\n"; }
}
// Prefix mode: FASTA output collects no quality evidence from deferred
// reads, so only their sample counts need to be kept; retained variants and
// FASTQ output keep the read (as before). Exact-key mode keeps counts only.
deferCountsOnly_ = b_derep_as_fasta_ && !(coarse_ && (coarse_->storesQualities() || coarse_->storesDiffs()));
deferredKeyCapPerShard_ = std::max<size_t>(1, kDeferredKeyCap / std::max<size_t>(1, shards_.size()));
}
Dereplicate::~Dereplicate() {
if (merger != nullptr) { delete merger; merger = nullptr; }
}
Dereplicate::ActiveAddGuard::ActiveAddGuard(Dereplicate& owner, ThreadLocalBatch& batch)
: owner(owner), batch(batch) {
for (;;) {
if (owner.lifecycle_pause_.load()) {
std::unique_lock<std::mutex> lock(owner.lifecycle_wait_mtx_);
owner.lifecycle_wait_cv_.wait(lock, [&owner] { return !owner.lifecycle_pause_.load(); });
}
// Sequential consistency pairs this announcement/recheck with the
// snapshot's pause/store and activity scan. Either it sees this producer,
// or this producer sees the pause before touching any pending entries.
batch.active.store(true);
if (!owner.lifecycle_pause_.load()) { return; }
owner.release_batch_activity(batch);
}
}
Dereplicate::ActiveAddGuard::~ActiveAddGuard() { owner.release_batch_activity(batch); }
void Dereplicate::release_batch_activity(ThreadLocalBatch& batch) {
batch.active.store(false);
if (lifecycle_pause_.load()) {
// Synchronize notification with the waiter's predicate check so the
// final producer cannot notify just before the waiter goes to sleep.
std::lock_guard<std::mutex> lock(lifecycle_wait_mtx_);
lifecycle_wait_cv_.notify_all();
}
}
Dereplicate::LifecyclePause::LifecyclePause(Dereplicate& owner)
: owner(owner), operationLock(owner.lifecycle_operation_mtx_) {
std::unique_lock<std::mutex> lock(owner.lifecycle_wait_mtx_);
std::vector<std::shared_ptr<ThreadLocalBatch>> batches;
{
std::lock_guard<std::mutex> registryLock(owner.batch_registry_mtx_);
// Copy before publishing the pause: allocation failure leaves producers running.
batches = owner.batch_registry_;
owner.lifecycle_pause_.store(true);
}
// Newly registered producers see the pause before touching their batches.
// Release the registry lock before waiting/reacquiring the condition mutex.
owner.lifecycle_wait_cv_.wait(lock, [&batches] {
return std::all_of(batches.begin(), batches.end(), [](const auto& batch) {
return !batch->active.load();
});
});
}
Dereplicate::LifecyclePause::~LifecyclePause() {
std::lock_guard<std::mutex> lock(owner.lifecycle_wait_mtx_);
owner.lifecycle_pause_.store(false);
owner.lifecycle_wait_cv_.notify_all();
}
bool Dereplicate::addDNA(shared_ptr<DNA> dna, shared_ptr<DNA> dna2, Filters* filter,
const DerepTierRoute* route, bool* queued) {
if (queued) { *queued = false; }
if (coarse_ && coarse_->storesQualities() && bool(dna2) != b_pairedInput) {
throw std::invalid_argument("-derepStoreQuals requires complete pairs for paired input, or consistently single-end input");
}
ThreadLocalBatch& threadBatch = get_or_create_thread_batch();
ActiveAddGuard activeGuard(*this, threadBatch);
if (coarse_ && coarse_->storesQualities() && dna2 && dna2->mem_length() == 0) {
skippedEmptyMates_.fetch_add(1, std::memory_order_relaxed);
return false;
}
//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 || b_merge_pairs_derep_) && dna2 != nullptr && dna->merge_seed_pos_ != -1 && merger != nullptr) {
//MrgPos1 = dna2->merge_seed_pos_;
dna_merged = merger->merge(dna, dna2);
Filters* mergedFilter = filter ? filter : mainFilter;
if (dna_merged && !mergedFilter->checkMergedDNA(dna_merged)) {
dna_merged.reset();
}
// Only an accepted consensus marks its mates as merged (length and
// overlap errors feed representative selection and the report).
if (dna_merged) { dna->adoptMergeStats(*dna_merged); dna2->adoptMergeStats(*dna_merged); }
}
if (dna_merged && mergedSearchKeys_){
const std::string_view mergedSeq = dna_merged->getSeqPseudoView();
const size_t searchLen = (searchLength == -1)
? mergedSeq.size()
: std::min(static_cast<size_t>(searchLength), mergedSeq.size());
srchSeqBuffer.assign(mergedSeq.data(), searchLen);
srchSeqPtr = &srchSeqBuffer;
} else {
const std::string_view seq = dna->getSeqPseudoView();
const size_t searchLen = (searchLength == -1)
? seq.size()
: std::min(static_cast<size_t>(searchLength), seq.size());
srchSeqBuffer.assign(seq.data(), searchLen);
srchSeqPtr = &srchSeqBuffer;
}
const string& srchSeq = *srchSeqPtr;
if ((prefixMode_ || (coarse_ && !coarse_->storageOnly())) && srchSeq.empty()) {
skippedEmptyKeys_.fetch_add(1, std::memory_order_relaxed);
return false;
}
// Exact dereplication is keyed by R1/search sequence, including in coarse
// mode. Different R2s must reach the same owner to compete as best seeds.
const size_t keyHash = coarse_ && coarse_->storageOnly() && shards_.size() > 1 ?
coarse_->storagePartitionHash(srchSeq) : robin_hood::hash<string>{}(srchSeq);
threadBatch.pending.push_back(PendingDerepEntry{
srchSeq,
dna,
dna2,
dna_merged,
MrgPos1,
sample_id,
pass,
keyHash % shards_.size()
});
if (route) { threadBatch.pending.back().withheld = true; threadBatch.pending.back().route = *route; }