Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

3508 řádky
118 KiB

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