Debian Codegraph @

pysam/libcalignedsegment.pyx

raw
1 # cython: language_level=3
2 # cython: embedsignature=True
3 # cython: profile=True
4 ###############################################################################
5 ###############################################################################
6 # Cython wrapper for SAM/BAM/CRAM files based on htslib
7 ###############################################################################
8 # The principal classes defined in this module are:
9 #
10 # class AlignedSegment an aligned segment (read)
11 #
12 # class PileupColumn a collection of segments (PileupRead) aligned to
13 # a particular genomic position.
14 #
15 # class PileupRead an AlignedSegment aligned to a particular genomic
16 # position. Contains additional attributes with respect
17 # to this.
18 #
19 # Additionally this module defines numerous additional classes that are part
20 # of the internal API. These are:
21 #
22 # Various iterator classes to iterate over alignments in sequential (IteratorRow)
23 # or in a stacked fashion (IteratorColumn):
24 #
25 # class IteratorRow
26 # class IteratorRowRegion
27 # class IteratorRowHead
28 # class IteratorRowAll
29 # class IteratorRowAllRefs
30 # class IteratorRowSelection
31 #
32 ###############################################################################
33 #
34 # The MIT License
35 #
36 # Copyright (c) 2015 Andreas Heger
37 #
38 # Permission is hereby granted, free of charge, to any person obtaining a
39 # copy of this software and associated documentation files (the "Software"),
40 # to deal in the Software without restriction, including without limitation
41 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
42 # and/or sell copies of the Software, and to permit persons to whom the
43 # Software is furnished to do so, subject to the following conditions:
44 #
45 # The above copyright notice and this permission notice shall be included in
46 # all copies or substantial portions of the Software.
47 #
48 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
51 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
53 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
54 # DEALINGS IN THE SOFTWARE.
55 #
56 ###############################################################################
57 import re
58 import array
59 import json
60 import string
61 import ctypes
62 import struct
63
64 cimport cython
65 from cpython cimport array as c_array
66 from cpython cimport PyBytes_FromStringAndSize
67 from libc.string cimport memset, strchr
68 from libc.stdint cimport INT8_MIN, INT16_MIN, INT32_MIN, \
69 INT8_MAX, INT16_MAX, INT32_MAX, \
70 UINT8_MAX, UINT16_MAX, UINT32_MAX
71
72 from pysam.libchtslib cimport HTS_IDX_NOCOOR
73 from pysam.libcutils cimport force_bytes, force_str, \
74 charptr_to_str, charptr_to_bytes
75
76 # Constants for binary tag conversion
77 cdef char * htslib_types = 'cCsSiIf'
78 cdef char * parray_types = 'bBhHiIf'
79
80 # translation tables
81
82 # cigar code to character and vice versa
83 cdef char* CODE2CIGAR= "MIDNSHP=XB"
84 cdef int NCIGAR_CODES = 10
85
86 CIGAR2CODE = dict([y, x] for x, y in enumerate(CODE2CIGAR))
87 CIGAR_REGEX = re.compile("(\d+)([MIDNSHP=XB])")
88
89 # names for keys in dictionary representation of an AlignedSegment
90 KEY_NAMES = ["name", "flag", "ref_name", "ref_pos", "map_quality", "cigar",
91 "next_ref_name", "next_ref_pos", "length", "seq", "qual", "tags"]
92
93 #####################################################################
94 # C multiplication with wrapping around
95 cdef inline uint32_t c_mul(uint32_t a, uint32_t b):
96 return (a * b) & 0xffffffff
97
98
99 cdef inline uint8_t tolower(uint8_t ch):
100 if ch >= 65 and ch <= 90:
101 return ch + 32
102 else:
103 return ch
104
105
106 cdef inline uint8_t toupper(uint8_t ch):
107 if ch >= 97 and ch <= 122:
108 return ch - 32
109 else:
110 return ch
111
112
113 cdef inline uint8_t strand_mark_char(uint8_t ch, bam1_t *b):
114 if ch == b'=':
115 if bam_is_rev(b):
116 return b','
117 else:
118 return b'.'
119 else:
120 if bam_is_rev(b):
121 return tolower(ch)
122 else:
123 return toupper(ch)
124
125
126 cdef inline bint pileup_base_qual_skip(const bam_pileup1_t * p, uint32_t threshold):
127 cdef uint32_t c
128 if p.qpos < p.b.core.l_qseq:
129 c = bam_get_qual(p.b)[p.qpos]
130 else:
131 c = 0
132 if c < threshold:
133 return True
134 return False
135
136
137 cdef inline char map_typecode_htslib_to_python(uint8_t s):
138 """map an htslib typecode to the corresponding python typecode
139 to be used in the struct or array modules."""
140
141 # map type from htslib to python array
142 cdef char * f = strchr(htslib_types, s)
143
144 if f == NULL:
145 return 0
146 return parray_types[f - htslib_types]
147
148
149 cdef inline uint8_t map_typecode_python_to_htslib(char s):
150 """determine value type from type code of array"""
151 cdef char * f = strchr(parray_types, s)
152 if f == NULL:
153 return 0
154 return htslib_types[f - parray_types]
155
156
157 cdef inline void update_bin(bam1_t * src):
158 if src.core.flag & BAM_FUNMAP:
159 # treat alignment as length of 1 for unmapped reads
160 src.core.bin = hts_reg2bin(
161 src.core.pos,
162 src.core.pos + 1,
163 14,
164 5)
165 elif pysam_get_n_cigar(src):
166 src.core.bin = hts_reg2bin(
167 src.core.pos,
168 bam_endpos(src),
169 14,
170 5)
171 else:
172 src.core.bin = hts_reg2bin(
173 src.core.pos,
174 src.core.pos + 1,
175 14,
176 5)
177
178
179 # optional tag data manipulation
180 cdef convert_binary_tag(uint8_t * tag):
181 """return bytesize, number of values and array of values
182 in aux_data memory location pointed to by tag."""
183 cdef uint8_t auxtype
184 cdef uint8_t byte_size
185 cdef int32_t nvalues
186 # get byte size
187 auxtype = tag[0]
188 byte_size = aux_type2size(auxtype)
189 tag += 1
190 # get number of values in array
191 nvalues = (<int32_t*>tag)[0]
192 tag += 4
193
194 # define python array
195 cdef c_array.array c_values = array.array(
196 chr(map_typecode_htslib_to_python(auxtype)))
197 c_array.resize(c_values, nvalues)
198
199 # copy data
200 memcpy(c_values.data.as_voidptr, <uint8_t*>tag, nvalues * byte_size)
201
202 # no need to check for endian-ness as bam1_core_t fields
203 # and aux_data are in host endian-ness. See sam.c and calls
204 # to swap_data
205 return byte_size, nvalues, c_values
206
207
208 cdef inline uint8_t get_tag_typecode(value, value_type=None):
209 """guess type code for a *value*. If *value_type* is None, the type
210 code will be inferred based on the Python type of *value*
211
212 """
213 # 0 is unknown typecode
214 cdef char typecode = 0
215
216 if value_type is None:
217 if isinstance(value, int):
218 if value < 0:
219 if value >= INT8_MIN:
220 typecode = b'c'
221 elif value >= INT16_MIN:
222 typecode = b's'
223 elif value >= INT32_MIN:
224 typecode = b'i'
225 # unsigned ints
226 else:
227 if value <= UINT8_MAX:
228 typecode = b'C'
229 elif value <= UINT16_MAX:
230 typecode = b'S'
231 elif value <= UINT32_MAX:
232 typecode = b'I'
233 elif isinstance(value, float):
234 typecode = b'f'
235 elif isinstance(value, str):
236 typecode = b'Z'
237 elif isinstance(value, bytes):
238 typecode = b'Z'
239 elif isinstance(value, array.array) or \
240 isinstance(value, list) or \
241 isinstance(value, tuple):
242 typecode = b'B'
243 else:
244 if value_type in 'aAsSIcCZidfH':
245 typecode = force_bytes(value_type)[0]
246
247 return typecode
248
249
250 cdef inline uint8_t get_btag_typecode(value, min_value=None, max_value=None):
251 '''returns the value typecode of a value.
252
253 If max is specified, the appropriate type is returned for a range
254 where value is the minimum.
255
256 Note that this method returns types from the extended BAM alphabet
257 of types that includes tags that are not part of the SAM
258 specification.
259 '''
260
261
262 cdef uint8_t typecode
263
264 t = type(value)
265
266 if t is float:
267 typecode = b'f'
268 elif t is int:
269 if max_value is None:
270 max_value = value
271 if min_value is None:
272 min_value = value
273 # signed ints
274 if min_value < 0:
275 if min_value >= INT8_MIN and max_value <= INT8_MAX:
276 typecode = b'c'
277 elif min_value >= INT16_MIN and max_value <= INT16_MAX:
278 typecode = b's'
279 elif min_value >= INT32_MIN or max_value <= INT32_MAX:
280 typecode = b'i'
281 else:
282 raise ValueError(
283 "at least one signed integer out of range of "
284 "BAM/SAM specification")
285 # unsigned ints
286 else:
287 if max_value <= UINT8_MAX:
288 typecode = b'C'
289 elif max_value <= UINT16_MAX:
290 typecode = b'S'
291 elif max_value <= UINT32_MAX:
292 typecode = b'I'
293 else:
294 raise ValueError(
295 "at least one integer out of range of BAM/SAM specification")
296 else:
297 # Note: hex strings (H) are not supported yet
298 if t is not bytes:
299 value = value.encode('ascii')
300 if len(value) == 1:
301 typecode = b'A'
302 else:
303 typecode = b'Z'
304
305 return typecode
306
307
308 # mapping python array.array and htslib typecodes to struct typecodes
309 DATATYPE2FORMAT = {
310 ord('c'): ('b', 1),
311 ord('C'): ('B', 1),
312 ord('s'): ('h', 2),
313 ord('S'): ('H', 2),
314 ord('i'): ('i', 4),
315 ord('I'): ('I', 4),
316 ord('f'): ('f', 4),
317 ord('d'): ('d', 8),
318 ord('A'): ('c', 1),
319 ord('a'): ('c', 1)}
320
321
322 cdef inline pack_tags(tags):
323 """pack a list of tags. Each tag is a tuple of (tag, tuple).
324
325 Values are packed into the most space efficient data structure
326 possible unless the tag contains a third field with the typecode.
327
328 Returns a format string and the associated list of arguments to be
329 used in a call to struct.pack_into.
330 """
331 fmts, args = ["<"], []
332
333 # htslib typecode
334 cdef uint8_t typecode
335 for tag in tags:
336
337 if len(tag) == 2:
338 pytag, value = tag
339 valuetype = None
340 elif len(tag) == 3:
341 pytag, value, valuetype = tag
342 else:
343 raise ValueError("malformatted tag: %s" % str(tag))
344
345 if valuetype is None:
346 typecode = 0
347 else:
348 # only first character in valuecode matters
349 typecode = force_bytes(valuetype)[0]
350
351 pytag = force_bytes(pytag)
352 pytype = type(value)
353
354 if pytype is tuple or pytype is list:
355 # binary tags from tuples or lists
356 if not typecode:
357 # automatically determine value type - first value
358 # determines type. If there is a mix of types, the
359 # result is undefined.
360 typecode = get_btag_typecode(min(value),
361 min_value=min(value),
362 max_value=max(value))
363
364 if typecode not in DATATYPE2FORMAT:
365 raise ValueError("invalid value type '{}'".format(chr(typecode)))
366
367 datafmt = "2sBBI%i%s" % (len(value), DATATYPE2FORMAT[typecode][0])
368 args.extend([pytag[:2],
369 ord("B"),
370 typecode,
371 len(value)] + list(value))
372
373 elif isinstance(value, array.array):
374 # binary tags from arrays
375 if typecode == 0:
376 typecode = map_typecode_python_to_htslib(ord(value.typecode))
377
378 if typecode == 0:
379 raise ValueError("unsupported type code '{}'".format(value.typecode))
380
381 if typecode not in DATATYPE2FORMAT:
382 raise ValueError("invalid value type '{}'".format(chr(typecode)))
383
384 # use array.tostring() to retrieve byte representation and
385 # save as bytes
386 datafmt = "2sBBI%is" % (len(value) * DATATYPE2FORMAT[typecode][1])
387 args.extend([pytag[:2],
388 ord("B"),
389 typecode,
390 len(value),
391 value.tobytes()])
392
393 else:
394 if typecode == 0:
395 typecode = get_tag_typecode(value)
396 if typecode == 0:
397 raise ValueError("could not deduce typecode for value {}".format(value))
398
399 if typecode == b'a' or typecode == b'A' or typecode == b'Z' or typecode == b'H':
400 value = force_bytes(value)
401
402 if typecode == b"a":
403 typecode = b'A'
404
405 if typecode == b'Z' or typecode == b'H':
406 datafmt = "2sB%is" % (len(value)+1)
407 elif typecode in DATATYPE2FORMAT:
408 datafmt = "2sB%s" % DATATYPE2FORMAT[typecode][0]
409 else:
410 raise ValueError("invalid value type '{}'".format(chr(typecode)))
411
412 args.extend([pytag[:2],
413 typecode,
414 value])
415
416 fmts.append(datafmt)
417
418 return "".join(fmts), args
419
420
421 cdef inline int32_t calculateQueryLengthWithoutHardClipping(bam1_t * src):
422 """return query length computed from CIGAR alignment.
423
424 Length ignores hard-clipped bases.
425
426 Return 0 if there is no CIGAR alignment.
427 """
428
429 cdef uint32_t * cigar_p = pysam_bam_get_cigar(src)
430
431 if cigar_p == NULL:
432 return 0
433
434 cdef uint32_t k, qpos
435 cdef int op
436 qpos = 0
437
438 for k from 0 <= k < pysam_get_n_cigar(src):
439 op = cigar_p[k] & BAM_CIGAR_MASK
440
441 if op == BAM_CMATCH or \
442 op == BAM_CINS or \
443 op == BAM_CSOFT_CLIP or \
444 op == BAM_CEQUAL or \
445 op == BAM_CDIFF:
446 qpos += cigar_p[k] >> BAM_CIGAR_SHIFT
447
448 return qpos
449
450
451 cdef inline int32_t calculateQueryLengthWithHardClipping(bam1_t * src):
452 """return query length computed from CIGAR alignment.
453
454 Length includes hard-clipped bases.
455
456 Return 0 if there is no CIGAR alignment.
457 """
458
459 cdef uint32_t * cigar_p = pysam_bam_get_cigar(src)
460
461 if cigar_p == NULL:
462 return 0
463
464 cdef uint32_t k, qpos
465 cdef int op
466 qpos = 0
467
468 for k from 0 <= k < pysam_get_n_cigar(src):
469 op = cigar_p[k] & BAM_CIGAR_MASK
470
471 if op == BAM_CMATCH or \
472 op == BAM_CINS or \
473 op == BAM_CSOFT_CLIP or \
474 op == BAM_CHARD_CLIP or \
475 op == BAM_CEQUAL or \
476 op == BAM_CDIFF:
477 qpos += cigar_p[k] >> BAM_CIGAR_SHIFT
478
479 return qpos
480
481
482 cdef inline int32_t getQueryStart(bam1_t *src) except -1:
483 cdef uint32_t * cigar_p
484 cdef uint32_t start_offset = 0
485 cdef uint32_t k, op
486
487 cigar_p = pysam_bam_get_cigar(src);
488 for k from 0 <= k < pysam_get_n_cigar(src):
489 op = cigar_p[k] & BAM_CIGAR_MASK
490 if op == BAM_CHARD_CLIP:
491 if start_offset != 0 and start_offset != src.core.l_qseq:
492 raise ValueError('Invalid clipping in CIGAR string')
493 elif op == BAM_CSOFT_CLIP:
494 start_offset += cigar_p[k] >> BAM_CIGAR_SHIFT
495 else:
496 break
497
498 return start_offset
499
500
501 cdef inline int32_t getQueryEnd(bam1_t *src) except -1:
502 cdef uint32_t * cigar_p = pysam_bam_get_cigar(src)
503 cdef uint32_t end_offset = src.core.l_qseq
504 cdef uint32_t k, op
505
506 # if there is no sequence, compute length from cigar string
507 if end_offset == 0:
508 for k from 0 <= k < pysam_get_n_cigar(src):
509 op = cigar_p[k] & BAM_CIGAR_MASK
510 if op == BAM_CMATCH or \
511 op == BAM_CINS or \
512 op == BAM_CEQUAL or \
513 op == BAM_CDIFF or \
514 (op == BAM_CSOFT_CLIP and end_offset == 0):
515 end_offset += cigar_p[k] >> BAM_CIGAR_SHIFT
516 else:
517 # walk backwards in cigar string
518 for k from pysam_get_n_cigar(src) > k >= 1:
519 op = cigar_p[k] & BAM_CIGAR_MASK
520 if op == BAM_CHARD_CLIP:
521 if end_offset != src.core.l_qseq:
522 raise ValueError('Invalid clipping in CIGAR string')
523 elif op == BAM_CSOFT_CLIP:
524 end_offset -= cigar_p[k] >> BAM_CIGAR_SHIFT
525 else:
526 break
527
528 return end_offset
529
530
531 cdef inline bytes getSequenceInRange(bam1_t *src,
532 uint32_t start,
533 uint32_t end):
534 """return python string of the sequence in a bam1_t object.
535 """
536
537 cdef uint8_t * p
538 cdef uint32_t k
539 cdef char * s
540
541 if not src.core.l_qseq:
542 return None
543
544 seq = PyBytes_FromStringAndSize(NULL, end - start)
545 s = <char*>seq
546 p = pysam_bam_get_seq(src)
547
548 for k from start <= k < end:
549 # equivalent to seq_nt16_str[bam1_seqi(s, i)] (see bam.c)
550 # note: do not use string literal as it will be a python string
551 s[k-start] = seq_nt16_str[p[k//2] >> 4 * (1 - k%2) & 0xf]
552
553 return charptr_to_bytes(seq)
554
555
556 #####################################################################
557 ## factory methods for instantiating extension classes
558 cdef class AlignedSegment
559 cdef AlignedSegment makeAlignedSegment(bam1_t *src,
560 AlignmentHeader header):
561 '''return an AlignedSegment object constructed from `src`'''
562 # note that the following does not call __init__
563 cdef AlignedSegment dest = AlignedSegment.__new__(AlignedSegment)
564 dest._delegate = bam_dup1(src)
565 dest.header = header
566 dest.cache = _AlignedSegment_Cache()
567 return dest
568
569
570 cdef class PileupColumn
571 cdef PileupColumn makePileupColumn(const bam_pileup1_t ** plp,
572 int tid,
573 int pos,
574 int n_pu,
575 uint32_t min_base_quality,
576 char * reference_sequence,
577 AlignmentHeader header):
578 '''return a PileupColumn object constructed from pileup in `plp` and
579 setting additional attributes.
580
581 '''
582 # note that the following does not call __init__
583 cdef PileupColumn dest = PileupColumn.__new__(PileupColumn)
584 dest.header = header
585 dest.plp = plp
586 dest.tid = tid
587 dest.pos = pos
588 dest.n_pu = n_pu
589 dest.min_base_quality = min_base_quality
590 dest.reference_sequence = reference_sequence
591 dest.buf.l = dest.buf.m = 0
592 dest.buf.s = NULL
593
594 return dest
595
596
597 cdef class PileupRead
598 cdef PileupRead makePileupRead(const bam_pileup1_t *src,
599 AlignmentHeader header):
600 '''return a PileupRead object construted from a bam_pileup1_t * object.'''
601 # note that the following does not call __init__
602 cdef PileupRead dest = PileupRead.__new__(PileupRead)
603 dest._alignment = makeAlignedSegment(src.b, header)
604 dest._qpos = src.qpos
605 dest._indel = src.indel
606 dest._level = src.level
607 dest._is_del = src.is_del
608 dest._is_head = src.is_head
609 dest._is_tail = src.is_tail
610 dest._is_refskip = src.is_refskip
611 return dest
612
613
614 cdef inline uint32_t get_alignment_length(bam1_t *src):
615 cdef uint32_t k = 0
616 cdef uint32_t l = 0
617 if src == NULL:
618 return 0
619 cdef uint32_t * cigar_p = bam_get_cigar(src)
620 if cigar_p == NULL:
621 return 0
622 cdef int op
623 cdef uint32_t n = pysam_get_n_cigar(src)
624 for k from 0 <= k < n:
625 op = cigar_p[k] & BAM_CIGAR_MASK
626 if op == BAM_CSOFT_CLIP or op == BAM_CHARD_CLIP:
627 continue
628 l += cigar_p[k] >> BAM_CIGAR_SHIFT
629 return l
630
631
632 cdef inline uint32_t get_md_reference_length(char * md_tag):
633 cdef int l = 0
634 cdef int md_idx = 0
635 cdef int nmatches = 0
636
637 while md_tag[md_idx] != 0:
638 if md_tag[md_idx] >= 48 and md_tag[md_idx] <= 57:
639 nmatches *= 10
640 nmatches += md_tag[md_idx] - 48
641 md_idx += 1
642 continue
643 else:
644 l += nmatches
645 nmatches = 0
646 if md_tag[md_idx] == b'^':
647 md_idx += 1
648 while md_tag[md_idx] >= 65 and md_tag[md_idx] <= 90:
649 md_idx += 1
650 l += 1
651 else:
652 md_idx += 1
653 l += 1
654
655 l += nmatches
656 return l
657
658 # TODO: avoid string copying for getSequenceInRange, reconstituneSequenceFromMD, ...
659 cdef inline bytes build_alignment_sequence(bam1_t * src):
660 """return expanded sequence from MD tag.
661
662 The sequence includes substitutions and both insertions in the
663 reference as well as deletions to the reference sequence. Combine
664 with the cigar string to reconstitute the query or the reference
665 sequence.
666
667 Positions corresponding to `N` (skipped region from the reference)
668 or `P` (padding (silent deletion from padded reference)) in the CIGAR
669 string will not appear in the returned sequence. The MD should
670 correspondingly not contain these. Thus proper tags are::
671
672 Deletion from the reference: cigar=5M1D5M MD=5^C5
673 Skipped region from reference: cigar=5M1N5M MD=10
674 Padded region in the reference: cigar=5M1P5M MD=10
675
676 Returns
677 -------
678
679 None, if no MD tag is present.
680
681 """
682 if src == NULL:
683 return None
684
685 cdef uint8_t * md_tag_ptr = bam_aux_get(src, "MD")
686 if md_tag_ptr == NULL:
687 return None
688
689 cdef uint32_t start = getQueryStart(src)
690 cdef uint32_t end = getQueryEnd(src)
691 # get read sequence, taking into account soft-clipping
692 r = getSequenceInRange(src, start, end)
693 cdef char * read_sequence = r
694 cdef uint32_t * cigar_p = pysam_bam_get_cigar(src)
695 if cigar_p == NULL:
696 return None
697
698 cdef uint32_t r_idx = 0
699 cdef int op
700 cdef uint32_t k, i, l, x
701 cdef int nmatches = 0
702 cdef int s_idx = 0
703
704 cdef uint32_t max_len = get_alignment_length(src)
705 if max_len == 0:
706 raise ValueError("could not determine alignment length")
707
708 cdef char * s = <char*>calloc(max_len + 1, sizeof(char))
709 if s == NULL:
710 raise ValueError(
711 "could not allocate sequence of length %i" % max_len)
712
713 for k from 0 <= k < pysam_get_n_cigar(src):
714 op = cigar_p[k] & BAM_CIGAR_MASK
715 l = cigar_p[k] >> BAM_CIGAR_SHIFT
716 if op == BAM_CMATCH or op == BAM_CEQUAL or op == BAM_CDIFF:
717 for i from 0 <= i < l:
718 s[s_idx] = read_sequence[r_idx]
719 r_idx += 1
720 s_idx += 1
721 elif op == BAM_CDEL:
722 for i from 0 <= i < l:
723 s[s_idx] = b'-'
724 s_idx += 1
725 elif op == BAM_CREF_SKIP:
726 pass
727 elif op == BAM_CINS or op == BAM_CPAD:
728 for i from 0 <= i < l:
729 # encode insertions into reference as lowercase
730 s[s_idx] = read_sequence[r_idx] + 32
731 r_idx += 1
732 s_idx += 1
733 elif op == BAM_CSOFT_CLIP:
734 pass
735 elif op == BAM_CHARD_CLIP:
736 pass # advances neither
737
738 cdef char md_buffer[2]
739 cdef char *md_tag
740 cdef uint8_t md_typecode = md_tag_ptr[0]
741 if md_typecode == b'Z':
742 md_tag = bam_aux2Z(md_tag_ptr)
743 elif md_typecode == b'A':
744 # Work around HTSeq bug that writes 1-character strings as MD:A:v
745 md_buffer[0] = bam_aux2A(md_tag_ptr)
746 md_buffer[1] = b'\0'
747 md_tag = md_buffer
748 else:
749 raise TypeError('Tagged field MD:{}:<value> does not have expected type MD:Z'.format(chr(md_typecode)))
750
751 cdef int md_idx = 0
752 cdef char c
753 s_idx = 0
754
755 # Check if MD tag is valid by matching CIGAR length to MD tag defined length
756 # Insertions would be in addition to what is described by MD, so we calculate
757 # the number of insertions separately.
758 cdef int insertions = 0
759
760 while s[s_idx] != 0:
761 if s[s_idx] >= b'a':
762 insertions += 1
763 s_idx += 1
764 s_idx = 0
765
766 cdef uint32_t md_len = get_md_reference_length(md_tag)
767 if md_len + insertions > max_len:
768 free(s)
769 raise AssertionError(
770 "Invalid MD tag: MD length {} mismatch with CIGAR length {} and {} insertions".format(
771 md_len, max_len, insertions))
772
773 while md_tag[md_idx] != 0:
774 # c is numerical
775 if md_tag[md_idx] >= 48 and md_tag[md_idx] <= 57:
776 nmatches *= 10
777 nmatches += md_tag[md_idx] - 48
778 md_idx += 1
779 continue
780 else:
781 # save matches up to this point, skipping insertions
782 for x from 0 <= x < nmatches:
783 while s[s_idx] >= b'a':
784 s_idx += 1
785 s_idx += 1
786 while s[s_idx] >= b'a':
787 s_idx += 1
788
789 r_idx += nmatches
790 nmatches = 0
791 if md_tag[md_idx] == b'^':
792 md_idx += 1
793 while md_tag[md_idx] >= 65 and md_tag[md_idx] <= 90:
794 # assert s[s_idx] == '-'
795 s[s_idx] = md_tag[md_idx]
796 s_idx += 1
797 md_idx += 1
798 else:
799 # save mismatch
800 # enforce lower case
801 c = md_tag[md_idx]
802 if c <= 90:
803 c += 32
804 s[s_idx] = c
805 s_idx += 1
806 r_idx += 1
807 md_idx += 1
808
809 # save matches up to this point, skipping insertions
810 for x from 0 <= x < nmatches:
811 while s[s_idx] >= b'a':
812 s_idx += 1
813 s_idx += 1
814 while s[s_idx] >= b'a':
815 s_idx += 1
816
817 seq = PyBytes_FromStringAndSize(s, s_idx)
818 free(s)
819
820 return seq
821
822
823 cdef inline bytes build_reference_sequence(bam1_t * src):
824 """return the reference sequence in the region that is covered by the
825 alignment of the read to the reference.
826
827 This method requires the MD tag to be set.
828
829 """
830 cdef uint32_t k, i, l
831 cdef int op
832 cdef int s_idx = 0
833 ref_seq = build_alignment_sequence(src)
834 if ref_seq is None:
835 raise ValueError("MD tag not present")
836
837 cdef char * s = <char*>calloc(len(ref_seq) + 1, sizeof(char))
838 if s == NULL:
839 raise ValueError(
840 "could not allocate sequence of length %i" % len(ref_seq))
841
842 cdef char * cref_seq = ref_seq
843 cdef uint32_t * cigar_p = pysam_bam_get_cigar(src)
844 cdef uint32_t r_idx = 0
845 for k from 0 <= k < pysam_get_n_cigar(src):
846 op = cigar_p[k] & BAM_CIGAR_MASK
847 l = cigar_p[k] >> BAM_CIGAR_SHIFT
848 if op == BAM_CMATCH or op == BAM_CEQUAL or op == BAM_CDIFF:
849 for i from 0 <= i < l:
850 s[s_idx] = cref_seq[r_idx]
851 r_idx += 1
852 s_idx += 1
853 elif op == BAM_CDEL:
854 for i from 0 <= i < l:
855 s[s_idx] = cref_seq[r_idx]
856 r_idx += 1
857 s_idx += 1
858 elif op == BAM_CREF_SKIP:
859 pass
860 elif op == BAM_CINS or op == BAM_CPAD:
861 r_idx += l
862 elif op == BAM_CSOFT_CLIP:
863 pass
864 elif op == BAM_CHARD_CLIP:
865 pass # advances neither
866
867 seq = PyBytes_FromStringAndSize(s, s_idx)
868 free(s)
869
870 return seq
871
872
873 cdef inline str safe_reference_name(AlignmentHeader header, int tid):
874 if tid == -1: return "*"
875 elif header is not None: return header.get_reference_name(tid)
876 else: return f"#{tid}"
877
878
879 # Tuple-building helper functions used by AlignedSegment.get_aligned_pairs()
880
881 cdef _alignedpairs_positions(qpos, pos, ref_seq, uint32_t r_idx, int op):
882 return (qpos, pos)
883
884
885 cdef _alignedpairs_with_seq(qpos, pos, ref_seq, uint32_t r_idx, int op):
886 ref_base = ref_seq[r_idx] if ref_seq is not None else None
887 return (qpos, pos, ref_base)
888
889
890 cdef _alignedpairs_with_cigar(qpos, pos, ref_seq, uint32_t r_idx, int op):
891 return (qpos, pos, CIGAR_OPS(op))
892
893
894 cdef _alignedpairs_with_seq_cigar(qpos, pos, ref_seq, uint32_t r_idx, int op):
895 ref_base = ref_seq[r_idx] if ref_seq is not None else None
896 return (qpos, pos, ref_base, CIGAR_OPS(op))
897
898
899 cdef class _AlignedSegment_Cache:
900 def __cinit__(self):
901 self.clear_query_sequences()
902 self.clear_query_qualities()
903
904 cdef clear_query_sequences(self):
905 self.query_sequence = NotImplemented
906 self.query_alignment_sequence = NotImplemented
907
908 cdef clear_query_qualities(self):
909 self.query_qualities = NotImplemented
910 self.query_qualities_str = NotImplemented
911 self.query_alignment_qualities = NotImplemented
912 self.query_alignment_qualities_str = NotImplemented
913
914
915 cdef class AlignedSegment:
916 '''Class representing an aligned segment.
917
918 This class stores a handle to the samtools C-structure representing
919 an aligned read. Member read access is forwarded to the C-structure
920 and converted into python objects. This implementation should be fast,
921 as only the data needed is converted.
922
923 For write access, the C-structure is updated in-place. This is
924 not the most efficient way to build BAM entries, as the variable
925 length data is concatenated and thus needs to be resized if
926 a field is updated. Furthermore, the BAM entry might be
927 in an inconsistent state.
928
929 One issue to look out for is that the sequence should always
930 be set *before* the quality scores. Setting the sequence will
931 also erase any quality scores that were set previously.
932
933 Parameters
934 ----------
935
936 header:
937 :class:`~pysam.AlignmentHeader` object to map numerical
938 identifiers to chromosome names. If not given, an empty
939 header is created.
940 '''
941
942 # Now only called when instances are created from Python
943 def __init__(self, AlignmentHeader header=None):
944 # see bam_init1
945 self._delegate = <bam1_t*>calloc(1, sizeof(bam1_t))
946 if self._delegate == NULL:
947 raise MemoryError("could not allocated memory of {} bytes".format(sizeof(bam1_t)))
948 # allocate some memory. If size is 0, calloc does not return a
949 # pointer that can be passed to free() so allocate 40 bytes
950 # for a new read
951 self._delegate.m_data = 40
952 self._delegate.data = <uint8_t *>calloc(
953 self._delegate.m_data, 1)
954 if self._delegate.data == NULL:
955 raise MemoryError("could not allocate memory of {} bytes".format(self._delegate.m_data))
956 self._delegate.l_data = 0
957 # set some data to make read approximately legit.
958 # Note, SAM writing fails with q_name of length 0
959 self._delegate.core.l_qname = 0
960 self._delegate.core.tid = -1
961 self._delegate.core.pos = -1
962 self._delegate.core.mtid = -1
963 self._delegate.core.mpos = -1
964
965 # caching for selected fields
966 self.cache = _AlignedSegment_Cache()
967
968 self.header = header
969
970 def __dealloc__(self):
971 bam_destroy1(self._delegate)
972
973 def __str__(self):
974 """return string representation of alignment.
975
976 The representation is an approximate :term:`SAM` format, because
977 an aligned read might not be associated with a :term:`AlignmentFile`.
978 Hence when the read does not have an associated :class:`AlignedHeader`,
979 :term:`tid` is shown instead of the reference name.
980 Similarly, the tags field is returned in its parsed state.
981
982 To get a valid SAM record, use :meth:`to_string`.
983 """
984 # sam-parsing is done in sam.c/bam_format1_core which
985 # requires a valid header.
986 return "\t".join(map(str, (self.query_name,
987 self.flag,
988 safe_reference_name(self.header, self.reference_id),
989 self.reference_start + 1,
990 self.mapping_quality,
991 self.cigarstring,
992 safe_reference_name(self.header, self.next_reference_id),
993 self.next_reference_start + 1,
994 self.template_length,
995 self.query_sequence,
996 self.query_qualities,
997 self.tags)))
998
999 def __repr__(self):
1000 ref = self.reference_name if self.header is not None else self.reference_id
1001 return f'<{type(self).__name__}({self.query_name!r}, flags={self.flag}={self.flag:#x}, ref={ref!r}, zpos={self.reference_start}, mapq={self.mapping_quality}, cigar={self.cigarstring!r}, ...)>'
1002
1003 def __copy__(self):
1004 return makeAlignedSegment(self._delegate, self.header)
1005
1006 def __deepcopy__(self, memo):
1007 return makeAlignedSegment(self._delegate, self.header)
1008
1009 def compare(self, AlignedSegment other):
1010 '''return -1,0,1, if contents in this are binary
1011 <,=,> to *other*
1012 '''
1013
1014 # avoid segfault when other equals None
1015 if other is None:
1016 return -1
1017
1018 cdef int retval, x
1019 cdef bam1_t *t
1020 cdef bam1_t *o
1021
1022 t = self._delegate
1023 o = other._delegate
1024
1025 # uncomment for debugging purposes
1026 # cdef unsigned char * oo, * tt
1027 # tt = <unsigned char*>(&t.core)
1028 # oo = <unsigned char*>(&o.core)
1029 # for x from 0 <= x < sizeof( bam1_core_t): print x, tt[x], oo[x]
1030 # tt = <unsigned char*>(t.data)
1031 # oo = <unsigned char*>(o.data)
1032 # for x from 0 <= x < max(t.l_data, o.l_data): print x, tt[x], oo[x], chr(tt[x]), chr(oo[x])
1033
1034 # Fast-path test for object identity
1035 if t == o:
1036 return 0
1037
1038 cdef uint8_t *a = <uint8_t*>&t.core
1039 cdef uint8_t *b = <uint8_t*>&o.core
1040
1041 retval = memcmp(&t.core, &o.core, sizeof(bam1_core_t))
1042 if retval:
1043 return retval
1044
1045 # cmp(t.l_data, o.l_data)
1046 retval = (t.l_data > o.l_data) - (t.l_data < o.l_data)
1047 if retval:
1048 return retval
1049 return memcmp(t.data, o.data, t.l_data)
1050
1051 def __richcmp__(self, AlignedSegment other, int op):
1052 if op == 2: # == operator
1053 return self.compare(other) == 0
1054 elif op == 3: # != operator
1055 return self.compare(other) != 0
1056 else:
1057 return NotImplemented
1058
1059 def __hash__(self):
1060 cdef bam1_t * src = self._delegate
1061 cdef int x
1062
1063 # see http://effbot.org/zone/python-hash.htm
1064 cdef uint8_t * c = <uint8_t *>&src.core
1065 cdef uint32_t hash_value = c[0]
1066 for x from 1 <= x < sizeof(bam1_core_t):
1067 hash_value = c_mul(hash_value, 1000003) ^ c[x]
1068 c = <uint8_t *>src.data
1069 for x from 0 <= x < src.l_data:
1070 hash_value = c_mul(hash_value, 1000003) ^ c[x]
1071
1072 return hash_value
1073
1074 cpdef to_string(self):
1075 """returns a string representation of the aligned segment.
1076
1077 The output format is valid SAM format if a header is associated
1078 with the AlignedSegment.
1079 """
1080 cdef kstring_t line
1081 line.l = line.m = 0
1082 line.s = NULL
1083
1084 if self.header:
1085 if sam_format1(self.header.ptr, self._delegate, &line) < 0:
1086 if line.m:
1087 free(line.s)
1088 raise ValueError('sam_format failed')
1089 else:
1090 raise NotImplementedError("todo")
1091
1092 ret = force_str(line.s[:line.l])
1093
1094 if line.m:
1095 free(line.s)
1096
1097 return ret
1098
1099 @classmethod
1100 def fromstring(cls, sam, AlignmentHeader header):
1101 """parses a string representation of the aligned segment.
1102
1103 The input format should be valid SAM format.
1104
1105 Parameters
1106 ----------
1107 sam:
1108 :term:`SAM` formatted string
1109
1110 """
1111 cdef AlignedSegment dest = cls.__new__(cls)
1112 dest._delegate = <bam1_t*>calloc(1, sizeof(bam1_t))
1113 dest.header = header
1114 dest.cache = _AlignedSegment_Cache()
1115
1116 cdef kstring_t line
1117 line.l = line.m = len(sam)
1118 _sam = force_bytes(sam)
1119 line.s = _sam
1120
1121 cdef int ret
1122 ret = sam_parse1(&line, dest.header.ptr, dest._delegate)
1123 if ret < 0:
1124 raise ValueError("parsing SAM record string failed (error code {})".format(ret))
1125
1126 return dest
1127
1128 cpdef tostring(self, htsfile=None):
1129 """deprecated, use :meth:`to_string()` instead.
1130
1131 Parameters
1132 ----------
1133
1134 htsfile:
1135 (deprecated) AlignmentFile object to map numerical
1136 identifiers to chromosome names. This parameter is present
1137 for backwards compatibility and ignored.
1138 """
1139
1140 return self.to_string()
1141
1142 def to_dict(self):
1143 """returns a json representation of the aligned segment.
1144
1145 Field names are abbreviated versions of the class attributes.
1146 """
1147 # let htslib do the string conversions, but treat optional field properly as list
1148 vals = self.to_string().split("\t")
1149 n = len(KEY_NAMES) - 1
1150 return dict(list(zip(KEY_NAMES[:-1], vals[:n])) + [(KEY_NAMES[-1], vals[n:])])
1151
1152 @classmethod
1153 def from_dict(cls, sam_dict, AlignmentHeader header):
1154 """parses a dictionary representation of the aligned segment.
1155
1156 Parameters
1157 ----------
1158 sam_dict:
1159 dictionary of alignment values, keys corresponding to output from
1160 :meth:`todict()`.
1161
1162 """
1163 # let htslib do the parsing
1164 # the tags field can be missing
1165 return cls.fromstring(
1166 "\t".join((sam_dict[x] for x in KEY_NAMES[:-1])) +
1167 "\t" +
1168 "\t".join(sam_dict.get(KEY_NAMES[-1], [])), header)
1169
1170 ########################################################
1171 ## Basic attributes in order of appearance in SAM format
1172 property query_name:
1173 """the query template name (None if not present)"""
1174 def __get__(self):
1175
1176 cdef bam1_t * src = self._delegate
1177 if src.core.l_qname == 0:
1178 return None
1179
1180 return charptr_to_str(<char *>pysam_bam_get_qname(src))
1181
1182 def __set__(self, qname):
1183
1184 if qname is None or len(qname) == 0:
1185 return
1186
1187 if len(qname) > 254:
1188 raise ValueError("query length out of range {} > 254".format(
1189 len(qname)))
1190
1191 qname = force_bytes(qname)
1192 cdef bam1_t * src = self._delegate
1193 # the qname is \0 terminated
1194 cdef uint8_t l = len(qname) + 1
1195
1196 cdef char * p = pysam_bam_get_qname(src)
1197 cdef uint8_t l_extranul = 0
1198
1199 if l % 4 != 0:
1200 l_extranul = 4 - l % 4
1201
1202 cdef bam1_t * retval = pysam_bam_update(src,
1203 src.core.l_qname,
1204 l + l_extranul,
1205 <uint8_t*>p)
1206 if retval == NULL:
1207 raise MemoryError("could not allocate memory")
1208
1209 src.core.l_extranul = l_extranul
1210 src.core.l_qname = l + l_extranul
1211
1212 # re-acquire pointer to location in memory
1213 # as it might have moved
1214 p = pysam_bam_get_qname(src)
1215
1216 strncpy(p, qname, l)
1217 # x might be > 255
1218 cdef uint16_t x = 0
1219
1220 for x from l <= x < l + l_extranul:
1221 p[x] = b'\0'
1222
1223 property flag:
1224 """properties flag"""
1225 def __get__(self):
1226 return self._delegate.core.flag
1227 def __set__(self, flag):
1228 self._delegate.core.flag = flag
1229
1230 property reference_name:
1231 """:term:`reference` name"""
1232 def __get__(self):
1233 if self._delegate.core.tid == -1:
1234 return None
1235 if self.header:
1236 return self.header.get_reference_name(self._delegate.core.tid)
1237 else:
1238 raise ValueError("reference_name unknown if no header associated with record")
1239 def __set__(self, reference):
1240 cdef int tid
1241 if reference is None or reference == "*":
1242 self._delegate.core.tid = -1
1243 elif self.header:
1244 tid = self.header.get_tid(reference)
1245 if tid < 0:
1246 raise ValueError("reference {} does not exist in header".format(
1247 reference))
1248 self._delegate.core.tid = tid
1249 else:
1250 raise ValueError("reference_name can not be set if no header associated with record")
1251
1252 property reference_id:
1253 """:term:`reference` ID
1254
1255 .. note::
1256
1257 This field contains the index of the reference sequence in
1258 the sequence dictionary. To obtain the name of the
1259 reference sequence, use :meth:`get_reference_name()`
1260
1261 """
1262 def __get__(self):
1263 return self._delegate.core.tid
1264 def __set__(self, tid):
1265 if tid != -1 and self.header and not self.header.is_valid_tid(tid):
1266 raise ValueError("reference id {} does not exist in header".format(
1267 tid))
1268 self._delegate.core.tid = tid
1269
1270 property reference_start:
1271 """0-based leftmost coordinate"""
1272 def __get__(self):
1273 return self._delegate.core.pos
1274 def __set__(self, pos):
1275 ## setting the position requires updating the "bin" attribute
1276 cdef bam1_t * src
1277 src = self._delegate
1278 src.core.pos = pos
1279 update_bin(src)
1280
1281 property mapping_quality:
1282 """mapping quality"""
1283 def __get__(self):
1284 return pysam_get_qual(self._delegate)
1285 def __set__(self, qual):
1286 pysam_set_qual(self._delegate, qual)
1287
1288 property cigarstring:
1289 '''the :term:`cigar` alignment as a string.
1290
1291 The cigar string is a string of alternating integers
1292 and characters denoting the length and the type of
1293 an operation.
1294
1295 .. note::
1296 The order length,operation is specified in the
1297 SAM format. It is different from the order of
1298 the :attr:`cigar` property.
1299
1300 Returns None if not present.
1301
1302 To unset the cigarstring, assign None or the
1303 empty string.
1304 '''
1305 def __get__(self):
1306 cdef bam1_t *src = self._delegate
1307 if pysam_get_n_cigar(src) == 0:
1308 return None
1309
1310 cdef kstring_t buf
1311 buf.l = buf.m = 0
1312 buf.s = NULL
1313
1314 cdef uint32_t *cigar_p = pysam_bam_get_cigar(src)
1315 cdef uint32_t op, l
1316 cdef int k
1317 for k from 0 <= k < pysam_get_n_cigar(src):
1318 op = cigar_p[k] & BAM_CIGAR_MASK
1319 l = cigar_p[k] >> BAM_CIGAR_SHIFT
1320 kputl(l, &buf)
1321 kputc(CODE2CIGAR[op], &buf)
1322
1323 try:
1324 return buf.s[:buf.l].decode("ascii")
1325 finally:
1326 free(buf.s)
1327
1328 def __set__(self, cigar):
1329 if cigar is None or len(cigar) == 0 or cigar == "*":
1330 self.cigartuples = []
1331 else:
1332 parts = CIGAR_REGEX.findall(cigar)
1333 # reverse order
1334 self.cigartuples = [(CIGAR2CODE[ord(y)], int(x)) for x,y in parts]
1335
1336 # TODO
1337 # property cigar:
1338 # """the cigar alignment"""
1339
1340 property next_reference_id:
1341 """the :term:`reference` id of the mate/next read."""
1342 def __get__(self):
1343 return self._delegate.core.mtid
1344 def __set__(self, mtid):
1345 if mtid != -1 and self.header and not self.header.is_valid_tid(mtid):
1346 raise ValueError("reference id {} does not exist in header".format(
1347 mtid))
1348 self._delegate.core.mtid = mtid
1349
1350 property next_reference_name:
1351 """:term:`reference` name of the mate/next read (None if no
1352 AlignmentFile is associated)"""
1353 def __get__(self):
1354 if self._delegate.core.mtid == -1:
1355 return None
1356 if self.header:
1357 return self.header.get_reference_name(self._delegate.core.mtid)
1358 else:
1359 raise ValueError("next_reference_name unknown if no header associated with record")
1360
1361 def __set__(self, reference):
1362 cdef int mtid
1363 if reference is None or reference == "*":
1364 self._delegate.core.mtid = -1
1365 elif reference == "=":
1366 self._delegate.core.mtid = self._delegate.core.tid
1367 elif self.header:
1368 mtid = self.header.get_tid(reference)
1369 if mtid < 0:
1370 raise ValueError("reference {} does not exist in header".format(
1371 reference))
1372 self._delegate.core.mtid = mtid
1373 else:
1374 raise ValueError("next_reference_name can not be set if no header associated with record")
1375
1376 property next_reference_start:
1377 """the position of the mate/next read."""
1378 def __get__(self):
1379 return self._delegate.core.mpos
1380 def __set__(self, mpos):
1381 self._delegate.core.mpos = mpos
1382
1383 property query_length:
1384 """the length of the query/read.
1385
1386 This value corresponds to the length of the sequence supplied
1387 in the BAM/SAM file. The length of a query is 0 if there is no
1388 sequence in the BAM/SAM file. In those cases, the read length
1389 can be inferred from the CIGAR alignment, see
1390 :meth:`pysam.AlignedSegment.infer_query_length`.
1391
1392 The length includes soft-clipped bases and is equal to
1393 ``len(query_sequence)``.
1394
1395 This property is read-only but is updated when a new query
1396 sequence is assigned to this AlignedSegment.
1397
1398 Returns 0 if not available.
1399
1400 """
1401 def __get__(self):
1402 return self._delegate.core.l_qseq
1403
1404 property template_length:
1405 """the observed query template length"""
1406 def __get__(self):
1407 return self._delegate.core.isize
1408 def __set__(self, isize):
1409 self._delegate.core.isize = isize
1410
1411 property query_sequence:
1412 """read sequence bases, including :term:`soft clipped` bases
1413 (None if not present).
1414
1415 Assigning to this attribute will invalidate any quality scores.
1416 Thus, to in-place edit the sequence and quality scores, copies of
1417 the quality scores need to be taken. Consider trimming for example::
1418
1419 q = read.query_qualities
1420 read.query_sequence = read.query_sequence[5:10]
1421 read.query_qualities = q[5:10]
1422
1423 The sequence is returned as it is stored in the BAM file. (This will
1424 be the reverse complement of the original read sequence if the mapper
1425 has aligned the read to the reverse strand.)
1426 """
1427 def __get__(self):
1428 if self.cache.query_sequence is not NotImplemented:
1429 return self.cache.query_sequence
1430
1431 cdef bam1_t * src
1432 cdef char * s
1433 src = self._delegate
1434
1435 if src.core.l_qseq == 0:
1436 self.cache.query_sequence = None
1437 return None
1438
1439 self.cache.query_sequence = force_str(getSequenceInRange(
1440 src, 0, src.core.l_qseq))
1441 return self.cache.query_sequence
1442
1443 def __set__(self, seq):
1444 # samtools manages sequence and quality length memory together
1445 # if no quality information is present, the first byte says 0xff.
1446 cdef bam1_t * src
1447 cdef uint8_t * p
1448 cdef char * s
1449 cdef int l, k
1450 cdef Py_ssize_t nbytes_new, nbytes_old
1451
1452 if seq is None or len(seq) == 0 or seq == "*":
1453 l = 0
1454 else:
1455 l = len(seq)
1456 seq = force_bytes(seq)
1457
1458 src = self._delegate
1459
1460 # as the sequence is stored in half-bytes, the total length (sequence
1461 # plus quality scores) is (l+1)/2 + l
1462 nbytes_new = (l + 1) // 2 + l
1463 nbytes_old = (src.core.l_qseq + 1) // 2 + src.core.l_qseq
1464
1465 # acquire pointer to location in memory
1466 p = pysam_bam_get_seq(src)
1467 src.core.l_qseq = l
1468
1469 # change length of data field
1470 cdef bam1_t * retval = pysam_bam_update(src,
1471 nbytes_old,
1472 nbytes_new,
1473 p)
1474
1475 if retval == NULL:
1476 raise MemoryError("could not allocate memory")
1477
1478 if l > 0:
1479 # re-acquire pointer to location in memory
1480 # as it might have moved
1481 p = pysam_bam_get_seq(src)
1482 for k from 0 <= k < nbytes_new:
1483 p[k] = 0
1484 # convert to C string
1485 s = seq
1486 for k from 0 <= k < l:
1487 p[k // 2] |= seq_nt16_table[<unsigned char>s[k]] << 4 * (1 - k % 2)
1488
1489 # erase qualities
1490 p = pysam_bam_get_qual(src)
1491 memset(p, 0xff, l)
1492
1493 self.cache.clear_query_sequences()
1494 self.cache.clear_query_qualities()
1495
1496 property query_qualities:
1497 """read sequence base qualities, including :term:`soft clipped` bases
1498 (None if not present).
1499
1500 Quality scores are returned as a python array of unsigned
1501 chars. Note that this is not the ASCII-encoded value typically
1502 seen in FASTQ or SAM formatted files. Thus, no offset of 33
1503 needs to be subtracted.
1504
1505 Note that to set quality scores the sequence has to be set
1506 beforehand as this will determine the expected length of the
1507 quality score array. Setting will raise a ValueError if the
1508 length of the new quality scores is not the same as the
1509 length of the existing sequence.
1510
1511 Quality scores to be set may be specified as a Python array
1512 or other iterable of ints, or as a string of ASCII-encooded
1513 FASTQ/SAM-style base quality characters.
1514 """
1515 def __get__(self):
1516 if self.cache.query_qualities is not NotImplemented:
1517 return self.cache.query_qualities
1518
1519 cdef bam1_t *src = self._delegate
1520 cdef int qual_len = src.core.l_qseq
1521 cdef uint8_t *qual = pysam_bam_get_qual(src)
1522
1523 if qual_len == 0 or qual[0] == 0xff:
1524 self.cache.query_qualities = None
1525 return None
1526
1527 cdef c_array.array qual_array = array.array('B')
1528 c_array.resize(qual_array, qual_len)
1529 memcpy(qual_array.data.as_uchars, qual, qual_len)
1530 self.cache.query_qualities = qual_array
1531 return qual_array
1532
1533 def __set__(self, new_qual):
1534 if isinstance(new_qual, str):
1535 self.query_qualities_str = new_qual
1536 return
1537
1538 cdef bam1_t *src = self._delegate
1539 cdef int qual_len = src.core.l_qseq
1540 cdef uint8_t *qual = pysam_bam_get_qual(src)
1541
1542 cdef int new_qual_len = len(new_qual) if new_qual is not None else 0
1543 if new_qual_len == 0:
1544 if qual_len != 0: memset(qual, 0xff, qual_len)
1545 self.cache.clear_query_qualities()
1546 return
1547
1548 if new_qual_len != qual_len:
1549 raise ValueError(f"quality ({new_qual_len}) and sequence ({qual_len}) length mismatch")
1550
1551 if isinstance(new_qual, array.array) and new_qual.typecode == 'B':
1552 memcpy(qual, (<c_array.array> new_qual).data.as_uchars, qual_len)
1553 self.cache.clear_query_qualities()
1554 return
1555
1556 cdef uint8_t *s = qual
1557 cdef uint8_t q
1558 for q in new_qual:
1559 s[0] = q
1560 s += 1
1561
1562 self.cache.clear_query_qualities()
1563
1564 property query_qualities_str:
1565 """read sequence base qualities, including :term:`soft clipped` bases,
1566 returned as an ASCII-encoded string similar to that in FASTQ or SAM files,
1567 or None if base qualities are not present.
1568
1569 Note that to set quality scores the sequence has to be set beforehand
1570 as this will determine the expected length of the quality score string.
1571 Setting will raise a ValueError if the length of the new quality scores
1572 is not the same as the length of the existing sequence.
1573 """
1574 def __get__(self):
1575 if self.cache.query_qualities_str is not NotImplemented:
1576 return self.cache.query_qualities_str
1577
1578 cdef bam1_t *src = self._delegate
1579 cdef int qual_len = src.core.l_qseq
1580 cdef uint8_t *qual = pysam_bam_get_qual(src)
1581
1582 if qual_len == 0 or qual[0] == 0xff:
1583 self.cache.query_qualities_str = None
1584 return None
1585
1586 cdef bytes qual_bytes = qual[:qual_len]
1587 cdef char *s = qual_bytes
1588 cdef int i
1589 for i in range(qual_len): s[i] += 33
1590
1591 self.cache.query_qualities_str = qual_bytes.decode('ascii')
1592 return self.cache.query_qualities_str
1593
1594 def __set__(self, new_qual):
1595 cdef bam1_t *src = self._delegate
1596 cdef int qual_len = src.core.l_qseq
1597 cdef uint8_t *qual = pysam_bam_get_qual(src)
1598
1599 cdef int new_qual_len = len(new_qual) if new_qual is not None else 0
1600 if new_qual_len == 0 or new_qual == "*":
1601 if qual_len != 0: memset(qual, 0xff, qual_len)
1602 self.cache.clear_query_qualities()
1603 return
1604
1605 if new_qual_len != qual_len:
1606 raise ValueError(f"quality ({new_qual_len}) and sequence ({qual_len}) length mismatch")
1607
1608 cdef bytes new_qual_bytes = new_qual.encode('ascii')
1609 cdef const char *s = new_qual_bytes
1610 cdef int i
1611 for i in range(qual_len): qual[i] = s[i] - 33
1612
1613 self.cache.clear_query_qualities()
1614
1615 property bin:
1616 """properties bin"""
1617 def __get__(self):
1618 return self._delegate.core.bin
1619 def __set__(self, bin):
1620 self._delegate.core.bin = bin
1621
1622
1623 ##########################################################
1624 # Derived simple attributes. These are simple attributes of
1625 # AlignedSegment getting and setting values.
1626 ##########################################################
1627 # 1. Flags
1628 ##########################################################
1629 property is_paired:
1630 """true if read is paired in sequencing"""
1631 def __get__(self):
1632 return (self.flag & BAM_FPAIRED) != 0
1633 def __set__(self,val):
1634 pysam_update_flag(self._delegate, val, BAM_FPAIRED)
1635
1636 property is_proper_pair:
1637 """true if read is mapped in a proper pair"""
1638 def __get__(self):
1639 return (self.flag & BAM_FPROPER_PAIR) != 0
1640 def __set__(self,val):
1641 pysam_update_flag(self._delegate, val, BAM_FPROPER_PAIR)
1642
1643 property is_unmapped:
1644 """true if read itself is unmapped"""
1645 def __get__(self):
1646 return (self.flag & BAM_FUNMAP) != 0
1647 def __set__(self, val):
1648 pysam_update_flag(self._delegate, val, BAM_FUNMAP)
1649 # setting the unmapped flag requires recalculation of
1650 # bin as alignment length is now implicitly 1
1651 update_bin(self._delegate)
1652
1653 property is_mapped:
1654 """true if read itself is mapped
1655 (implemented in terms of :attr:`is_unmapped`)"""
1656 def __get__(self):
1657 return (self.flag & BAM_FUNMAP) == 0
1658 def __set__(self, val):
1659 pysam_update_flag(self._delegate, not val, BAM_FUNMAP)
1660 update_bin(self._delegate)
1661
1662 property mate_is_unmapped:
1663 """true if the mate is unmapped"""
1664 def __get__(self):
1665 return (self.flag & BAM_FMUNMAP) != 0
1666 def __set__(self,val):
1667 pysam_update_flag(self._delegate, val, BAM_FMUNMAP)
1668
1669 property mate_is_mapped:
1670 """true if the mate is mapped
1671 (implemented in terms of :attr:`mate_is_unmapped`)"""
1672 def __get__(self):
1673 return (self.flag & BAM_FMUNMAP) == 0
1674 def __set__(self,val):
1675 pysam_update_flag(self._delegate, not val, BAM_FMUNMAP)
1676
1677 property is_reverse:
1678 """true if read is mapped to reverse strand"""
1679 def __get__(self):
1680 return (self.flag & BAM_FREVERSE) != 0
1681 def __set__(self,val):
1682 pysam_update_flag(self._delegate, val, BAM_FREVERSE)
1683
1684 property is_forward:
1685 """true if read is mapped to forward strand
1686 (implemented in terms of :attr:`is_reverse`)"""
1687 def __get__(self):
1688 return (self.flag & BAM_FREVERSE) == 0
1689 def __set__(self,val):
1690 pysam_update_flag(self._delegate, not val, BAM_FREVERSE)
1691
1692 property mate_is_reverse:
1693 """true if the mate is mapped to reverse strand"""
1694 def __get__(self):
1695 return (self.flag & BAM_FMREVERSE) != 0
1696 def __set__(self,val):
1697 pysam_update_flag(self._delegate, val, BAM_FMREVERSE)
1698
1699 property mate_is_forward:
1700 """true if the mate is mapped to forward strand
1701 (implemented in terms of :attr:`mate_is_reverse`)"""
1702 def __get__(self):
1703 return (self.flag & BAM_FMREVERSE) == 0
1704 def __set__(self,val):
1705 pysam_update_flag(self._delegate, not val, BAM_FMREVERSE)
1706
1707 property is_read1:
1708 """true if this is read1"""
1709 def __get__(self):
1710 return (self.flag & BAM_FREAD1) != 0
1711 def __set__(self,val):
1712 pysam_update_flag(self._delegate, val, BAM_FREAD1)
1713 property is_read2:
1714 """true if this is read2"""
1715 def __get__(self):
1716 return (self.flag & BAM_FREAD2) != 0
1717 def __set__(self, val):
1718 pysam_update_flag(self._delegate, val, BAM_FREAD2)
1719 property is_secondary:
1720 """true if not primary alignment"""
1721 def __get__(self):
1722 return (self.flag & BAM_FSECONDARY) != 0
1723 def __set__(self, val):
1724 pysam_update_flag(self._delegate, val, BAM_FSECONDARY)
1725 property is_qcfail:
1726 """true if QC failure"""
1727 def __get__(self):
1728 return (self.flag & BAM_FQCFAIL) != 0
1729 def __set__(self, val):
1730 pysam_update_flag(self._delegate, val, BAM_FQCFAIL)
1731 property is_duplicate:
1732 """true if optical or PCR duplicate"""
1733 def __get__(self):
1734 return (self.flag & BAM_FDUP) != 0
1735 def __set__(self, val):
1736 pysam_update_flag(self._delegate, val, BAM_FDUP)
1737 property is_supplementary:
1738 """true if this is a supplementary alignment"""
1739 def __get__(self):
1740 return (self.flag & BAM_FSUPPLEMENTARY) != 0
1741 def __set__(self, val):
1742 pysam_update_flag(self._delegate, val, BAM_FSUPPLEMENTARY)
1743
1744 # 2. Coordinates and lengths
1745 property reference_end:
1746 '''aligned reference position of the read on the reference genome.
1747
1748 reference_end points to one past the last aligned residue.
1749 Returns None if not available (read is unmapped or no cigar
1750 alignment present).
1751
1752 '''
1753 def __get__(self):
1754 cdef bam1_t * src
1755 src = self._delegate
1756 if (self.flag & BAM_FUNMAP) or pysam_get_n_cigar(src) == 0:
1757 return None
1758 return bam_endpos(src)
1759
1760 property reference_length:
1761 '''aligned length of the read on the reference genome.
1762
1763 This is equal to `reference_end - reference_start`.
1764 Returns None if not available.
1765 '''
1766 def __get__(self):
1767 cdef bam1_t * src
1768 src = self._delegate
1769 if (self.flag & BAM_FUNMAP) or pysam_get_n_cigar(src) == 0:
1770 return None
1771 return bam_endpos(src) - \
1772 self._delegate.core.pos
1773
1774 property query_alignment_sequence:
1775 """aligned portion of the read.
1776
1777 This is a substring of :attr:`query_sequence` that excludes flanking
1778 bases that were :term:`soft clipped` (None if not present). It
1779 is equal to ``query_sequence[query_alignment_start:query_alignment_end]``.
1780
1781 SAM/BAM files may include extra flanking bases that are not
1782 part of the alignment. These bases may be the result of the
1783 Smith-Waterman or other algorithms, which may not require
1784 alignments that begin at the first residue or end at the last.
1785 In addition, extra sequencing adapters, multiplex identifiers,
1786 and low-quality bases that were not considered for alignment
1787 may have been retained.
1788
1789 """
1790
1791 def __get__(self):
1792 if self.cache.query_alignment_sequence is not NotImplemented:
1793 return self.cache.query_alignment_sequence
1794
1795 cdef bam1_t * src
1796 cdef uint32_t start, end
1797
1798 src = self._delegate
1799
1800 if src.core.l_qseq == 0:
1801 self.cache.query_alignment_sequence = None
1802 return None
1803
1804 start = getQueryStart(src)
1805 end = getQueryEnd(src)
1806
1807 self.cache.query_alignment_sequence = force_str(getSequenceInRange(src, start, end))
1808 return self.cache.query_alignment_sequence
1809
1810 property query_alignment_qualities:
1811 """aligned query sequence quality values (None if not present). These
1812 are the quality values that correspond to
1813 :attr:`query_alignment_sequence`, that is, they exclude qualities of
1814 :term:`soft clipped` bases. This is equal to
1815 ``query_qualities[query_alignment_start:query_alignment_end]``.
1816
1817 Quality scores are returned as a python array of unsigned
1818 chars. Note that this is not the ASCII-encoded value typically
1819 seen in FASTQ or SAM formatted files. Thus, no offset of 33
1820 needs to be subtracted.
1821
1822 This property is read-only.
1823 """
1824 def __get__(self):
1825 if self.cache.query_alignment_qualities is not NotImplemented:
1826 return self.cache.query_alignment_qualities
1827
1828 cdef object full_qual = self.query_qualities
1829 if full_qual is None:
1830 self.cache.query_alignment_qualities = None
1831 return None
1832
1833 cdef bam1_t *src = self._delegate
1834 cdef uint32_t start = getQueryStart(src)
1835 cdef uint32_t end = getQueryEnd(src)
1836 self.cache.query_alignment_qualities = full_qual[start:end]
1837 return self.cache.query_alignment_qualities
1838
1839 property query_alignment_qualities_str:
1840 """aligned query sequence quality values, returned as an ASCII-encoded string
1841 similar to that in FASTQ or SAM files, or None if base qualities are not present.
1842 These are the quality values that correspond to :attr:`query_alignment_sequence`,
1843 i.e., excluding qualities corresponding to soft-clipped bases.
1844
1845 This property is read-only.
1846 """
1847 def __get__(self):
1848 if self.cache.query_alignment_qualities_str is not NotImplemented:
1849 return self.cache.query_alignment_qualities_str
1850
1851 cdef object full_qual = self.query_qualities_str
1852 if full_qual is None:
1853 self.cache.query_alignment_qualities_str = None
1854 return None
1855
1856 cdef bam1_t *src = self._delegate
1857 cdef uint32_t start = getQueryStart(src)
1858 cdef uint32_t end = getQueryEnd(src)
1859 self.cache.query_alignment_qualities_str = full_qual[start:end]
1860 return self.cache.query_alignment_qualities_str
1861
1862 property query_alignment_start:
1863 """start index of the aligned query portion of the sequence (0-based,
1864 inclusive).
1865
1866 This the index of the first base in :attr:`query_sequence`
1867 that is not soft-clipped.
1868 """
1869 def __get__(self):
1870 return getQueryStart(self._delegate)
1871
1872 property query_alignment_end:
1873 """end index of the aligned query portion of the sequence (0-based,
1874 exclusive)
1875
1876 This the index just past the last base in :attr:`query_sequence`
1877 that is not soft-clipped.
1878 """
1879 def __get__(self):
1880 return getQueryEnd(self._delegate)
1881
1882 property modified_bases:
1883 """Modified bases annotations from Ml/Mm tags. The output is
1884 Dict[(canonical base, strand, modification)] -> [ (pos,qual), ...]
1885 with qual being (256*probability), or -1 if unknown.
1886 Strand==0 for forward and 1 for reverse strand modification
1887 """
1888 def __get__(self):
1889 cdef bam1_t * src
1890 cdef hts_base_mod_state *m = hts_base_mod_state_alloc()
1891 cdef hts_base_mod mods[5]
1892 cdef int pos
1893
1894 ret = {}
1895 src = self._delegate
1896
1897 if bam_parse_basemod(src, m) < 0:
1898 return None
1899
1900 n = bam_next_basemod(src, m, mods, 5, &pos)
1901
1902 while n>0:
1903 for i in range(n):
1904 mod_code = chr(mods[i].modified_base) if mods[i].modified_base>0 else -mods[i].modified_base
1905 mod_strand = mods[i].strand
1906 if self.is_reverse:
1907 mod_strand = 1 - mod_strand
1908 key = (chr(mods[i].canonical_base),
1909 mod_strand,
1910 mod_code )
1911 ret.setdefault(key,[]).append((pos,mods[i].qual))
1912
1913 n = bam_next_basemod(src, m, mods, 5, &pos)
1914
1915 if n<0:
1916 return None
1917
1918 hts_base_mod_state_free(m)
1919 return ret
1920
1921 property modified_bases_forward:
1922 """Modified bases annotations from Ml/Mm tags. The output is
1923 Dict[(canonical base, strand, modification)] -> [ (pos,qual), ...]
1924 with qual being (256*probability), or -1 if unknown.
1925 Strand==0 for forward and 1 for reverse strand modification.
1926 The positions are with respect to the original sequence from get_forward_sequence()
1927 """
1928 def __get__(self):
1929 pmods = self.modified_bases
1930 if pmods and self.is_reverse:
1931 rmod = {}
1932
1933 # Try to find the length of the original sequence
1934 rlen = self.infer_read_length()
1935 if rlen is None and self.query_sequence is None:
1936 return rmod
1937 else:
1938 rlen = len(self.query_sequence)
1939
1940 for k,mods in pmods.items():
1941 nk = k[0],1 - k[1],k[2]
1942 for i in range(len(mods)):
1943
1944 mods[i] = (rlen - 1 -mods[i][0], mods[i][1])
1945 rmod[nk] = mods
1946 return rmod
1947
1948 return pmods
1949
1950
1951 property query_alignment_length:
1952 """length of the aligned query sequence.
1953
1954 This is equal to :attr:`query_alignment_end` -
1955 :attr:`query_alignment_start`
1956 """
1957 def __get__(self):
1958 cdef bam1_t * src
1959 src = self._delegate
1960 return getQueryEnd(src) - getQueryStart(src)
1961
1962 #####################################################
1963 # Computed properties
1964
1965 def get_reference_positions(self, full_length=False):
1966 """a list of reference positions that this read aligns to.
1967
1968 By default, this method returns the (0-based) positions on the
1969 reference that are within the read's alignment, leaving gaps
1970 corresponding to deletions and other reference skips.
1971
1972 When *full_length* is True, the returned list is the same length
1973 as the read and additionally includes None values corresponding
1974 to insertions or soft-clipping, i.e., to bases of the read that
1975 are not aligned to a reference position.
1976 (See also :meth:`get_aligned_pairs` which additionally returns
1977 the corresponding positions along the read.)
1978 """
1979 cdef uint32_t k, i, l, pos
1980 cdef int op
1981 cdef uint32_t * cigar_p
1982 cdef bam1_t * src
1983 cdef bint _full = full_length
1984
1985 src = self._delegate
1986 if pysam_get_n_cigar(src) == 0:
1987 return []
1988
1989 result = []
1990 pos = src.core.pos
1991 cigar_p = pysam_bam_get_cigar(src)
1992
1993 for k from 0 <= k < pysam_get_n_cigar(src):
1994 op = cigar_p[k] & BAM_CIGAR_MASK
1995 l = cigar_p[k] >> BAM_CIGAR_SHIFT
1996
1997 if op == BAM_CSOFT_CLIP or op == BAM_CINS:
1998 if _full:
1999 for i from 0 <= i < l:
2000 result.append(None)
2001 elif op == BAM_CMATCH or op == BAM_CEQUAL or op == BAM_CDIFF:
2002 for i from pos <= i < pos + l:
2003 result.append(i)
2004 pos += l
2005 elif op == BAM_CDEL or op == BAM_CREF_SKIP:
2006 pos += l
2007
2008 return result
2009
2010 def infer_query_length(self, always=False):
2011 """infer query length from CIGAR alignment.
2012
2013 This method deduces the query length from the CIGAR alignment
2014 but does not include hard-clipped bases.
2015
2016 Returns None if CIGAR alignment is not present.
2017
2018 If *always* is set to True, `infer_read_length` is used instead.
2019 This is deprecated and only present for backward compatibility.
2020 """
2021 if always is True:
2022 return self.infer_read_length()
2023 cdef int32_t l = calculateQueryLengthWithoutHardClipping(self._delegate)
2024 if l > 0:
2025 return l
2026 else:
2027 return None
2028
2029 def infer_read_length(self):
2030 """infer read length from CIGAR alignment.
2031
2032 This method deduces the read length from the CIGAR alignment
2033 including hard-clipped bases.
2034
2035 Returns None if CIGAR alignment is not present.
2036 """
2037 cdef int32_t l = calculateQueryLengthWithHardClipping(self._delegate)
2038 if l > 0:
2039 return l
2040 else:
2041 return None
2042
2043 def get_reference_sequence(self):
2044 """return the reference sequence in the region that is covered by the
2045 alignment of the read to the reference.
2046
2047 This method requires the MD tag to be set.
2048
2049 """
2050 return force_str(build_reference_sequence(self._delegate))
2051
2052 def get_forward_sequence(self):
2053 """return the original read sequence.
2054
2055 Reads mapped to the reverse strand are stored reverse complemented in
2056 the BAM file. This method returns such reads reverse complemented back
2057 to their original orientation.
2058
2059 Returns None if the record has no query sequence.
2060 """
2061 if self.query_sequence is None:
2062 return None
2063 s = force_str(self.query_sequence)
2064 if self.is_reverse:
2065 s = s.translate(str.maketrans("ACGTacgtNnXx", "TGCAtgcaNnXx"))[::-1]
2066 return s
2067
2068 def get_forward_qualities(self):
2069 """return the original base qualities of the read sequence,
2070 in the same format as the :attr:`query_qualities` property.
2071
2072 Reads mapped to the reverse strand have their base qualities stored
2073 reversed in the BAM file. This method returns such reads' base qualities
2074 reversed back to their original orientation.
2075 """
2076 if self.is_reverse:
2077 return self.query_qualities[::-1]
2078 else:
2079 return self.query_qualities
2080
2081 def get_aligned_pairs(self, matches_only=False, with_seq=False, with_cigar=False):
2082 """a list of aligned read (query) and reference positions.
2083
2084 Each item in the returned list is a tuple consisting of
2085 the 0-based offset from the start of the read sequence
2086 followed by the 0-based reference position.
2087
2088 For inserts, deletions, skipping either query or reference
2089 position may be None.
2090
2091 For padding in the reference, the reference position will
2092 always be None.
2093
2094 Parameters
2095 ----------
2096
2097 matches_only : bool
2098 If True, only matched bases are returned --- no None on either
2099 side.
2100 with_seq : bool
2101 If True, return a third element in the tuple containing the
2102 reference sequence. For CIGAR 'P' (padding in the reference)
2103 operations, the third tuple element will be None. Substitutions
2104 are lower-case. This option requires an MD tag to be present.
2105 with_cigar : bool
2106 If True, return an extra element in the tuple containing the
2107 CIGAR operator corresponding to this position tuple.
2108
2109 Returns
2110 -------
2111
2112 aligned_pairs : list of tuples
2113
2114 """
2115 cdef uint32_t k, i, pos, qpos, r_idx, l
2116 cdef int op
2117 cdef uint32_t * cigar_p
2118 cdef bam1_t * src = self._delegate
2119 cdef bint _matches_only = bool(matches_only)
2120 cdef bint _with_seq = bool(with_seq)
2121 cdef bint _with_cigar = bool(with_cigar)
2122 cdef object (*make_tuple)(object, object, object, uint32_t, int)
2123
2124 # TODO: this method performs no checking and assumes that
2125 # read sequence, cigar and MD tag are consistent.
2126
2127 if _with_seq:
2128 # force_str required for py2/py3 compatibility
2129 ref_seq = force_str(build_reference_sequence(src))
2130 if ref_seq is None:
2131 raise ValueError("MD tag not present")
2132 make_tuple = _alignedpairs_with_seq_cigar if _with_cigar else _alignedpairs_with_seq
2133 else:
2134 ref_seq = None
2135 make_tuple = _alignedpairs_with_cigar if _with_cigar else _alignedpairs_positions
2136
2137 r_idx = 0
2138
2139 if pysam_get_n_cigar(src) == 0:
2140 return []
2141
2142 result = []
2143 pos = src.core.pos
2144 qpos = 0
2145 cigar_p = pysam_bam_get_cigar(src)
2146 for k from 0 <= k < pysam_get_n_cigar(src):
2147 op = cigar_p[k] & BAM_CIGAR_MASK
2148 l = cigar_p[k] >> BAM_CIGAR_SHIFT
2149
2150 if op == BAM_CMATCH or op == BAM_CEQUAL or op == BAM_CDIFF:
2151 for i from pos <= i < pos + l:
2152 result.append(make_tuple(qpos, i, ref_seq, r_idx, op))
2153 r_idx += 1
2154 qpos += 1
2155 pos += l
2156
2157 elif op == BAM_CINS or op == BAM_CSOFT_CLIP or op == BAM_CPAD:
2158 if not _matches_only:
2159 for i from pos <= i < pos + l:
2160 result.append(make_tuple(qpos, None, None, 0, op))
2161 qpos += 1
2162 else:
2163 qpos += l
2164
2165 elif op == BAM_CDEL:
2166 if not _matches_only:
2167 for i from pos <= i < pos + l:
2168 result.append(make_tuple(None, i, ref_seq, r_idx, op))
2169 r_idx += 1
2170 else:
2171 r_idx += l
2172 pos += l
2173
2174 elif op == BAM_CHARD_CLIP:
2175 pass # advances neither
2176
2177 elif op == BAM_CREF_SKIP:
2178 if not _matches_only:
2179 for i from pos <= i < pos + l:
2180 result.append(make_tuple(None, i, None, 0, op))
2181
2182 pos += l
2183
2184 return result
2185
2186 def get_blocks(self):
2187 """ a list of start and end positions of
2188 aligned gapless blocks.
2189
2190 The start and end positions are in genomic
2191 coordinates.
2192
2193 Blocks are not normalized, i.e. two blocks
2194 might be directly adjacent. This happens if
2195 the two blocks are separated by an insertion
2196 in the read.
2197 """
2198
2199 cdef uint32_t k, pos, l
2200 cdef int op
2201 cdef uint32_t * cigar_p
2202 cdef bam1_t * src
2203
2204 src = self._delegate
2205 if pysam_get_n_cigar(src) == 0:
2206 return []
2207
2208 result = []
2209 pos = src.core.pos
2210 cigar_p = pysam_bam_get_cigar(src)
2211 l = 0
2212
2213 for k from 0 <= k < pysam_get_n_cigar(src):
2214 op = cigar_p[k] & BAM_CIGAR_MASK
2215 l = cigar_p[k] >> BAM_CIGAR_SHIFT
2216 if op == BAM_CMATCH or op == BAM_CEQUAL or op == BAM_CDIFF:
2217 result.append((pos, pos + l))
2218 pos += l
2219 elif op == BAM_CDEL or op == BAM_CREF_SKIP:
2220 pos += l
2221
2222 return result
2223
2224 def get_overlap(self, uint32_t start, uint32_t end):
2225 """return number of aligned bases of read overlapping the interval
2226 *start* and *end* on the reference sequence.
2227
2228 Return None if cigar alignment is not available.
2229 """
2230 cdef uint32_t k, i, pos, overlap
2231 cdef int op, o
2232 cdef uint32_t * cigar_p
2233 cdef bam1_t * src
2234
2235 overlap = 0
2236
2237 src = self._delegate
2238 if pysam_get_n_cigar(src) == 0:
2239 return None
2240 pos = src.core.pos
2241 o = 0
2242
2243 cigar_p = pysam_bam_get_cigar(src)
2244 for k from 0 <= k < pysam_get_n_cigar(src):
2245 op = cigar_p[k] & BAM_CIGAR_MASK
2246 l = cigar_p[k] >> BAM_CIGAR_SHIFT
2247
2248 if op == BAM_CMATCH or op == BAM_CEQUAL or op == BAM_CDIFF:
2249 o = min( pos + l, end) - max( pos, start )
2250 if o > 0: overlap += o
2251
2252 if op == BAM_CMATCH or op == BAM_CDEL or op == BAM_CREF_SKIP or op == BAM_CEQUAL or op == BAM_CDIFF:
2253 pos += l
2254
2255 return overlap
2256
2257 def get_cigar_stats(self):
2258 """summary of operations in cigar string.
2259
2260 The output order in the array is "MIDNSHP=X" followed by a
2261 field for the NM tag. If the NM tag is not present, this
2262 field will always be 0. (Accessing this field via index -1
2263 avoids changes if more CIGAR operators are added in future.)
2264
2265 +-----+--------------------------+--------+
2266 |M |pysam.CIGAR_OPS.CMATCH |0 |
2267 +-----+--------------------------+--------+
2268 |I |pysam.CIGAR_OPS.CINS |1 |
2269 +-----+--------------------------+--------+
2270 |D |pysam.CIGAR_OPS.CDEL |2 |
2271 +-----+--------------------------+--------+
2272 |N |pysam.CIGAR_OPS.CREF_SKIP |3 |
2273 +-----+--------------------------+--------+
2274 |S |pysam.CIGAR_OPS.CSOFT_CLIP|4 |
2275 +-----+--------------------------+--------+
2276 |H |pysam.CIGAR_OPS.CHARD_CLIP|5 |
2277 +-----+--------------------------+--------+
2278 |P |pysam.CIGAR_OPS.CPAD |6 |
2279 +-----+--------------------------+--------+
2280 |= |pysam.CIGAR_OPS.CEQUAL |7 |
2281 +-----+--------------------------+--------+
2282 |X |pysam.CIGAR_OPS.CDIFF |8 |
2283 +-----+--------------------------+--------+
2284 |B |pysam.CIGAR_OPS.CBACK |9 |
2285 +-----+--------------------------+--------+
2286 |NM |NM tag |10 or -1|
2287 +-----+--------------------------+--------+
2288
2289 If no cigar string is present, empty arrays will be returned.
2290
2291 Returns:
2292 arrays :
2293 two arrays. The first contains the nucleotide counts within
2294 each cigar operation, the second contains the number of blocks
2295 for each cigar operation.
2296
2297 """
2298
2299 cdef int nfields = NCIGAR_CODES + 1
2300
2301 cdef c_array.array base_counts = array.array(
2302 "I",
2303 [0] * nfields)
2304 cdef uint32_t [:] base_view = base_counts
2305 cdef c_array.array block_counts = array.array(
2306 "I",
2307 [0] * nfields)
2308 cdef uint32_t [:] block_view = block_counts
2309
2310 cdef bam1_t * src = self._delegate
2311 cdef int op
2312 cdef uint32_t l
2313 cdef int32_t k
2314 cdef uint32_t * cigar_p = pysam_bam_get_cigar(src)
2315
2316 if cigar_p == NULL:
2317 return None
2318
2319 for k from 0 <= k < pysam_get_n_cigar(src):
2320 op = cigar_p[k] & BAM_CIGAR_MASK
2321 l = cigar_p[k] >> BAM_CIGAR_SHIFT
2322 base_view[op] += l
2323 block_view[op] += 1
2324
2325 cdef uint8_t * v = bam_aux_get(src, 'NM')
2326 if v != NULL:
2327 base_view[nfields - 1] = <int32_t>bam_aux2i(v)
2328
2329 return base_counts, block_counts
2330
2331 #####################################################
2332 ## Unsorted as yet
2333 # TODO: capture in CIGAR object
2334 property cigartuples:
2335 """the :term:`cigar` alignment. The alignment
2336 is returned as a list of tuples of (operation, length).
2337
2338 If the alignment is not present, None is returned.
2339
2340 The operations are:
2341
2342 +-----+--------------------------+-----+
2343 |M |pysam.CIGAR_OPS.CMATCH |0 |
2344 +-----+--------------------------+-----+
2345 |I |pysam.CIGAR_OPS.CINS |1 |
2346 +-----+--------------------------+-----+
2347 |D |pysam.CIGAR_OPS.CDEL |2 |
2348 +-----+--------------------------+-----+
2349 |N |pysam.CIGAR_OPS.CREF_SKIP |3 |
2350 +-----+--------------------------+-----+
2351 |S |pysam.CIGAR_OPS.CSOFT_CLIP|4 |
2352 +-----+--------------------------+-----+
2353 |H |pysam.CIGAR_OPS.CHARD_CLIP|5 |
2354 +-----+--------------------------+-----+
2355 |P |pysam.CIGAR_OPS.CPAD |6 |
2356 +-----+--------------------------+-----+
2357 |= |pysam.CIGAR_OPS.CEQUAL |7 |
2358 +-----+--------------------------+-----+
2359 |X |pysam.CIGAR_OPS.CDIFF |8 |
2360 +-----+--------------------------+-----+
2361 |B |pysam.CIGAR_OPS.CBACK |9 |
2362 +-----+--------------------------+-----+
2363
2364 .. note::
2365 The output is a list of (operation, length) tuples, such as
2366 ``[(0, 30)]``.
2367 This is different from the SAM specification and
2368 the :attr:`cigarstring` property, which uses a
2369 (length, operation) order, for example: ``30M``.
2370
2371 To unset the cigar property, assign an empty list
2372 or None.
2373 """
2374 def __get__(self):
2375 cdef uint32_t * cigar_p
2376 cdef bam1_t * src
2377 cdef uint32_t op, l
2378 cdef uint32_t k
2379
2380 src = self._delegate
2381 if pysam_get_n_cigar(src) == 0:
2382 return None
2383
2384 cigar = []
2385
2386 cigar_p = pysam_bam_get_cigar(src);
2387 for k from 0 <= k < pysam_get_n_cigar(src):
2388 op = cigar_p[k] & BAM_CIGAR_MASK
2389 l = cigar_p[k] >> BAM_CIGAR_SHIFT
2390 cigar.append((op, l))
2391 return cigar
2392
2393 def __set__(self, values):
2394 cdef uint32_t * p
2395 cdef bam1_t * src
2396 cdef op, l
2397 cdef int k
2398
2399 k = 0
2400
2401 src = self._delegate
2402
2403 # get location of cigar string
2404 p = pysam_bam_get_cigar(src)
2405
2406 # empty values for cigar string
2407 if values is None:
2408 values = []
2409
2410 cdef uint32_t ncigar = len(values)
2411
2412 cdef bam1_t * retval = pysam_bam_update(src,
2413 pysam_get_n_cigar(src) * 4,
2414 ncigar * 4,
2415 <uint8_t*>p)
2416
2417 if retval == NULL:
2418 raise MemoryError("could not allocate memory")
2419
2420 # length is number of cigar operations, not bytes
2421 pysam_set_n_cigar(src, ncigar)
2422
2423 # re-acquire pointer to location in memory
2424 # as it might have moved
2425 p = pysam_bam_get_cigar(src)
2426
2427 # insert cigar operations
2428 for op, l in values:
2429 p[k] = l << BAM_CIGAR_SHIFT | op
2430 k += 1
2431
2432 ## setting the cigar string requires updating the bin
2433 update_bin(src)
2434
2435 cpdef set_tag(self,
2436 tag,
2437 value,
2438 value_type=None,
2439 replace=True):
2440 """sets a particular field *tag* to *value* in the optional alignment
2441 section.
2442
2443 *value_type* describes the type of *value* that is to entered
2444 into the alignment record. It can be set explicitly to one of
2445 the valid one-letter type codes. If unset, an appropriate type
2446 will be chosen automatically based on the python type of
2447 *value*.
2448
2449 An existing value of the same *tag* will be overwritten unless
2450 *replace* is set to False. This is usually not recommended as a
2451 tag may only appear once in the optional alignment section.
2452
2453 If *value* is `None`, the tag will be deleted.
2454
2455 This method accepts valid SAM specification value types, which
2456 are::
2457
2458 A: printable char
2459 i: signed int
2460 f: float
2461 Z: printable string
2462 H: Byte array in hex format
2463 B: Integer or numeric array
2464
2465 Additionally, it will accept the integer BAM types ('cCsSI')
2466
2467 For htslib compatibility, 'a' is synonymous with 'A' and the
2468 method accepts a 'd' type code for a double precision float.
2469
2470 When deducing the type code by the python type of *value*, the
2471 following mapping is applied::
2472
2473 i: python int
2474 f: python float
2475 Z: python str or bytes
2476 B: python array.array, list or tuple
2477
2478 Note that a single character string will be output as 'Z' and
2479 not 'A' as the former is the more general type.
2480 """
2481
2482 cdef int value_size
2483 cdef uint8_t tc
2484 cdef uint8_t * value_ptr
2485 cdef uint8_t *existing_ptr
2486 cdef float float_value
2487 cdef double double_value
2488 cdef int32_t int32_t_value
2489 cdef uint32_t uint32_t_value
2490 cdef int16_t int16_t_value
2491 cdef uint16_t uint16_t_value
2492 cdef int8_t int8_t_value
2493 cdef uint8_t uint8_t_value
2494 cdef bam1_t * src = self._delegate
2495 cdef char * _value_type
2496 cdef c_array.array array_value
2497 cdef object buffer
2498
2499 if len(tag) != 2:
2500 raise ValueError('Invalid tag: %s' % tag)
2501
2502 tag = force_bytes(tag)
2503 if replace:
2504 existing_ptr = bam_aux_get(src, tag)
2505 if existing_ptr:
2506 bam_aux_del(src, existing_ptr)
2507
2508 # setting value to None deletes a tag
2509 if value is None:
2510 return
2511
2512 cdef uint8_t typecode = get_tag_typecode(value, value_type)
2513 if typecode == 0:
2514 raise ValueError("can't guess type or invalid type code specified: {} {}".format(
2515 value, value_type))
2516
2517 # sam_format1 for typecasting
2518 if typecode == b'Z':
2519 value = force_bytes(value)
2520 value_ptr = <uint8_t*><char*>value
2521 value_size = len(value)+1
2522 elif typecode == b'H':
2523 # Note that hex tags are stored the very same
2524 # way as Z string.s
2525 value = force_bytes(value)
2526 value_ptr = <uint8_t*><char*>value
2527 value_size = len(value)+1
2528 elif typecode == b'A' or typecode == b'a':
2529 value = force_bytes(value)
2530 value_ptr = <uint8_t*><char*>value
2531 value_size = sizeof(char)
2532 typecode = b'A'
2533 elif typecode == b'i':
2534 int32_t_value = value
2535 value_ptr = <uint8_t*>&int32_t_value
2536 value_size = sizeof(int32_t)
2537 elif typecode == b'I':
2538 uint32_t_value = value
2539 value_ptr = <uint8_t*>&uint32_t_value
2540 value_size = sizeof(uint32_t)
2541 elif typecode == b's':
2542 int16_t_value = value
2543 value_ptr = <uint8_t*>&int16_t_value
2544 value_size = sizeof(int16_t)
2545 elif typecode == b'S':
2546 uint16_t_value = value
2547 value_ptr = <uint8_t*>&uint16_t_value
2548 value_size = sizeof(uint16_t)
2549 elif typecode == b'c':
2550 int8_t_value = value
2551 value_ptr = <uint8_t*>&int8_t_value
2552 value_size = sizeof(int8_t)
2553 elif typecode == b'C':
2554 uint8_t_value = value
2555 value_ptr = <uint8_t*>&uint8_t_value
2556 value_size = sizeof(uint8_t)
2557 elif typecode == b'd':
2558 double_value = value
2559 value_ptr = <uint8_t*>&double_value
2560 value_size = sizeof(double)
2561 elif typecode == b'f':
2562 float_value = value
2563 value_ptr = <uint8_t*>&float_value
2564 value_size = sizeof(float)
2565 elif typecode == b'B':
2566 # the following goes through python, needs to be cleaned up
2567 # pack array using struct
2568 fmt, args = pack_tags([(tag, value, value_type)])
2569
2570 # remove tag and type code as set by bam_aux_append
2571 # first four chars of format (<2sB)
2572 fmt = '<' + fmt[4:]
2573 # first two values to pack
2574 args = args[2:]
2575 value_size = struct.calcsize(fmt)
2576 # buffer will be freed when object goes out of scope
2577 buffer = ctypes.create_string_buffer(value_size)
2578 struct.pack_into(fmt, buffer, 0, *args)
2579 # bam_aux_append copies data from value_ptr
2580 bam_aux_append(src,
2581 tag,
2582 typecode,
2583 value_size,
2584 <uint8_t*>buffer.raw)
2585 return
2586 else:
2587 raise ValueError('unsupported value_type {} in set_option'.format(typecode))
2588
2589 bam_aux_append(src,
2590 tag,
2591 typecode,
2592 value_size,
2593 value_ptr)
2594
2595 cpdef has_tag(self, tag):
2596 """returns true if the optional alignment section
2597 contains a given *tag*."""
2598 cdef uint8_t * v
2599 cdef int nvalues
2600 btag = force_bytes(tag)
2601 v = bam_aux_get(self._delegate, btag)
2602 return v != NULL
2603
2604 cpdef get_tag(self, tag, with_value_type=False):
2605 """
2606 retrieves data from the optional alignment section
2607 given a two-letter *tag* denoting the field.
2608
2609 The returned value is cast into an appropriate python type.
2610
2611 This method is the fastest way to access the optional
2612 alignment section if only few tags need to be retrieved.
2613
2614 Possible value types are "AcCsSiIfZHB" (see BAM format
2615 specification) as well as additional value type 'd' as
2616 implemented in htslib.
2617
2618 Parameters:
2619
2620 tag :
2621 data tag.
2622
2623 with_value_type : Optional[bool]
2624 if set to True, the return value is a tuple of (tag value, type
2625 code). (default False)
2626
2627 Returns:
2628
2629 A python object with the value of the `tag`. The type of the
2630 object depends on the data type in the data record.
2631
2632 Raises:
2633
2634 KeyError
2635 If `tag` is not present, a KeyError is raised.
2636
2637 """
2638 cdef uint8_t * v
2639 cdef int nvalues
2640 btag = force_bytes(tag)
2641 v = bam_aux_get(self._delegate, btag)
2642 if v == NULL:
2643 raise KeyError("tag '%s' not present" % tag)
2644 if chr(v[0]) == "B":
2645 auxtype = chr(v[0]) + chr(v[1])
2646 else:
2647 auxtype = chr(v[0])
2648
2649 if auxtype in "iIcCsS":
2650 value = bam_aux2i(v)
2651 elif auxtype == 'f' or auxtype == 'F':
2652 value = bam_aux2f(v)
2653 elif auxtype == 'd' or auxtype == 'D':
2654 value = bam_aux2f(v)
2655 elif auxtype == 'A' or auxtype == 'a':
2656 # force A to a
2657 v[0] = b'A'
2658 # there might a more efficient way
2659 # to convert a char into a string
2660 value = '%c' % <char>bam_aux2A(v)
2661 elif auxtype == 'Z' or auxtype == 'H':
2662 # Z and H are treated equally as strings in htslib
2663 value = charptr_to_str(<char*>bam_aux2Z(v))
2664 elif auxtype[0] == 'B':
2665 bytesize, nvalues, values = convert_binary_tag(v + 1)
2666 value = values
2667 else:
2668 raise ValueError("unknown auxiliary type '%s'" % auxtype)
2669
2670 if with_value_type:
2671 return (value, auxtype)
2672 else:
2673 return value
2674
2675 def get_tags(self, with_value_type=False):
2676 """the fields in the optional alignment section.
2677
2678 Returns a list of all fields in the optional
2679 alignment section. Values are converted to appropriate python
2680 values. For example: ``[(NM, 2), (RG, "GJP00TM04")]``
2681
2682 If *with_value_type* is set, the value type as encode in
2683 the AlignedSegment record will be returned as well:
2684
2685 [(NM, 2, "i"), (RG, "GJP00TM04", "Z")]
2686
2687 This method will convert all values in the optional alignment
2688 section. When getting only one or few tags, please see
2689 :meth:`get_tag` for a quicker way to achieve this.
2690
2691 """
2692
2693 cdef char * ctag
2694 cdef bam1_t * src
2695 cdef uint8_t * s
2696 cdef char auxtag[3]
2697 cdef char auxtype
2698 cdef uint8_t byte_size
2699 cdef int32_t nvalues
2700
2701 src = self._delegate
2702 if src.l_data == 0:
2703 return []
2704 s = pysam_bam_get_aux(src)
2705 result = []
2706 auxtag[2] = 0
2707 while s < (src.data + src.l_data):
2708 # get tag
2709 auxtag[0] = s[0]
2710 auxtag[1] = s[1]
2711 s += 2
2712 auxtype = s[0]
2713 if auxtype in (b'c', b'C'):
2714 value = <int>bam_aux2i(s)
2715 s += 1
2716 elif auxtype in (b's', b'S'):
2717 value = <int>bam_aux2i(s)
2718 s += 2
2719 elif auxtype in (b'i', b'I'):
2720 value = <int32_t>bam_aux2i(s)
2721 s += 4
2722 elif auxtype == b'f':
2723 value = <float>bam_aux2f(s)
2724 s += 4
2725 elif auxtype == b'd':
2726 value = <double>bam_aux2f(s)
2727 s += 8
2728 elif auxtype in (b'A', b'a'):
2729 value = "%c" % <char>bam_aux2A(s)
2730 s += 1
2731 elif auxtype in (b'Z', b'H'):
2732 value = charptr_to_str(<char*>bam_aux2Z(s))
2733 # +1 for NULL terminated string
2734 s += len(value) + 1
2735 elif auxtype == b'B':
2736 s += 1
2737 byte_size, nvalues, value = convert_binary_tag(s)
2738 # 5 for 1 char and 1 int
2739 s += 5 + (nvalues * byte_size) - 1
2740 else:
2741 raise KeyError("unknown type '%s'" % auxtype)
2742
2743 s += 1
2744
2745 if with_value_type:
2746 result.append((charptr_to_str(auxtag), value, chr(auxtype)))
2747 else:
2748 result.append((charptr_to_str(auxtag), value))
2749
2750 return result
2751
2752 def set_tags(self, tags):
2753 """sets the fields in the optional alignment section with
2754 a list of (tag, value) tuples.
2755
2756 The value type of the values is determined from the
2757 python type. Optionally, a type may be given explicitly as
2758 a third value in the tuple, For example:
2759
2760 x.set_tags([(NM, 2, "i"), (RG, "GJP00TM04", "Z")]
2761
2762 This method will not enforce the rule that the same tag may appear
2763 only once in the optional alignment section.
2764 """
2765
2766 cdef bam1_t * src
2767 cdef uint8_t * s
2768 cdef char * temp
2769 cdef int new_size = 0
2770 cdef int old_size
2771 src = self._delegate
2772
2773 # convert and pack the data
2774 if tags is not None and len(tags) > 0:
2775 fmt, args = pack_tags(tags)
2776 new_size = struct.calcsize(fmt)
2777 buffer = ctypes.create_string_buffer(new_size)
2778 struct.pack_into(fmt,
2779 buffer,
2780 0,
2781 *args)
2782
2783
2784 # delete the old data and allocate new space.
2785 # If total_size == 0, the aux field will be
2786 # empty
2787 old_size = pysam_bam_get_l_aux(src)
2788 cdef bam1_t * retval = pysam_bam_update(src,
2789 old_size,
2790 new_size,
2791 pysam_bam_get_aux(src))
2792 if retval == NULL:
2793 raise MemoryError("could not allocate memory")
2794
2795 # copy data only if there is any
2796 if new_size > 0:
2797
2798 # get location of new data
2799 s = pysam_bam_get_aux(src)
2800
2801 # check if there is direct path from buffer.raw to tmp
2802 p = buffer.raw
2803 # create handle to make sure buffer stays alive long
2804 # enough for memcpy, see issue 129
2805 temp = p
2806 memcpy(s, temp, new_size)
2807
2808
2809 ########################################################
2810 # Compatibility Accessors
2811 # Functions, properties for compatibility with pysam < 0.8
2812 #
2813 # Several options
2814 # change the factory functions according to API
2815 # * requires code changes throughout, incl passing
2816 # handles to factory functions
2817 # subclass functions and add attributes at runtime
2818 # e.g.: AlignedSegments.qname = AlignedSegments.query_name
2819 # * will slow down the default interface
2820 # explicit declaration of getters/setters
2821 ########################################################
2822 property qname:
2823 """deprecated, use :attr:`query_name` instead."""
2824 def __get__(self): return self.query_name
2825 def __set__(self, v): self.query_name = v
2826 property tid:
2827 """deprecated, use :attr:`reference_id` instead."""
2828 def __get__(self): return self.reference_id
2829 def __set__(self, v): self.reference_id = v
2830 property pos:
2831 """deprecated, use :attr:`reference_start` instead."""
2832 def __get__(self): return self.reference_start
2833 def __set__(self, v): self.reference_start = v
2834 property mapq:
2835 """deprecated, use :attr:`mapping_quality` instead."""
2836 def __get__(self): return self.mapping_quality
2837 def __set__(self, v): self.mapping_quality = v
2838 property rnext:
2839 """deprecated, use :attr:`next_reference_id` instead."""
2840 def __get__(self): return self.next_reference_id
2841 def __set__(self, v): self.next_reference_id = v
2842 property pnext:
2843 """deprecated, use :attr:`next_reference_start` instead."""
2844 def __get__(self):
2845 return self.next_reference_start
2846 def __set__(self, v):
2847 self.next_reference_start = v
2848 property cigar:
2849 """deprecated, use :attr:`cigarstring` or :attr:`cigartuples` instead."""
2850 def __get__(self):
2851 r = self.cigartuples
2852 if r is None:
2853 r = []
2854 return r
2855 def __set__(self, v): self.cigartuples = v
2856 property tlen:
2857 """deprecated, use :attr:`template_length` instead."""
2858 def __get__(self):
2859 return self.template_length
2860 def __set__(self, v):
2861 self.template_length = v
2862 property seq:
2863 """deprecated, use :attr:`query_sequence` instead."""
2864 def __get__(self):
2865 return self.query_sequence
2866 def __set__(self, v):
2867 self.query_sequence = v
2868 property qual:
2869 """deprecated, use :attr:`query_qualities` or :attr:`query_qualities_str` instead."""
2870 def __get__(self):
2871 return self.query_qualities_str
2872 def __set__(self, v):
2873 self.query_qualities_str = v
2874 property alen:
2875 """deprecated, use :attr:`reference_length` instead."""
2876 def __get__(self):
2877 return self.reference_length
2878 def __set__(self, v):
2879 self.reference_length = v
2880 property aend:
2881 """deprecated, use :attr:`reference_end` instead."""
2882 def __get__(self):
2883 return self.reference_end
2884 def __set__(self, v):
2885 self.reference_end = v
2886 property rlen:
2887 """deprecated, use :attr:`query_length` instead."""
2888 def __get__(self):
2889 return self.query_length
2890 def __set__(self, v):
2891 self.query_length = v
2892 property query:
2893 """deprecated, use :attr:`query_alignment_sequence`
2894 instead."""
2895 def __get__(self):
2896 return self.query_alignment_sequence
2897 property qqual:
2898 """deprecated, use :attr:`query_alignment_qualities` or :attr:`query_alignment_qualities_str`
2899 instead."""
2900 def __get__(self):
2901 return self.query_alignment_qualities_str
2902 property qstart:
2903 """deprecated, use :attr:`query_alignment_start` instead."""
2904 def __get__(self):
2905 return self.query_alignment_start
2906 property qend:
2907 """deprecated, use :attr:`query_alignment_end` instead."""
2908 def __get__(self):
2909 return self.query_alignment_end
2910 property qlen:
2911 """deprecated, use :attr:`query_alignment_length`
2912 instead."""
2913 def __get__(self):
2914 return self.query_alignment_length
2915 property mrnm:
2916 """deprecated, use :attr:`next_reference_id` instead."""
2917 def __get__(self):
2918 return self.next_reference_id
2919 def __set__(self, v):
2920 self.next_reference_id = v
2921 property mpos:
2922 """deprecated, use :attr:`next_reference_start`
2923 instead."""
2924 def __get__(self):
2925 return self.next_reference_start
2926 def __set__(self, v):
2927 self.next_reference_start = v
2928 property rname:
2929 """deprecated, use :attr:`reference_id` instead."""
2930 def __get__(self):
2931 return self.reference_id
2932 def __set__(self, v):
2933 self.reference_id = v
2934 property isize:
2935 """deprecated, use :attr:`template_length` instead."""
2936 def __get__(self):
2937 return self.template_length
2938 def __set__(self, v):
2939 self.template_length = v
2940 property blocks:
2941 """deprecated, use :meth:`get_blocks()` instead."""
2942 def __get__(self):
2943 return self.get_blocks()
2944 property aligned_pairs:
2945 """deprecated, use :meth:`get_aligned_pairs()` instead."""
2946 def __get__(self):
2947 return self.get_aligned_pairs()
2948 property inferred_length:
2949 """deprecated, use :meth:`infer_query_length()` instead."""
2950 def __get__(self):
2951 return self.infer_query_length()
2952 property positions:
2953 """deprecated, use :meth:`get_reference_positions()` instead."""
2954 def __get__(self):
2955 return self.get_reference_positions()
2956 property tags:
2957 """deprecated, use :meth:`get_tags()` instead."""
2958 def __get__(self):
2959 return self.get_tags()
2960 def __set__(self, tags):
2961 self.set_tags(tags)
2962 def overlap(self):
2963 """deprecated, use :meth:`get_overlap()` instead."""
2964 return self.get_overlap()
2965 def opt(self, tag):
2966 """deprecated, use :meth:`get_tag()` instead."""
2967 return self.get_tag(tag)
2968 def setTag(self, tag, value, value_type=None, replace=True):
2969 """deprecated, use :meth:`set_tag()` instead."""
2970 return self.set_tag(tag, value, value_type, replace)
2971
2972
2973 cdef class PileupColumn:
2974 '''A pileup of reads at a particular reference sequence position
2975 (:term:`column`). A pileup column contains all the reads that map
2976 to a certain target base.
2977
2978 This class is a proxy for results returned by the samtools pileup
2979 engine. If the underlying engine iterator advances, the results
2980 of this column will change.
2981 '''
2982 def __init__(self):
2983 raise TypeError("this class cannot be instantiated from Python")
2984
2985 def __str__(self):
2986 return "\t".join(map(str,
2987 (self.reference_id,
2988 self.reference_pos,
2989 self.nsegments))) +\
2990 "\n" +\
2991 "\n".join(map(str, self.pileups))
2992
2993 def __dealloc__(self):
2994 free(self.buf.s)
2995
2996 def set_min_base_quality(self, min_base_quality):
2997 """set the minimum base quality for this pileup column.
2998 """
2999 self.min_base_quality = min_base_quality
3000
3001 def __len__(self):
3002 """return number of reads aligned to this column.
3003
3004 see :meth:`get_num_aligned`
3005 """
3006 return self.get_num_aligned()
3007
3008 property reference_id:
3009 '''the reference sequence number as defined in the header'''
3010 def __get__(self):
3011 return self.tid
3012
3013 property reference_name:
3014 """:term:`reference` name (None if no AlignmentFile is associated)"""
3015 def __get__(self):
3016 if self.header is not None:
3017 return self.header.get_reference_name(self.tid)
3018 return None
3019
3020 property nsegments:
3021 '''number of reads mapping to this column.
3022
3023 Note that this number ignores the base quality filter.'''
3024 def __get__(self):
3025 return self.n_pu
3026 def __set__(self, n):
3027 self.n_pu = n
3028
3029 property reference_pos:
3030 '''the position in the reference sequence (0-based).'''
3031 def __get__(self):
3032 return self.pos
3033
3034 property pileups:
3035 '''list of reads (:class:`pysam.PileupRead`) aligned to this column'''
3036 def __get__(self):
3037 if self.plp == NULL or self.plp[0] == NULL:
3038 raise ValueError("PileupColumn accessed after iterator finished")
3039
3040 cdef int x
3041 cdef const bam_pileup1_t * p = NULL
3042 pileups = []
3043
3044 # warning: there could be problems if self.n and self.buf are
3045 # out of sync.
3046 for x from 0 <= x < self.n_pu:
3047 p = &(self.plp[0][x])
3048 if p == NULL:
3049 raise ValueError(
3050 "pileup buffer out of sync - most likely use of iterator "
3051 "outside loop")
3052 if pileup_base_qual_skip(p, self.min_base_quality):
3053 continue
3054 pileups.append(makePileupRead(p, self.header))
3055 return pileups
3056
3057 ########################################################
3058 # Compatibility Accessors
3059 # Functions, properties for compatibility with pysam < 0.8
3060 ########################################################
3061 property pos:
3062 """deprecated, use :attr:`reference_pos` instead."""
3063 def __get__(self):
3064 return self.reference_pos
3065 def __set__(self, v):
3066 self.reference_pos = v
3067
3068 property tid:
3069 """deprecated, use :attr:`reference_id` instead."""
3070 def __get__(self):
3071 return self.reference_id
3072 def __set__(self, v):
3073 self.reference_id = v
3074
3075 property n:
3076 """deprecated, use :attr:`nsegments` instead."""
3077 def __get__(self):
3078 return self.nsegments
3079 def __set__(self, v):
3080 self.nsegments = v
3081
3082 def get_num_aligned(self):
3083 """return number of aligned bases at pileup column position.
3084
3085 This method applies a base quality filter and the number is
3086 equal to the size of :meth:`get_query_sequences`,
3087 :meth:`get_mapping_qualities`, etc.
3088
3089 """
3090 cdef uint32_t x = 0
3091 cdef uint32_t c = 0
3092 cdef uint32_t cnt = 0
3093 cdef const bam_pileup1_t * p = NULL
3094 if self.plp == NULL or self.plp[0] == NULL:
3095 raise ValueError("PileupColumn accessed after iterator finished")
3096
3097 for x from 0 <= x < self.n_pu:
3098 p = &(self.plp[0][x])
3099 if p == NULL:
3100 raise ValueError(
3101 "pileup buffer out of sync - most likely use of iterator "
3102 "outside loop")
3103 if pileup_base_qual_skip(p, self.min_base_quality):
3104 continue
3105 cnt += 1
3106 return cnt
3107
3108 def get_query_sequences(self, bint mark_matches=False, bint mark_ends=False, bint add_indels=False):
3109 """query bases/sequences at pileup column position.
3110
3111 Optionally, the bases/sequences can be annotated according to the samtools
3112 mpileup format. This is the format description from the samtools mpileup tool::
3113
3114 Information on match, mismatch, indel, strand, mapping
3115 quality and start and end of a read are all encoded at the
3116 read base column. At this column, a dot stands for a match
3117 to the reference base on the forward strand, a comma for a
3118 match on the reverse strand, a '>' or '<' for a reference
3119 skip, `ACGTN' for a mismatch on the forward strand and
3120 `acgtn' for a mismatch on the reverse strand. A pattern
3121 `\\+[0-9]+[ACGTNacgtn]+' indicates there is an insertion
3122 between this reference position and the next reference
3123 position. The length of the insertion is given by the
3124 integer in the pattern, followed by the inserted
3125 sequence. Similarly, a pattern `-[0-9]+[ACGTNacgtn]+'
3126 represents a deletion from the reference. The deleted bases
3127 will be presented as `*' in the following lines. Also at
3128 the read base column, a symbol `^' marks the start of a
3129 read. The ASCII of the character following `^' minus 33
3130 gives the mapping quality. A symbol `$' marks the end of a
3131 read segment
3132
3133 To reproduce samtools mpileup format, set all of mark_matches,
3134 mark_ends and add_indels to True.
3135
3136 Parameters
3137 ----------
3138
3139 mark_matches: bool
3140
3141 If True, output bases matching the reference as "." or ","
3142 for forward and reverse strand, respectively. This mark
3143 requires the reference sequence. If no reference is
3144 present, this option is ignored.
3145
3146 mark_ends : bool
3147
3148 If True, add markers "^" and "$" for read start and end, respectively.
3149
3150 add_indels : bool
3151
3152 If True, add bases for bases inserted into or skipped from the
3153 reference. The latter requires a reference sequence file to have
3154 been given, e.g. via `pileup(fastafile = ...)`. If no reference
3155 sequence is available, skipped bases are represented as 'N's.
3156
3157 Returns
3158 -------
3159
3160 a list of bases/sequences per read at pileup column position. : list
3161
3162 """
3163 cdef uint32_t x = 0
3164 cdef uint32_t j = 0
3165 cdef uint32_t c = 0
3166 cdef uint8_t cc = 0
3167 cdef uint8_t rb = 0
3168 cdef kstring_t * buf = &self.buf
3169 cdef const bam_pileup1_t * p = NULL
3170
3171 if self.plp == NULL or self.plp[0] == NULL:
3172 raise ValueError("PileupColumn accessed after iterator finished")
3173
3174 buf.l = 0
3175
3176 # todo: reference sequence to count matches/mismatches
3177 # todo: convert assertions to exceptions
3178 for x from 0 <= x < self.n_pu:
3179 p = &(self.plp[0][x])
3180 if p == NULL:
3181 raise ValueError(
3182 "pileup buffer out of sync - most likely use of iterator "
3183 "outside loop")
3184 if pileup_base_qual_skip(p, self.min_base_quality):
3185 continue
3186 # see samtools pileup_seq
3187 if mark_ends and p.is_head:
3188 kputc(b'^', buf)
3189
3190 if p.b.core.qual > 93:
3191 kputc(126, buf)
3192 else:
3193 kputc(p.b.core.qual + 33, buf)
3194 if not p.is_del:
3195 if p.qpos < p.b.core.l_qseq:
3196 cc = <uint8_t>seq_nt16_str[bam_seqi(bam_get_seq(p.b), p.qpos)]
3197 else:
3198 cc = b'N'
3199
3200 if mark_matches and self.reference_sequence != NULL:
3201 rb = self.reference_sequence[self.reference_pos]
3202 if seq_nt16_table[cc] == seq_nt16_table[rb]:
3203 cc = b'='
3204 kputc(strand_mark_char(cc, p.b), buf)
3205 elif add_indels:
3206 if p.is_refskip:
3207 if bam_is_rev(p.b):
3208 kputc(b'<', buf)
3209 else:
3210 kputc(b'>', buf)
3211 else:
3212 kputc(b'*', buf)
3213 if add_indels:
3214 if p.indel > 0:
3215 kputc(b'+', buf)
3216 kputw(p.indel, buf)
3217 for j from 1 <= j <= p.indel:
3218 cc = seq_nt16_str[bam_seqi(bam_get_seq(p.b), p.qpos + j)]
3219 kputc(strand_mark_char(cc, p.b), buf)
3220 elif p.indel < 0:
3221 kputc(b'-', buf)
3222 kputw(-p.indel, buf)
3223 for j from 1 <= j <= -p.indel:
3224 # TODO: out-of-range check here?
3225 if self.reference_sequence == NULL:
3226 cc = b'N'
3227 else:
3228 cc = self.reference_sequence[self.reference_pos + j]
3229 kputc(strand_mark_char(cc, p.b), buf)
3230 if mark_ends and p.is_tail:
3231 kputc(b'$', buf)
3232
3233 kputc(b':', buf)
3234
3235 if buf.l == 0:
3236 # could be zero if all qualities are too low
3237 return ""
3238 else:
3239 # quicker to ensemble all and split than to encode all separately.
3240 # ignore last ":"
3241 return force_str(PyBytes_FromStringAndSize(buf.s, buf.l-1)).split(":")
3242
3243 def get_query_qualities(self):
3244 """query base quality scores at pileup column position.
3245
3246 Returns
3247 -------
3248
3249 a list of quality scores : list
3250 """
3251 cdef uint32_t x = 0
3252 cdef const bam_pileup1_t * p = NULL
3253 cdef uint32_t c = 0
3254 result = []
3255 for x from 0 <= x < self.n_pu:
3256 p = &(self.plp[0][x])
3257 if p == NULL:
3258 raise ValueError(
3259 "pileup buffer out of sync - most likely use of iterator "
3260 "outside loop")
3261
3262 if p.qpos < p.b.core.l_qseq:
3263 c = bam_get_qual(p.b)[p.qpos]
3264 else:
3265 c = 0
3266 if c < self.min_base_quality:
3267 continue
3268 result.append(c)
3269 return result
3270
3271 def get_mapping_qualities(self):
3272 """query mapping quality scores at pileup column position.
3273
3274 Returns
3275 -------
3276
3277 a list of quality scores : list
3278 """
3279 if self.plp == NULL or self.plp[0] == NULL:
3280 raise ValueError("PileupColumn accessed after iterator finished")
3281
3282 cdef uint32_t x = 0
3283 cdef const bam_pileup1_t * p = NULL
3284 result = []
3285 for x from 0 <= x < self.n_pu:
3286 p = &(self.plp[0][x])
3287 if p == NULL:
3288 raise ValueError(
3289 "pileup buffer out of sync - most likely use of iterator "
3290 "outside loop")
3291
3292 if pileup_base_qual_skip(p, self.min_base_quality):
3293 continue
3294 result.append(p.b.core.qual)
3295 return result
3296
3297 def get_query_positions(self):
3298 """positions in read at pileup column position.
3299
3300 Returns
3301 -------
3302
3303 a list of read positions : list
3304 """
3305 if self.plp == NULL or self.plp[0] == NULL:
3306 raise ValueError("PileupColumn accessed after iterator finished")
3307
3308 cdef uint32_t x = 0
3309 cdef const bam_pileup1_t * p = NULL
3310 result = []
3311 for x from 0 <= x < self.n_pu:
3312 p = &(self.plp[0][x])
3313 if p == NULL:
3314 raise ValueError(
3315 "pileup buffer out of sync - most likely use of iterator "
3316 "outside loop")
3317
3318 if pileup_base_qual_skip(p, self.min_base_quality):
3319 continue
3320 result.append(p.qpos)
3321 return result
3322
3323 def get_query_names(self):
3324 """query/read names aligned at pileup column position.
3325
3326 Returns
3327 -------
3328
3329 a list of query names at pileup column position. : list
3330 """
3331 if self.plp == NULL or self.plp[0] == NULL:
3332 raise ValueError("PileupColumn accessed after iterator finished")
3333
3334 cdef uint32_t x = 0
3335 cdef const bam_pileup1_t * p = NULL
3336 result = []
3337 for x from 0 <= x < self.n_pu:
3338 p = &(self.plp[0][x])
3339 if p == NULL:
3340 raise ValueError(
3341 "pileup buffer out of sync - most likely use of iterator "
3342 "outside loop")
3343
3344 if pileup_base_qual_skip(p, self.min_base_quality):
3345 continue
3346 result.append(charptr_to_str(pysam_bam_get_qname(p.b)))
3347 return result
3348
3349
3350 cdef class PileupRead:
3351 '''Representation of a read aligned to a particular position in the
3352 reference sequence.
3353
3354 '''
3355
3356 def __init__(self):
3357 raise TypeError(
3358 "this class cannot be instantiated from Python")
3359
3360 def __str__(self):
3361 return "\t".join(
3362 map(str,
3363 (self.alignment, self.query_position,
3364 self.indel, self.level,
3365 self.is_del, self.is_head,
3366 self.is_tail, self.is_refskip)))
3367
3368 property alignment:
3369 """a :class:`pysam.AlignedSegment` object of the aligned read"""
3370 def __get__(self):
3371 return self._alignment
3372
3373 property query_position:
3374 """position of the read base at the pileup site, 0-based.
3375 None if :attr:`is_del` or :attr:`is_refskip` is set.
3376
3377 """
3378 def __get__(self):
3379 if self.is_del or self.is_refskip:
3380 return None
3381 else:
3382 return self._qpos
3383
3384 property query_position_or_next:
3385 """position of the read base at the pileup site, 0-based.
3386
3387 If the current position is a deletion, returns the next
3388 aligned base.
3389
3390 """
3391 def __get__(self):
3392 return self._qpos
3393
3394 property indel:
3395 """indel length for the position following the current pileup site.
3396
3397 This quantity peeks ahead to the next cigar operation in this
3398 alignment. If the next operation is an insertion, indel will
3399 be positive. If the next operation is a deletion, it will be
3400 negation. 0 if the next operation is not an indel.
3401
3402 """
3403 def __get__(self):
3404 return self._indel
3405
3406 property level:
3407 """the level of the read in the "viewer" mode. Note that this value
3408 is currently not computed."""
3409 def __get__(self):
3410 return self._level
3411
3412 property is_del:
3413 """1 iff the base on the padded read is a deletion"""
3414 def __get__(self):
3415 return self._is_del
3416
3417 property is_head:
3418 """1 iff the base on the padded read is the left-most base."""
3419 def __get__(self):
3420 return self._is_head
3421
3422 property is_tail:
3423 """1 iff the base on the padded read is the right-most base."""
3424 def __get__(self):
3425 return self._is_tail
3426
3427 property is_refskip:
3428 """1 iff the base on the padded read is part of CIGAR N op."""
3429 def __get__(self):
3430 return self._is_refskip
3431
3432
3433
3434 cpdef enum CIGAR_OPS:
3435 CMATCH = 0
3436 CINS = 1
3437 CDEL = 2
3438 CREF_SKIP = 3
3439 CSOFT_CLIP = 4
3440 CHARD_CLIP = 5
3441 CPAD = 6
3442 CEQUAL = 7
3443 CDIFF = 8
3444 CBACK = 9
3445
3446
3447 cpdef enum SAM_FLAGS:
3448 # the read is paired in sequencing, no matter whether it is mapped in a pair
3449 FPAIRED = 1
3450 # the read is mapped in a proper pair
3451 FPROPER_PAIR = 2
3452 # the read itself is unmapped; conflictive with FPROPER_PAIR
3453 FUNMAP = 4
3454 # the mate is unmapped
3455 FMUNMAP = 8
3456 # the read is mapped to the reverse strand
3457 FREVERSE = 16
3458 # the mate is mapped to the reverse strand
3459 FMREVERSE = 32
3460 # this is read1
3461 FREAD1 = 64
3462 # this is read2
3463 FREAD2 = 128
3464 # not primary alignment
3465 FSECONDARY = 256
3466 # QC failure
3467 FQCFAIL = 512
3468 # optical or PCR duplicate
3469 FDUP = 1024
3470 # supplementary alignment
3471 FSUPPLEMENTARY = 2048
3472
3473
3474 # TODO Remove these and remove the enumerators from __all__
3475 globals().update(getattr(CIGAR_OPS, "__members__"))
3476 globals().update(getattr(SAM_FLAGS, "__members__"))
3477
3478
3479 __all__ = [
3480 "AlignedSegment",
3481 "PileupColumn",
3482 "PileupRead",
3483 "CIGAR_OPS",
3484 "CMATCH",
3485 "CINS",
3486 "CDEL",
3487 "CREF_SKIP",
3488 "CSOFT_CLIP",
3489 "CHARD_CLIP",
3490 "CPAD",
3491 "CEQUAL",
3492 "CDIFF",
3493 "CBACK",
3494 "SAM_FLAGS",
3495 "FPAIRED",
3496 "FPROPER_PAIR",
3497 "FUNMAP",
3498 "FMUNMAP",
3499 "FREVERSE",
3500 "FMREVERSE",
3501 "FREAD1",
3502 "FREAD2",
3503 "FSECONDARY",
3504 "FQCFAIL",
3505 "FDUP",
3506 "FSUPPLEMENTARY",
3507 "KEY_NAMES"]