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