Debian Codegraph @

src/data/MappedRead.cpp

raw
1 #include <pbcopper/data/MappedRead.h>
2
3 #include <pbcopper/data/Clipping.h>
4 #include <pbcopper/data/internal/ClippingImpl.h>
5 #include <pbcopper/utility/SequenceUtils.h>
6
7 #include <algorithm>
8 #include <numeric>
9 #include <ostream>
10 #include <stdexcept>
11 #include <type_traits>
12
13 namespace PacBio {
14 namespace Data {
15 namespace {
16
17 struct InvalidMappedReadException : public std::runtime_error
18 {
19 InvalidMappedReadException(std::string reason)
20 : std::runtime_error{"[pbcopper] mapped read ERROR: " + reason}
21 {}
22 };
23
24 template <class InputIt, class Size, class OutputIt>
25 OutputIt Move_N(InputIt first, Size count, OutputIt result)
26 {
27 return std::move(first, first + count, result);
28 }
29
30 template <typename F, typename N>
31 void ClipAndGapify(F* seq, const Cigar& cigar, const GapBehavior gapBehavior,
32 const SoftClipBehavior softClipBehavior, N paddingNullValue, N deletionNullValue)
33 {
34 assert(seq);
35 assert((gapBehavior == GapBehavior::SHOW) || (softClipBehavior == SoftClipBehavior::REMOVE));
36
37 const bool showGaps = (gapBehavior == GapBehavior::SHOW);
38 const bool removeSoftClips = (softClipBehavior == SoftClipBehavior::REMOVE);
39
40 // clang-format off
41 // determine output container's length
42 const size_t outputLength = std::accumulate(cigar.cbegin(), cigar.cend(), 0,
43 [&](size_t totalLength, const CigarOperation& op) {
44 const auto opLength = op.Length();
45 switch (op.Type())
46 {
47 // these operations never increment output length
48 case CigarOperationType::HARD_CLIP:
49 case CigarOperationType::REFERENCE_SKIP:
50 return totalLength;
51
52 // if we're removing soft clip, do not increment output length
53 case CigarOperationType::SOFT_CLIP:
54 return totalLength + (removeSoftClips ? 0 : opLength);
55
56 // increase output length only if we're adding deletion/padding chars
57 case CigarOperationType::DELETION:
58 case CigarOperationType::PADDING:
59 return totalLength + (showGaps ? opLength : 0);
60
61 // otherwise, all operations contribute to output length
62 default:
63 return totalLength + opLength;
64 }
65 });
66 // clang-format on
67
68 // move original data to temp, prep output container size
69 F originalSeq = std::move(*seq);
70 seq->resize(outputLength);
71
72 // apply CIGAR ops
73 size_t srcIndex = 0;
74 size_t dstIndex = 0;
75 for (const auto& op : cigar) {
76 const auto opLength = op.Length();
77 const auto opType = op.Type();
78
79 // nothing to do for hard-clipped & ref-skipped positions
80 if (opType == CigarOperationType::HARD_CLIP ||
81 opType == CigarOperationType::REFERENCE_SKIP) {
82 continue;
83 }
84
85 // maybe skip soft-clipped positions
86 else if (opType == CigarOperationType::SOFT_CLIP && removeSoftClips) {
87 srcIndex += opLength;
88
89 // maybe add deletions
90 } else if (opType == CigarOperationType::DELETION && showGaps) {
91 for (size_t i = 0; i < opLength; ++i) {
92 (*seq)[dstIndex] = deletionNullValue;
93 ++dstIndex;
94 }
95 }
96
97 // maybe add padding
98 else if (opType == CigarOperationType::PADDING && showGaps) {
99 for (size_t i = 0; i < opLength; ++i) {
100 (*seq)[dstIndex] = paddingNullValue;
101 ++dstIndex;
102 }
103 }
104
105 // otherwise move input sequence to output
106 else {
107 Move_N(originalSeq.begin() + srcIndex, opLength, seq->begin() + dstIndex);
108 srcIndex += opLength;
109 dstIndex += opLength;
110 }
111 }
112 }
113
114 template <typename Container>
115 void OrientData(Container* data, Orientation currentOrientation, Orientation targetOrientation,
116 enum Strand strand)
117 {
118 if ((currentOrientation != targetOrientation) && (strand == Strand::REVERSE)) {
119 std::reverse(data->begin(), data->end());
120 }
121 }
122
123 template <>
124 void OrientData(std::string* data, Orientation currentOrientation, Orientation targetOrientation,
125 enum Strand strand)
126 {
127 if ((currentOrientation != targetOrientation) && (strand == Strand::REVERSE)) {
128 Utility::ReverseComplement(*data);
129 }
130 }
131
132 } // namespace
133
134 MappedRead::MappedRead(Read read) noexcept : Read{std::move(read)} {}
135
136 MappedRead::MappedRead(Read read, enum Strand strand, Position templateStart, Position templateEnd,
137 bool pinStart, bool pinEnd) noexcept
138 : Read{std::move(read)}
139 , Strand{strand}
140 , TemplateStart(templateStart)
141 , TemplateEnd(templateEnd)
142 , PinStart{pinStart}
143 , PinEnd{pinEnd}
144 {}
145
146 MappedRead::MappedRead(Read read, PacBio::Data::Strand strand, Position templateStart,
147 PacBio::Data::Cigar cigar, uint8_t mapQV)
148 : MappedRead{std::move(read), strand, templateStart, UNMAPPED_POSITION, std::move(cigar), mapQV}
149 {
150 if (!Cigar.empty()) {
151 TemplateEnd = TemplateStart;
152 for (const auto& op : Cigar) {
153 const auto type = op.Type();
154 const auto len = op.Length();
155
156 switch (type) {
157 case CigarOperationType::ALIGNMENT_MATCH:
158 case CigarOperationType::SEQUENCE_MATCH:
159 case CigarOperationType::SEQUENCE_MISMATCH:
160 case CigarOperationType::DELETION:
161 case CigarOperationType::REFERENCE_SKIP:
162 TemplateEnd += len;
163 break;
164
165 case CigarOperationType::INSERTION:
166 case CigarOperationType::SOFT_CLIP:
167 case CigarOperationType::HARD_CLIP:
168 break;
169
170 default:
171 throw InvalidMappedReadException{"encountered unrecognized CIGAR operation"};
172 }
173 }
174 }
175 }
176
177 MappedRead::MappedRead(Read read, PacBio::Data::Strand strand, Position templateStart,
178 Position templateEnd, PacBio::Data::Cigar cigar, uint8_t mapQV)
179 : Read{std::move(read)}
180 , Strand{strand}
181 , TemplateStart{templateStart}
182 , TemplateEnd{templateEnd}
183 , Cigar{std::move(cigar)}
184 , MapQuality{mapQV}
185 {}
186
187 std::string MappedRead::AlignedSequence(Orientation orientation, GapBehavior gapBehavior,
188 SoftClipBehavior softClipBehavior) const
189 {
190 if (Strand == Strand::UNMAPPED || Cigar.empty()) {
191 return Seq;
192 }
193
194 std::string bases = Seq; // native orientation
195 Orientation currentOrientation = Orientation::NATIVE;
196
197 // if we need to touch CIGAR, force into genomic orientation (for mapping to CIGAR),
198 // then apply gaps and/or remove soft clips
199 if ((gapBehavior == GapBehavior::SHOW) || (softClipBehavior == SoftClipBehavior::REMOVE)) {
200 OrientData(&bases, currentOrientation, Orientation::GENOMIC, AlignedStrand());
201 currentOrientation = Orientation::GENOMIC;
202 ClipAndGapify(&bases, Cigar, gapBehavior, softClipBehavior, '*', '-');
203 }
204
205 // place back in requested orientation
206 OrientData(&bases, currentOrientation, orientation, AlignedStrand());
207 return bases;
208 }
209
210 QualityValues MappedRead::AlignedQualities(Orientation orientation, GapBehavior gapBehavior,
211 SoftClipBehavior softClipBehavior) const
212 {
213 if (Strand == Strand::UNMAPPED || Cigar.empty()) {
214 return Qualities;
215 }
216
217 QualityValues quals = Qualities; // native orientation
218 Orientation currentOrientation = Orientation::NATIVE;
219
220 // if we need to touch CIGAR, force into genomic orientation (for mapping to CIGAR),
221 // then apply gaps and/or remove soft clips
222 if ((gapBehavior == GapBehavior::SHOW) || (softClipBehavior == SoftClipBehavior::REMOVE)) {
223 OrientData(&quals, currentOrientation, Orientation::GENOMIC, AlignedStrand());
224 currentOrientation = Orientation::GENOMIC;
225 ClipAndGapify(&quals, Cigar, gapBehavior, softClipBehavior, QualityValue{0},
226 QualityValue{0});
227 }
228
229 // place back in requested orientation
230 OrientData(&quals, currentOrientation, orientation, AlignedStrand());
231 return quals;
232 }
233
234 std::optional<Frames> MappedRead::AlignedIPD(Orientation orientation, GapBehavior gapBehavior,
235 SoftClipBehavior softClipBehavior) const
236 {
237 if (!IPD) {
238 return {};
239 }
240 if (Strand == Strand::UNMAPPED || Cigar.empty()) {
241 return IPD;
242 }
243
244 Frames ipd = *IPD; // native orientation
245 Orientation currentOrientation = Orientation::NATIVE;
246
247 // if we need to touch CIGAR, force into genomic orientation (for mapping to CIGAR),
248 // then apply gaps and/or remove soft clips
249 if ((gapBehavior == GapBehavior::SHOW) || (softClipBehavior == SoftClipBehavior::REMOVE)) {
250 OrientData(&ipd, currentOrientation, Orientation::GENOMIC, AlignedStrand());
251 currentOrientation = Orientation::GENOMIC;
252 ClipAndGapify(&ipd, Cigar, gapBehavior, softClipBehavior, 0, 0);
253 }
254
255 // place back in requested orientation
256 OrientData(&ipd, currentOrientation, orientation, AlignedStrand());
257 return ipd;
258 }
259
260 std::optional<Frames> MappedRead::AlignedPulseWidth(Orientation orientation,
261 GapBehavior gapBehavior,
262 SoftClipBehavior softClipBehavior) const
263 {
264 if (!PulseWidth) {
265 return {};
266 }
267 if (Strand == Strand::UNMAPPED || Cigar.empty()) {
268 return PulseWidth;
269 }
270
271 Frames pw = *PulseWidth; // native orientation
272 Orientation currentOrientation = Orientation::NATIVE;
273
274 // if we need to touch CIGAR, force into genomic orientation (for mapping to CIGAR),
275 // then apply gaps and/or remove soft clips
276 if ((gapBehavior == GapBehavior::SHOW) || (softClipBehavior == SoftClipBehavior::REMOVE)) {
277 OrientData(&pw, currentOrientation, Orientation::GENOMIC, AlignedStrand());
278 currentOrientation = Orientation::GENOMIC;
279 ClipAndGapify(&pw, Cigar, gapBehavior, softClipBehavior, 0, 0);
280 }
281
282 // place back in requested orientation
283 OrientData(&pw, currentOrientation, orientation, AlignedStrand());
284 return pw;
285 }
286
287 Position MappedRead::AlignedStart() const
288 {
289 if (QueryStart == UNMAPPED_POSITION) {
290 throw InvalidMappedReadException{"contains unmapped query start position"};
291 }
292 if (Strand == Strand::UNMAPPED) {
293 throw InvalidMappedReadException{"contains unmapped strand"};
294 }
295
296 Position startOffset = QueryStart;
297 const Position seqLength = Seq.length();
298 const auto findAlignedStart = [&startOffset, seqLength](auto it, const auto end) {
299 for (; it != end; ++it) {
300 const auto type = it->Type();
301 const auto len = it->Length();
302 if (type == CigarOperationType::HARD_CLIP) {
303 if (startOffset != 0 && startOffset != seqLength) {
304 startOffset = -1;
305 break;
306 }
307 } else if (type == CigarOperationType::SOFT_CLIP) {
308 startOffset += len;
309 } else {
310 break;
311 }
312 }
313 };
314
315 if (Strand == Strand::FORWARD) {
316 findAlignedStart(Cigar.cbegin(), Cigar.cend());
317 } else {
318 findAlignedStart(Cigar.crbegin(), Cigar.crend());
319 }
320
321 return startOffset;
322 }
323
324 Position MappedRead::AlignedEnd() const
325 {
326 if (QueryEnd == UNMAPPED_POSITION) {
327 throw InvalidMappedReadException{"contains unmapped query end position"};
328 }
329 if (Strand == Strand::UNMAPPED) {
330 throw InvalidMappedReadException{"contains unmapped strand"};
331 }
332
333 Position endOffset = QueryEnd;
334 const Position seqLength = Seq.length();
335 const auto findAlignedEnd = [&endOffset, seqLength](auto it, const auto end) {
336 for (; it != end; ++it) {
337 const auto type = it->Type();
338 const auto len = it->Length();
339 if (type == CigarOperationType::HARD_CLIP) {
340 if (endOffset != 0 && endOffset != seqLength) {
341 endOffset = -1;
342 break;
343 }
344 } else if (type == CigarOperationType::SOFT_CLIP) {
345 endOffset -= len;
346 } else {
347 break;
348 }
349 }
350 };
351
352 if (Strand == Strand::FORWARD) {
353 findAlignedEnd(Cigar.crbegin(), Cigar.crend());
354 } else {
355 findAlignedEnd(Cigar.cbegin(), Cigar.cend());
356 }
357
358 return endOffset;
359 }
360
361 Position MappedRead::ReferenceStart() const
362 {
363 if (TemplateStart == UNMAPPED_POSITION) {
364 throw InvalidMappedReadException{"contains unmapped template start position"};
365 }
366 return TemplateStart;
367 }
368
369 Position MappedRead::ReferenceEnd() const
370 {
371 if (TemplateEnd == UNMAPPED_POSITION) {
372 throw InvalidMappedReadException{"contains unmapped template end position"};
373 }
374 return TemplateEnd;
375 }
376
377 Strand MappedRead::AlignedStrand() const { return Strand; }
378
379 int32_t MappedRead::NumMismatches() const
380 {
381 int32_t result = 0;
382
383 for (const auto& op : Cigar) {
384 const auto type = op.Type();
385 const auto len = op.Length();
386 result += (type == CigarOperationType::SEQUENCE_MISMATCH) * len;
387 }
388
389 return result;
390 }
391
392 std::ostream& operator<<(std::ostream& os, const MappedRead& mr)
393 {
394 os << "MappedRead(" << static_cast<const Read&>(mr) << ", RefId=" << mr.RefId << ", Strand=";
395 switch (mr.Strand) {
396 case Strand::FORWARD:
397 os << "FORWARD";
398 break;
399 case Strand::REVERSE:
400 os << "REVERSE";
401 break;
402 case Strand::UNMAPPED:
403 os << "UNMAPPED";
404 break;
405 default:
406 throw InvalidMappedReadException{"encountered unrecognized strand"};
407 }
408 os << ", TemplateStart=" << mr.TemplateStart << ", TemplateEnd=" << mr.TemplateEnd
409 << ", PinStart=" << mr.PinStart << ", PinEnd=" << mr.PinEnd << ", Cigar=" << mr.Cigar
410 << ", MapQuality=" << int{mr.MapQuality} << ')';
411 return os;
412 }
413
414 void ClipToQuery(MappedRead& read, Position start, Position end)
415 {
416 // skip out if clip not needed
417 if (start <= read.QueryStart && end >= read.QueryEnd) {
418 return;
419 }
420
421 // calculate clipping
422 ClipToQueryConfig clipConfig{read.Seq.size(),
423 read.QueryStart,
424 read.QueryEnd,
425 start,
426 end,
427 read.TemplateStart,
428 read.Strand,
429 std::move(read.Cigar), // we'll get this back
430 true};
431 auto result = ClipToQuery(clipConfig);
432
433 // apply clipping
434 internal::ClipMappedRead(read, std::move(result));
435 }
436
437 void ClipToReference(MappedRead& read, Position start, Position end, bool exciseFlankingInserts)
438 {
439 // return emptied read if clip region is disjoint from
440 if (end <= read.TemplateStart || start >= read.TemplateEnd) {
441 read.Seq.clear();
442 read.Qualities.clear();
443 read.QueryStart = -1;
444 read.QueryEnd = -1;
445 if (read.PulseWidth) {
446 read.PulseWidth->clear();
447 }
448 if (read.IPD) {
449 read.IPD->clear();
450 }
451 read.TemplateStart = -1;
452 read.TemplateEnd = -1;
453 read.Cigar.clear();
454 read.MapQuality = 255;
455 return;
456 }
457
458 // skip out if clip region covers aligned region (no clip needed)
459 if (start <= read.TemplateStart && end >= read.TemplateEnd) {
460 return;
461 }
462
463 // calculate clipping
464 ClipToReferenceConfig clipConfig{
465 ClipToQueryConfig{read.Seq.size(), read.QueryStart, read.QueryEnd, start, end,
466 read.TemplateStart, read.Strand,
467 std::move(read.Cigar), // we'll get this back
468 true},
469 read.TemplateEnd, start, end, exciseFlankingInserts};
470 auto result = ClipToReference(clipConfig);
471
472 // apply clipping
473 internal::ClipMappedRead(read, std::move(result));
474 }
475
476 } // namespace Data
477 } // namespace PacBio