-
Notifications
You must be signed in to change notification settings - Fork 164
/
SalmonAlevin.cpp
2963 lines (2571 loc) · 114 KB
/
SalmonAlevin.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
>HEADER
Copyright (c) 2013, 2014, 2015, 2016 Rob Patro rob.patro@cs.stonybrook.edu
This file is part of Salmon.
Salmon 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.
Salmon 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 Salmon. If not, see <http://www.gnu.org/licenses/>.
<HEADER
**/
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <exception>
#include <functional>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
#include <random>
#include <sstream>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// C++ string formatting library
#include "spdlog/fmt/fmt.h"
// C Includes for BWA
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
// Jellyfish 2 include
// #include "jellyfish/mer_dna.hpp"
// Boost Includes
#include <boost/container/flat_map.hpp>
#include <boost/dynamic_bitset/dynamic_bitset.hpp>
#include <boost/filesystem.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/program_options.hpp>
#include <boost/range/irange.hpp>
#include <boost/thread/thread.hpp>
// TBB Includes
#include "oneapi/tbb/blocked_range.h"
#include "oneapi/tbb/concurrent_queue.h"
#include "oneapi/tbb/concurrent_unordered_map.h"
#include "oneapi/tbb/concurrent_unordered_set.h"
#include "oneapi/tbb/concurrent_vector.h"
#include "oneapi/tbb/parallel_for.h"
#include "oneapi/tbb/parallel_for_each.h"
#include "oneapi/tbb/parallel_reduce.h"
#include "oneapi/tbb/partitioner.h"
// logger includes
#include "spdlog/spdlog.h"
// Cereal includes
#include "cereal/archives/binary.hpp"
#include "cereal/types/vector.hpp"
#include "concurrentqueue.h"
#include <cuckoohash_map.hh>
// core includes
#include "core/range.hpp"
// radicl includes
#include "radicl/BasicBinWriter.hpp"
#include "radicl/RADHeader.hpp"
//alevin include
#include "AlevinOpts.hpp"
#include "AlevinUtils.hpp"
#include "SingleCellProtocols.hpp"
#include "CollapsedCellOptimizer.hpp"
#include "BarcodeGroup.hpp"
// salmon includes
#include "ClusterForest.hpp"
#include "FastxParser.hpp"
#include "IOUtils.hpp"
#include "LibraryFormat.hpp"
#include "ReadLibrary.hpp"
#include "SalmonConfig.hpp"
#include "SalmonIndex.hpp"
#include "SalmonMath.hpp"
#include "SalmonUtils.hpp"
#include "Transcript.hpp"
#include "AlignmentGroup.hpp"
#include "BiasParams.hpp"
#include "CollapsedEMOptimizer.hpp"
#include "CollapsedGibbsSampler.hpp"
#include "EquivalenceClassBuilder.hpp"
#include "ForgettingMassCalculator.hpp"
#include "FragmentLengthDistribution.hpp"
#include "GZipWriter.hpp"
#include "SalmonMappingUtils.hpp"
#include "ReadExperiment.hpp"
#include "SalmonOpts.hpp"
#include "PairedAlignmentFormatter.hpp"
#include "pufferfish/Util.hpp"
#include "pufferfish/MemCollector.hpp"
#include "pufferfish/MemChainer.hpp"
#include "pufferfish/SAMWriter.hpp"
#include "pufferfish/PuffAligner.hpp"
#include "pufferfish/ksw2pp/KSW2Aligner.hpp"
#include "pufferfish/metro/metrohash64.h"
#include "parallel_hashmap/phmap.h"
#include "pufferfish/itlib/static_vector.hpp"
#include "pufferfish/SelectiveAlignmentUtils.hpp"
namespace alevin{
/****** QUASI MAPPING DECLARATIONS *********/
using MateStatus = pufferfish::util::MateStatus;
using QuasiAlignment = pufferfish::util::QuasiAlignment;
/****** QUASI MAPPING DECLARATIONS *******/
using paired_parser = fastx_parser::FastxParser<fastx_parser::ReadPair>;
using single_parser = fastx_parser::FastxParser<fastx_parser::ReadSeq>;
using TranscriptID = uint32_t;
using TranscriptIDVector = std::vector<TranscriptID>;
using KmerIDMap = std::vector<TranscriptIDVector>;
constexpr uint32_t miniBatchSize{5000};
// NOTE: Consider the implications of using uint32_t below.
// Currently, this should not limit the barcode length to <= 16 in
// "fry" mode (either sla or sketch) since we never actually put the
// barcode in the corresponding variable of the AlignmentGroup class.
// In traditional alevin, this should be referring to a barcode *index*
// rather than the sequence itself, so it should be OK so long as we have
// < std::numeric_limits<uint32_t>::max() distinct barcodes / reads.
// However, that assumption should be tested more thoroughly.
using CellBarcodeT = uint32_t;
using UMIBarcodeT = uint64_t;
template <typename AlnT> using AlevinAlnGroup = AlignmentGroup<AlnT, CellBarcodeT, UMIBarcodeT>;
template <typename AlnT> using AlnGroupVec = std::vector<AlevinAlnGroup<AlnT>>;
template <typename AlnT>
using AlnGroupVecRange = core::range<typename AlnGroupVec<AlnT>::iterator>;
#define __MOODYCAMEL__
#if defined(__MOODYCAMEL__)
template <typename AlnT>
using AlnGroupQueue = moodycamel::ConcurrentQueue<AlevinAlnGroup<AlnT>*>;
#else
template <typename AlnT>
using AlnGroupQueue = oneapi::tbb::concurrent_queue<AlevinAlnGroup<AlnT>*>;
#endif
//#include "LightweightAlignmentDefs.hpp"
}
//have to create new namespace because of multiple definition
using namespace alevin;
/* ALEVIN DECLERATIONS*/
using bcEnd = BarcodeEnd;
namespace aut = alevin::utils;
using BlockedIndexRange = oneapi::tbb::blocked_range<size_t>;
using ReadExperimentT = ReadExperiment<EquivalenceClassBuilder<SCTGValue>>;
/////// REDUNDANT CODE END//
template <typename AlnT>
void processMiniBatchSimple(ReadExperimentT& readExp, ForgettingMassCalculator& fmCalc,
ReadLibrary& readLib,
const SalmonOpts& salmonOpts,
AlnGroupVecRange<AlnT> batchHits,
std::vector<Transcript>& transcripts,
ClusterForest& clusterForest,
FragmentLengthDistribution& fragLengthDist,
std::atomic<uint64_t>& numAssignedFragments,
bool initialRound,
std::atomic<bool>& burnedIn, double& maxZeroFrac){
using salmon::math::LOG_0;
using salmon::math::LOG_1;
using salmon::math::LOG_EPSILON;
using salmon::math::LOG_ONEHALF;
using salmon::math::logAdd;
using salmon::math::logSub;
const uint64_t numBurninFrags = salmonOpts.numBurninFrags;
auto& log = salmonOpts.jointLog;
size_t numTranscripts{transcripts.size()};
size_t localNumAssignedFragments{0};
size_t priorNumAssignedFragments{numAssignedFragments};
std::uniform_real_distribution<> uni(
0.0, 1.0 + std::numeric_limits<double>::min());
std::vector<uint64_t> libTypeCounts(LibraryFormat::maxLibTypeID() + 1);
bool hasCompatibleMapping{false};
uint64_t numCompatibleFragments{0};
std::vector<FragmentStartPositionDistribution>& fragStartDists =
readExp.fragmentStartPositionDistributions();
bool updateCounts = initialRound;
double incompatPrior = salmonOpts.incompatPrior;
bool useReadCompat = incompatPrior != salmon::math::LOG_1;
// If we're auto detecting the library type
auto* detector = readLib.getDetector();
bool autoDetect = (detector != nullptr) ? detector->isActive() : false;
// If we haven't detected yet, nothing is incompatible
if (autoDetect) { incompatPrior = salmon::math::LOG_1; }
double logForgettingMass{0.0};
uint64_t currentMinibatchTimestep{0};
// logForgettingMass and currentMinibatchTimestep are OUT parameters!
fmCalc.getLogMassAndTimestep(logForgettingMass, currentMinibatchTimestep);
auto expectedLibraryFormat = readLib.format();
uint64_t zeroProbFrags{0};
// EQClass
auto& eqBuilder = readExp.equivalenceClassBuilder();
// Build reverse map from transcriptID => hit id
using HitID = uint32_t;
int i{0};
{
// Iterate over each group of alignments (a group consists of all alignments
// reported
// for a single read). Distribute the read's mass to the transcripts
// where it potentially aligns.
for (auto& alnGroup : batchHits) {
// If we had no alignments for this read, then skip it
if (alnGroup.size() == 0) {
continue;
}
//extract barcode of the read
uint32_t barcode = alnGroup.barcode();
uint64_t umi = alnGroup.umi();
// We start out with probability 0
double sumOfAlignProbs{LOG_0};
// Record whether or not this read is unique to a single transcript.
bool transcriptUnique{true};
auto firstTranscriptID = alnGroup.alignments().front().transcriptID();
std::vector<uint32_t> txpIDs;
uint32_t numInGroup{0};
uint32_t prevTxpID{0};
hasCompatibleMapping = false;
// For each alignment of this read
for (auto& aln : alnGroup.alignments()) {
auto transcriptID = aln.transcriptID();
auto& transcript = transcripts[transcriptID];
transcriptUnique =
transcriptUnique and (transcriptID == firstTranscriptID);
if (autoDetect) {
detector->addSample(aln.libFormat());
if (detector->canGuess()) {
detector->mostLikelyType(readLib.getFormat());
expectedLibraryFormat = readLib.getFormat();
incompatPrior = salmonOpts.incompatPrior;
autoDetect = false;
} else if (!detector->isActive()) {
expectedLibraryFormat = readLib.getFormat();
incompatPrior = salmonOpts.incompatPrior;
autoDetect = false;
}
}
// The probability that the fragments align to the given strands in
// the given orientations.
bool isCompat =
salmon::utils::isCompatible(
aln.libFormat(),
expectedLibraryFormat,
static_cast<int32_t>(aln.pos),
aln.fwd,
aln.mateStatus);
double logAlignCompatProb = isCompat ? LOG_1 : incompatPrior;
aln.logProb = logAlignCompatProb;
if (!isCompat and salmonOpts.ignoreIncompat) {
aln.logProb = salmon::math::LOG_0;
continue;
}
// Increment the count of this type of read that we've seen
++libTypeCounts[aln.libFormat().formatID()];
if (!hasCompatibleMapping and logAlignCompatProb == LOG_1) { hasCompatibleMapping = true; }
// If this alignment had a zero probability, then skip it
if (std::abs(aln.logProb) == LOG_0) {
continue;
}
sumOfAlignProbs = logAdd(sumOfAlignProbs, aln.logProb);
if (transcriptID < prevTxpID) {
std::cerr << "[ERROR] Transcript IDs are not in sorted order; "
"please report this bug on GitHub!\n";
}
prevTxpID = transcriptID;
txpIDs.push_back(transcriptID);
}
// If this fragment has a zero probability,
// go to the next one
if (sumOfAlignProbs == LOG_0) {
++zeroProbFrags;
continue;
} else { // otherwise, count it as assigned
++localNumAssignedFragments;
if (hasCompatibleMapping) { ++numCompatibleFragments; }
}
auto eqSize = txpIDs.size();
if (eqSize > 0) {
TranscriptGroup tg(txpIDs);
eqBuilder.addBarcodeGroup(std::move(tg), barcode, umi);
}
// update the single target transcript
if (transcriptUnique) {
if (updateCounts) {
transcripts[firstTranscriptID].addUniqueCount(1);
}
} else { // or the appropriate clusters
clusterForest.mergeClusters<AlnT>(alnGroup.alignments().begin(),
alnGroup.alignments().end());
clusterForest.updateCluster(
alnGroup.alignments().front().transcriptID(), 1.0,
logForgettingMass, updateCounts);
}
} // end read group
} // end timer
if (zeroProbFrags > 0) {
auto batchReads = batchHits.size();
maxZeroFrac = std::max(maxZeroFrac, static_cast<double>(100.0 * zeroProbFrags) / batchReads);
}
numAssignedFragments += localNumAssignedFragments;
if (numAssignedFragments >= numBurninFrags and !burnedIn) {
// NOTE: only one thread should succeed here, and that
// thread will set burnedIn to true.
readExp.updateTranscriptLengthsAtomic(burnedIn);
fragLengthDist.cacheCMF();
}
if (initialRound) {
readLib.updateLibTypeCounts(libTypeCounts);
readLib.updateCompatCounts(numCompatibleFragments);
}
}
/**
* Perform sketch mapping of sc reads and produce output file.
**/
template <typename IndexT, typename ProtocolT>
void process_reads_sc_sketch(paired_parser* parser, ReadExperimentT& readExp, ReadLibrary& rl,
AlnGroupVec<QuasiAlignment>& structureVec,
std::atomic<uint64_t>& numObservedFragments,
std::atomic<uint64_t>& numAssignedFragments,
std::atomic<uint64_t>& numUniqueMappings,
std::atomic<uint64_t>& validHits,
std::atomic<uint32_t>& smallSeqs,
std::atomic<uint32_t>& nSeqs,
IndexT* qidx, std::vector<Transcript>& transcripts,
FragmentLengthDistribution& fragLengthDist,
SalmonOpts& salmonOpts,
std::atomic<uint64_t>& num_chunks,
std::ofstream& rad_file,
std::ofstream& ubc_file, // unmapped barcode count
std::mutex& fileMutex,
std::mutex& ubc_file_mutex, // mutex for barcode count
std::mutex& iomutex,
AlevinOpts<ProtocolT>& alevinOpts,
MappingStatistics& mstats) {
(void) numAssignedFragments;
(void) fragLengthDist;
uint64_t count_fwd = 0, count_bwd = 0;
uint64_t prevObservedFrags{1};
uint64_t leftHitCount{0};
uint64_t hitListCount{0};
salmon::utils::ShortFragStats shortFragStats;
double maxZeroFrac{0.0};
bool quiet = salmonOpts.quiet;
if (salmonOpts.writeQualities) {
salmonOpts.jointLog->warn("The --writeQualities flag has no effect when writing results to a RAD file.");
}
BasicBinWriter bw;
uint32_t num_reads_in_chunk{0};
bw << num_reads_in_chunk;
bw << num_reads_in_chunk;
size_t minK = qidx->k();
int32_t signed_k = static_cast<int32_t>(minK);
size_t locRead{0};
size_t rangeSize{0};
uint64_t localNumAssignedFragments{0};
uint64_t localNumUniqueMappings{0};
size_t readLenLeft{0};
size_t readLenRight{0};
salmon::utils::MappingType mapType{salmon::utils::MappingType::UNMAPPED};
fmt::MemoryWriter sstream;
auto* qmLog = salmonOpts.qmLog.get();
bool writeQuasimappings = (qmLog != nullptr);
PairedAlignmentFormatter<IndexT*> formatter(qidx);
// map to recall the number of unmapped reads we see
// for each barcode
phmap::flat_hash_map<uint64_t, uint32_t> unmapped_bc_map;
// check the frequency and decide here if we should
// be attempting recovery of highly-multimapping reads
const size_t max_occ_default = salmonOpts.maxReadOccs;
const size_t max_occ_recover = salmonOpts.maxRecoverReadOccs;
const bool attempt_occ_recover = (max_occ_recover > max_occ_default);
// think if this should be different since it's at the read level
const size_t max_read_occs = salmonOpts.maxReadOccs;
size_t alt_max_occ = max_read_occs;
// we'll use this for mapping
salmon::mapping_utils::pasc::mapping_cache_info<IndexT> map_cache_first(qidx, max_occ_default, max_occ_recover, max_read_occs);
salmon::mapping_utils::pasc::mapping_cache_info<IndexT> map_cache_second(qidx, max_occ_default, max_occ_recover, max_read_occs);
std::vector<salmon::mapping_utils::pasc::simple_hit>* accepted_hits_left_ptr;
std::vector<salmon::mapping_utils::pasc::simple_hit>* accepted_hits_right_ptr;
std::vector<salmon::mapping_utils::pasc::simple_hit>* accepted_hits_ptr;
// buffer in which to accumulate accepted hits if we are merging for left
// and right reads
std::vector<salmon::mapping_utils::pasc::simple_hit> accepted_hits_buffer;
std::string readBuffer;
std::string umi(alevinOpts.protocol.umiLength, 'N');
std::string barcode(alevinOpts.protocol.barcodeLength, 'N');
//////////////////////
auto localProtocol = alevinOpts.protocol;
// start parsing reads
auto rg = parser->getReadGroup();
while (parser->refill(rg)) {
rangeSize = rg.size();
if (rangeSize > structureVec.size()) {
salmonOpts.jointLog->error("rangeSize = {}, but structureVec.size() = {} "
"--- this shouldn't happen.\n"
"Please report this bug on GitHub",
rangeSize, structureVec.size());
std::exit(1);
}
LibraryFormat expectedLibraryFormat = rl.format();
std::string extraBAMtags;
if(writeQuasimappings) {
size_t reserveSize { alevinOpts.protocol.barcodeLength + alevinOpts.protocol.umiLength + 12};
extraBAMtags.reserve(reserveSize);
}
for (size_t i = 0; i < rangeSize; ++i) { // For all the read in this batch
auto& rp = rg[i];
readLenLeft = rp.first.seq.length();
readLenRight= rp.second.seq.length();
// while the pasc code path will use the jointHitGroup to
// store UMI and BarCode info, it won't actually use the
// "alignment" fields
bool tooShortRight = (readLenRight < (minK+alevinOpts.trimRight));
auto& jointHitGroup = structureVec[i];
jointHitGroup.clearAlignments();
mapType = salmon::utils::MappingType::UNMAPPED;
// ensure that accepted_hits_ptr points to a valid
// vector in case it's not set below
accepted_hits_ptr = &accepted_hits_buffer;
alt_max_occ = max_read_occs;
//////////////////////////////////////////////////////////////
// extracting barcodes
size_t barcodeLength = alevinOpts.protocol.barcodeLength;
size_t umiLength = alevinOpts.protocol.umiLength;
nonstd::optional<uint32_t> barcodeIdx;
extraBAMtags.clear();
bool seqOk = false;
if (alevinOpts.protocol.end == bcEnd::FIVE ||
alevinOpts.protocol.end == bcEnd::THREE) {
// If the barcode sequence could be extracted, then this is set to true,
// but the barcode sequence itself may still be invalid (e.g. contain `N` characters).
// However, if extracted_barcode is false here, there is no hope to even recover the
// barcode and we shouldn't attempt it.
bool extracted_barcode = aut::extractBarcode(rp.first.seq, rp.second.seq, localProtocol, barcode);
// If we could pull out something where the barcode sequence should have been
// then continue to process it.
if (extracted_barcode) {
// if the barcode consisted of valid nucleotides, then seqOk is true
// otherwise false
seqOk = aut::sequenceCheck(barcode, Sequence::BARCODE);
if (not seqOk){
// If the barcode contained invalid nucleotides
// this attempts to replace the first one with an `A`.
// If this returns true, there was only one `N` and we
// replaced it; otherwise there was more than one `N`
// and the barcode sequence should be treated as invalid.
seqOk = aut::recoverBarcode(barcode);
}
}
// If we have a valid barcode
if (seqOk) {
bool umi_ok = aut::extractUMI(rp.first.seq, rp.second.seq, localProtocol, umi);
if ( !umi_ok ) {
smallSeqs += 1;
} else {
alevin::types::AlevinUMIKmer umiIdx;
bool isUmiIdxOk = umiIdx.fromChars(umi);
if (isUmiIdxOk) {
jointHitGroup.setUMI(umiIdx.word(0));
// get the subsequence for the alignable portion of the read
std::string* readSubSeq = aut::getReadSequence(localProtocol, rp.first.seq, rp.second.seq, readBuffer);
// try and map it
bool early_exit = salmon::mapping_utils::pasc::map_read(readSubSeq, map_cache_second, PairingStatus::UNPAIRED_RIGHT);
// in this case accepted_hits_ptr gets set to what we found
accepted_hits_ptr = &map_cache_second.accepted_hits;
alt_max_occ = map_cache_second.alt_max_occ;
} else {
nSeqs += 1;
}
}
}
} else {
salmonOpts.jointLog->error( "wrong barcode-end parameters.\n"
"Please report this bug on Github");
salmonOpts.jointLog->flush();
spdlog::drop_all();
std::exit(1);
}
//////////////////////////////////////////////////////////////
// Consider a read as too short if the ``non-barcode'' end is too short
if (tooShortRight) {
++shortFragStats.numTooShort;
shortFragStats.shortest = std::min(shortFragStats.shortest,
std::max(readLenLeft, readLenRight));
}
// If the read mapped to > maxReadOccs places, discard it
if (accepted_hits_ptr->size() > alt_max_occ) {
accepted_hits_ptr->clear();
} else if (!accepted_hits_ptr->empty()) {
mapType = salmon::utils::MappingType::SINGLE_MAPPED;
}
alevin::types::AlevinCellBarcodeKmer bck;
bool barcode_ok = bck.fromChars(barcode);
// NOTE: Think if we should put decoy mappings in the RAD file
if (mapType == salmon::utils::MappingType::SINGLE_MAPPED) {
// num aln
bw << static_cast<uint32_t>(accepted_hits_ptr->size());
// bc
// if we can fit the barcode into an integer
if ( barcodeLength <= 32 ) {
if (barcode_ok) {
if ( barcodeLength <= 16 ) { // can use 32-bit int
uint32_t shortbck = static_cast<uint32_t>(0x00000000FFFFFFFF & bck.word(0));
bw << shortbck;
} else { // must use 64-bit int
bw << bck.word(0);
}
}
} else { // must use a string for the barcode
bw << barcode;
}
// umi
if ( umiLength <= 16 ) { // if we can use 32-bit int
uint64_t umiint = jointHitGroup.umi();
uint32_t shortumi = static_cast<uint32_t>(0x00000000FFFFFFFF & umiint);
bw << shortumi;
} else if ( umiLength <= 32 ) { // if we can use 64-bit int
uint64_t umiint = jointHitGroup.umi();
bw << umiint;
} else { // must use string
bw << umi;
}
for (auto& aln : (*accepted_hits_ptr)) {
uint32_t fw_mask = aln.is_fw ? 0x80000000 : 0x00000000;
bw << (aln.tid | fw_mask);
}
++num_reads_in_chunk;
} else { // if read was not mapped
if (barcode_ok) {
unmapped_bc_map[bck.word(0)] += 1;
}
}
if (num_reads_in_chunk > 5000) {
++num_chunks;
uint32_t num_bytes = bw.num_bytes();
bw.write_integer_at_offset(0, num_bytes);
bw.write_integer_at_offset(sizeof(num_bytes), num_reads_in_chunk);
fileMutex.lock();
rad_file << bw;
fileMutex.unlock();
bw.clear();
num_reads_in_chunk = 0;
// reserve space for headers of next chunk
bw << num_reads_in_chunk;
bw << num_reads_in_chunk;
}
validHits += accepted_hits_ptr->size();
localNumAssignedFragments += (accepted_hits_ptr->size() > 0);
localNumUniqueMappings += (accepted_hits_ptr->size() == 1) ? 1 : 0;
locRead++;
++numObservedFragments;
jointHitGroup.clearAlignments();
if (!quiet and numObservedFragments % 500000 == 0) {
iomutex.lock();
const char RESET_COLOR[] = "\x1b[0m";
char green[] = "\x1b[30m";
green[3] = '0' + static_cast<char>(fmt::GREEN);
char red[] = "\x1b[30m";
red[3] = '0' + static_cast<char>(fmt::RED);
fmt::print(
stderr, "\033[A\r\r{}processed{} {} Million {}fragments{}\n",
green, red, numObservedFragments / 1000000, green, RESET_COLOR);
fmt::print(stderr, "hits: {}, hits per frag: {}", validHits,
validHits / static_cast<float>(prevObservedFrags));
iomutex.unlock();
}
} // end for i < j->nb_filled
prevObservedFrags = numObservedFragments;
}
// If we have any unwritten records left to write
if (num_reads_in_chunk > 0) {
++num_chunks;
uint32_t num_bytes = bw.num_bytes();
bw.write_integer_at_offset(0, num_bytes);
bw.write_integer_at_offset(sizeof(num_bytes), num_reads_in_chunk);
fileMutex.lock();
rad_file << bw;
fileMutex.unlock();
bw.clear();
num_reads_in_chunk = 0;
}
// unmapped barcode writer
{ // make a scope and dump the unmapped barcode counts
BasicBinWriter ubcw;
for (auto& kv : unmapped_bc_map) {
ubcw << kv.first;
ubcw << kv.second;
}
ubc_file_mutex.lock();
ubc_file << ubcw;
ubc_file_mutex.unlock();
ubcw.clear();
}
if (maxZeroFrac > 5.0) {
salmonOpts.jointLog->info("Thread saw mini-batch with a maximum of {0:.2f}\% zero probability fragments",
maxZeroFrac);
}
numAssignedFragments += localNumAssignedFragments;
numUniqueMappings += localNumUniqueMappings;
mstats.numDecoyFragments += 0; // no decoys with pasc (yet?)
readExp.updateShortFrags(shortFragStats);
}
/**
* Perform selective alignment of sc reads and produce output file.
**/
template <typename IndexT, typename ProtocolT>
void process_reads_sc_align(paired_parser* parser, ReadExperimentT& readExp, ReadLibrary& rl,
AlnGroupVec<QuasiAlignment>& structureVec,
std::atomic<uint64_t>& numObservedFragments,
std::atomic<uint64_t>& numAssignedFragments,
std::atomic<uint64_t>& validHits,
std::atomic<uint32_t>& smallSeqs,
std::atomic<uint32_t>& nSeqs,
IndexT* qidx, std::vector<Transcript>& transcripts,
FragmentLengthDistribution& fragLengthDist,
SalmonOpts& salmonOpts,
std::atomic<uint64_t>& num_chunks,
std::ofstream& rad_file,
std::ofstream& ubc_file, // unmapped barcode count
std::mutex& fileMutex,
std::mutex& ubc_file_mutex, // mutex for barcode count
std::mutex& iomutex,
AlevinOpts<ProtocolT>& alevinOpts,
MappingStatistics& mstats) {
(void) numAssignedFragments;
(void) fragLengthDist;
uint64_t count_fwd = 0, count_bwd = 0;
uint64_t prevObservedFrags{1};
uint64_t leftHitCount{0};
uint64_t hitListCount{0};
salmon::utils::ShortFragStats shortFragStats;
double maxZeroFrac{0.0};
// Write unmapped reads
fmt::MemoryWriter unmappedNames;
bool writeUnmapped = salmonOpts.writeUnmappedNames;
spdlog::logger* unmappedLogger = (writeUnmapped) ? salmonOpts.unmappedLog.get() : nullptr;
// Write unmapped reads
fmt::MemoryWriter orphanLinks;
bool writeOrphanLinks = salmonOpts.writeOrphanLinks;
spdlog::logger* orphanLinkLogger = (writeOrphanLinks) ? salmonOpts.orphanLinkLog.get() : nullptr;
BasicBinWriter bw;
uint32_t num_reads_in_chunk{0};
bw << num_reads_in_chunk;
bw << num_reads_in_chunk;
size_t minK = qidx->k();
size_t locRead{0};
size_t rangeSize{0};
uint64_t localNumAssignedFragments{0};
bool consistentHits = salmonOpts.consistentHits;
bool quiet = salmonOpts.quiet;
size_t maxNumHits{salmonOpts.maxReadOccs};
size_t readLenLeft{0};
size_t readLenRight{0};
constexpr const int32_t invalidScore = std::numeric_limits<int32_t>::min();
MemCollector<IndexT> memCollector(qidx);
ksw2pp::KSW2Aligner aligner;
pufferfish::util::AlignmentConfig aconf;
pufferfish::util::MappingConstraintPolicy mpol;
bool initOK = salmon::mapping_utils::initMapperSettings(salmonOpts, memCollector, aligner, aconf, mpol);
PuffAligner puffaligner(qidx->refseq_, qidx->refAccumLengths_, qidx->k(), aconf, aligner);
pufferfish::util::CachedVectorMap<size_t, std::vector<pufferfish::util::MemCluster>, std::hash<size_t>> hits;
std::vector<pufferfish::util::MemCluster> recoveredHits;
std::vector<pufferfish::util::JointMems> jointHits;
PairedAlignmentFormatter<IndexT*> formatter(qidx);
if (salmonOpts.writeQualities) {
salmonOpts.jointLog->warn("The --writeQualities flag has no effect when writing results to a RAD file.");
}
pufferfish::util::QueryCache qc;
bool mimicStrictBT2 = salmonOpts.mimicStrictBT2;
bool mimicBT2 = salmonOpts.mimicBT2;
bool noDovetail = !salmonOpts.allowDovetail;
bool useChainingHeuristic = !salmonOpts.disableChainingHeuristic;
pufferfish::util::HitCounters hctr;
salmon::utils::MappingType mapType{salmon::utils::MappingType::UNMAPPED};
bool hardFilter = salmonOpts.hardFilter;
fmt::MemoryWriter sstream;
auto* qmLog = salmonOpts.qmLog.get();
bool writeQuasimappings = (qmLog != nullptr);
// map to recall the number of unmapped reads we see
// for each barcode
phmap::flat_hash_map<uint64_t, uint32_t> unmapped_bc_map;
//////////////////////
// NOTE: validation mapping based new parameters
std::string rc1; rc1.reserve(300);
AlnCacheMap alnCache; alnCache.reserve(16);
/*
auto ap{selective_alignment::utils::AlignmentPolicy::DEFAULT};
if (mimicBT2) {
ap = selective_alignment::utils::AlignmentPolicy::BT2;
} else if (mimicStrictBT2) {
ap = selective_alignment::utils::AlignmentPolicy::BT2_STRICT;
}
*/
size_t numMappingsDropped{0};
size_t numDecoyFrags{0};
const double decoyThreshold = salmonOpts.decoyThreshold;
salmon::mapping_utils::MappingScoreInfo msi(decoyThreshold);
// we only collect detailed decoy information if we will be
// writing output to SAM.
msi.collect_decoys(writeQuasimappings);
std::string* readSubSeq{nullptr};
std::string readBuffer;
std::string umi(alevinOpts.protocol.umiLength, 'N');
std::string barcode(alevinOpts.protocol.barcodeLength, 'N');
//////////////////////
bool tryAlign{salmonOpts.validateMappings};
auto rg = parser->getReadGroup();
while (parser->refill(rg)) {
rangeSize = rg.size();
if (rangeSize > structureVec.size()) {
salmonOpts.jointLog->error("rangeSize = {}, but structureVec.size() = {} "
"--- this shouldn't happen.\n"
"Please report this bug on GitHub",
rangeSize, structureVec.size());
std::exit(1);
}
LibraryFormat expectedLibraryFormat = rl.format();
std::string extraBAMtags;
if(writeQuasimappings) {
size_t reserveSize { alevinOpts.protocol.barcodeLength + alevinOpts.protocol.umiLength + 12};
extraBAMtags.reserve(reserveSize);
}
auto localProtocol = alevinOpts.protocol;
for (size_t i = 0; i < rangeSize; ++i) { // For all the read in this batch
auto& rp = rg[i];
readLenLeft = rp.first.seq.length();
readLenRight= rp.second.seq.length();
bool tooShortRight = (readLenRight < (minK+alevinOpts.trimRight));
//localUpperBoundHits = 0;
auto& jointHitGroup = structureVec[i];
jointHitGroup.clearAlignments();
auto& jointAlignments= jointHitGroup.alignments();
hits.clear();
jointHits.clear();
memCollector.clear();
//jointAlignments.clear();
readSubSeq = nullptr;//.clear();
mapType = salmon::utils::MappingType::UNMAPPED;
//////////////////////////////////////////////////////////////
// extracting barcodes
size_t barcodeLength = alevinOpts.protocol.barcodeLength;
size_t umiLength = alevinOpts.protocol.umiLength;
//umi.clear();
//barcode.clear();
nonstd::optional<uint32_t> barcodeIdx;
extraBAMtags.clear();
bool seqOk = false;
if (alevinOpts.protocol.end == bcEnd::FIVE ||
alevinOpts.protocol.end == bcEnd::THREE){
// If the barcode sequence could be extracted, then this is set to true,
// but the barcode sequence itself may still be invalid (e.g. contain `N` characters).
// However, if extracted_barcode is false here, there is no hope to even recover the
// barcode and we shouldn't attempt it.
bool extracted_barcode = aut::extractBarcode(rp.first.seq, rp.second.seq, localProtocol, barcode);
// If we could pull out something where the barcode sequence should have been
// then continue to process it.
if (extracted_barcode) {
// if the barcode consisted of valid nucleotides, then seqOk is true
// otherwise false
seqOk = aut::sequenceCheck(barcode, Sequence::BARCODE);
if (not seqOk){
// If the barcode contained invalid nucleotides
// this attempts to replace the first one with an `A`.
// If this returns true, there was only one `N` and we
// replaced it; otherwise there was more than one `N`
// and the barcode sequence should be treated as invalid.
seqOk = aut::recoverBarcode(barcode);
}
}
// If we have a valid barcode
if (seqOk) {
bool umi_ok = aut::extractUMI(rp.first.seq, rp.second.seq, localProtocol, umi);
if ( !umi_ok ) {
smallSeqs += 1;
} else {
alevin::types::AlevinUMIKmer umiIdx;
bool isUmiIdxOk = umiIdx.fromChars(umi);
if (isUmiIdxOk) {
jointHitGroup.setUMI(umiIdx.word(0));
/*
auto seq_len = rp.second.seq.size();
if (alevinOpts.trimRight > 0) {
if (!tooShortRight) {
readSubSeq = rp.second.seq.substr(0, seq_len - alevinOpts.trimRight);
auto rh = memCollector(readSubSeq, qc,
true, // isLeft
false // verbose
);
}
} else {
*/
readSubSeq = aut::getReadSequence(localProtocol, rp.first.seq, rp.second.seq, readBuffer);
auto rh = tooShortRight ? false
: memCollector(*readSubSeq, qc,
true, // isLeft
false // verbose
);
// }
memCollector.findChains(
*readSubSeq, hits, salmonOpts.fragLenDistMax,
MateStatus::PAIRED_END_RIGHT,
useChainingHeuristic, // heuristic chaining
true, // isLeft
false // verbose
);
pufferfish::util::joinReadsAndFilterSingle(
hits, jointHits, readSubSeq->length(),
memCollector.getConsensusFraction());
} else {
nSeqs += 1;
}
}
}
} else{
salmonOpts.jointLog->error( "wrong barcode-end parameters.\n"
"Please report this bug on Github");
salmonOpts.jointLog->flush();
spdlog::drop_all();
std::exit(1);
}
//////////////////////////////////////////////////////////////
// Consider a read as too short if the ``non-barcode'' end is too short
if (tooShortRight) {
++shortFragStats.numTooShort;
shortFragStats.shortest = std::min(shortFragStats.shortest,
std::max(readLenLeft, readLenRight));
}
// If the read mapped to > maxReadOccs places, discard it
if (jointHits.size() > salmonOpts.maxReadOccs) {
jointHitGroup.clearAlignments();
}
if (!jointHits.empty()) {
puffaligner.clear();
puffaligner.getScoreStatus().reset();
msi.clear(jointHits.size());
size_t idx{0};
bool is_multimapping = (jointHits.size() > 1);
for (auto &&jointHit : jointHits) {
// for alevin, currently, we need these to have a mate status of PAIRED_END_RIGHT
jointHit.mateStatus = MateStatus::PAIRED_END_RIGHT;
auto hitScore = puffaligner.calculateAlignments(*readSubSeq, jointHit, hctr, is_multimapping, false);
bool validScore = (hitScore != invalidScore);
numMappingsDropped += validScore ? 0 : 1;
auto tid = qidx->getRefId(jointHit.tid);
// NOTE: Here, we know that the read arising from the transcriptome is the "right"
// read (read 2). So we interpret compatibility in that context.
// TODO: Make this code more generic and modular (account for the possibility of different library)
// protocols or setups where the reads are not always "paired-end" and the transcriptomic read is not