Debian Codegraph @

SeqLib/BamRecord.h

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #ifndef SEQLIB_BAM_RECORD_H
2 #define SEQLIB_BAM_RECORD_H
3
4 #include <stdint.h>
5 //#include <cstdint> //+11
6 #include <vector>
7 #include <iostream>
8 #include <sstream>
9 #include <cassert>
10 #include <algorithm>
11
12 extern "C" {
13 #include "htslib/htslib/hts.h"
14 #include "htslib/htslib/sam.h"
15 #include "htslib/htslib/bgzf.h"
16 #include "htslib/htslib/kstring.h"
17 #include "htslib/htslib/faidx.h"
18
19 }
20
21 #include "SeqLib/SeqLibUtils.h"
22 #include "SeqLib/GenomicRegion.h"
23 #include "SeqLib/UnalignedSequence.h"
24
25 static const char BASES[16] = {' ', 'A', 'C', ' ',
26 'G', ' ', ' ', ' ',
27 'T', ' ', ' ', ' ',
28 ' ', ' ', ' ', 'N'};
29
30 static std::string cigar_delimiters = "MIDNSHPX";
31
32 static const uint8_t CIGTAB[255] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
33 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
34 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
35 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
36 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
37 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
38 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
39 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
40 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
41 #define FRORIENTATION 0
42 #define FFORIENTATION 1
43 #define RFORIENTATION 2
44 #define RRORIENTATION 3
45 #define UDORIENTATION 4
46
47 namespace SeqLib {
48
49 /** Basic container for a single cigar operation
50 *
51 * Stores a single cigar element in a compact 32bit form (same as HTSlib).
52 */
53 class CigarField {
54
55 friend class Cigar;
56
57 public:
58
59 /** Construct the cigar op by type (MIDNSHP=X) and length
60 * @param t Cigar op (MIDNSHP=X)
61 * @param l Cigar length
62 * @exception Throws an invalid_argument if l <= 0 or invalid cigar op
63 */
64 CigarField(char t, uint32_t l);
65
66 /** Construct the cigar op from the raw sam.h uint32_t (first 4 bits op, last 28 len) */
67 CigarField(uint32_t f) : data(f) {}
68
69 /** Return the raw sam.h uint8_t cigar data */
70 inline uint32_t raw() const { return data; }
71
72 /** Print the cigar field (eg 35M) */
73 friend std::ostream& operator<<(std::ostream& out, const CigarField& c);
74
75 /** Return the cigar op type (one of MIDNSHPX) as a char */
76 inline char Type() const { return bam_cigar_opchr(data); }
77
78 /** Return the raw sam.h uint8_t cigar type (bam_cigar_op(data)) */
79 inline uint8_t RawType() const { return bam_cigar_op(data); }
80
81 /** Return the length of the cigar op (eg 35M returns 35) */
82 inline uint32_t Length() const { return bam_cigar_oplen(data); }
83
84 /** Returns true if cigar op matches bases on the reference (MDN=X) */
85 inline bool ConsumesReference() const { return bam_cigar_type(bam_cigar_op(data))&2; }
86
87 /** Returuns true cigar op matches bases on the query (MIS=X) */
88 inline bool ConsumesQuery() const { return bam_cigar_type(bam_cigar_op(data))&1; }
89
90 /** Return whether two CigarField objects have same op and len */
91 inline bool operator==(const CigarField& c) const { return c.Type() == Type() && c.Length() == Length(); }
92
93 /** Return whether two CigarField objects have different op and/or len */
94 inline bool operator!=(const CigarField& c) const { return !(c == *this); }
95
96 private:
97
98 // first 4 bits hold op, last 28 hold len
99 uint32_t data;
100
101 };
102
103 /** CIGAR for a single gapped alignment
104 *
105 * Constructed as a vector of CigarField objects.
106 */
107 class Cigar {
108
109 public:
110
111 /** Construct an empty CIGAR */
112 Cigar() {}
113
114 /** Construct from a CIGAR string
115 * @param cig CIGAR string, e.g. 54M46S
116 */
117 Cigar(const std::string& cig);
118
119 typedef std::vector<CigarField>::iterator iterator; ///< Iterator for move between CigarField ops
120 typedef std::vector<CigarField>::const_iterator const_iterator; ///< Iterator (const) for move between CigarField ops
121 iterator begin() { return m_data.begin(); } ///< Iterator (aka std::vector<CigarField>.begin()
122 iterator end() { return m_data.end(); } ///< Iterator (aka std::vector<CigarField>.end()
123 const_iterator begin() const { return m_data.begin(); } ///< Iterator (aka std::vector<CigarField>.begin()
124 const_iterator end() const { return m_data.end(); } ///< Iterator (aka std::vector<CigarField>.end()
125
126 /** Const reference to last cigar op */
127 inline const CigarField& back() const { return m_data.back(); }
128
129 /** Reference to last cigar op */
130 inline CigarField& back() { return m_data.back(); }
131
132 /** Const reference to first cigar op */
133 inline const CigarField& front() const { return m_data.front(); }
134
135 /** Reference to first cigar op */
136 inline CigarField& front() { return m_data.front(); }
137
138 /** Returns the number of cigar ops */
139 inline size_t size() const { return m_data.size(); }
140
141 /** Returns the i'th cigar op */
142 inline CigarField& operator[](size_t i) { return m_data[i]; }
143
144 /** Returns the i'th cigar op (const) */
145 const CigarField& operator[](size_t i) const { return m_data[i]; }
146
147 /** Return the sum of all of the lengths for all kinds */
148 inline int TotalLength() const {
149 int t = 0;
150 for (Cigar::const_iterator c = m_data.begin(); c != m_data.end(); ++c)
151 //for (auto& c : m_data)
152 t += c->Length();
153 return t;
154 }
155
156 /** Return the number of query-consumed bases */
157 inline int NumQueryConsumed() const {
158 int out = 0;
159 for (Cigar::const_iterator c = m_data.begin(); c != m_data.end(); ++c)
160 if (c->ConsumesQuery())
161 out += c->Length();
162 return out;
163 }
164
165 /** Return the number of reference-consumed bases */
166 inline int NumReferenceConsumed() const {
167 int out = 0;
168 // for (auto& c : m_data)
169 for (Cigar::const_iterator c = m_data.begin(); c != m_data.end(); ++c)
170 if (c->ConsumesReference())
171 out += c->Length();
172 return out;
173 }
174
175 /** Add a new cigar op */
176 inline void add(const CigarField& c) {
177 m_data.push_back(c);
178 }
179
180 /** Return whether two Cigar objects are equivalent */
181 bool operator==(const Cigar& c) const;
182
183 /** Return whether two Cigar objects are not equivalent */
184 bool operator!=(const Cigar& c) const { return !(c == *this); }
185
186 /** Print cigar string (eg 35M25S) */
187 friend std::ostream& operator<<(std::ostream& out, const Cigar& c);
188
189
190 private:
191
192 std::vector<CigarField> m_data; // should make this simpler
193
194 };
195
196 typedef SeqHashMap<std::string, size_t> CigarMap;
197
198 /** Class to store and interact with a SAM alignment record
199 *
200 * HTSLibrary reads are stored in the bam1_t struct. Memory allocation
201 * is taken care of by bam1_t init, and deallocation by destroy_bam1. This
202 * class is a C++ interface that automatically takes care of memory management
203 * for these C allocs/deallocs. The only member of BamRecord is a bam1_t object.
204 * Alloc/dealloc is taken care of by the constructor and destructor.
205 */
206 class BamRecord {
207
208 friend class BLATWraper;
209 friend class BWAWrapper;
210
211 public:
212
213 /** Construct a BamRecord manually from a name, sequence, cigar and location
214 * @param name Name of the read
215 * @param seq Sequence of the read (compsed of ACTG or N).
216 * @param gr Location of the alignment
217 * @param cig Cigar alignment
218 * @exception Throws an invalid_argument exception if length of seq is not commensurate
219 * with number of query-bases consumed in cigar.
220 * @exception Throws an invalid_argument exception if width of gr is not commensurate
221 * with number of reference-bases consumed in cigar.
222 */
223 BamRecord(const std::string& name, const std::string& seq, const GenomicRegion * gr, const Cigar& cig);
224
225 /** Construct an empty BamRecord by calling bam_init1()
226 */
227 void init();
228
229 /** Check if a read is empty (not initialized)
230 * @return true if read was not initialized with any values
231 */
232 bool isEmpty() const { return !b; }
233
234 /** Explicitly pass a bam1_t to the BamRecord.
235 *
236 * The BamRecord now controls the memory, and will delete at destruction
237 * @param a An allocated bam1_t
238 */
239 void assign(bam1_t* a);
240
241 /** Make a BamRecord with no memory allocated and a null header */
242 BamRecord() {}
243
244 /** BamRecord is aligned on reverse strand */
245 inline bool ReverseFlag() const { return b ? ((b->core.flag&BAM_FREVERSE) != 0) : false; }
246
247 /** BamRecord has mate aligned on reverse strand */
248 inline bool MateReverseFlag() const { return b ? ((b->core.flag&BAM_FMREVERSE) != 0) : false; }
249
250 /** BamRecord has is an interchromosomal alignment */
251 inline bool Interchromosomal() const { return b ? b->core.tid != b->core.mtid && PairMappedFlag() : false; }
252
253 /** BamRecord is a duplicate */
254 inline bool DuplicateFlag() const { return b ? ((b->core.flag&BAM_FDUP) != 0) : false; }
255
256 /** BamRecord is a secondary alignment */
257 inline bool SecondaryFlag() const { return b ? ((b->core.flag&BAM_FSECONDARY) != 0) : false; }
258
259 /** BamRecord is paired */
260 inline bool PairedFlag() const { return b ? ((b->core.flag&BAM_FPAIRED) != 0) : false; }
261
262 /** Get the relative pair orientations
263 *
264 * 0 - FR (RFORIENTATION) (lower pos read is Fwd strand, higher is reverse)
265 * 1 - FF (FFORIENTATION)
266 * 2 - RF (RFORIENTATION)
267 * 3 - RR (RRORIENTATION)
268 * 4 - Undefined (UDORIENTATION) (unpaired or one/both is unmapped)
269 */
270 inline int PairOrientation() const {
271 if (!PairMappedFlag())
272 return UDORIENTATION;
273 else if ( (!ReverseFlag() && Position() <= MatePosition() && MateReverseFlag() ) || // read 1
274 (ReverseFlag() && Position() >= MatePosition() && !MateReverseFlag() ) ) // read 2
275 return FRORIENTATION;
276 else if (!ReverseFlag() && !MateReverseFlag())
277 return FFORIENTATION;
278 else if (ReverseFlag() && MateReverseFlag())
279 return RRORIENTATION;
280 else if ( ( ReverseFlag() && Position() < MatePosition() && !MateReverseFlag()) ||
281 (!ReverseFlag() && Position() > MatePosition() && MateReverseFlag()))
282 return RFORIENTATION;
283 assert(false);
284 }
285
286 /** BamRecord is failed QC */
287 inline bool QCFailFlag() const { return b ? ((b->core.flag&BAM_FQCFAIL) != 0) : false; }
288
289 /** BamRecord is supplementary alignment */
290 inline bool SupplementaryFlag() const { return b ? ((b->core.flag&BAM_FSUPPLEMENTARY) != 0) : false; }
291
292 /** BamRecord is mapped */
293 inline bool MappedFlag() const { return b ? ((b->core.flag&BAM_FUNMAP) == 0) : false; }
294
295 /** BamRecord mate is mapped */
296 inline bool MateMappedFlag() const { return b ? ((b->core.flag&BAM_FMUNMAP) == 0) : false; }
297
298 /** BamRecord is mapped and mate is mapped and in pair */
299 inline bool PairMappedFlag() const { return b ? (!(b->core.flag&BAM_FMUNMAP) && !(b->core.flag&BAM_FUNMAP) && (b->core.flag&BAM_FPAIRED) ) : false; }
300
301 /** BamRecord is mapped in proper pair */
302 inline bool ProperPair() const { return b ? (b->core.flag&BAM_FPROPER_PAIR) : false;}
303
304 /** BamRecord has proper orientation (FR) */
305 inline bool ProperOrientation() const {
306 if (!b)
307 return false;
308
309 // mate on diff chrom gets false
310 if (b->core.tid != b->core.mtid)
311 return false;
312
313 // if FR return true
314 if (b->core.pos < b->core.mpos) {
315 return (b->core.flag&BAM_FREVERSE) == 0 && (b->core.flag&BAM_FMREVERSE) != 0 ? true : false;
316 } else {
317 return (b->core.flag&BAM_FREVERSE) == 0 && (b->core.flag&BAM_FMREVERSE) != 0 ? false : true;
318 }
319
320 }
321
322 /** Count the total number of N bases in this sequence */
323 int32_t CountNBases() const;
324
325 /** Trim the sequence down by removing bases from ends with low quality scores. Stores the
326 * trimmed sequence in the GV tag, but does not affect any other part of read.
327 * @param qualTrim Minimal quality score, zero-based (eg # == 2)
328 * @param startpoint Returns the new starting point for the sequence
329 * @param endpoint Return the new ending point for the sequence
330 */
331 void QualityTrimmedSequence(int32_t qualTrim, int32_t& startpoint, int32_t& endpoint) const;
332
333 /** Retrieve the quality trimmed seqeuence from QT tag if made. Otherwise return normal seq */
334 std::string QualitySequence() const;
335
336 /** Get the alignment position */
337 inline int32_t Position() const { return b ? b->core.pos : -1; }
338
339 /** Get the alignment position, including soft clips */
340 int32_t PositionWithSClips() const;
341
342 /** Get the alignment position of mate */
343 inline int32_t MatePosition() const { return b ? b->core.mpos: -1; }
344
345 /** Count the number of secondary alignments by looking at XA tag.
346 * @note A secondary alignment is an alternative mapping. This may not
347 * work for non-BWA aligners that may not place the XA tag.
348 */
349 int32_t CountBWASecondaryAlignments() const;
350
351 /** Count the number of chimeric alignments by looking at XP and SA tags
352 * @note A secondary alignment is an alternative mapping. This may not
353 * work for non-BWA aligners that may not place the XP/SA tags. BWA-MEM
354 * used the XP tag prior to v0.7.5, and SA aftewards.
355 */
356 int32_t CountBWAChimericAlignments() const;
357
358 /** Get the end of the alignment */
359 int32_t PositionEnd() const;
360
361 /** Get the end of the alignment, including soft clips */
362 int32_t PositionEndWithSClips() const;
363
364 /** Get the end of the aligment mate pair */
365 int32_t PositionEndMate() const;
366
367 /** Get the chromosome ID of the read */
368 inline int32_t ChrID() const { return b ? b->core.tid : -1; }
369
370 /** Get the chrosome ID of the mate read */
371 inline int32_t MateChrID() const { return b ? b->core.mtid : -1; }
372
373 /** Get the mapping quality */
374 inline int32_t MapQuality() const { return b ? b->core.qual : -1; }
375
376 /** Set the qc fail flag on/off (true -> on) */
377 inline void SetQCFail(bool f) {
378 if (f)
379 b->core.flag |= BAM_FQCFAIL;
380 else
381 b->core.flag &= ~BAM_FQCFAIL;
382 }
383
384 /** Set the mapping quality */
385 inline void SetMapQuality(int32_t m) { if (b) b->core.qual = m; }
386
387 /** Set the chr id */
388 inline void SetChrID(int32_t i) { b->core.tid = i; }
389
390 /** Set the chr id of mate */
391 inline void SetChrIDMate(int32_t i) { b->core.mtid = i; }
392
393 /** Set the position of the mate read */
394 inline void SetPositionMate(int32_t i) { b->core.mpos = i; }
395
396 /** Set the pair mapped flag on/off (true -> on) */
397 inline void SetPairMappedFlag(bool f) {
398 if (f)
399 b->core.flag |= BAM_FPAIRED;
400 else
401 b->core.flag &= ~BAM_FPAIRED;
402 }
403
404 /** Set the mate reverse flag on/off (true -> on) */
405 inline void SetMateReverseFlag(bool f) {
406 if (f)
407 b->core.flag |= BAM_FMREVERSE;
408 else
409 b->core.flag &= ~BAM_FMREVERSE;
410 }
411
412 /** Get the number of cigar fields */
413 inline int32_t CigarSize() const { return b ? b->core.n_cigar : -1; }
414
415 /** Check if this read is first in pair */
416 inline bool FirstFlag() const { return (b->core.flag&BAM_FREAD1); }
417
418 /** Get the qname of this read as a string */
419 inline std::string Qname() const { return std::string(bam_get_qname(b)); }
420
421 /** Get the qname of this read as a char array */
422 inline char* QnameChar() const { return bam_get_qname(b); }
423
424 /** Get the full alignment flag for this read */
425 inline uint32_t AlignmentFlag() const { return b->core.flag; }
426
427 /** Get the insert size for this read */
428 inline int32_t InsertSize() const { return b->core.isize; }
429
430 /** Get the read group, first from qname, then by RG tag
431 * @return empty string if no readgroup found
432 */
433 inline std::string ParseReadGroup() const {
434
435 // try to get from RG tag first
436 std::string RG;
437 if (GetZTag("RG", RG))
438 return RG;
439
440 // try to get the read group tag from qname second
441 std::string qn = Qname();
442 size_t posr = qn.find(":", 0);
443 return (posr != std::string::npos) ? qn.substr(0, posr) : "NA";
444 }
445
446 /** Get the insert size, absolute value, and always taking into account read length */
447 inline int32_t FullInsertSize() const {
448
449 if (b->core.tid != b->core.mtid || !PairMappedFlag())
450 return 0;
451
452 return std::abs(b->core.pos - b->core.mpos) + GetCigar().NumQueryConsumed();
453
454 }
455
456 /** Get the number of query bases of this read (aka length) */
457 inline int32_t Length() const { return b->core.l_qseq; }
458
459 /** Append a tag with new value, delimited by 'x' */
460 void SmartAddTag(const std::string& tag, const std::string& val);
461
462 /** Set the query name */
463 void SetQname(const std::string& n);
464
465 /** Set the quality scores
466 * @param n String of quality scores or empty string
467 * @param offset Offset parameter for encoding (eg 33)
468 * @exception Throws an invalid_argument if n is non-empty
469 * and different length than sequence
470 */
471 void SetQualities(const std::string& n, int offset);
472
473 /** Set the sequence name
474 * @param seq Sequence in upper-case (ACTGN) letters.
475 */
476 void SetSequence(const std::string& seq);
477
478 /** Set the cigar field explicitly
479 * @param c Cigar operation to set
480 * @note Will not check if the cigar ops are consistent with
481 * the length of the sequence.
482 */
483 void SetCigar(const Cigar& c);
484
485 /** Print a SAM-lite record for this alignment */
486 friend std::ostream& operator<<(std::ostream& out, const BamRecord &r);
487
488 /** Return read as a GenomicRegion */
489 GenomicRegion AsGenomicRegion() const;
490
491 /** Return mate read as a GenomicRegion */
492 GenomicRegion AsGenomicRegionMate() const;
493
494 /** Return the number of "aligned bases" in the same style as BamTools
495 *
496 * BamTools reports AlignedBases, which for example returns the literal strings (for diff CIGARs):
497 * 3S5M - CTG
498 * 5M - CTAGC
499 * 3M1D3M - ATG-TGA
500 * 3M1I3M - ATGCTGA
501 *
502 * @return The number of M, D, X, = and I bases
503 */
504 inline int NumAlignedBases() const {
505 int out = 0;
506 uint32_t* c = bam_get_cigar(b);
507 for (size_t i = 0; i < b->core.n_cigar; i++)
508 if (bam_cigar_opchr(c[i]) == 'M' ||
509 bam_cigar_opchr(c[i]) == 'I' ||
510 bam_cigar_opchr(c[i]) == '=' ||
511 bam_cigar_opchr(c[i]) == 'X' ||
512 bam_cigar_opchr(c[i]) == 'D')
513 out += bam_cigar_oplen(c[i]);
514 return out;
515 }
516
517
518 /** Return the max single insertion size on this cigar */
519 inline uint32_t MaxInsertionBases() const {
520 uint32_t* c = bam_get_cigar(b);
521 uint32_t imax = 0;
522 for (size_t i = 0; i < b->core.n_cigar; i++)
523 if (bam_cigar_opchr(c[i]) == 'I')
524 imax = std::max(bam_cigar_oplen(c[i]), imax);
525 return imax;
526 }
527
528 /** Return the max single deletion size on this cigar */
529 inline uint32_t MaxDeletionBases() const {
530 uint32_t* c = bam_get_cigar(b);
531 uint32_t dmax = 0;
532 for (size_t i = 0; i < b->core.n_cigar; i++)
533 if (bam_cigar_opchr(c[i]) == 'D')
534 dmax = std::max(bam_cigar_oplen(c[i]), dmax);
535 return dmax;
536 }
537
538 /** Get the number of matched bases in this alignment */
539 inline uint32_t NumMatchBases() const {
540 uint32_t* c = bam_get_cigar(b);
541 uint32_t dmax = 0;
542 for (size_t i = 0; i < b->core.n_cigar; i++)
543 if (bam_cigar_opchr(c[i]) == 'M')
544 dmax += bam_cigar_oplen(c[i]);
545 return dmax;
546 }
547
548
549 /** Retrieve the CIGAR as a more managable Cigar structure */
550 Cigar GetCigar() const {
551 uint32_t* c = bam_get_cigar(b);
552 Cigar cig;
553 for (size_t k = 0; k < b->core.n_cigar; ++k) {
554 cig.add(CigarField(c[k]));
555 }
556 return cig;
557 }
558
559 /** Retrieve the inverse of the CIGAR as a more managable Cigar structure */
560 Cigar GetReverseCigar() const {
561 uint32_t* c = bam_get_cigar(b);
562 Cigar cig;
563 for (int k = b->core.n_cigar - 1; k >= 0; --k)
564 cig.add(CigarField(c[k]));
565 return cig;
566 }
567
568 /** Remove the sequence, quality and alignment tags.
569 * Make a more compact alignment stucture, without the string data
570 */
571 void ClearSeqQualAndTags();
572
573 /** Retrieve the sequence of this read as a string (ACTGN) */
574 std::string Sequence() const;
575
576 /** Return the mean quality score
577 */
578 double MeanPhred() const;
579
580 /** Performa a Smith-Waterman alignment between two strings
581 * @param name Name of the query sequence to align
582 * @param seq Sequence (ACTGN) of the query string
583 * @param ref Sequence (ACTGN) of the reference string
584 * @param gr Location of the reference string. The alignment record after Smith-Waterman alignment
585 * will be relative to this location.
586 */
587 BamRecord(const std::string& name, const std::string& seq, const std::string& ref, const GenomicRegion * gr);
588
589 /** Get the quality scores of this read as a string
590 * @param offset Encoding offset for phred quality scores. Default 33
591 * @return Qualties scores after converting offset. If first char is empty, returns empty string
592 */
593 inline std::string Qualities(int offset = 33) const {
594 uint8_t * p = bam_get_qual(b);
595 if (!p)
596 return std::string();
597 //if (!p[0])
598 // return std::string();
599 std::string out(b->core.l_qseq, ' ');
600 for (int32_t i = 0; i < b->core.l_qseq; ++i)
601 out[i] = (char)(p[i] + offset);
602 return out;
603 }
604
605 /** Get the start of the alignment on the read, by removing soft-clips
606 * Do this in the reverse orientation though.
607 */
608 inline int32_t AlignmentPositionReverse() const {
609 uint32_t* c = bam_get_cigar(b);
610 int32_t p = 0;
611 for (int32_t i = b->core.n_cigar - 1; i >= 0; --i) {
612 if ( (bam_cigar_opchr(c[i]) == 'S') || (bam_cigar_opchr(c[i]) == 'H'))
613 p += bam_cigar_oplen(c[i]);
614 else // not a clip, so stop counting
615 break;
616 }
617 return p;
618 }
619
620 /** Get the end of the alignment on the read, by removing soft-clips
621 * Do this in the reverse orientation though.
622 */
623 inline int32_t AlignmentEndPositionReverse() const {
624 uint32_t* c = bam_get_cigar(b);
625 int32_t p = 0;
626 for (size_t i = 0; i < b->core.n_cigar; ++i) { // loop from the end
627 if ( (bam_cigar_opchr(c[i]) == 'S') || (bam_cigar_opchr(c[i]) == 'H'))
628 p += bam_cigar_oplen(c[i]);
629 else // not a clip, so stop counting
630 break;
631 }
632 return (b->core.l_qseq - p);
633 }
634
635
636 /** Get the start of the alignment on the read, by removing soft-clips
637 */
638 inline int32_t AlignmentPosition() const {
639 uint32_t* c = bam_get_cigar(b);
640 int32_t p = 0;
641 for (size_t i = 0; i < b->core.n_cigar; ++i) {
642 if (bam_cigar_opchr(c[i]) == 'S')
643 p += bam_cigar_oplen(c[i]);
644 else if (bam_cigar_opchr(c[i]) != 'H')
645 break;
646 }
647 return p;
648 }
649
650 /** Get the end of the alignment on the read, by removing soft-clips
651 */
652 inline int32_t AlignmentEndPosition() const {
653 uint32_t* c = bam_get_cigar(b);
654 int32_t p = 0;
655 for (int32_t i = b->core.n_cigar - 1; i >= 0; --i) { // loop from the end
656 if ( (bam_cigar_opchr(c[i]) == 'S') || (bam_cigar_opchr(c[i]) == 'H'))
657 p += bam_cigar_oplen(c[i]);
658 else // not a clip, so stop counting
659 break;
660 }
661 return (b->core.l_qseq - p);
662 }
663
664 /** Get the number of soft clipped bases */
665 inline int32_t NumSoftClip() const {
666 int32_t p = 0;
667 uint32_t* c = bam_get_cigar(b);
668 for (size_t i = 0; i < b->core.n_cigar; ++i)
669 if (bam_cigar_opchr(c[i]) == 'S')
670 p += bam_cigar_oplen(c[i]);
671 return p;
672 }
673
674 /** Get the number of hard clipped bases */
675 inline int32_t NumHardClip() const {
676 int32_t p = 0;
677 uint32_t* c = bam_get_cigar(b);
678 for (size_t i = 0; i < b->core.n_cigar; ++i)
679 if (bam_cigar_opchr(c[i]) == 'H')
680 p += bam_cigar_oplen(c[i]);
681 return p;
682 }
683
684
685 /** Get the number of clipped bases (hard clipped and soft clipped) */
686 inline int32_t NumClip() const {
687 int32_t p = 0;
688 uint32_t* c = bam_get_cigar(b);
689 for (size_t i = 0; i < b->core.n_cigar; ++i)
690 if ( (bam_cigar_opchr(c[i]) == 'S') || (bam_cigar_opchr(c[i]) == 'H') )
691 p += bam_cigar_oplen(c[i]);
692 return p;
693 }
694
695 /** Get a string (Z) tag
696 * @param tag Name of the tag. eg "XP"
697 * @param s The string to be filled in with the tag information
698 * @return Returns true if the tag is present, even if empty. Return false if no tag or not a Z tag.
699 */
700 bool GetZTag(const std::string& tag, std::string& s) const;
701
702 /** Get a string of either Z, f or i type. Useful if tag type not known at compile time.
703 * @param tag Name of the tag. eg "XP"
704 * @param s The string to be filled in with the tag information
705 * @return Returns true if the tag is present and is either Z or i, even if empty. Return false if no tag or not Z or i.
706 */
707 bool GetTag(const std::string& tag, std::string& s) const;
708
709 /** Get a vector of type int from a Z tag delimited by "^"
710 * Smart-tags allow one to store vectors of strings, ints or doubles in the alignment tags, and
711 * do not require an additional data structure on top of bseq1_t.
712 * @param tag Name of the tag eg "AL"
713 * @return A vector of ints, retrieved from the x delimited Z tag
714 * @exception Throws an invalid_argument if cannot convert delimited field val to int
715 */
716 std::vector<int> GetSmartIntTag(const std::string& tag) const;
717
718 /** Get a vector of type double from a Z tag delimited by "x"
719 * Smart-tags allow one to store vectors of string, ints or doubles in the alignment tags, and
720 * do not require an additional data structure on top of bseq1_t.
721 * @param tag Name of the tag eg "AL"
722 * @return A vector of double elems, retrieved from the "^" delimited Z tag
723 * @exception Throws an invalid_argument if cannot convert delimited field val to double
724 */
725 std::vector<double> GetSmartDoubleTag(const std::string& tag) const;
726
727 /** Get a vector of strings from a Z tag delimited by "^"
728 * Smart-tags allow one to store vectors of strings, ints or doubles in the alignment tags, and
729 * do not require an additional data structure on top of bseq1_t.
730 * @param tag Name of the tag eg "CN"
731 * @return A vector of strngs, retrieved from the x delimited Z tag
732 */
733 std::vector<std::string> GetSmartStringTag(const std::string& tag) const;
734
735 /** Get an int (i) tag
736 * @param tag Name of the tag. eg "XP"
737 * @param t Value to be filled in with the tag value.
738 * @return Return true if the tag exists.
739 */
740 inline bool GetIntTag(const std::string& tag, int32_t& t) const {
741 uint8_t* p = bam_aux_get(b.get(),tag.c_str());
742 if (!p)
743 return false;
744 t = bam_aux2i(p);
745 int type = *p++;
746 if (!(type == 'i' || type == 'C' || type=='S' || type=='s' || type =='I' || type=='c'))
747 return false;
748
749 return true;
750 }
751
752 /** Get a float (f) tag
753 * @param tag Name of the tag. eg "AS"
754 * @param t Value to be filled in with the tag value.
755 * @return Return true if the tag exists.
756 */
757 inline bool GetFloatTag(const std::string& tag, float& t) const {
758 uint8_t* p = bam_aux_get(b.get(),tag.c_str());
759 if (!p)
760 return false;
761
762 t = bam_aux2f(p);
763 int type = *p;
764 type = *p++;
765 if (!(type == 'f' || type == 'd'))
766 return false;
767
768 return true;
769 }
770
771 /** Add a string (Z) tag
772 * @param tag Name of the tag. eg "XP"
773 * @param val Value for the tag
774 */
775 void AddZTag(std::string tag, std::string val);
776
777 /** Add an int (i) tag
778 * @param tag Name of the tag. eg "XP"
779 * @param val Value for the tag
780 */
781 inline void AddIntTag(const std::string& tag, int32_t val) {
782 bam_aux_append(b.get(), tag.data(), 'i', 4, (uint8_t*)&val);
783 }
784
785 /** Set the chr id number
786 * @param id Chromosome id. Typically is 0 for chr1, etc
787 */
788 inline void SetID(int32_t id) {
789 b->core.tid = id;
790 }
791
792 /** Set the alignment start position
793 * @param pos Alignment start position
794 */
795 inline void SetPosition(int32_t pos) {
796 b->core.pos = pos;
797 }
798
799 /** Convert CIGAR to a string
800 */
801 inline std::string CigarString() const {
802 std::stringstream cig;
803 uint32_t* c = bam_get_cigar(b);
804 for (size_t k = 0; k < b->core.n_cigar; ++k)
805 cig << bam_cigar_oplen(c[k]) << "MIDNSHP=XB"[c[k]&BAM_CIGAR_MASK];
806 return cig.str();
807 }
808
809 /** Return a human readable chromosome name assuming chr is indexed
810 * from 0 (eg id 0 return "1")
811 * @note This is a quick convienence function, and is not robust to non-numbered
812 * chromosomes (eg chrX becomes 23). For accurate string representation of
813 * any chromosomes, use the full ChrName with BamHeader input.
814 */
815 inline std::string ChrName() const {
816 std::stringstream ss;
817 ss << (b->core.tid + 1);
818
819 return ss.str();
820 //return std::to_string(b->core.tid + 1); //c++11
821 }
822
823 /** Retrieve the human readable chromosome name.
824 * @param h Dictionary for chr name lookup. If it is empty, assumes this is chr1 based reference.
825 * @exception Throws an out_of_range exception if chr id is not in dictionary
826 * @return Empty string if chr id < 0, otherwise chromosome name from dictionary.
827 */
828 inline std::string ChrName(const SeqLib::BamHeader& h) const {
829 if (b->core.tid < 0)
830 return std::string();
831
832 if (!h.isEmpty())
833 return h.IDtoName(b->core.tid);
834
835 // c++98
836 std::stringstream ss;
837 ss << b->core.tid;
838
839 // no header, assume zero based
840 return ss.str(); //std::to_string(b->core.tid + 1);
841
842 }
843
844 /** Return a short description (chr:pos) of this read */
845 inline std::string Brief() const {
846 //if (!h)
847 // c++11
848 // return(std::to_string(b->core.tid + 1) + ":" + AddCommas<int32_t>(b->core.pos) + "(" + ((b->core.flag&BAM_FREVERSE) != 0 ? "+" : "-") + ")");
849 // c++98
850 std::stringstream ss;
851 ss << (b->core.tid + 1) << ":" << AddCommas(b->core.pos) << "(" << ((b->core.flag&BAM_FREVERSE) != 0 ? "+" : "-") << ")";
852 return ss.str();
853 //else
854 // return(std::string(h->target_name[b->core.tid]) + ":" + AddCommas<int32_t>(b->core.pos) + "(" + ((b->core.flag&BAM_FREVERSE) != 0 ? "+" : "-") + ")");
855 }
856
857 /** Return a short description (chr:pos) of this read's mate */
858 inline std::string BriefMate() const {
859 //if (!h)
860 // c++11
861 // return(std::to_string(b->core.mtid + 1) + ":" + AddCommas<int32_t>(b->core.mpos) + "(" + ((b->core.flag&BAM_FMREVERSE) != 0 ? "+" : "-") + ")");
862 std::stringstream ss;
863 ss << (b->core.mtid + 1) << ":" << AddCommas(b->core.mpos) << "(" << ((b->core.flag&BAM_FMREVERSE) != 0 ? "+" : "-") << ")";
864 return ss.str();
865 //else
866 // return(std::string(h->target_name[b->core.mtid]) + ":" + AddCommas<int32_t>(b->core.mpos) + "(" + ((b->core.flag&BAM_FMREVERSE) != 0 ? "+" : "-") + ")");
867 }
868
869 /** Strip a particular alignment tag
870 * @param tag Tag to remove
871 */
872 inline void RemoveTag(const char* tag) {
873 uint8_t* p = bam_aux_get(b.get(), tag);
874 if (p)
875 bam_aux_del(b.get(), p);
876 }
877
878 /** Strip all of the alignment tags */
879 inline void RemoveAllTags() {
880 size_t keep = (b->core.n_cigar<<2) + b->core.l_qname + ((b->core.l_qseq + 1)>>1) + b->core.l_qseq;
881 b->data = (uint8_t*)realloc(b->data, keep); // free the end, which has aux data
882 b->l_data = keep;
883 b->m_data = b->l_data;
884 }
885
886 /** Return the raw pointer */
887 inline bam1_t* raw() const { return b.get(); }
888
889 /** Return the number of bases on the query that are covered by a match (M) on both reads
890 * This is for tracking overlapping coverage on the reads, regardless of their alignment locations.
891 * For instance, two reads with 101M will have overlapping coverage of 101, regardless of alignment location.
892 * A read with 50S50M and 50M50S will have 0 overlapping coverage.
893 */
894 int OverlappingCoverage(const BamRecord& r) const;
895
896 /** Return the shared pointer */
897 SeqPointer<bam1_t> shared_pointer() const { return b; }
898
899 protected:
900
901 SeqPointer<bam1_t> b; // bam1_t shared pointer
902
903 };
904
905 typedef std::vector<BamRecord> BamRecordVector; ///< Store a vector of alignment records
906
907 typedef std::vector<BamRecordVector> BamRecordClusterVector; ///< Store a vector of alignment vectors
908
909 /** @brief Sort methods for alignment records
910 */
911 namespace BamRecordSort {
912
913 /** @brief Sort by read position
914 */
915 struct ByReadPosition
916 {
917 bool operator()( const BamRecord& lx, const BamRecord& rx ) const {
918 return (lx.ChrID() < rx.ChrID()) || (lx.ChrID() == rx.ChrID() && lx.Position() < rx.Position());
919 }
920 };
921
922 /** @brief Sort by mate position
923 */
924 struct ByMatePosition
925 {
926 bool operator()( const BamRecord& lx, const BamRecord& rx ) const {
927 return (lx.MateChrID() < rx.MateChrID()) || (lx.MateChrID() == rx.MateChrID() && lx.MatePosition() < rx.MatePosition());
928 }
929 };
930
931 }
932
933 }
934 #endif