You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2980 line
102 KiB

  1. # cython: embedsignature=True
  2. # cython: profile=True
  3. ########################################################
  4. ########################################################
  5. # Cython wrapper for SAM/BAM/CRAM files based on htslib
  6. ########################################################
  7. # The principal classes defined in this module are:
  8. #
  9. # class AlignmentFile read/write access to SAM/BAM/CRAM formatted files
  10. #
  11. # class AlignmentHeader manage SAM/BAM/CRAM header data
  12. #
  13. # class IndexedReads index a SAM/BAM/CRAM file by query name while keeping
  14. # the original sort order intact
  15. #
  16. # Additionally this module defines numerous additional classes that
  17. # are part of the internal API. These are:
  18. #
  19. # Various iterator classes to iterate over alignments in sequential
  20. # (IteratorRow) or in a stacked fashion (IteratorColumn):
  21. #
  22. # class IteratorRow
  23. # class IteratorRowRegion
  24. # class IteratorRowHead
  25. # class IteratorRowAll
  26. # class IteratorRowAllRefs
  27. # class IteratorRowSelection
  28. # class IteratorColumn
  29. # class IteratorColumnRegion
  30. # class IteratorColumnAll
  31. # class IteratorColumnAllRefs
  32. #
  33. ########################################################
  34. #
  35. # The MIT License
  36. #
  37. # Copyright (c) 2015 Andreas Heger
  38. #
  39. # Permission is hereby granted, free of charge, to any person obtaining a
  40. # copy of this software and associated documentation files (the "Software"),
  41. # to deal in the Software without restriction, including without limitation
  42. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  43. # and/or sell copies of the Software, and to permit persons to whom the
  44. # Software is furnished to do so, subject to the following conditions:
  45. #
  46. # The above copyright notice and this permission notice shall be included in
  47. # all copies or substantial portions of the Software.
  48. #
  49. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  50. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  51. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  52. # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  53. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  54. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  55. # DEALINGS IN THE SOFTWARE.
  56. #
  57. ########################################################
  58. import os
  59. import collections
  60. try:
  61. from collections.abc import Sequence, Mapping # noqa
  62. except ImportError:
  63. from collections import Sequence, Mapping # noqa
  64. import re
  65. import warnings
  66. import array
  67. from libc.errno cimport errno, EPIPE
  68. from libc.string cimport strcmp, strpbrk
  69. from libc.stdint cimport INT32_MAX
  70. from cpython cimport array as c_array
  71. from pysam.libcutils cimport force_bytes, force_str, charptr_to_str
  72. from pysam.libcutils cimport OSError_from_errno, encode_filename, from_string_and_size
  73. from pysam.libcalignedsegment cimport makeAlignedSegment, makePileupColumn
  74. from pysam.libchtslib cimport HTSFile, hisremote, sam_index_load2, sam_index_load3, \
  75. HTS_IDX_SAVE_REMOTE, HTS_IDX_SILENT_FAIL
  76. from io import StringIO
  77. cimport cython
  78. __all__ = [
  79. "AlignmentFile",
  80. "AlignmentHeader",
  81. "IteratorRow",
  82. "IteratorColumn",
  83. "IndexedReads"]
  84. IndexStats = collections.namedtuple("IndexStats",
  85. ("contig",
  86. "mapped",
  87. "unmapped",
  88. "total"))
  89. ########################################################
  90. ## global variables
  91. # maximum genomic coordinace
  92. # for some reason, using 'int' causes overflow
  93. cdef int MAX_POS = (1 << 31) - 1
  94. # valid types for SAM headers
  95. VALID_HEADER_TYPES = {"HD" : Mapping,
  96. "SQ" : Sequence,
  97. "RG" : Sequence,
  98. "PG" : Sequence,
  99. "CO" : Sequence}
  100. # order of records within SAM headers
  101. VALID_HEADERS = ("HD", "SQ", "RG", "PG", "CO")
  102. # default type conversions within SAM header records
  103. KNOWN_HEADER_FIELDS = {"HD" : {"VN" : str, "SO" : str, "GO" : str,
  104. "SS" : str,},
  105. "SQ" : {"SN" : str, "LN" : int, "AS" : str,
  106. "M5" : str, "SP" : str, "UR" : str,
  107. "AH" : str, "TP" : str, "DS" : str,
  108. "AN" : str,},
  109. "RG" : {"ID" : str, "CN" : str, "DS" : str,
  110. "DT" : str, "FO" : str, "KS" : str,
  111. "LB" : str, "PG" : str, "PI" : str,
  112. "PL" : str, "PM" : str, "PU" : str,
  113. "SM" : str, "BC" : str,},
  114. "PG" : {"ID" : str, "PN" : str, "CL" : str,
  115. "PP" : str, "DS" : str, "VN" : str,},}
  116. # output order of fields within records. Ensure that CL is at
  117. # the end as parsing a CL will ignore any subsequent records.
  118. VALID_HEADER_ORDER = {"HD" : ("VN", "SO", "SS", "GO"),
  119. "SQ" : ("SN", "LN", "AS", "M5",
  120. "UR", "SP", "AH", "TP",
  121. "DS", "AN"),
  122. "RG" : ("ID", "CN", "SM", "LB",
  123. "PU", "PI", "DT", "DS",
  124. "PL", "FO", "KS", "PG",
  125. "PM", "BC"),
  126. "PG" : ("PN", "ID", "VN", "PP",
  127. "DS", "CL"),}
  128. def build_header_line(fields, record):
  129. '''build a header line from `fields` dictionary for `record`'''
  130. # TODO: add checking for field and sort order
  131. line = ["@%s" % record]
  132. # comment
  133. if record == "CO":
  134. line.append(fields)
  135. # user tags
  136. elif record.islower():
  137. for key in sorted(fields):
  138. line.append("%s:%s" % (key, str(fields[key])))
  139. # defined tags
  140. else:
  141. # write fields of the specification
  142. for key in VALID_HEADER_ORDER[record]:
  143. if key in fields:
  144. line.append("%s:%s" % (key, str(fields[key])))
  145. # write user fields
  146. for key in fields:
  147. if not key.isupper():
  148. line.append("%s:%s" % (key, str(fields[key])))
  149. return "\t".join(line)
  150. cdef AlignmentHeader makeAlignmentHeader(bam_hdr_t *hdr):
  151. if not hdr:
  152. raise ValueError('cannot create AlignmentHeader, received NULL pointer')
  153. # check: is AlignmetHeader.__cinit__ called?
  154. cdef AlignmentHeader header = AlignmentHeader.__new__(AlignmentHeader)
  155. header.ptr = hdr
  156. return header
  157. def read_failure_reason(code):
  158. if code == -2:
  159. return 'truncated file'
  160. else:
  161. return "error {} while reading file".format(code)
  162. # the following should be class-method for VariantHeader, but cdef @classmethods
  163. # are not implemented in cython.
  164. cdef int fill_AlignmentHeader_from_list(bam_hdr_t *dest,
  165. reference_names,
  166. reference_lengths,
  167. add_sq_text=True,
  168. text=None) except -1:
  169. """build header from list of reference names and lengths.
  170. """
  171. cdef class AlignmentHeader(object):
  172. """header information for a :class:`AlignmentFile` object
  173. Parameters
  174. ----------
  175. header_dict : dict
  176. build header from a multi-level dictionary. The
  177. first level are the four types ('HD', 'SQ', ...). The second
  178. level are a list of lines, with each line being a list of
  179. tag-value pairs. The header is constructed first from all the
  180. defined fields, followed by user tags in alphabetical
  181. order. Alternatively, an :class:`~pysam.AlignmentHeader`
  182. object can be passed directly.
  183. text : string
  184. use the string provided as the header
  185. reference_names : list
  186. see reference_lengths
  187. reference_lengths : list
  188. build header from list of chromosome names and lengths. By
  189. default, 'SQ' and 'LN' tags will be added to the header
  190. text. This option can be changed by unsetting the flag
  191. `add_sq_text`.
  192. add_sq_text : bool
  193. do not add 'SQ' and 'LN' tags to header. This option permits
  194. construction :term:`SAM` formatted files without a header.
  195. """
  196. # See makeVariantHeader for C constructor
  197. def __cinit__(self):
  198. self.ptr = NULL
  199. # Python constructor
  200. def __init__(self):
  201. self.ptr = bam_hdr_init()
  202. if self.ptr is NULL:
  203. raise MemoryError("could not create header")
  204. @classmethod
  205. def _from_text_and_lengths(cls, text, reference_names, reference_lengths):
  206. cdef AlignmentHeader self = AlignmentHeader()
  207. cdef char *ctext
  208. cdef int l_text
  209. cdef int n, x
  210. if text is not None:
  211. btext = force_bytes(text)
  212. ctext = btext
  213. l_text = len(btext)
  214. self.ptr.text = <char*>calloc(l_text + 1, sizeof(char))
  215. if self.ptr.text == NULL:
  216. raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char))
  217. self.ptr.l_text = l_text
  218. memcpy(self.ptr.text, ctext, l_text + 1)
  219. if reference_names and reference_lengths:
  220. reference_names = [force_bytes(ref) for ref in reference_names]
  221. self.ptr.n_targets = len(reference_names)
  222. n = sum([len(reference_names) + 1])
  223. self.ptr.target_name = <char**>calloc(n, sizeof(char*))
  224. if self.ptr.target_name == NULL:
  225. raise MemoryError("could not allocate {} bytes".format(n, sizeof(char *)))
  226. self.ptr.target_len = <uint32_t*>calloc(n, sizeof(uint32_t))
  227. if self.ptr.target_len == NULL:
  228. raise MemoryError("could not allocate {} bytes".format(n, sizeof(uint32_t)))
  229. for x from 0 <= x < self.ptr.n_targets:
  230. self.ptr.target_len[x] = reference_lengths[x]
  231. name = reference_names[x]
  232. self.ptr.target_name[x] = <char*>calloc(len(name) + 1, sizeof(char))
  233. if self.ptr.target_name[x] == NULL:
  234. raise MemoryError("could not allocate {} bytes".format(len(name) + 1, sizeof(char)))
  235. strncpy(self.ptr.target_name[x], name, len(name))
  236. return self
  237. @classmethod
  238. def from_text(cls, text):
  239. reference_names, reference_lengths = [], []
  240. for line in text.splitlines():
  241. if line.startswith("@SQ"):
  242. fields = dict([x.split(":", 1) for x in line.split("\t")[1:]])
  243. try:
  244. reference_names.append(fields["SN"])
  245. reference_lengths.append(int(fields["LN"]))
  246. except KeyError:
  247. raise KeyError("incomplete sequence information in '%s'" % str(fields))
  248. except ValueError:
  249. raise ValueError("wrong sequence information in '%s'" % str(fields))
  250. return cls._from_text_and_lengths(text, reference_names, reference_lengths)
  251. @classmethod
  252. def from_dict(cls, header_dict):
  253. cdef list lines = []
  254. # first: defined tags
  255. for record in VALID_HEADERS:
  256. if record in header_dict:
  257. data = header_dict[record]
  258. if not isinstance(data, VALID_HEADER_TYPES[record]):
  259. raise ValueError(
  260. "invalid type for record {}: {}, expected {}".format(
  261. record, type(data), VALID_HEADER_TYPES[record]))
  262. if isinstance(data, Mapping):
  263. lines.append(build_header_line(data, record))
  264. else:
  265. for fields in header_dict[record]:
  266. lines.append(build_header_line(fields, record))
  267. # then: user tags (lower case), sorted alphabetically
  268. for record, data in sorted(header_dict.items()):
  269. if record in VALID_HEADERS:
  270. continue
  271. if isinstance(data, Mapping):
  272. lines.append(build_header_line(data, record))
  273. else:
  274. for fields in header_dict[record]:
  275. lines.append(build_header_line(fields, record))
  276. text = "\n".join(lines) + "\n"
  277. reference_names, reference_lengths = [], []
  278. if "SQ" in header_dict:
  279. for fields in header_dict["SQ"]:
  280. try:
  281. reference_names.append(fields["SN"])
  282. reference_lengths.append(fields["LN"])
  283. except KeyError:
  284. raise KeyError("incomplete sequence information in '%s'" % str(fields))
  285. return cls._from_text_and_lengths(text, reference_names, reference_lengths)
  286. @classmethod
  287. def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True):
  288. if len(reference_names) != len(reference_lengths):
  289. raise ValueError("number of reference names and lengths do not match")
  290. # optionally, if there is no text, add a SAM compatible header to output file.
  291. if text is None and add_sq_text:
  292. text = "".join(["@SQ\tSN:{}\tLN:{}\n".format(x, y) for x, y in zip(
  293. reference_names, reference_lengths)])
  294. return cls._from_text_and_lengths(text, reference_names, reference_lengths)
  295. def __dealloc__(self):
  296. bam_hdr_destroy(self.ptr)
  297. self.ptr = NULL
  298. def __bool__(self):
  299. return self.ptr != NULL
  300. def copy(self):
  301. return makeAlignmentHeader(bam_hdr_dup(self.ptr))
  302. property nreferences:
  303. """int with the number of :term:`reference` sequences in the file.
  304. This is a read-only attribute."""
  305. def __get__(self):
  306. return self.ptr.n_targets
  307. property references:
  308. """tuple with the names of :term:`reference` sequences. This is a
  309. read-only attribute"""
  310. def __get__(self):
  311. t = []
  312. cdef int x
  313. for x in range(self.ptr.n_targets):
  314. t.append(charptr_to_str(self.ptr.target_name[x]))
  315. return tuple(t)
  316. property lengths:
  317. """tuple of the lengths of the :term:`reference` sequences. This is a
  318. read-only attribute. The lengths are in the same order as
  319. :attr:`pysam.AlignmentFile.references`
  320. """
  321. def __get__(self):
  322. t = []
  323. cdef int x
  324. for x in range(self.ptr.n_targets):
  325. t.append(self.ptr.target_len[x])
  326. return tuple(t)
  327. def _build_sequence_section(self):
  328. """return sequence section of header.
  329. The sequence section is built from the list of reference names and
  330. lengths stored in the BAM-file and not from any @SQ entries that
  331. are part of the header's text section.
  332. """
  333. cdef int x
  334. text = []
  335. for x in range(self.ptr.n_targets):
  336. text.append("@SQ\tSN:{}\tLN:{}\n".format(
  337. force_str(self.ptr.target_name[x]),
  338. self.ptr.target_len[x]))
  339. return "".join(text)
  340. def to_dict(self):
  341. """return two-level dictionary with header information from the file.
  342. The first level contains the record (``HD``, ``SQ``, etc) and
  343. the second level contains the fields (``VN``, ``LN``, etc).
  344. The parser is validating and will raise an AssertionError if
  345. if encounters any record or field tags that are not part of
  346. the SAM specification. Use the
  347. :attr:`pysam.AlignmentFile.text` attribute to get the unparsed
  348. header.
  349. The parsing follows the SAM format specification with the
  350. exception of the ``CL`` field. This option will consume the
  351. rest of a header line irrespective of any additional fields.
  352. This behaviour has been added to accommodate command line
  353. options that contain characters that are not valid field
  354. separators.
  355. If no @SQ entries are within the text section of the header,
  356. this will be automatically added from the reference names and
  357. lengths stored in the binary part of the header.
  358. """
  359. result = collections.OrderedDict()
  360. # convert to python string
  361. t = self.__str__()
  362. for line in t.split("\n"):
  363. line = line.strip(' \0')
  364. if not line:
  365. continue
  366. assert line.startswith("@"), \
  367. "header line without '@': '%s'" % line
  368. fields = line[1:].split("\t")
  369. record = fields[0]
  370. assert record in VALID_HEADER_TYPES, \
  371. "header line with invalid type '%s': '%s'" % (record, line)
  372. # treat comments
  373. if record == "CO":
  374. if record not in result:
  375. result[record] = []
  376. result[record].append("\t".join( fields[1:]))
  377. continue
  378. # the following is clumsy as generators do not work?
  379. x = {}
  380. for idx, field in enumerate(fields[1:]):
  381. if ":" not in field:
  382. raise ValueError("malformatted header: no ':' in field" )
  383. key, value = field.split(":", 1)
  384. if key in ("CL",):
  385. # special treatment for command line
  386. # statements (CL). These might contain
  387. # characters that are non-conformant with
  388. # the valid field separators in the SAM
  389. # header. Thus, in contravention to the
  390. # SAM API, consume the rest of the line.
  391. key, value = "\t".join(fields[idx+1:]).split(":", 1)
  392. x[key] = KNOWN_HEADER_FIELDS[record][key](value)
  393. break
  394. # interpret type of known header record tags, default to str
  395. x[key] = KNOWN_HEADER_FIELDS[record].get(key, str)(value)
  396. if VALID_HEADER_TYPES[record] == Mapping:
  397. if record in result:
  398. raise ValueError(
  399. "multiple '%s' lines are not permitted" % record)
  400. result[record] = x
  401. elif VALID_HEADER_TYPES[record] == Sequence:
  402. if record not in result: result[record] = []
  403. result[record].append(x)
  404. # if there are no SQ lines in the header, add the
  405. # reference names from the information in the bam
  406. # file.
  407. #
  408. # Background: c-samtools keeps the textual part of the
  409. # header separate from the list of reference names and
  410. # lengths. Thus, if a header contains only SQ lines,
  411. # the SQ information is not part of the textual header
  412. # and thus are missing from the output. See issue 84.
  413. if "SQ" not in result:
  414. sq = []
  415. for ref, length in zip(self.references, self.lengths):
  416. sq.append({'LN': length, 'SN': ref })
  417. result["SQ"] = sq
  418. return result
  419. def as_dict(self):
  420. """deprecated, use :meth:`to_dict()` instead"""
  421. return self.to_dict()
  422. def get_reference_name(self, tid):
  423. if tid == -1:
  424. return None
  425. if not 0 <= tid < self.ptr.n_targets:
  426. raise ValueError("reference_id %i out of range 0<=tid<%i" %
  427. (tid, self.ptr.n_targets))
  428. return charptr_to_str(self.ptr.target_name[tid])
  429. def get_reference_length(self, reference):
  430. cdef int tid = self.get_tid(reference)
  431. if tid < 0:
  432. raise KeyError("unknown reference {}".format(reference))
  433. else:
  434. return self.ptr.target_len[tid]
  435. def is_valid_tid(self, int tid):
  436. """
  437. return True if the numerical :term:`tid` is valid; False otherwise.
  438. Note that the unmapped tid code (-1) counts as an invalid.
  439. """
  440. return 0 <= tid < self.ptr.n_targets
  441. def get_tid(self, reference):
  442. """
  443. return the numerical :term:`tid` corresponding to
  444. :term:`reference`
  445. returns -1 if reference is not known.
  446. """
  447. reference = force_bytes(reference)
  448. tid = bam_name2id(self.ptr, reference)
  449. if tid < -1:
  450. raise ValueError('could not parse header')
  451. return tid
  452. def __str__(self):
  453. '''string with the full contents of the :term:`sam file` header as a
  454. string.
  455. If no @SQ entries are within the text section of the header,
  456. this will be automatically added from the reference names and
  457. lengths stored in the binary part of the header.
  458. See :attr:`pysam.AlignmentFile.header.to_dict()` to get a parsed
  459. representation of the header.
  460. '''
  461. text = from_string_and_size(self.ptr.text, self.ptr.l_text)
  462. if "@SQ" not in text:
  463. text += "\n" + self._build_sequence_section()
  464. return text
  465. # dictionary access methods, for backwards compatibility.
  466. def __setitem__(self, key, value):
  467. raise TypeError("AlignmentHeader does not support item assignment (use header.to_dict()")
  468. def __getitem__(self, key):
  469. return self.to_dict().__getitem__(key)
  470. def items(self):
  471. return self.to_dict().items()
  472. # PY2 compatibility
  473. def iteritems(self):
  474. return self.to_dict().items()
  475. def keys(self):
  476. return self.to_dict().keys()
  477. def values(self):
  478. return self.to_dict().values()
  479. def get(self, *args):
  480. return self.to_dict().get(*args)
  481. def __len__(self):
  482. return self.to_dict().__len__()
  483. def __contains__(self, key):
  484. return self.to_dict().__contains__(key)
  485. cdef class AlignmentFile(HTSFile):
  486. """AlignmentFile(filepath_or_object, mode=None, template=None,
  487. reference_names=None, reference_lengths=None, text=NULL,
  488. header=None, add_sq_text=False, check_header=True, check_sq=True,
  489. reference_filename=None, filename=None, index_filename=None,
  490. filepath_index=None, require_index=False, duplicate_filehandle=True,
  491. ignore_truncation=False, threads=1)
  492. A :term:`SAM`/:term:`BAM`/:term:`CRAM` formatted file.
  493. If `filepath_or_object` is a string, the file is automatically
  494. opened. If `filepath_or_object` is a python File object, the
  495. already opened file will be used.
  496. If the file is opened for reading and an index exists (if file is BAM, a
  497. .bai file or if CRAM a .crai file), it will be opened automatically.
  498. `index_filename` may be specified explicitly. If the index is not named
  499. in the standard manner, not located in the same directory as the
  500. BAM/CRAM file, or is remote. Without an index, random access via
  501. :meth:`~pysam.AlignmentFile.fetch` and :meth:`~pysam.AlignmentFile.pileup`
  502. is disabled.
  503. For writing, the header of a :term:`SAM` file/:term:`BAM` file can
  504. be constituted from several sources (see also the samtools format
  505. specification):
  506. 1. If `template` is given, the header is copied from another
  507. `AlignmentFile` (`template` must be a
  508. :class:`~pysam.AlignmentFile`).
  509. 2. If `header` is given, the header is built from a
  510. multi-level dictionary.
  511. 3. If `text` is given, new header text is copied from raw
  512. text.
  513. 4. The names (`reference_names`) and lengths
  514. (`reference_lengths`) are supplied directly as lists.
  515. When reading or writing a CRAM file, the filename of a FASTA-formatted
  516. reference can be specified with `reference_filename`.
  517. By default, if a file is opened in mode 'r', it is checked
  518. for a valid header (`check_header` = True) and a definition of
  519. chromosome names (`check_sq` = True).
  520. Parameters
  521. ----------
  522. mode : string
  523. `mode` should be ``r`` for reading or ``w`` for writing. The
  524. default is text mode (:term:`SAM`). For binary (:term:`BAM`)
  525. I/O you should append ``b`` for compressed or ``u`` for
  526. uncompressed :term:`BAM` output. Use ``h`` to output header
  527. information in text (:term:`TAM`) mode. Use ``c`` for
  528. :term:`CRAM` formatted files.
  529. If ``b`` is present, it must immediately follow ``r`` or
  530. ``w``. Valid modes are ``r``, ``w``, ``wh``, ``rb``, ``wb``,
  531. ``wbu``, ``wb0``, ``rc`` and ``wc``. For instance, to open a
  532. :term:`BAM` formatted file for reading, type::
  533. f = pysam.AlignmentFile('ex1.bam','rb')
  534. If mode is not specified, the method will try to auto-detect
  535. in the order 'rb', 'r', thus both the following should work::
  536. f1 = pysam.AlignmentFile('ex1.bam')
  537. f2 = pysam.AlignmentFile('ex1.sam')
  538. template : AlignmentFile
  539. when writing, copy header from file `template`.
  540. header : dict or AlignmentHeader
  541. when writing, build header from a multi-level dictionary. The
  542. first level are the four types ('HD', 'SQ', ...). The second
  543. level are a list of lines, with each line being a list of
  544. tag-value pairs. The header is constructed first from all the
  545. defined fields, followed by user tags in alphabetical
  546. order. Alternatively, an :class:`~pysam.AlignmentHeader`
  547. object can be passed directly.
  548. text : string
  549. when writing, use the string provided as the header
  550. reference_names : list
  551. see reference_lengths
  552. reference_lengths : list
  553. when writing or opening a SAM file without header build header
  554. from list of chromosome names and lengths. By default, 'SQ'
  555. and 'LN' tags will be added to the header text. This option
  556. can be changed by unsetting the flag `add_sq_text`.
  557. add_sq_text : bool
  558. do not add 'SQ' and 'LN' tags to header. This option permits
  559. construction :term:`SAM` formatted files without a header.
  560. add_sam_header : bool
  561. when outputting SAM the default is to output a header. This is
  562. equivalent to opening the file in 'wh' mode. If this option is
  563. set to False, no header will be output. To read such a file,
  564. set `check_header=False`.
  565. check_header : bool
  566. obsolete: when reading a SAM file, check if header is present
  567. (default=True)
  568. check_sq : bool
  569. when reading, check if SQ entries are present in header
  570. (default=True)
  571. reference_filename : string
  572. Path to a FASTA-formatted reference file. Valid only for CRAM files.
  573. When reading a CRAM file, this overrides both ``$REF_PATH`` and the URL
  574. specified in the header (``UR`` tag), which are normally used to find
  575. the reference.
  576. index_filename : string
  577. Explicit path to the index file. Only needed if the index is not
  578. named in the standard manner, not located in the same directory as
  579. the BAM/CRAM file, or is remote. An IOError is raised if the index
  580. cannot be found or is invalid.
  581. filepath_index : string
  582. Alias for `index_filename`.
  583. require_index : bool
  584. When reading, require that an index file is present and is valid or
  585. raise an IOError. (default=False)
  586. filename : string
  587. Alternative to filepath_or_object. Filename of the file
  588. to be opened.
  589. duplicate_filehandle: bool
  590. By default, file handles passed either directly or through
  591. File-like objects will be duplicated before passing them to
  592. htslib. The duplication prevents issues where the same stream
  593. will be closed by htslib and through destruction of the
  594. high-level python object. Set to False to turn off
  595. duplication.
  596. ignore_truncation: bool
  597. Issue a warning, instead of raising an error if the current file
  598. appears to be truncated due to a missing EOF marker. Only applies
  599. to bgzipped formats. (Default=False)
  600. format_options: list
  601. A list of key=value strings, as accepted by --input-fmt-option and
  602. --output-fmt-option in samtools.
  603. threads: integer
  604. Number of threads to use for compressing/decompressing BAM/CRAM files.
  605. Setting threads to > 1 cannot be combined with `ignore_truncation`.
  606. (Default=1)
  607. """
  608. def __cinit__(self, *args, **kwargs):
  609. self.htsfile = NULL
  610. self.filename = None
  611. self.mode = None
  612. self.threads = 1
  613. self.is_stream = False
  614. self.is_remote = False
  615. self.index = NULL
  616. if "filename" in kwargs:
  617. args = [kwargs["filename"]]
  618. del kwargs["filename"]
  619. self._open(*args, **kwargs)
  620. # allocate memory for iterator
  621. self.b = <bam1_t*>calloc(1, sizeof(bam1_t))
  622. if self.b == NULL:
  623. raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t)))
  624. def has_index(self):
  625. """return true if htsfile has an existing (and opened) index.
  626. """
  627. return self.index != NULL
  628. def check_index(self):
  629. """return True if index is present.
  630. Raises
  631. ------
  632. AttributeError
  633. if htsfile is :term:`SAM` formatted and thus has no index.
  634. ValueError
  635. if htsfile is closed or index could not be opened.
  636. """
  637. if not self.is_open:
  638. raise ValueError("I/O operation on closed file")
  639. if not self.is_bam and not self.is_cram:
  640. raise AttributeError(
  641. "AlignmentFile.mapped only available in bam files")
  642. if self.index == NULL:
  643. raise ValueError(
  644. "mapping information not recorded in index "
  645. "or index not available")
  646. return True
  647. def _open(self,
  648. filepath_or_object,
  649. mode=None,
  650. AlignmentFile template=None,
  651. reference_names=None,
  652. reference_lengths=None,
  653. reference_filename=None,
  654. text=None,
  655. header=None,
  656. port=None,
  657. add_sq_text=True,
  658. add_sam_header=True,
  659. check_header=True,
  660. check_sq=True,
  661. index_filename=None,
  662. filepath_index=None,
  663. require_index=False,
  664. referencenames=None,
  665. referencelengths=None,
  666. duplicate_filehandle=True,
  667. ignore_truncation=False,
  668. format_options=None,
  669. threads=1):
  670. '''open a sam, bam or cram formatted file.
  671. If _open is called on an existing file, the current file
  672. will be closed and a new file will be opened.
  673. '''
  674. cdef char *cfilename = NULL
  675. cdef char *creference_filename = NULL
  676. cdef char *cindexname = NULL
  677. cdef char *cmode = NULL
  678. cdef bam_hdr_t * hdr = NULL
  679. cdef int ret
  680. if threads > 1 and ignore_truncation:
  681. # This won't raise errors if reaching a truncated alignment,
  682. # because bgzf_mt_reader in htslib does not deal with
  683. # bgzf_mt_read_block returning non-zero values, contrary
  684. # to bgzf_read (https://github.com/samtools/htslib/blob/1.7/bgzf.c#L888)
  685. # Better to avoid this (for now) than to produce seemingly correct results.
  686. raise ValueError('Cannot add extra threads when "ignore_truncation" is True')
  687. self.threads = threads
  688. # for backwards compatibility:
  689. if referencenames is not None:
  690. reference_names = referencenames
  691. if referencelengths is not None:
  692. reference_lengths = referencelengths
  693. # close a previously opened file
  694. if self.is_open:
  695. self.close()
  696. # autodetection for read
  697. if mode is None:
  698. mode = "r"
  699. if add_sam_header and mode == "w":
  700. mode = "wh"
  701. assert mode in ("r", "w", "rb", "wb", "wh",
  702. "wbu", "rU", "wb0",
  703. "rc", "wc"), \
  704. "invalid file opening mode `%s`" % mode
  705. self.duplicate_filehandle = duplicate_filehandle
  706. # StringIO not supported
  707. if isinstance(filepath_or_object, StringIO):
  708. raise NotImplementedError(
  709. "access from StringIO objects not supported")
  710. # reading from a file descriptor
  711. elif isinstance(filepath_or_object, int):
  712. self.filename = filepath_or_object
  713. filename = None
  714. self.is_remote = False
  715. self.is_stream = True
  716. # reading from a File object or other object with fileno
  717. elif hasattr(filepath_or_object, "fileno"):
  718. if filepath_or_object.closed:
  719. raise ValueError('I/O operation on closed file')
  720. self.filename = filepath_or_object
  721. # .name can be TextIOWrapper
  722. try:
  723. filename = encode_filename(str(filepath_or_object.name))
  724. cfilename = filename
  725. except AttributeError:
  726. filename = None
  727. self.is_remote = False
  728. self.is_stream = True
  729. # what remains is a filename
  730. else:
  731. self.filename = filename = encode_filename(filepath_or_object)
  732. cfilename = filename
  733. self.is_remote = hisremote(cfilename)
  734. self.is_stream = self.filename == b'-'
  735. # for htslib, wbu seems to not work
  736. if mode == "wbu":
  737. mode = "wb0"
  738. self.mode = force_bytes(mode)
  739. self.reference_filename = reference_filename = encode_filename(
  740. reference_filename)
  741. if mode[0] == 'w':
  742. # open file for writing
  743. if not (template or header or text or (reference_names and reference_lengths)):
  744. raise ValueError(
  745. "either supply options `template`, `header`, `text` or both `reference_names` "
  746. "and `reference_lengths` for writing")
  747. if template:
  748. # header is copied, though at the moment not strictly
  749. # necessary as AlignmentHeader is immutable.
  750. self.header = template.header.copy()
  751. elif isinstance(header, AlignmentHeader):
  752. self.header = header.copy()
  753. elif isinstance(header, Mapping):
  754. self.header = AlignmentHeader.from_dict(header)
  755. elif reference_names and reference_lengths:
  756. self.header = AlignmentHeader.from_references(
  757. reference_names,
  758. reference_lengths,
  759. add_sq_text=add_sq_text,
  760. text=text)
  761. elif text:
  762. self.header = AlignmentHeader.from_text(text)
  763. else:
  764. raise ValueError("not enough information to construct header. Please provide template, "
  765. "header, text or reference_names/reference_lengths")
  766. self.htsfile = self._open_htsfile()
  767. if self.htsfile == NULL:
  768. if errno:
  769. raise OSError_from_errno("Could not open alignment file", filename)
  770. else:
  771. raise ValueError("could not open alignment file `{}`".format(force_str(filename)))
  772. if format_options and len(format_options):
  773. self.add_hts_options(format_options)
  774. # set filename with reference sequences. If no filename
  775. # is given, the CRAM reference arrays will be built from
  776. # the @SQ header in the header
  777. if "c" in mode and reference_filename:
  778. if (hts_set_fai_filename(self.htsfile, self.reference_filename) != 0):
  779. raise ValueError("failure when setting reference filename")
  780. # write header to htsfile
  781. if "b" in mode or "c" in mode or "h" in mode:
  782. hdr = self.header.ptr
  783. with nogil:
  784. ret = sam_hdr_write(self.htsfile, hdr)
  785. if ret < 0:
  786. raise OSError_from_errno("Could not write headers", filename)
  787. elif mode[0] == "r":
  788. # open file for reading
  789. self.htsfile = self._open_htsfile()
  790. if self.htsfile == NULL:
  791. if errno:
  792. raise OSError_from_errno("Could not open alignment file", filename)
  793. else:
  794. raise ValueError("could not open alignment file `{}`".format(force_str(filename)))
  795. if self.htsfile.format.category != sequence_data:
  796. raise ValueError("file does not contain alignment data")
  797. if format_options and len(format_options):
  798. self.add_hts_options(format_options)
  799. self.check_truncation(ignore_truncation)
  800. # bam/cram files require a valid header
  801. if self.is_bam or self.is_cram:
  802. with nogil:
  803. hdr = sam_hdr_read(self.htsfile)
  804. if hdr == NULL:
  805. raise ValueError(
  806. "file does not have a valid header (mode='%s') "
  807. "- is it BAM/CRAM format?" % mode)
  808. self.header = makeAlignmentHeader(hdr)
  809. else:
  810. # in sam files a header is optional. If not given,
  811. # user may provide reference names and lengths to built
  812. # an on-the-fly header.
  813. if reference_names and reference_lengths:
  814. # build header from a target names and lengths
  815. self.header = AlignmentHeader.from_references(
  816. reference_names=reference_names,
  817. reference_lengths=reference_lengths,
  818. add_sq_text=add_sq_text,
  819. text=text)
  820. else:
  821. with nogil:
  822. hdr = sam_hdr_read(self.htsfile)
  823. if hdr == NULL:
  824. raise ValueError(
  825. "SAM? file does not have a valid header (mode='%s'), "
  826. "please provide reference_names and reference_lengths")
  827. self.header = makeAlignmentHeader(hdr)
  828. # set filename with reference sequences
  829. if self.is_cram and reference_filename:
  830. creference_filename = self.reference_filename
  831. hts_set_opt(self.htsfile,
  832. CRAM_OPT_REFERENCE,
  833. creference_filename)
  834. if check_sq and self.header.nreferences == 0:
  835. raise ValueError(
  836. ("file has no sequences defined (mode='%s') - "
  837. "is it SAM/BAM format? Consider opening with "
  838. "check_sq=False") % mode)
  839. if self.is_bam or self.is_cram:
  840. self.index_filename = index_filename or filepath_index
  841. if self.index_filename:
  842. cindexname = bfile_name = encode_filename(self.index_filename)
  843. if cfilename or cindexname:
  844. with nogil:
  845. self.index = sam_index_load3(self.htsfile, cfilename, cindexname,
  846. HTS_IDX_SAVE_REMOTE|HTS_IDX_SILENT_FAIL)
  847. if not self.index and (cindexname or require_index):
  848. if errno:
  849. raise OSError_from_errno("Could not open index file", self.index_filename)
  850. else:
  851. raise IOError('unable to open index file `%s`' % self.index_filename)
  852. elif require_index:
  853. raise IOError('unable to open index file')
  854. # save start of data section
  855. if not self.is_stream:
  856. self.start_offset = self.tell()
  857. def fetch(self,
  858. contig=None,
  859. start=None,
  860. stop=None,
  861. region=None,
  862. tid=None,
  863. until_eof=False,
  864. multiple_iterators=False,
  865. reference=None,
  866. end=None):
  867. """fetch reads aligned in a :term:`region`.
  868. See :meth:`~pysam.HTSFile.parse_region` for more information
  869. on how genomic regions can be specified. :term:`reference` and
  870. `end` are also accepted for backward compatibility as synonyms
  871. for :term:`contig` and `stop`, respectively.
  872. Without a `contig` or `region` all mapped reads in the file
  873. will be fetched. The reads will be returned ordered by reference
  874. sequence, which will not necessarily be the order within the
  875. file. This mode of iteration still requires an index. If there is
  876. no index, use `until_eof=True`.
  877. If only `contig` is set, all reads aligned to `contig`
  878. will be fetched.
  879. A :term:`SAM` file does not allow random access. If `region`
  880. or `contig` are given, an exception is raised.
  881. Parameters
  882. ----------
  883. until_eof : bool
  884. If `until_eof` is True, all reads from the current file
  885. position will be returned in order as they are within the
  886. file. Using this option will also fetch unmapped reads.
  887. multiple_iterators : bool
  888. If `multiple_iterators` is True, multiple
  889. iterators on the same file can be used at the same time. The
  890. iterator returned will receive its own copy of a filehandle to
  891. the file effectively re-opening the file. Re-opening a file
  892. creates some overhead, so beware.
  893. Returns
  894. -------
  895. An iterator over a collection of reads. : IteratorRow
  896. Raises
  897. ------
  898. ValueError
  899. if the genomic coordinates are out of range or invalid or the
  900. file does not permit random access to genomic coordinates.
  901. """
  902. cdef int rtid, rstart, rstop, has_coord
  903. if not self.is_open:
  904. raise ValueError( "I/O operation on closed file" )
  905. has_coord, rtid, rstart, rstop = self.parse_region(
  906. contig, start, stop, region, tid,
  907. end=end, reference=reference)
  908. # Turn of re-opening if htsfile is a stream
  909. if self.is_stream:
  910. multiple_iterators = False
  911. if self.is_bam or self.is_cram:
  912. if not until_eof and not self.is_remote:
  913. if not self.has_index():
  914. raise ValueError(
  915. "fetch called on bamfile without index")
  916. if has_coord:
  917. return IteratorRowRegion(
  918. self, rtid, rstart, rstop,
  919. multiple_iterators=multiple_iterators)
  920. else:
  921. if until_eof:
  922. return IteratorRowAll(
  923. self,
  924. multiple_iterators=multiple_iterators)
  925. else:
  926. # AH: check - reason why no multiple_iterators for
  927. # AllRefs?
  928. return IteratorRowAllRefs(
  929. self,
  930. multiple_iterators=multiple_iterators)
  931. else:
  932. if has_coord:
  933. raise ValueError(
  934. "fetching by region is not available for SAM files")
  935. if multiple_iterators == True:
  936. raise ValueError(
  937. "multiple iterators not implemented for SAM files")
  938. return IteratorRowAll(self,
  939. multiple_iterators=multiple_iterators)
  940. def head(self, n, multiple_iterators=True):
  941. '''return an iterator over the first n alignments.
  942. This iterator is is useful for inspecting the bam-file.
  943. Parameters
  944. ----------
  945. multiple_iterators : bool
  946. is set to True by default in order to
  947. avoid changing the current file position.
  948. Returns
  949. -------
  950. an iterator over a collection of reads : IteratorRowHead
  951. '''
  952. return IteratorRowHead(self, n,
  953. multiple_iterators=multiple_iterators)
  954. def mate(self, AlignedSegment read):
  955. '''return the mate of :class:`pysam.AlignedSegment` `read`.
  956. .. note::
  957. Calling this method will change the file position.
  958. This might interfere with any iterators that have
  959. not re-opened the file.
  960. .. note::
  961. This method is too slow for high-throughput processing.
  962. If a read needs to be processed with its mate, work
  963. from a read name sorted file or, better, cache reads.
  964. Returns
  965. -------
  966. the mate : AlignedSegment
  967. Raises
  968. ------
  969. ValueError
  970. if the read is unpaired or the mate is unmapped
  971. '''
  972. cdef uint32_t flag = read._delegate.core.flag
  973. if flag & BAM_FPAIRED == 0:
  974. raise ValueError("read %s: is unpaired" %
  975. (read.query_name))
  976. if flag & BAM_FMUNMAP != 0:
  977. raise ValueError("mate %s: is unmapped" %
  978. (read.query_name))
  979. # xor flags to get the other mate
  980. cdef int x = BAM_FREAD1 + BAM_FREAD2
  981. flag = (flag ^ x) & x
  982. # Make sure to use a separate file to jump around
  983. # to mate as otherwise the original file position
  984. # will be lost
  985. # The following code is not using the C API and
  986. # could thus be made much quicker, for example
  987. # by using tell and seek.
  988. for mate in self.fetch(
  989. read._delegate.core.mpos,
  990. read._delegate.core.mpos + 1,
  991. tid=read._delegate.core.mtid,
  992. multiple_iterators=True):
  993. if mate.flag & flag != 0 and \
  994. mate.query_name == read.query_name:
  995. break
  996. else:
  997. raise ValueError("mate not found")
  998. return mate
  999. def pileup(self,
  1000. contig=None,
  1001. start=None,
  1002. stop=None,
  1003. region=None,
  1004. reference=None,
  1005. end=None,
  1006. **kwargs):
  1007. """perform a :term:`pileup` within a :term:`region`. The region is
  1008. specified by :term:`contig`, `start` and `stop` (using
  1009. 0-based indexing). :term:`reference` and `end` are also accepted for
  1010. backward compatibility as synonyms for :term:`contig` and `stop`,
  1011. respectively. Alternatively, a samtools 'region' string
  1012. can be supplied.
  1013. Without 'contig' or 'region' all reads will be used for the
  1014. pileup. The reads will be returned ordered by
  1015. :term:`contig` sequence, which will not necessarily be the
  1016. order within the file.
  1017. Note that :term:`SAM` formatted files do not allow random
  1018. access. In these files, if a 'region' or 'contig' are
  1019. given an exception is raised.
  1020. .. note::
  1021. 'all' reads which overlap the region are returned. The
  1022. first base returned will be the first base of the first
  1023. read 'not' necessarily the first base of the region used
  1024. in the query.
  1025. Parameters
  1026. ----------
  1027. truncate : bool
  1028. By default, the samtools pileup engine outputs all reads
  1029. overlapping a region. If truncate is True and a region is
  1030. given, only columns in the exact region specified are
  1031. returned.
  1032. max_depth : int
  1033. Maximum read depth permitted. The default limit is '8000'.
  1034. stepper : string
  1035. The stepper controls how the iterator advances.
  1036. Possible options for the stepper are
  1037. ``all``
  1038. skip reads in which any of the following flags are set:
  1039. BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL, BAM_FDUP
  1040. ``nofilter``
  1041. uses every single read turning off any filtering.
  1042. ``samtools``
  1043. same filter and read processing as in samtools
  1044. pileup. For full compatibility, this requires a
  1045. 'fastafile' to be given. The following options all pertain
  1046. to filtering of the ``samtools`` stepper.
  1047. fastafile : :class:`~pysam.FastaFile` object.
  1048. This is required for some of the steppers.
  1049. ignore_overlaps: bool
  1050. If set to True, detect if read pairs overlap and only take
  1051. the higher quality base. This is the default.
  1052. flag_filter : int
  1053. ignore reads where any of the bits in the flag are set. The default is
  1054. BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP.
  1055. flag_require : int
  1056. only use reads where certain flags are set. The default is 0.
  1057. ignore_orphans: bool
  1058. ignore orphans (paired reads that are not in a proper pair).
  1059. The default is to ignore orphans.
  1060. min_base_quality: int
  1061. Minimum base quality. Bases below the minimum quality will
  1062. not be output. The default is 13.
  1063. adjust_capq_threshold: int
  1064. adjust mapping quality. The default is 0 for no
  1065. adjustment. The recommended value for adjustment is 50.
  1066. min_mapping_quality : int
  1067. only use reads above a minimum mapping quality. The default is 0.
  1068. compute_baq: bool
  1069. re-alignment computing per-Base Alignment Qualities (BAQ). The
  1070. default is to do re-alignment. Realignment requires a reference
  1071. sequence. If none is present, no realignment will be performed.
  1072. redo_baq: bool
  1073. recompute per-Base Alignment Quality on the fly ignoring
  1074. existing base qualities. The default is False (use existing
  1075. base qualities).
  1076. Returns
  1077. -------
  1078. an iterator over genomic positions. : IteratorColumn
  1079. """
  1080. cdef int rtid, has_coord
  1081. cdef int32_t rstart, rstop
  1082. if not self.is_open:
  1083. raise ValueError("I/O operation on closed file")
  1084. has_coord, rtid, rstart, rstop = self.parse_region(
  1085. contig, start, stop, region, reference=reference, end=end)
  1086. if has_coord:
  1087. if not self.has_index():
  1088. raise ValueError("no index available for pileup")
  1089. return IteratorColumnRegion(self,
  1090. tid=rtid,
  1091. start=rstart,
  1092. stop=rstop,
  1093. **kwargs)
  1094. else:
  1095. if self.has_index():
  1096. return IteratorColumnAllRefs(self, **kwargs)
  1097. else:
  1098. return IteratorColumnAll(self, **kwargs)
  1099. def count(self,
  1100. contig=None,
  1101. start=None,
  1102. stop=None,
  1103. region=None,
  1104. until_eof=False,
  1105. read_callback="nofilter",
  1106. reference=None,
  1107. end=None):
  1108. '''count the number of reads in :term:`region`
  1109. The region is specified by :term:`contig`, `start` and `stop`.
  1110. :term:`reference` and `end` are also accepted for backward
  1111. compatibility as synonyms for :term:`contig` and `stop`,
  1112. respectively. Alternatively, a `samtools`_ :term:`region`
  1113. string can be supplied.
  1114. A :term:`SAM` file does not allow random access and if
  1115. `region` or `contig` are given, an exception is raised.
  1116. Parameters
  1117. ----------
  1118. contig : string
  1119. reference_name of the genomic region (chromosome)
  1120. start : int
  1121. start of the genomic region (0-based inclusive)
  1122. stop : int
  1123. end of the genomic region (0-based exclusive)
  1124. region : string
  1125. a region string in samtools format.
  1126. until_eof : bool
  1127. count until the end of the file, possibly including
  1128. unmapped reads as well.
  1129. read_callback: string or function
  1130. select a call-back to ignore reads when counting. It can
  1131. be either a string with the following values:
  1132. ``all``
  1133. skip reads in which any of the following
  1134. flags are set: BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL,
  1135. BAM_FDUP
  1136. ``nofilter``
  1137. uses every single read
  1138. Alternatively, `read_callback` can be a function
  1139. ``check_read(read)`` that should return True only for
  1140. those reads that shall be included in the counting.
  1141. reference : string
  1142. backward compatible synonym for `contig`
  1143. end : int
  1144. backward compatible synonym for `stop`
  1145. Raises
  1146. ------
  1147. ValueError
  1148. if the genomic coordinates are out of range or invalid.
  1149. '''
  1150. cdef AlignedSegment read
  1151. cdef long counter = 0
  1152. if not self.is_open:
  1153. raise ValueError("I/O operation on closed file")
  1154. cdef int filter_method = 0
  1155. if read_callback == "all":
  1156. filter_method = 1
  1157. elif read_callback == "nofilter":
  1158. filter_method = 2
  1159. for read in self.fetch(contig=contig,
  1160. start=start,
  1161. stop=stop,
  1162. reference=reference,
  1163. end=end,
  1164. region=region,
  1165. until_eof=until_eof):
  1166. # apply filter
  1167. if filter_method == 1:
  1168. # filter = "all"
  1169. if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)):
  1170. continue
  1171. elif filter_method == 2:
  1172. # filter = "nofilter"
  1173. pass
  1174. else:
  1175. if not read_callback(read):
  1176. continue
  1177. counter += 1
  1178. return counter
  1179. @cython.boundscheck(False) # we do manual bounds checking
  1180. def count_coverage(self,
  1181. contig,
  1182. start=None,
  1183. stop=None,
  1184. region=None,
  1185. quality_threshold=15,
  1186. read_callback='all',
  1187. reference=None,
  1188. end=None):
  1189. """count the coverage of genomic positions by reads in :term:`region`.
  1190. The region is specified by :term:`contig`, `start` and `stop`.
  1191. :term:`reference` and `end` are also accepted for backward
  1192. compatibility as synonyms for :term:`contig` and `stop`,
  1193. respectively. Alternatively, a `samtools`_ :term:`region`
  1194. string can be supplied. The coverage is computed per-base [ACGT].
  1195. Parameters
  1196. ----------
  1197. contig : string
  1198. reference_name of the genomic region (chromosome)
  1199. start : int
  1200. start of the genomic region (0-based inclusive). If not
  1201. given, count from the start of the chromosome.
  1202. stop : int
  1203. end of the genomic region (0-based exclusive). If not given,
  1204. count to the end of the chromosome.
  1205. region : string
  1206. a region string.
  1207. quality_threshold : int
  1208. quality_threshold is the minimum quality score (in phred) a
  1209. base has to reach to be counted.
  1210. read_callback: string or function
  1211. select a call-back to ignore reads when counting. It can
  1212. be either a string with the following values:
  1213. ``all``
  1214. skip reads in which any of the following
  1215. flags are set: BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL,
  1216. BAM_FDUP
  1217. ``nofilter``
  1218. uses every single read
  1219. Alternatively, `read_callback` can be a function
  1220. ``check_read(read)`` that should return True only for
  1221. those reads that shall be included in the counting.
  1222. reference : string
  1223. backward compatible synonym for `contig`
  1224. end : int
  1225. backward compatible synonym for `stop`
  1226. Raises
  1227. ------
  1228. ValueError
  1229. if the genomic coordinates are out of range or invalid.
  1230. Returns
  1231. -------
  1232. four array.arrays of the same length in order A C G T : tuple
  1233. """
  1234. cdef uint32_t contig_length = self.get_reference_length(contig)
  1235. cdef int _start = start if start is not None else 0
  1236. cdef int _stop = stop if stop is not None else contig_length
  1237. _stop = _stop if _stop < contig_length else contig_length
  1238. if _stop == _start:
  1239. raise ValueError("interval of size 0")
  1240. if _stop < _start:
  1241. raise ValueError("interval of size less than 0")
  1242. cdef int length = _stop - _start
  1243. cdef c_array.array int_array_template = array.array('L', [])
  1244. cdef c_array.array count_a
  1245. cdef c_array.array count_c
  1246. cdef c_array.array count_g
  1247. cdef c_array.array count_t
  1248. count_a = c_array.clone(int_array_template, length, zero=True)
  1249. count_c = c_array.clone(int_array_template, length, zero=True)
  1250. count_g = c_array.clone(int_array_template, length, zero=True)
  1251. count_t = c_array.clone(int_array_template, length, zero=True)
  1252. cdef AlignedSegment read
  1253. cdef cython.str seq
  1254. cdef c_array.array quality
  1255. cdef int qpos
  1256. cdef int refpos
  1257. cdef int c = 0
  1258. cdef int filter_method = 0
  1259. if read_callback == "all":
  1260. filter_method = 1
  1261. elif read_callback == "nofilter":
  1262. filter_method = 2
  1263. cdef int _threshold = quality_threshold or 0
  1264. for read in self.fetch(contig=contig,
  1265. reference=reference,
  1266. start=start,
  1267. stop=stop,
  1268. end=end,
  1269. region=region):
  1270. # apply filter
  1271. if filter_method == 1:
  1272. # filter = "all"
  1273. if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)):
  1274. continue
  1275. elif filter_method == 2:
  1276. # filter = "nofilter"
  1277. pass
  1278. else:
  1279. if not read_callback(read):
  1280. continue
  1281. # count
  1282. seq = read.seq
  1283. if seq is None:
  1284. continue
  1285. quality = read.query_qualities
  1286. for qpos, refpos in read.get_aligned_pairs(True):
  1287. if qpos is not None and refpos is not None and \
  1288. _start <= refpos < _stop:
  1289. # only check base quality if _threshold > 0
  1290. if (_threshold and quality and quality[qpos] >= _threshold) or not _threshold:
  1291. if seq[qpos] == 'A':
  1292. count_a.data.as_ulongs[refpos - _start] += 1
  1293. if seq[qpos] == 'C':
  1294. count_c.data.as_ulongs[refpos - _start] += 1
  1295. if seq[qpos] == 'G':
  1296. count_g.data.as_ulongs[refpos - _start] += 1
  1297. if seq[qpos] == 'T':
  1298. count_t.data.as_ulongs[refpos - _start] += 1
  1299. return count_a, count_c, count_g, count_t
  1300. def find_introns_slow(self, read_iterator):
  1301. """Return a dictionary {(start, stop): count}
  1302. Listing the intronic sites in the reads (identified by 'N' in the cigar strings),
  1303. and their support ( = number of reads ).
  1304. read_iterator can be the result of a .fetch(...) call.
  1305. Or it can be a generator filtering such reads. Example
  1306. samfile.find_introns((read for read in samfile.fetch(...) if read.is_reverse)
  1307. """
  1308. res = collections.Counter()
  1309. for r in read_iterator:
  1310. if 'N' in r.cigarstring:
  1311. last_read_pos = False
  1312. for read_loc, genome_loc in r.get_aligned_pairs():
  1313. if read_loc is None and last_read_pos:
  1314. start = genome_loc
  1315. elif read_loc and last_read_pos is None:
  1316. stop = genome_loc # we are right exclusive ,so this is correct
  1317. res[(start, stop)] += 1
  1318. del start
  1319. del stop
  1320. last_read_pos = read_loc
  1321. return res
  1322. def find_introns(self, read_iterator):
  1323. """Return a dictionary {(start, stop): count}
  1324. Listing the intronic sites in the reads (identified by 'N' in the cigar strings),
  1325. and their support ( = number of reads ).
  1326. read_iterator can be the result of a .fetch(...) call.
  1327. Or it can be a generator filtering such reads. Example
  1328. samfile.find_introns((read for read in samfile.fetch(...) if read.is_reverse)
  1329. """
  1330. cdef:
  1331. uint32_t base_position, junc_start, nt
  1332. int op
  1333. AlignedSegment r
  1334. int BAM_CREF_SKIP = 3 #BAM_CREF_SKIP
  1335. res = collections.Counter()
  1336. match_or_deletion = {0, 2, 7, 8} # only M/=/X (0/7/8) and D (2) are related to genome position
  1337. for r in read_iterator:
  1338. base_position = r.pos
  1339. cigar = r.cigartuples
  1340. if cigar is None:
  1341. continue
  1342. for op, nt in cigar:
  1343. if op in match_or_deletion:
  1344. base_position += nt
  1345. elif op == BAM_CREF_SKIP:
  1346. junc_start = base_position
  1347. base_position += nt
  1348. res[(junc_start, base_position)] += 1
  1349. return res
  1350. def close(self):
  1351. '''closes the :class:`pysam.AlignmentFile`.'''
  1352. if self.htsfile == NULL:
  1353. return
  1354. if self.index != NULL:
  1355. hts_idx_destroy(self.index)
  1356. self.index = NULL
  1357. cdef int ret = hts_close(self.htsfile)
  1358. self.htsfile = NULL
  1359. self.header = None
  1360. if ret < 0 and errno != EPIPE:
  1361. if isinstance(self.filename, (str, bytes)):
  1362. raise OSError_from_errno("Closing failed", self.filename)
  1363. else:
  1364. raise OSError_from_errno("Closing failed")
  1365. def __dealloc__(self):
  1366. cdef int ret = 0
  1367. if self.index != NULL:
  1368. hts_idx_destroy(self.index)
  1369. self.index = NULL
  1370. if self.htsfile != NULL:
  1371. ret = hts_close(self.htsfile)
  1372. self.htsfile = NULL
  1373. self.header = None
  1374. if self.b:
  1375. bam_destroy1(self.b)
  1376. self.b = NULL
  1377. if ret < 0 and errno != EPIPE:
  1378. if isinstance(self.filename, (str, bytes)):
  1379. raise OSError_from_errno("Closing failed", self.filename)
  1380. else:
  1381. raise OSError_from_errno("Closing failed")
  1382. cpdef int write(self, AlignedSegment read) except -1:
  1383. '''
  1384. write a single :class:`pysam.AlignedSegment` to disk.
  1385. Raises:
  1386. ValueError
  1387. if the writing failed
  1388. Returns:
  1389. int :
  1390. the number of bytes written. If the file is closed,
  1391. this will be 0.
  1392. '''
  1393. if not self.is_open:
  1394. return 0
  1395. if self.header.ptr.n_targets <= read._delegate.core.tid:
  1396. raise ValueError(
  1397. "AlignedSegment refers to reference number {} that "
  1398. "is larger than the number of references ({}) in the header".format(
  1399. read._delegate.core.tid, self.header.ptr.n_targets))
  1400. cdef int ret
  1401. with nogil:
  1402. ret = sam_write1(self.htsfile,
  1403. self.header.ptr,
  1404. read._delegate)
  1405. # kbj: Still need to raise an exception with except -1. Otherwise
  1406. # when ret == -1 we get a "SystemError: error return without
  1407. # exception set".
  1408. if ret < 0:
  1409. raise IOError("sam_write1 failed with error code {}".format(ret))
  1410. return ret
  1411. # context manager interface
  1412. def __enter__(self):
  1413. return self
  1414. def __exit__(self, exc_type, exc_value, traceback):
  1415. self.close()
  1416. return False
  1417. ###############################################################
  1418. ###############################################################
  1419. ###############################################################
  1420. ## properties
  1421. ###############################################################
  1422. property mapped:
  1423. """int with total number of mapped alignments according to the
  1424. statistics recorded in the index. This is a read-only
  1425. attribute.
  1426. (This will be 0 for a CRAM file indexed by a .crai index, as that
  1427. index format does not record these statistics.)
  1428. """
  1429. def __get__(self):
  1430. self.check_index()
  1431. cdef int tid
  1432. cdef uint64_t total = 0
  1433. cdef uint64_t mapped, unmapped
  1434. for tid from 0 <= tid < self.header.nreferences:
  1435. with nogil:
  1436. hts_idx_get_stat(self.index, tid, &mapped, &unmapped)
  1437. total += mapped
  1438. return total
  1439. property unmapped:
  1440. """int with total number of unmapped reads according to the statistics
  1441. recorded in the index. This number of reads includes the number of reads
  1442. without coordinates. This is a read-only attribute.
  1443. (This will be 0 for a CRAM file indexed by a .crai index, as that
  1444. index format does not record these statistics.)
  1445. """
  1446. def __get__(self):
  1447. self.check_index()
  1448. cdef int tid
  1449. cdef uint64_t total = hts_idx_get_n_no_coor(self.index)
  1450. cdef uint64_t mapped, unmapped
  1451. for tid from 0 <= tid < self.header.nreferences:
  1452. with nogil:
  1453. hts_idx_get_stat(self.index, tid, &mapped, &unmapped)
  1454. total += unmapped
  1455. return total
  1456. property nocoordinate:
  1457. """int with total number of reads without coordinates according to the
  1458. statistics recorded in the index, i.e., the statistic printed for "*"
  1459. by the ``samtools idxstats`` command. This is a read-only attribute.
  1460. (This will be 0 for a CRAM file indexed by a .crai index, as that
  1461. index format does not record these statistics.)
  1462. """
  1463. def __get__(self):
  1464. self.check_index()
  1465. cdef uint64_t n
  1466. with nogil:
  1467. n = hts_idx_get_n_no_coor(self.index)
  1468. return n
  1469. def get_index_statistics(self):
  1470. """return statistics about mapped/unmapped reads per chromosome as
  1471. they are stored in the index, similarly to the statistics printed
  1472. by the ``samtools idxstats`` command.
  1473. CRAI indexes do not record these statistics, so for a CRAM file
  1474. with a .crai index the returned statistics will all be 0.
  1475. Returns:
  1476. list :
  1477. a list of records for each chromosome. Each record has the
  1478. attributes 'contig', 'mapped', 'unmapped' and 'total'.
  1479. """
  1480. self.check_index()
  1481. cdef int tid
  1482. cdef uint64_t mapped, unmapped
  1483. results = []
  1484. # TODO: use header
  1485. for tid from 0 <= tid < self.nreferences:
  1486. with nogil:
  1487. hts_idx_get_stat(self.index, tid, &mapped, &unmapped)
  1488. results.append(
  1489. IndexStats._make((
  1490. self.get_reference_name(tid),
  1491. mapped,
  1492. unmapped,
  1493. mapped + unmapped)))
  1494. return results
  1495. ###############################################################
  1496. ## file-object like iterator access
  1497. ## note: concurrent access will cause errors (see IteratorRow
  1498. ## and multiple_iterators)
  1499. ## Possible solutions: deprecate or open new file handle
  1500. def __iter__(self):
  1501. if not self.is_open:
  1502. raise ValueError("I/O operation on closed file")
  1503. if not self.is_bam and self.header.nreferences == 0:
  1504. raise NotImplementedError(
  1505. "can not iterate over samfile without header")
  1506. return self
  1507. cdef bam1_t * getCurrent(self):
  1508. return self.b
  1509. cdef int cnext(self):
  1510. '''
  1511. cversion of iterator. Used by :class:`pysam.AlignmentFile.IteratorColumn`.
  1512. '''
  1513. cdef int ret
  1514. cdef bam_hdr_t * hdr = self.header.ptr
  1515. with nogil:
  1516. ret = sam_read1(self.htsfile,
  1517. hdr,
  1518. self.b)
  1519. return ret
  1520. def __next__(self):
  1521. cdef int ret = self.cnext()
  1522. if ret >= 0:
  1523. return makeAlignedSegment(self.b, self.header)
  1524. elif ret == -1:
  1525. raise StopIteration
  1526. else:
  1527. raise IOError(read_failure_reason(ret))
  1528. ###########################################
  1529. # methods/properties referencing the header
  1530. def is_valid_tid(self, int tid):
  1531. """
  1532. return True if the numerical :term:`tid` is valid; False otherwise.
  1533. Note that the unmapped tid code (-1) counts as an invalid.
  1534. """
  1535. if self.header is None:
  1536. raise ValueError("header not available in closed files")
  1537. return self.header.is_valid_tid(tid)
  1538. def get_tid(self, reference):
  1539. """
  1540. return the numerical :term:`tid` corresponding to
  1541. :term:`reference`
  1542. returns -1 if reference is not known.
  1543. """
  1544. if self.header is None:
  1545. raise ValueError("header not available in closed files")
  1546. return self.header.get_tid(reference)
  1547. def get_reference_name(self, tid):
  1548. """
  1549. return :term:`reference` name corresponding to numerical :term:`tid`
  1550. """
  1551. if self.header is None:
  1552. raise ValueError("header not available in closed files")
  1553. return self.header.get_reference_name(tid)
  1554. def get_reference_length(self, reference):
  1555. """
  1556. return :term:`reference` length corresponding to numerical :term:`tid`
  1557. """
  1558. if self.header is None:
  1559. raise ValueError("header not available in closed files")
  1560. return self.header.get_reference_length(reference)
  1561. property nreferences:
  1562. """int with the number of :term:`reference` sequences in the file.
  1563. This is a read-only attribute."""
  1564. def __get__(self):
  1565. if self.header:
  1566. return self.header.nreferences
  1567. else:
  1568. raise ValueError("header not available in closed files")
  1569. property references:
  1570. """tuple with the names of :term:`reference` sequences. This is a
  1571. read-only attribute"""
  1572. def __get__(self):
  1573. if self.header:
  1574. return self.header.references
  1575. else:
  1576. raise ValueError("header not available in closed files")
  1577. property lengths:
  1578. """tuple of the lengths of the :term:`reference` sequences. This is a
  1579. read-only attribute. The lengths are in the same order as
  1580. :attr:`pysam.AlignmentFile.references`
  1581. """
  1582. def __get__(self):
  1583. if self.header:
  1584. return self.header.lengths
  1585. else:
  1586. raise ValueError("header not available in closed files")
  1587. # Compatibility functions for pysam < 0.14
  1588. property text:
  1589. """deprecated, use :attr:`references` and :attr:`lengths` instead"""
  1590. def __get__(self):
  1591. if self.header:
  1592. return self.header.__str__()
  1593. else:
  1594. raise ValueError("header not available in closed files")
  1595. # Compatibility functions for pysam < 0.8.3
  1596. def gettid(self, reference):
  1597. """deprecated, use :meth:`get_tid` instead"""
  1598. return self.get_tid(reference)
  1599. def getrname(self, tid):
  1600. """deprecated, use :meth:`get_reference_name` instead"""
  1601. return self.get_reference_name(tid)
  1602. cdef class IteratorRow:
  1603. '''abstract base class for iterators over mapped reads.
  1604. Various iterators implement different behaviours for wrapping around
  1605. contig boundaries. Examples include:
  1606. :class:`pysam.IteratorRowRegion`
  1607. iterate within a single contig and a defined region.
  1608. :class:`pysam.IteratorRowAll`
  1609. iterate until EOF. This iterator will also include unmapped reads.
  1610. :class:`pysam.IteratorRowAllRefs`
  1611. iterate over all reads in all reference sequences.
  1612. The method :meth:`AlignmentFile.fetch` returns an IteratorRow.
  1613. .. note::
  1614. It is usually not necessary to create an object of this class
  1615. explicitly. It is returned as a result of call to a
  1616. :meth:`AlignmentFile.fetch`.
  1617. '''
  1618. def __init__(self, AlignmentFile samfile, int multiple_iterators=False):
  1619. cdef char *cfilename
  1620. cdef char *creference_filename
  1621. cdef char *cindexname = NULL
  1622. if not samfile.is_open:
  1623. raise ValueError("I/O operation on closed file")
  1624. # makes sure that samfile stays alive as long as the
  1625. # iterator is alive
  1626. self.samfile = samfile
  1627. # reopen the file - note that this makes the iterator
  1628. # slow and causes pileup to slow down significantly.
  1629. if multiple_iterators:
  1630. cfilename = samfile.filename
  1631. with nogil:
  1632. self.htsfile = hts_open(cfilename, 'r')
  1633. assert self.htsfile != NULL
  1634. if samfile.has_index():
  1635. if samfile.index_filename:
  1636. cindexname = bindex_filename = encode_filename(samfile.index_filename)
  1637. with nogil:
  1638. self.index = sam_index_load2(self.htsfile, cfilename, cindexname)
  1639. else:
  1640. self.index = NULL
  1641. # need to advance in newly opened file to position after header
  1642. # better: use seek/tell?
  1643. with nogil:
  1644. hdr = sam_hdr_read(self.htsfile)
  1645. if hdr is NULL:
  1646. raise IOError("unable to read header information")
  1647. self.header = makeAlignmentHeader(hdr)
  1648. self.owns_samfile = True
  1649. # options specific to CRAM files
  1650. if samfile.is_cram and samfile.reference_filename:
  1651. creference_filename = samfile.reference_filename
  1652. hts_set_opt(self.htsfile,
  1653. CRAM_OPT_REFERENCE,
  1654. creference_filename)
  1655. else:
  1656. self.htsfile = samfile.htsfile
  1657. self.index = samfile.index
  1658. self.owns_samfile = False
  1659. self.header = samfile.header
  1660. self.retval = 0
  1661. self.b = bam_init1()
  1662. def __dealloc__(self):
  1663. bam_destroy1(self.b)
  1664. if self.owns_samfile:
  1665. hts_idx_destroy(self.index)
  1666. hts_close(self.htsfile)
  1667. cdef class IteratorRowRegion(IteratorRow):
  1668. """*(AlignmentFile samfile, int tid, int beg, int stop,
  1669. int multiple_iterators=False)*
  1670. iterate over mapped reads in a region.
  1671. .. note::
  1672. It is usually not necessary to create an object of this class
  1673. explicitly. It is returned as a result of call to a
  1674. :meth:`AlignmentFile.fetch`.
  1675. """
  1676. def __init__(self, AlignmentFile samfile,
  1677. int tid, int beg, int stop,
  1678. int multiple_iterators=False):
  1679. if not samfile.has_index():
  1680. raise ValueError("no index available for iteration")
  1681. super().__init__(samfile, multiple_iterators=multiple_iterators)
  1682. with nogil:
  1683. self.iter = sam_itr_queryi(
  1684. self.index,
  1685. tid,
  1686. beg,
  1687. stop)
  1688. def __iter__(self):
  1689. return self
  1690. cdef bam1_t * getCurrent(self):
  1691. return self.b
  1692. cdef int cnext(self):
  1693. '''cversion of iterator. Used by IteratorColumn'''
  1694. with nogil:
  1695. self.retval = hts_itr_next(hts_get_bgzfp(self.htsfile),
  1696. self.iter,
  1697. self.b,
  1698. self.htsfile)
  1699. def __next__(self):
  1700. self.cnext()
  1701. if self.retval >= 0:
  1702. return makeAlignedSegment(self.b, self.header)
  1703. elif self.retval == -1:
  1704. raise StopIteration
  1705. elif self.retval == -2:
  1706. # Note: it is currently not the case that hts_iter_next
  1707. # returns -2 for a truncated file.
  1708. # See https://github.com/pysam-developers/pysam/pull/50#issuecomment-64928625
  1709. raise IOError('truncated file')
  1710. else:
  1711. raise IOError("error while reading file {}: {}".format(self.samfile.filename, self.retval))
  1712. def __dealloc__(self):
  1713. hts_itr_destroy(self.iter)
  1714. cdef class IteratorRowHead(IteratorRow):
  1715. """*(AlignmentFile samfile, n, int multiple_iterators=False)*
  1716. iterate over first n reads in `samfile`
  1717. .. note::
  1718. It is usually not necessary to create an object of this class
  1719. explicitly. It is returned as a result of call to a
  1720. :meth:`AlignmentFile.head`.
  1721. """
  1722. def __init__(self,
  1723. AlignmentFile samfile,
  1724. int n,
  1725. int multiple_iterators=False):
  1726. super().__init__(samfile, multiple_iterators=multiple_iterators)
  1727. self.max_rows = n
  1728. self.current_row = 0
  1729. def __iter__(self):
  1730. return self
  1731. cdef bam1_t * getCurrent(self):
  1732. return self.b
  1733. cdef int cnext(self):
  1734. '''cversion of iterator. Used by IteratorColumn'''
  1735. cdef int ret
  1736. cdef bam_hdr_t * hdr = self.header.ptr
  1737. with nogil:
  1738. ret = sam_read1(self.htsfile,
  1739. hdr,
  1740. self.b)
  1741. return ret
  1742. def __next__(self):
  1743. if self.current_row >= self.max_rows:
  1744. raise StopIteration
  1745. cdef int ret = self.cnext()
  1746. if ret >= 0:
  1747. self.current_row += 1
  1748. return makeAlignedSegment(self.b, self.header)
  1749. elif ret == -1:
  1750. raise StopIteration
  1751. else:
  1752. raise IOError(read_failure_reason(ret))
  1753. cdef class IteratorRowAll(IteratorRow):
  1754. """*(AlignmentFile samfile, int multiple_iterators=False)*
  1755. iterate over all reads in `samfile`
  1756. .. note::
  1757. It is usually not necessary to create an object of this class
  1758. explicitly. It is returned as a result of call to a
  1759. :meth:`AlignmentFile.fetch`.
  1760. """
  1761. def __init__(self, AlignmentFile samfile, int multiple_iterators=False):
  1762. super().__init__(samfile, multiple_iterators=multiple_iterators)
  1763. def __iter__(self):
  1764. return self
  1765. cdef bam1_t * getCurrent(self):
  1766. return self.b
  1767. cdef int cnext(self):
  1768. '''cversion of iterator. Used by IteratorColumn'''
  1769. cdef int ret
  1770. cdef bam_hdr_t * hdr = self.header.ptr
  1771. with nogil:
  1772. ret = sam_read1(self.htsfile,
  1773. hdr,
  1774. self.b)
  1775. return ret
  1776. def __next__(self):
  1777. cdef int ret = self.cnext()
  1778. if ret >= 0:
  1779. return makeAlignedSegment(self.b, self.header)
  1780. elif ret == -1:
  1781. raise StopIteration
  1782. else:
  1783. raise IOError(read_failure_reason(ret))
  1784. cdef class IteratorRowAllRefs(IteratorRow):
  1785. """iterates over all mapped reads by chaining iterators over each
  1786. reference
  1787. .. note::
  1788. It is usually not necessary to create an object of this class
  1789. explicitly. It is returned as a result of call to a
  1790. :meth:`AlignmentFile.fetch`.
  1791. """
  1792. def __init__(self, AlignmentFile samfile, multiple_iterators=False):
  1793. super().__init__(samfile, multiple_iterators=multiple_iterators)
  1794. if not samfile.has_index():
  1795. raise ValueError("no index available for fetch")
  1796. self.tid = -1
  1797. def nextiter(self):
  1798. # get a new iterator for a chromosome. The file
  1799. # will not be re-opened.
  1800. self.rowiter = IteratorRowRegion(self.samfile,
  1801. self.tid,
  1802. 0,
  1803. MAX_POS)
  1804. # set htsfile and header of the rowiter
  1805. # to the values in this iterator to reflect multiple_iterators
  1806. self.rowiter.htsfile = self.htsfile
  1807. self.rowiter.header = self.header
  1808. # make sure the iterator understand that IteratorRowAllRefs
  1809. # has ownership
  1810. self.rowiter.owns_samfile = False
  1811. def __iter__(self):
  1812. return self
  1813. def __next__(self):
  1814. # Create an initial iterator
  1815. if self.tid == -1:
  1816. if not self.samfile.nreferences:
  1817. raise StopIteration
  1818. self.tid = 0
  1819. self.nextiter()
  1820. while 1:
  1821. self.rowiter.cnext()
  1822. # If current iterator is not exhausted, return aligned read
  1823. if self.rowiter.retval > 0:
  1824. return makeAlignedSegment(self.rowiter.b, self.header)
  1825. self.tid += 1
  1826. # Otherwise, proceed to next reference or stop
  1827. if self.tid < self.samfile.nreferences:
  1828. self.nextiter()
  1829. else:
  1830. raise StopIteration
  1831. cdef class IteratorRowSelection(IteratorRow):
  1832. """*(AlignmentFile samfile)*
  1833. iterate over reads in `samfile` at a given list of file positions.
  1834. .. note::
  1835. It is usually not necessary to create an object of this class
  1836. explicitly. It is returned as a result of call to a :meth:`AlignmentFile.fetch`.
  1837. """
  1838. def __init__(self, AlignmentFile samfile, positions, int multiple_iterators=True):
  1839. super().__init__(samfile, multiple_iterators=multiple_iterators)
  1840. self.positions = positions
  1841. self.current_pos = 0
  1842. def __iter__(self):
  1843. return self
  1844. cdef bam1_t * getCurrent(self):
  1845. return self.b
  1846. cdef int cnext(self):
  1847. '''cversion of iterator'''
  1848. # end iteration if out of positions
  1849. if self.current_pos >= len(self.positions): return -1
  1850. cdef int ret
  1851. cdef uint64_t pos = self.positions[self.current_pos]
  1852. with nogil:
  1853. ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0)
  1854. if ret < 0:
  1855. raise OSError_from_errno("Can't seek", self.samfile.filename)
  1856. self.current_pos += 1
  1857. cdef bam_hdr_t * hdr = self.header.ptr
  1858. with nogil:
  1859. ret = sam_read1(self.htsfile,
  1860. hdr,
  1861. self.b)
  1862. return ret
  1863. def __next__(self):
  1864. cdef int ret = self.cnext()
  1865. if ret >= 0:
  1866. return makeAlignedSegment(self.b, self.header)
  1867. elif ret == -1:
  1868. raise StopIteration
  1869. else:
  1870. raise IOError(read_failure_reason(ret))
  1871. cdef int __advance_nofilter(void *data, bam1_t *b):
  1872. '''advance without any read filtering.
  1873. '''
  1874. cdef __iterdata * d = <__iterdata*>data
  1875. cdef int ret
  1876. with nogil:
  1877. ret = sam_itr_next(d.htsfile, d.iter, b)
  1878. return ret
  1879. cdef int __advance_raw_nofilter(void *data, bam1_t *b):
  1880. '''advance (without iterator) without any read filtering.
  1881. '''
  1882. cdef __iterdata * d = <__iterdata*>data
  1883. cdef int ret
  1884. with nogil:
  1885. ret = sam_read1(d.htsfile, d.header, b)
  1886. return ret
  1887. cdef int __advance_all(void *data, bam1_t *b):
  1888. '''only use reads for pileup passing basic filters such as
  1889. BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL, BAM_FDUP
  1890. '''
  1891. cdef __iterdata * d = <__iterdata*>data
  1892. cdef mask = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP
  1893. cdef int ret
  1894. while 1:
  1895. with nogil:
  1896. ret = sam_itr_next(d.htsfile, d.iter, b)
  1897. if ret < 0:
  1898. break
  1899. if b.core.flag & d.flag_filter:
  1900. continue
  1901. break
  1902. return ret
  1903. cdef int __advance_raw_all(void *data, bam1_t *b):
  1904. '''only use reads for pileup passing basic filters such as
  1905. BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL, BAM_FDUP
  1906. '''
  1907. cdef __iterdata * d = <__iterdata*>data
  1908. cdef int ret
  1909. while 1:
  1910. with nogil:
  1911. ret = sam_read1(d.htsfile, d.header, b)
  1912. if ret < 0:
  1913. break
  1914. if b.core.flag & d.flag_filter:
  1915. continue
  1916. break
  1917. return ret
  1918. cdef int __advance_samtools(void * data, bam1_t * b):
  1919. '''advance using same filter and read processing as in
  1920. the samtools pileup.
  1921. '''
  1922. cdef __iterdata * d = <__iterdata*>data
  1923. cdef int ret
  1924. cdef int q
  1925. while 1:
  1926. with nogil:
  1927. ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b)
  1928. if ret < 0:
  1929. break
  1930. if b.core.flag & d.flag_filter:
  1931. continue
  1932. if d.flag_require and not (b.core.flag & d.flag_require):
  1933. continue
  1934. # reload sequence
  1935. if d.fastafile != NULL and b.core.tid != d.tid:
  1936. if d.seq != NULL:
  1937. free(d.seq)
  1938. d.tid = b.core.tid
  1939. with nogil:
  1940. d.seq = faidx_fetch_seq(
  1941. d.fastafile,
  1942. d.header.target_name[d.tid],
  1943. 0, MAX_POS,
  1944. &d.seq_len)
  1945. if d.seq == NULL:
  1946. raise ValueError(
  1947. "reference sequence for '{}' (tid={}) not found".format(
  1948. d.header.target_name[d.tid], d.tid))
  1949. # realign read - changes base qualities
  1950. if d.seq != NULL and d.compute_baq:
  1951. # 4th option to realign is flag:
  1952. # apply_baq = flag&1, extend_baq = flag&2, redo_baq = flag&4
  1953. if d.redo_baq:
  1954. sam_prob_realn(b, d.seq, d.seq_len, 7)
  1955. else:
  1956. sam_prob_realn(b, d.seq, d.seq_len, 3)
  1957. if d.seq != NULL and d.adjust_capq_threshold > 10:
  1958. q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold)
  1959. if q < 0:
  1960. continue
  1961. elif b.core.qual > q:
  1962. b.core.qual = q
  1963. if b.core.qual < d.min_mapping_quality:
  1964. continue
  1965. if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR):
  1966. continue
  1967. break
  1968. return ret
  1969. cdef class IteratorColumn:
  1970. '''abstract base class for iterators over columns.
  1971. IteratorColumn objects wrap the pileup functionality of samtools.
  1972. For reasons of efficiency, the iterator points to the current
  1973. pileup buffer. The pileup buffer is updated at every iteration.
  1974. This might cause some unexpected behaviour. For example,
  1975. consider the conversion to a list::
  1976. f = AlignmentFile("file.bam", "rb")
  1977. result = list(f.pileup())
  1978. Here, ``result`` will contain ``n`` objects of type
  1979. :class:`~pysam.PileupColumn` for ``n`` columns, but each object in
  1980. ``result`` will contain the same information.
  1981. The desired behaviour can be achieved by list comprehension::
  1982. result = [x.pileups() for x in f.pileup()]
  1983. ``result`` will be a list of ``n`` lists of objects of type
  1984. :class:`~pysam.PileupRead`.
  1985. If the iterator is associated with a :class:`~pysam.Fastafile`
  1986. using the :meth:`add_reference` method, then the iterator will
  1987. export the current sequence via the methods :meth:`get_sequence`
  1988. and :meth:`seq_len`.
  1989. See :class:`~AlignmentFile.pileup` for kwargs to the iterator.
  1990. '''
  1991. def __cinit__( self, AlignmentFile samfile, **kwargs):
  1992. self.samfile = samfile
  1993. self.fastafile = kwargs.get("fastafile", None)
  1994. self.stepper = kwargs.get("stepper", "samtools")
  1995. self.max_depth = kwargs.get("max_depth", 8000)
  1996. self.ignore_overlaps = kwargs.get("ignore_overlaps", True)
  1997. self.min_base_quality = kwargs.get("min_base_quality", 13)
  1998. self.iterdata.seq = NULL
  1999. self.iterdata.min_mapping_quality = kwargs.get("min_mapping_quality", 0)
  2000. self.iterdata.flag_require = kwargs.get("flag_require", 0)
  2001. self.iterdata.flag_filter = kwargs.get("flag_filter", BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP)
  2002. self.iterdata.adjust_capq_threshold = kwargs.get("adjust_capq_threshold", 0)
  2003. self.iterdata.compute_baq = kwargs.get("compute_baq", True)
  2004. self.iterdata.redo_baq = kwargs.get("redo_baq", False)
  2005. self.iterdata.ignore_orphans = kwargs.get("ignore_orphans", True)
  2006. self.tid = 0
  2007. self.pos = 0
  2008. self.n_plp = 0
  2009. self.plp = NULL
  2010. self.pileup_iter = <bam_mplp_t>NULL
  2011. def __iter__(self):
  2012. return self
  2013. cdef int cnext(self):
  2014. '''perform next iteration.
  2015. '''
  2016. # do not release gil here because of call-backs
  2017. cdef int ret = bam_mplp_auto(self.pileup_iter,
  2018. &self.tid,
  2019. &self.pos,
  2020. &self.n_plp,
  2021. &self.plp)
  2022. return ret
  2023. cdef char * get_sequence(self):
  2024. '''return current reference sequence underlying the iterator.
  2025. '''
  2026. return self.iterdata.seq
  2027. property seq_len:
  2028. '''current sequence length.'''
  2029. def __get__(self):
  2030. return self.iterdata.seq_len
  2031. def add_reference(self, FastaFile fastafile):
  2032. '''
  2033. add reference sequences in `fastafile` to iterator.'''
  2034. self.fastafile = fastafile
  2035. if self.iterdata.seq != NULL:
  2036. free(self.iterdata.seq)
  2037. self.iterdata.tid = -1
  2038. self.iterdata.fastafile = self.fastafile.fastafile
  2039. def has_reference(self):
  2040. '''
  2041. return true if iterator is associated with a reference'''
  2042. return self.fastafile
  2043. cdef _setup_iterator(self,
  2044. int tid,
  2045. int start,
  2046. int stop,
  2047. int multiple_iterators=0):
  2048. '''setup the iterator structure'''
  2049. self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators)
  2050. self.iterdata.htsfile = self.samfile.htsfile
  2051. self.iterdata.iter = self.iter.iter
  2052. self.iterdata.seq = NULL
  2053. self.iterdata.tid = -1
  2054. self.iterdata.header = self.samfile.header.ptr
  2055. if self.fastafile is not None:
  2056. self.iterdata.fastafile = self.fastafile.fastafile
  2057. else:
  2058. self.iterdata.fastafile = NULL
  2059. # Free any previously allocated memory before reassigning
  2060. # pileup_iter
  2061. self._free_pileup_iter()
  2062. cdef void * data[1]
  2063. data[0] = <void*>&self.iterdata
  2064. if self.stepper is None or self.stepper == "all":
  2065. with nogil:
  2066. self.pileup_iter = bam_mplp_init(1,
  2067. <bam_plp_auto_f>&__advance_all,
  2068. data)
  2069. elif self.stepper == "nofilter":
  2070. with nogil:
  2071. self.pileup_iter = bam_mplp_init(1,
  2072. <bam_plp_auto_f>&__advance_nofilter,
  2073. data)
  2074. elif self.stepper == "samtools":
  2075. with nogil:
  2076. self.pileup_iter = bam_mplp_init(1,
  2077. <bam_plp_auto_f>&__advance_samtools,
  2078. data)
  2079. else:
  2080. raise ValueError(
  2081. "unknown stepper option `%s` in IteratorColumn" % self.stepper)
  2082. if self.max_depth:
  2083. with nogil:
  2084. bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth)
  2085. if self.ignore_overlaps:
  2086. with nogil:
  2087. bam_mplp_init_overlaps(self.pileup_iter)
  2088. cdef _setup_raw_rest_iterator(self):
  2089. '''set up an "iterator" that just uses sam_read1(), similar to HTS_IDX_REST'''
  2090. self.iter = None
  2091. self.iterdata.iter = NULL
  2092. self.iterdata.htsfile = self.samfile.htsfile
  2093. self.iterdata.seq = NULL
  2094. self.iterdata.tid = -1
  2095. self.iterdata.header = self.samfile.header.ptr
  2096. if self.fastafile is not None:
  2097. self.iterdata.fastafile = self.fastafile.fastafile
  2098. else:
  2099. self.iterdata.fastafile = NULL
  2100. # Free any previously allocated memory before reassigning
  2101. # pileup_iter
  2102. self._free_pileup_iter()
  2103. cdef void * data[1]
  2104. data[0] = <void*>&self.iterdata
  2105. if self.stepper is None or self.stepper == "all":
  2106. with nogil:
  2107. self.pileup_iter = bam_mplp_init(1,
  2108. <bam_plp_auto_f>&__advance_raw_all,
  2109. data)
  2110. elif self.stepper == "nofilter":
  2111. with nogil:
  2112. self.pileup_iter = bam_mplp_init(1,
  2113. <bam_plp_auto_f>&__advance_raw_nofilter,
  2114. data)
  2115. elif self.stepper == "samtools":
  2116. with nogil:
  2117. self.pileup_iter = bam_mplp_init(1,
  2118. <bam_plp_auto_f>&__advance_samtools,
  2119. data)
  2120. else:
  2121. raise ValueError(
  2122. "unknown stepper option `%s` in IteratorColumn" % self.stepper)
  2123. if self.max_depth:
  2124. with nogil:
  2125. bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth)
  2126. if self.ignore_overlaps:
  2127. with nogil:
  2128. bam_mplp_init_overlaps(self.pileup_iter)
  2129. cdef reset(self, tid, start, stop):
  2130. '''reset iterator position.
  2131. This permits using the iterator multiple times without
  2132. having to incur the full set-up costs.
  2133. '''
  2134. if self.iter is None:
  2135. raise TypeError("Raw iterator set up without region cannot be reset")
  2136. self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators=0)
  2137. self.iterdata.iter = self.iter.iter
  2138. # invalidate sequence if different tid
  2139. if self.tid != tid:
  2140. if self.iterdata.seq != NULL:
  2141. free(self.iterdata.seq)
  2142. self.iterdata.seq = NULL
  2143. self.iterdata.tid = -1
  2144. # self.pileup_iter = bam_mplp_init(1
  2145. # &__advancepileup,
  2146. # &self.iterdata)
  2147. with nogil:
  2148. bam_mplp_reset(self.pileup_iter)
  2149. cdef _free_pileup_iter(self):
  2150. '''free the memory alloc'd by bam_plp_init.
  2151. This is needed before setup_iterator allocates another
  2152. pileup_iter, or else memory will be lost. '''
  2153. if self.pileup_iter != <bam_mplp_t>NULL:
  2154. with nogil:
  2155. bam_mplp_reset(self.pileup_iter)
  2156. bam_mplp_destroy(self.pileup_iter)
  2157. self.pileup_iter = <bam_mplp_t>NULL
  2158. def __dealloc__(self):
  2159. # reset in order to avoid memory leak messages for iterators
  2160. # that have not been fully consumed
  2161. self._free_pileup_iter()
  2162. self.plp = <const bam_pileup1_t*>NULL
  2163. if self.iterdata.seq != NULL:
  2164. free(self.iterdata.seq)
  2165. self.iterdata.seq = NULL
  2166. # backwards compatibility
  2167. def hasReference(self):
  2168. return self.has_reference()
  2169. cdef char * getSequence(self):
  2170. return self.get_sequence()
  2171. def addReference(self, FastaFile fastafile):
  2172. return self.add_reference(fastafile)
  2173. cdef class IteratorColumnRegion(IteratorColumn):
  2174. '''iterates over a region only.
  2175. '''
  2176. def __cinit__(self,
  2177. AlignmentFile samfile,
  2178. int tid = 0,
  2179. int start = 0,
  2180. int stop = MAX_POS,
  2181. int truncate = False,
  2182. int multiple_iterators = True,
  2183. **kwargs ):
  2184. # initialize iterator. Multiple iterators not available
  2185. # for CRAM.
  2186. if multiple_iterators and samfile.is_cram:
  2187. warnings.warn("multiple_iterators not implemented for CRAM")
  2188. multiple_iterators = False
  2189. self._setup_iterator(tid, start, stop, multiple_iterators)
  2190. self.start = start
  2191. self.stop = stop
  2192. self.truncate = truncate
  2193. def __next__(self):
  2194. cdef int n
  2195. while 1:
  2196. n = self.cnext()
  2197. if n < 0:
  2198. raise ValueError("error during iteration" )
  2199. if n == 0:
  2200. raise StopIteration
  2201. if self.truncate:
  2202. if self.start > self.pos:
  2203. continue
  2204. if self.pos >= self.stop:
  2205. raise StopIteration
  2206. return makePileupColumn(&self.plp,
  2207. self.tid,
  2208. self.pos,
  2209. self.n_plp,
  2210. self.min_base_quality,
  2211. self.iterdata.seq,
  2212. self.samfile.header)
  2213. cdef class IteratorColumnAllRefs(IteratorColumn):
  2214. """iterates over all columns by chaining iterators over each reference
  2215. """
  2216. def __cinit__(self,
  2217. AlignmentFile samfile,
  2218. **kwargs):
  2219. # no iteration over empty files
  2220. if not samfile.nreferences:
  2221. raise StopIteration
  2222. # initialize iterator
  2223. self._setup_iterator(self.tid, 0, MAX_POS, 1)
  2224. def __next__(self):
  2225. cdef int n
  2226. while 1:
  2227. n = self.cnext()
  2228. if n < 0:
  2229. raise ValueError("error during iteration")
  2230. # proceed to next reference or stop
  2231. if n == 0:
  2232. self.tid += 1
  2233. if self.tid < self.samfile.nreferences:
  2234. self._setup_iterator(self.tid, 0, MAX_POS, 0)
  2235. else:
  2236. raise StopIteration
  2237. continue
  2238. # return result, if within same reference
  2239. return makePileupColumn(&self.plp,
  2240. self.tid,
  2241. self.pos,
  2242. self.n_plp,
  2243. self.min_base_quality,
  2244. self.iterdata.seq,
  2245. self.samfile.header)
  2246. cdef class IteratorColumnAll(IteratorColumn):
  2247. """iterates over all columns, without using an index
  2248. """
  2249. def __cinit__(self,
  2250. AlignmentFile samfile,
  2251. **kwargs):
  2252. self._setup_raw_rest_iterator()
  2253. def __next__(self):
  2254. cdef int n
  2255. n = self.cnext()
  2256. if n < 0:
  2257. raise ValueError("error during iteration")
  2258. if n == 0:
  2259. raise StopIteration
  2260. return makePileupColumn(&self.plp,
  2261. self.tid,
  2262. self.pos,
  2263. self.n_plp,
  2264. self.min_base_quality,
  2265. self.iterdata.seq,
  2266. self.samfile.header)
  2267. cdef class SNPCall:
  2268. '''the results of a SNP call.'''
  2269. cdef int _tid
  2270. cdef int _pos
  2271. cdef char _reference_base
  2272. cdef char _genotype
  2273. cdef int _consensus_quality
  2274. cdef int _snp_quality
  2275. cdef int _rms_mapping_quality
  2276. cdef int _coverage
  2277. property tid:
  2278. '''the chromosome ID as is defined in the header'''
  2279. def __get__(self):
  2280. return self._tid
  2281. property pos:
  2282. '''nucleotide position of SNP.'''
  2283. def __get__(self): return self._pos
  2284. property reference_base:
  2285. '''reference base at pos. ``N`` if no reference sequence supplied.'''
  2286. def __get__(self): return from_string_and_size( &self._reference_base, 1 )
  2287. property genotype:
  2288. '''the genotype called.'''
  2289. def __get__(self): return from_string_and_size( &self._genotype, 1 )
  2290. property consensus_quality:
  2291. '''the genotype quality (Phred-scaled).'''
  2292. def __get__(self): return self._consensus_quality
  2293. property snp_quality:
  2294. '''the snp quality (Phred scaled) - probability of consensus being
  2295. identical to reference sequence.'''
  2296. def __get__(self): return self._snp_quality
  2297. property mapping_quality:
  2298. '''the root mean square (rms) of the mapping quality of all reads
  2299. involved in the call.'''
  2300. def __get__(self): return self._rms_mapping_quality
  2301. property coverage:
  2302. '''coverage or read depth - the number of reads involved in the call.'''
  2303. def __get__(self): return self._coverage
  2304. def __str__(self):
  2305. return "\t".join( map(str, (
  2306. self.tid,
  2307. self.pos,
  2308. self.reference_base,
  2309. self.genotype,
  2310. self.consensus_quality,
  2311. self.snp_quality,
  2312. self.mapping_quality,
  2313. self.coverage ) ) )
  2314. cdef class IndexedReads:
  2315. """Index a Sam/BAM-file by query name while keeping the
  2316. original sort order intact.
  2317. The index is kept in memory and can be substantial.
  2318. By default, the file is re-opened to avoid conflicts if multiple
  2319. operators work on the same file. Set `multiple_iterators` = False
  2320. to not re-open `samfile`.
  2321. Parameters
  2322. ----------
  2323. samfile : AlignmentFile
  2324. File to be indexed.
  2325. multiple_iterators : bool
  2326. Flag indicating whether the file should be reopened. Reopening prevents
  2327. existing iterators being affected by the indexing.
  2328. """
  2329. def __init__(self, AlignmentFile samfile, int multiple_iterators=True):
  2330. cdef char *cfilename
  2331. # makes sure that samfile stays alive as long as this
  2332. # object is alive.
  2333. self.samfile = samfile
  2334. cdef bam_hdr_t * hdr = NULL
  2335. assert samfile.is_bam, "can only apply IndexReads on bam files"
  2336. # multiple_iterators the file - note that this makes the iterator
  2337. # slow and causes pileup to slow down significantly.
  2338. if multiple_iterators:
  2339. cfilename = samfile.filename
  2340. with nogil:
  2341. self.htsfile = hts_open(cfilename, 'r')
  2342. if self.htsfile == NULL:
  2343. raise OSError_from_errno("Unable to reopen file", cfilename)
  2344. # need to advance in newly opened file to position after header
  2345. # better: use seek/tell?
  2346. with nogil:
  2347. hdr = sam_hdr_read(self.htsfile)
  2348. if hdr == NULL:
  2349. raise OSError("unable to read header information")
  2350. self.header = makeAlignmentHeader(hdr)
  2351. self.owns_samfile = True
  2352. else:
  2353. self.htsfile = self.samfile.htsfile
  2354. self.header = samfile.header
  2355. self.owns_samfile = False
  2356. def build(self):
  2357. '''build the index.'''
  2358. self.index = collections.defaultdict(list)
  2359. # this method will start indexing from the current file position
  2360. cdef int ret = 1
  2361. cdef bam1_t * b = <bam1_t*>calloc(1, sizeof( bam1_t))
  2362. if b == NULL:
  2363. raise MemoryError("could not allocate {} bytes".format(sizeof(bam1_t)))
  2364. cdef uint64_t pos
  2365. cdef bam_hdr_t * hdr = self.header.ptr
  2366. while ret > 0:
  2367. with nogil:
  2368. pos = bgzf_tell(hts_get_bgzfp(self.htsfile))
  2369. ret = sam_read1(self.htsfile,
  2370. hdr,
  2371. b)
  2372. if ret > 0:
  2373. qname = charptr_to_str(pysam_bam_get_qname(b))
  2374. self.index[qname].append(pos)
  2375. bam_destroy1(b)
  2376. def find(self, query_name):
  2377. '''find `query_name` in index.
  2378. Returns
  2379. -------
  2380. IteratorRowSelection
  2381. Returns an iterator over all reads with query_name.
  2382. Raises
  2383. ------
  2384. KeyError
  2385. if the `query_name` is not in the index.
  2386. '''
  2387. if query_name in self.index:
  2388. return IteratorRowSelection(
  2389. self.samfile,
  2390. self.index[query_name],
  2391. multiple_iterators = False)
  2392. else:
  2393. raise KeyError("read %s not found" % query_name)
  2394. def __dealloc__(self):
  2395. if self.owns_samfile:
  2396. hts_close(self.htsfile)