| 1 |
# cython: language_level=3 |
| 2 |
import types |
| 3 |
import sys |
| 4 |
import string |
| 5 |
import re |
| 6 |
import tempfile |
| 7 |
import os |
| 8 |
import io |
| 9 |
from contextlib import contextmanager |
| 10 |
from codecs import register_error |
| 11 |
|
| 12 |
from cpython.version cimport PY_MAJOR_VERSION, PY_MINOR_VERSION |
| 13 |
from cpython cimport PyBytes_Check, PyUnicode_Check |
| 14 |
from cpython cimport array as c_array |
| 15 |
from libc.errno cimport errno |
| 16 |
from libc.stdlib cimport calloc, free |
| 17 |
from libc.string cimport strerror, strncpy |
| 18 |
from libc.stdint cimport INT32_MAX, int32_t |
| 19 |
from libc.stdio cimport fprintf, stderr, fflush |
| 20 |
from libc.stdio cimport stdout as c_stdout |
| 21 |
from posix.fcntl cimport open as c_open, O_WRONLY, O_CREAT, O_TRUNC |
| 22 |
from posix.unistd cimport dup as c_dup, SEEK_SET, SEEK_CUR, SEEK_END, STDOUT_FILENO |
| 23 |
|
| 24 |
from pysam.libcsamtools cimport samtools_dispatch, samtools_set_stdout, samtools_set_stderr, \ |
| 25 |
samtools_close_stdout, samtools_close_stderr, samtools_set_stdout_fn |
| 26 |
|
| 27 |
from pysam.libcbcftools cimport bcftools_dispatch, bcftools_set_stdout, bcftools_set_stderr, \ |
| 28 |
bcftools_close_stdout, bcftools_close_stderr, bcftools_set_stdout_fn |
| 29 |
|
| 30 |
##################################################################### |
| 31 |
# hard-coded constants |
| 32 |
cdef int MAX_POS = (1 << 31) - 1 |
| 33 |
|
| 34 |
################################################################# |
| 35 |
# Utility functions for quality string conversions |
| 36 |
cpdef c_array.array qualitystring_to_array(input_str, int offset=33): |
| 37 |
"""convert a qualitystring to an array of quality values.""" |
| 38 |
if input_str is None: |
| 39 |
return None |
| 40 |
qs = force_bytes(input_str) |
| 41 |
cdef char i |
| 42 |
return c_array.array('B', [i - offset for i in qs]) |
| 43 |
|
| 44 |
|
| 45 |
cpdef array_to_qualitystring(c_array.array qualities, int offset=33): |
| 46 |
"""convert an array of quality values to a string.""" |
| 47 |
if qualities is None: |
| 48 |
return None |
| 49 |
cdef int x |
| 50 |
|
| 51 |
cdef c_array.array result |
| 52 |
result = c_array.clone(qualities, len(qualities), zero=False) |
| 53 |
|
| 54 |
for x from 0 <= x < len(qualities): |
| 55 |
result[x] = qualities[x] + offset |
| 56 |
return force_str(result.tobytes()) |
| 57 |
|
| 58 |
|
| 59 |
cpdef qualities_to_qualitystring(qualities, int offset=33): |
| 60 |
"""convert a list or array of quality scores to the string |
| 61 |
representation used in the SAM format. |
| 62 |
|
| 63 |
Parameters |
| 64 |
---------- |
| 65 |
offset : int |
| 66 |
offset to be added to the quality scores to arrive at |
| 67 |
the characters of the quality string (default=33). |
| 68 |
|
| 69 |
Returns |
| 70 |
------- |
| 71 |
string |
| 72 |
a quality string |
| 73 |
|
| 74 |
""" |
| 75 |
cdef char x |
| 76 |
if qualities is None: |
| 77 |
return None |
| 78 |
elif isinstance(qualities, c_array.array): |
| 79 |
return array_to_qualitystring(qualities, offset=offset) |
| 80 |
else: |
| 81 |
# tuples and lists |
| 82 |
return force_str("".join([chr(x + offset) for x in qualities])) |
| 83 |
|
| 84 |
|
| 85 |
######################################################################## |
| 86 |
## String encoding configuration facilities |
| 87 |
######################################################################## |
| 88 |
|
| 89 |
# Codec error handler that just interprets each bad byte as ISO-8859-1. |
| 90 |
def latin1_replace(exception): |
| 91 |
return (chr(exception.object[exception.start]), exception.end) |
| 92 |
|
| 93 |
register_error('pysam.latin1replace', latin1_replace) |
| 94 |
|
| 95 |
|
| 96 |
cdef str ERROR_HANDLER = 'strict' |
| 97 |
|
| 98 |
cpdef get_encoding_error_handler(): |
| 99 |
return ERROR_HANDLER |
| 100 |
|
| 101 |
cpdef set_encoding_error_handler(name): |
| 102 |
global ERROR_HANDLER |
| 103 |
previous = ERROR_HANDLER |
| 104 |
ERROR_HANDLER = name |
| 105 |
return previous |
| 106 |
|
| 107 |
######################################################################## |
| 108 |
## Python 3 compatibility functions |
| 109 |
######################################################################## |
| 110 |
|
| 111 |
cdef from_string_and_size(const char* s, size_t length): |
| 112 |
return s[:length].decode('utf-8', ERROR_HANDLER) |
| 113 |
|
| 114 |
# filename encoding (adapted from lxml.etree.pyx) |
| 115 |
cdef str FILENAME_ENCODING = sys.getfilesystemencoding() or sys.getdefaultencoding() or 'ascii' |
| 116 |
cdef str TEXT_ENCODING = 'utf-8' |
| 117 |
|
| 118 |
cdef bytes encode_filename(object filename): |
| 119 |
"""Make sure a filename is 8-bit encoded (or None).""" |
| 120 |
if filename is None: |
| 121 |
return None |
| 122 |
return os.fsencode(filename) |
| 123 |
|
| 124 |
|
| 125 |
cdef bytes force_bytes(object s, encoding=None, errors=None): |
| 126 |
"""convert string or unicode object to bytes, assuming |
| 127 |
utf8 encoding. |
| 128 |
""" |
| 129 |
if s is None: |
| 130 |
return None |
| 131 |
elif PyBytes_Check(s): |
| 132 |
return s |
| 133 |
elif PyUnicode_Check(s): |
| 134 |
return s.encode(encoding or TEXT_ENCODING, errors or ERROR_HANDLER) |
| 135 |
else: |
| 136 |
raise TypeError("Argument must be string, bytes or unicode.") |
| 137 |
|
| 138 |
|
| 139 |
cdef charptr_to_str(const char* s, encoding=None, errors=None): |
| 140 |
if s == NULL: |
| 141 |
return None |
| 142 |
return s.decode(encoding or TEXT_ENCODING, errors or ERROR_HANDLER) |
| 143 |
|
| 144 |
|
| 145 |
cdef charptr_to_str_w_len(const char* s, size_t n, encoding=None, errors=None): |
| 146 |
if s == NULL: |
| 147 |
return None |
| 148 |
return s[:n].decode(encoding or TEXT_ENCODING, errors or ERROR_HANDLER) |
| 149 |
|
| 150 |
|
| 151 |
cdef bytes charptr_to_bytes(const char* s, encoding=None, errors=None): |
| 152 |
if s == NULL: |
| 153 |
return None |
| 154 |
else: |
| 155 |
return s |
| 156 |
|
| 157 |
|
| 158 |
cdef force_str(object s, encoding=None, errors=None): |
| 159 |
"""Return s converted to str type of current Python |
| 160 |
(bytes in Py2, unicode in Py3)""" |
| 161 |
if s is None: |
| 162 |
return None |
| 163 |
if PyBytes_Check(s): |
| 164 |
return s.decode(encoding or TEXT_ENCODING, errors or ERROR_HANDLER) |
| 165 |
# assume unicode |
| 166 |
return s |
| 167 |
|
| 168 |
|
| 169 |
cdef decode_bytes(bytes s, encoding=None, errors=None): |
| 170 |
"""Return s converted to current Python's str type, |
| 171 |
always decoding even in Python 2""" |
| 172 |
if s is None: |
| 173 |
return None |
| 174 |
else: |
| 175 |
return s.decode(encoding or TEXT_ENCODING, errors or ERROR_HANDLER) |
| 176 |
|
| 177 |
|
| 178 |
cdef OSError_from_errno(message, filename=None): |
| 179 |
cdef int err = errno |
| 180 |
if filename is not None: filename = os.fsdecode(filename) |
| 181 |
return OSError(err, f"{message}: {strerror(err).decode()}", filename) |
| 182 |
|
| 183 |
|
| 184 |
cpdef parse_region(contig=None, |
| 185 |
start=None, |
| 186 |
stop=None, |
| 187 |
region=None, |
| 188 |
reference=None, |
| 189 |
end=None): |
| 190 |
"""parse alternative ways to specify a genomic region. A region can |
| 191 |
either be specified by :term:`reference`, `start` and |
| 192 |
`end`. `start` and `end` denote 0-based, half-open intervals. |
| 193 |
|
| 194 |
:term:`reference` and `end` are also accepted for backward |
| 195 |
compatibility as synonyms for :term:`contig` and `stop`, |
| 196 |
respectively. |
| 197 |
|
| 198 |
Alternatively, a samtools :term:`region` string can be supplied. |
| 199 |
|
| 200 |
If any of the coordinates are missing they will be replaced by the |
| 201 |
minimum (`start`) or maximum (`end`) coordinate. |
| 202 |
|
| 203 |
Note that region strings are 1-based, while `start` and `end` |
| 204 |
denote an interval in python coordinates. |
| 205 |
|
| 206 |
Returns |
| 207 |
------- |
| 208 |
|
| 209 |
tuple : a tuple of `reference`, `start` and `end`. |
| 210 |
|
| 211 |
Raises |
| 212 |
------ |
| 213 |
|
| 214 |
ValueError |
| 215 |
for invalid or out of bounds regions. |
| 216 |
|
| 217 |
""" |
| 218 |
cdef int32_t rstart |
| 219 |
cdef int32_t rstop |
| 220 |
|
| 221 |
|
| 222 |
if reference is not None: |
| 223 |
if contig is not None: |
| 224 |
raise ValueError('contig and reference should not both be specified') |
| 225 |
contig = reference |
| 226 |
|
| 227 |
if contig is not None and region is not None: |
| 228 |
raise ValueError('contig/reference and region should not both be specified') |
| 229 |
|
| 230 |
if end is not None: |
| 231 |
if stop is not None: |
| 232 |
raise ValueError('stop and end should not both be specified') |
| 233 |
stop = end |
| 234 |
|
| 235 |
if contig is None and region is None: |
| 236 |
raise ValueError("neither contig nor region are given") |
| 237 |
|
| 238 |
rstart = 0 |
| 239 |
rstop = MAX_POS |
| 240 |
if start is not None: |
| 241 |
try: |
| 242 |
rstart = start |
| 243 |
except OverflowError: |
| 244 |
raise ValueError('start out of range (%i)' % start) |
| 245 |
|
| 246 |
if stop is not None: |
| 247 |
try: |
| 248 |
rstop = stop |
| 249 |
except OverflowError: |
| 250 |
raise ValueError('stop out of range (%i)' % stop) |
| 251 |
|
| 252 |
if region: |
| 253 |
if ":" in region: |
| 254 |
contig, coord = region.split(":") |
| 255 |
parts = coord.split("-") |
| 256 |
rstart = int(parts[0]) - 1 |
| 257 |
if len(parts) >= 1: |
| 258 |
rstop = int(parts[1]) |
| 259 |
else: |
| 260 |
contig = region |
| 261 |
|
| 262 |
if rstart > rstop: |
| 263 |
raise ValueError('invalid coordinates: start (%i) > stop (%i)' % (rstart, rstop)) |
| 264 |
if not 0 <= rstart < MAX_POS: |
| 265 |
raise ValueError('start out of range (%i)' % rstart) |
| 266 |
if not 0 <= rstop <= MAX_POS: |
| 267 |
raise ValueError('stop out of range (%i)' % rstop) |
| 268 |
|
| 269 |
return contig, rstart, rstop |
| 270 |
|
| 271 |
|
| 272 |
cdef int libc_whence_from_io(int whence): |
| 273 |
# io.SEEK_SET/_CUR/_END are by definition 0/1/2 but C/POSIX's equivalents |
| 274 |
# have unspecified values. So we must translate, but checking for 0/1/2 |
| 275 |
# rather than io.SEEK_SET/etc suffices. |
| 276 |
if whence == 0: return SEEK_SET |
| 277 |
if whence == 1: return SEEK_CUR |
| 278 |
if whence == 2: return SEEK_END |
| 279 |
return whence # Otherwise likely invalid, but let HTSlib or OS report it |
| 280 |
|
| 281 |
|
| 282 |
def _pysam_dispatch(collection, |
| 283 |
method, |
| 284 |
args=None, |
| 285 |
catch_stdout=True, |
| 286 |
is_usage=False, |
| 287 |
save_stdout=None): |
| 288 |
'''call ``method`` in samtools/bcftools providing arguments in args. |
| 289 |
|
| 290 |
By default, stdout is redirected to a temporary file using the patched |
| 291 |
C sources except for a few commands that have an explicit output option |
| 292 |
(typically: -o). In these commands (such as samtools view), this explicit |
| 293 |
option is used. If *is_usage* is True, then these explicit output options |
| 294 |
will not be used. |
| 295 |
|
| 296 |
Catching of stdout can be turned off by setting *catch_stdout* to |
| 297 |
False. |
| 298 |
''' |
| 299 |
|
| 300 |
if method == "index" and args: |
| 301 |
# We make sure that at least the first specified input file exists, |
| 302 |
# and if it doesn't we raise an IOError. |
| 303 |
ARGUMENTS = ['-m', '--min-shift', '-o', '--output', '--output-file', '-@', '--threads'] |
| 304 |
skip_next = False |
| 305 |
for arg in args: |
| 306 |
if skip_next: |
| 307 |
skip_next = False |
| 308 |
continue |
| 309 |
if arg.startswith('-'): |
| 310 |
# Skip next argument for e.g. '--min-shift' '12' or '-m' '12' but not '-m12' |
| 311 |
if arg in ARGUMENTS: |
| 312 |
skip_next = True |
| 313 |
continue |
| 314 |
if not os.path.exists(arg): |
| 315 |
raise IOError("No such file or directory: '%s'" % arg) |
| 316 |
else: |
| 317 |
break |
| 318 |
|
| 319 |
if args is None: |
| 320 |
args = [] |
| 321 |
else: |
| 322 |
args = list(args) |
| 323 |
|
| 324 |
# redirect stderr to file |
| 325 |
stderr_h, stderr_f = tempfile.mkstemp() |
| 326 |
|
| 327 |
# redirect stdout to file |
| 328 |
if save_stdout: |
| 329 |
stdout_f = save_stdout |
| 330 |
stdout_h = c_open(force_bytes(stdout_f), |
| 331 |
O_WRONLY|O_CREAT|O_TRUNC, 0666) |
| 332 |
if stdout_h == -1: |
| 333 |
raise OSError_from_errno("Could not redirect standard output", stdout_f) |
| 334 |
|
| 335 |
samtools_set_stdout_fn(force_bytes(stdout_f)) |
| 336 |
bcftools_set_stdout_fn(force_bytes(stdout_f)) |
| 337 |
|
| 338 |
elif catch_stdout: |
| 339 |
stdout_h, stdout_f = tempfile.mkstemp() |
| 340 |
MAP_STDOUT_OPTIONS = { |
| 341 |
"samtools": { |
| 342 |
"view": "-o {}", |
| 343 |
"mpileup": "-o {}", |
| 344 |
"depad": "-o {}", |
| 345 |
"calmd": "", # uses pysam_stdout_fn |
| 346 |
}, |
| 347 |
"bcftools": {} |
| 348 |
} |
| 349 |
|
| 350 |
stdout_option = None |
| 351 |
if collection == "bcftools": |
| 352 |
# in bcftools, most methods accept -o, the exceptions |
| 353 |
# are below: |
| 354 |
if method not in ("head", "index", "roh", "stats"): |
| 355 |
stdout_option = "-o {}" |
| 356 |
elif method in MAP_STDOUT_OPTIONS[collection]: |
| 357 |
# special case - samtools view -c outputs on stdout |
| 358 |
if not(method == "view" and "-c" in args): |
| 359 |
stdout_option = MAP_STDOUT_OPTIONS[collection][method] |
| 360 |
|
| 361 |
if stdout_option is not None and not is_usage: |
| 362 |
os.close(stdout_h) |
| 363 |
samtools_set_stdout_fn(force_bytes(stdout_f)) |
| 364 |
bcftools_set_stdout_fn(force_bytes(stdout_f)) |
| 365 |
args.extend(stdout_option.format(stdout_f).split(" ")) |
| 366 |
stdout_h = c_open(b"/dev/null", O_WRONLY) |
| 367 |
else: |
| 368 |
samtools_set_stdout_fn("-") |
| 369 |
bcftools_set_stdout_fn("-") |
| 370 |
if catch_stdout is None: stdout_h = c_dup(STDOUT_FILENO) |
| 371 |
else: stdout_h = c_open(b"/dev/null", O_WRONLY) |
| 372 |
|
| 373 |
# setup the function call to samtools/bcftools main |
| 374 |
cdef char ** cargs |
| 375 |
cdef int i, n, retval, l |
| 376 |
n = len(args) |
| 377 |
method = force_bytes(method) |
| 378 |
collection = force_bytes(collection) |
| 379 |
args = [force_bytes(a) for a in args] |
| 380 |
|
| 381 |
# allocate two more for first (dummy) argument (contains command) |
| 382 |
cdef int extra_args = 0 |
| 383 |
if method == b"index": |
| 384 |
extra_args = 1 |
| 385 |
# add extra arguments for commands accepting optional arguments |
| 386 |
# such as 'samtools index x.bam [out.index]' |
| 387 |
cargs = <char**>calloc(n + 2 + extra_args, sizeof(char *)) |
| 388 |
cargs[0] = collection |
| 389 |
cargs[1] = method |
| 390 |
|
| 391 |
# create copies of strings - getopt for long options permutes |
| 392 |
# arguments |
| 393 |
for i from 0 <= i < n: |
| 394 |
l = len(args[i]) |
| 395 |
cargs[i + 2] = <char *>calloc(l + 1, sizeof(char)) |
| 396 |
strncpy(cargs[i + 2], args[i], l) |
| 397 |
|
| 398 |
# call samtools/bcftools |
| 399 |
if collection == b"samtools": |
| 400 |
samtools_set_stdout(stdout_h) |
| 401 |
samtools_set_stderr(stderr_h) |
| 402 |
retval = samtools_dispatch(n + 2, cargs) |
| 403 |
samtools_close_stdout() |
| 404 |
samtools_close_stderr() |
| 405 |
elif collection == b"bcftools": |
| 406 |
bcftools_set_stdout(stdout_h) |
| 407 |
bcftools_set_stderr(stderr_h) |
| 408 |
retval = bcftools_dispatch(n + 2, cargs) |
| 409 |
bcftools_close_stdout() |
| 410 |
bcftools_close_stderr() |
| 411 |
else: |
| 412 |
# unknown -- just return a Unix shell's "command not found" exit status |
| 413 |
retval = 127 |
| 414 |
|
| 415 |
for i from 0 <= i < n: |
| 416 |
free(cargs[i + 2]) |
| 417 |
free(cargs) |
| 418 |
|
| 419 |
# get error messages |
| 420 |
def _collect(fn): |
| 421 |
out = [] |
| 422 |
try: |
| 423 |
with open(fn, "r") as inf: |
| 424 |
out = inf.read() |
| 425 |
except UnicodeDecodeError: |
| 426 |
with open(fn, "rb") as inf: |
| 427 |
# read binary output |
| 428 |
out = inf.read() |
| 429 |
finally: |
| 430 |
os.remove(fn) |
| 431 |
return out |
| 432 |
|
| 433 |
out_stderr = _collect(stderr_f) |
| 434 |
if save_stdout: |
| 435 |
out_stdout = None |
| 436 |
elif catch_stdout: |
| 437 |
out_stdout = _collect(stdout_f) |
| 438 |
else: |
| 439 |
out_stdout = None |
| 440 |
|
| 441 |
return retval, out_stderr, out_stdout |
| 442 |
|
| 443 |
|
| 444 |
__all__ = [ |
| 445 |
"qualitystring_to_array", |
| 446 |
"array_to_qualitystring", |
| 447 |
"qualities_to_qualitystring", |
| 448 |
"get_encoding_error_handler", |
| 449 |
"set_encoding_error_handler", |
| 450 |
] |