Debian Codegraph @

cyvcf2/cyvcf2.pyx

raw ◀ ▶
1 Debian patch touch this file
1 #cython: profile=False
2 #cython:language_level=3
3
4 #cython: embedsignature=True
5 from __future__ import print_function
6 import os
7 import sys
8 from collections import defaultdict
9 import atexit
10 import tempfile
11 import numpy as np
12 from array import array
13 import math
14 import ctypes
15 import warnings
16 try:
17 from pathlib import Path
18 except ImportError:
19 from pathlib2 import Path # python 2 backport
20
21 from libc cimport stdlib
22 cimport numpy as np
23 np.seterr(invalid='ignore')
24 np.import_array()
25 import locale
26
27 ENC = locale.getpreferredencoding()
28
29 from cython cimport view
30
31 from cpython.version cimport PY_MAJOR_VERSION
32
33 def set_htslib_log_level(int level):
34 """
35 Set htslib log level.
36
37 Parameters:
38 level (int): The desired log level. Per htslib's documentation (https://www.htslib.org/doc/samtools.html), the following values are supported:
39 - 0 or 1: Suppress some error messages.
40 - 2: Reduce warning messages.
41 - 3: Default level (HTS_LOG_WARNING).
42 - >3: Increase verbosity with additional warnings and logging messages.
43 """
44 hts_set_log_level(level)
45
46
47 def _init_logging_from_env():
48 """
49 If a valid CYVCF2_HTSLIB_LOG_LEVEL environment variable exists, use it to set htslib log level.
50 Otherwise use the htslib default: 3 (HTS_LOG_WARNING).
51 """
52 HTSLIB_DEFAULT = 3
53
54 s = stdlib.getenv("CYVCF2_HTSLIB_LOG_LEVEL")
55 if s is NULL:
56 set_htslib_log_level(HTSLIB_DEFAULT)
57 return
58
59 py_s = s.decode()
60 try:
61 level = int(py_s)
62 if level < 0:
63 warnings.warn(f"CYVCF2_HTSLIB_LOG_LEVEL={py_s!r} is not a non-negative integer; using htslib default")
64 level = HTSLIB_DEFAULT
65 except (ValueError, TypeError):
66 warnings.warn(f"CYVCF2_HTSLIB_LOG_LEVEL={py_s!r} is not a valid integer; using htslib default")
67 level = HTSLIB_DEFAULT
68
69 set_htslib_log_level(level)
70
71 _init_logging_from_env()
72
73
74 # overcome lack of __file__ in cython
75 import inspect
76 if not hasattr(sys.modules[__name__], '__file__'):
77 __file__ = inspect.getfile(inspect.currentframe())
78
79
80 def par_relatedness(vcf_path, samples, ncpus, sites, min_depth=5, each=1):
81 from multiprocessing import Pool
82 p = Pool(ncpus)
83 cdef np.ndarray aibs, an, ahets
84
85 for i, fname in enumerate(p.imap_unordered(_par_relatedness, [
86 (vcf_path, samples, min_depth, i, ncpus, each, sites) for i in range(ncpus)])):
87
88 arrays = np.load(fname)
89 os.unlink(fname)
90 if i == 0:
91 aibs, an, ahets = arrays['ibs'], arrays['n'], arrays['hets']
92 else:
93 aibs += arrays['ibs']
94 an += arrays['n']
95 ahets += arrays['hets']
96
97 return VCF(vcf_path, samples=samples)._relatedness_finish(aibs, an, ahets)
98
99
100 def par_het(vcf_path, samples, ncpus, qsites, min_depth=8, percentiles=(10, 90),
101 int each=1, int offset=0):
102 from multiprocessing import Pool
103 p = Pool(ncpus)
104
105 any_counts, sum_counts, het_counts = 0, 0, 0
106 all_gt_types, mean_depths, sites = [], [], []
107 maf_lists = defaultdict(list)
108 for ret in p.imap_unordered(_par_het, [(vcf_path, samples, qsites, min_depth, i, ncpus, each) for i in range(ncpus)]):
109 (mean_depths_, maf_lists_, het_counts_, sum_counts_,
110 all_gt_types_, sites_, any_counts_) = ret
111 mean_depths.extend(mean_depths_)
112 any_counts += any_counts_
113 sites.extend(sites_)
114 all_gt_types.extend(all_gt_types_)
115 sum_counts += sum_counts_ # an array
116 het_counts += het_counts_ # an array
117 for k in maf_lists_:
118 li = maf_lists_[k]
119 maf_lists[k].extend(li)
120 mean_depths = np.array(mean_depths, dtype=np.int32).T
121 vcf = VCF(vcf_path, samples=samples, gts012=True)
122 return vcf._finish_het(mean_depths, maf_lists,
123 percentiles,
124 het_counts, sum_counts, all_gt_types,
125 sites, any_counts)
126
127
128 def _par_het(args):
129 vcf_path, samples, sites, min_depth, offset, ncpus, each = args
130 each *= ncpus
131 vcf = VCF(vcf_path, samples=samples, gts012=True)
132 return vcf.het_check(min_depth=min_depth, sites=sites, each=each, offset=offset, _finish=False)
133
134
135 def _par_relatedness(args):
136 vcf_path, samples, min_depth, offset, ncpus, each, sites = args
137 vcf = VCF(vcf_path, samples=samples, gts012=True)
138 each = each * ncpus
139 vibs, vn, vhet = vcf._site_relatedness(min_depth=min_depth, offset=offset, each=each, sites=sites)
140 # to get around limits of multiprocessing size of transmitted data, we save
141 # the arrays to disk and return the file
142 fname = tempfile.mktemp(suffix=".npz")
143 atexit.register(os.unlink, fname)
144 np.savez_compressed(fname, ibs=np.asarray(vibs), hets=np.asarray(vhet), n=np.asarray(vn))
145 return fname
146
147
148 cdef unicode xstr(s):
149 if type(s) is unicode:
150 # fast path for most common case(s)
151 return <unicode>s
152 elif PY_MAJOR_VERSION < 3 and isinstance(s, bytes):
153 # only accept byte strings in Python 2.x, not in Py3
154 return (<bytes>s).decode('ascii')
155 elif isinstance(s, unicode):
156 # an evil cast to <unicode> might work here in some(!) cases,
157 # depending on what the further processing does. to be safe,
158 # we can always create a copy instead
159 return unicode(s)
160 else:
161 raise TypeError(...)
162
163
164 def r_(int32_t[::view.contiguous] a_gts, int32_t[::view.contiguous] b_gts, float f, int32_t n_samples):
165 return r_unphased(&a_gts[0], &b_gts[0], f, n_samples)
166
167
168 cdef char* pystring_to_cstring(str py_string):
169 # Convert Python string to byte string using UTF-8 encoding
170 cdef bytes byte_string = py_string.encode('utf-8') # Convert Python string to bytes
171 # Convert Python bytes to a C-compatible pointer
172 cdef const char* byte_string_ptr = byte_string
173
174 # Allocate memory for C string with size equal to byte string length plus null terminator
175 cdef size_t length = len(byte_string) + 1 # Plus 1 for the null terminator
176 cdef char* c_string = <char*>stdlib.malloc(length)
177 # return NULL if memory allocation fails
178 if c_string == NULL:
179 return c_string
180 # Copy byte string to C string using memcpy and add null terminator
181 memcpy(c_string, byte_string_ptr, length - 1) # Use memcpy to copy bytes to C string
182 c_string[length - 1] = b'\0' # Add null terminator to the end of the C string
183 return c_string
184
185
186 cdef set_constants(VCF v):
187 v.HOM_REF = 0
188 v.HET = 1
189 if v.gts012:
190 v.HOM_ALT = 2
191 v.UNKNOWN = 3
192 else:
193 v.UNKNOWN = 2
194 v.HOM_ALT = 3
195
196
197
198 cdef class HTSFile:
199
200 cdef htsFile *hts
201 cdef bytes fname
202 cdef bytes mode
203 cdef bint from_path
204
205 cdef _open_htsfile(self, fname, mode):
206 """Opens an htsfile for reading or writing.
207
208 Parameters
209 ----------
210 fname: str
211 filename (str or Path), file descriptor (int), or file-like object (has fileno method).
212 mode: str
213 the mode to pass to hts_open.
214 """
215 cdef hFILE *hf
216 self.mode = to_bytes(mode)
217 reading = b"r" in self.mode
218 writing = b"w" in self.mode
219 if not reading and not writing:
220 raise IOError("No 'r' or 'w' in mode %s" % str(self.mode))
221
222 self.from_path = isinstance(fname, (basestring, Path))
223 if self.from_path:
224 self.fname = to_bytes(str(fname))
225 if self.fname == b"-":
226 self.fname = to_bytes(b"/dev/stdin") if reading else to_bytes(b"/dev/stdout")
227
228 self.hts = hts_open(self.fname, self.mode)
229 # from a file descriptor
230 elif isinstance(fname, int):
231 hf = hdopen(int(fname), self.mode)
232 self.hts = hts_hopen(hf, "<file>", self.mode)
233 self.fname = None
234 # reading from a File object or other object with fileno
235 elif hasattr(fname, "fileno"):
236 if fname.closed:
237 raise IOError('I/O operation on closed file')
238 hf = hdopen(fname.fileno(), self.mode)
239 self.hts = hts_hopen(hf, "<file>", self.mode)
240 # .name can be TextIOWrapper
241 try:
242 self.fname = to_bytes(fname.name)
243 except AttributeError:
244 self.fname = None
245 else:
246 raise IOError("Cannot open '%s' for writing." % str(type(fname)))
247
248 if self.hts == NULL:
249 raise IOError("Error opening %s" % str(fname))
250 if reading:
251 if self.hts.format.format != vcf and self.hts.format.format != bcf:
252 raise IOError(
253 "%s is not valid bcf or vcf (format: %s mode: %s)" % (fname, self.hts.format.format, mode)
254 )
255 else:
256 if self.hts.format.format != text_format and self.hts.format.format != binary_format:
257 raise IOError(
258 "%s is not valid text_format or binary_format (format: %s mode: %s)" % (fname, self.hts.format.format, mode)
259 )
260
261 cdef _c_close(self):
262 if self.hts != NULL:
263 if self.from_path:
264 hts_close(self.hts)
265 self.hts = NULL
266
267 def close(self):
268 self._c_close()
269
270 cdef class VCF(HTSFile):
271 """
272 VCF class holds methods to iterate over and query a VCF.
273
274 Parameters
275 ----------
276 fname: str
277 path to file
278 gts012: bool
279 if True, then gt_types will be 0=HOM_REF, 1=HET, 2=HOM_ALT, 3=UNKNOWN. If False, 3, 2 are flipped.
280 lazy: bool
281 if True, then don't unpack (parse) the underlying record until needed.
282 strict_gt: bool
283 if True, then any '.' present in a genotype will classify the corresponding element in the gt_types array as UNKNOWN.
284 samples: list
285 list of samples to extract from full set in file.
286 threads: int
287 the number of threads to use including this reader.
288
289
290 Returns
291 -------
292 VCF object for iterating and querying.
293 """
294
295 cdef const bcf_hdr_t *hdr
296 cdef tbx_t *idx
297 cdef hts_idx_t *hidx
298 cdef int n_samples
299 cdef int PASS
300 cdef bint gts012
301 cdef bint lazy
302 cdef bint strict_gt
303 cdef list _seqnames
304 cdef list _seqlens
305 # holds a lookup of format field -> type.
306 cdef dict format_types
307
308 #: The constant used to indicate the the genotype is HOM_REF.
309 cdef readonly int HOM_REF
310 #: The constant used to indicate the the genotype is HET.
311 cdef readonly int HET
312 #: The constant used to indicate the the genotype is HOM_ALT.
313 cdef readonly int HOM_ALT
314 #: The constant used to indicate the the genotype is UNKNOWN.
315 cdef readonly int UNKNOWN
316
317 def __init__(self, fname, mode="r", gts012=False, lazy=False, strict_gt=False, samples=None, threads=None):
318 cdef bcf_hdr_t *hdr
319 self._open_htsfile(fname, mode)
320 hdr = self.hdr = bcf_hdr_read(self.hts)
321 if hdr == NULL:
322 raise Exception("cannot parse VCF header")
323 if samples is not None:
324 self.set_samples(samples)
325 self.n_samples = bcf_hdr_nsamples(self.hdr)
326 self.PASS = -1
327 self.gts012 = gts012
328 self.lazy = lazy
329 self.strict_gt = strict_gt
330 self._seqnames = []
331 self._seqlens = []
332 set_constants(self)
333 self.format_types = {}
334 if threads is not None:
335 self.set_threads(threads)
336
337 def __enter__(self):
338 return self
339
340 def __exit__(self, type, value, tb):
341 self.close()
342
343 def set_threads(self, int n):
344 v = hts_set_threads(self.hts, n)
345 if v < 0:
346 raise Exception("error setting number of threads: %d" % v)
347
348 cdef get_type(self, fmt):
349 fmt = from_bytes(fmt)
350 if not fmt in self.format_types:
351 s = self.get_header_type(fmt, order=[BCF_HL_FMT])
352 self.format_types[fmt] = s["Type"]
353 return from_bytes(self.format_types[fmt])
354
355 def add_to_header(self, line):
356 """Add a new line to the VCF header.
357
358 Parameters
359 ----------
360 line: str
361 full vcf header line.
362 """
363 ret = bcf_hdr_append(self.hdr, to_bytes(line))
364 if ret != 0:
365 raise Exception("couldn't add '%s' to header")
366 ret = bcf_hdr_sync(self.hdr)
367 if ret != 0:
368 raise Exception("couldn't add '%s' to header")
369 if line.startswith("##contig"):
370 # need to trigger a refresh of seqnames
371 self._seqnames = []
372 return ret
373
374 def add_info_to_header(self, adict):
375 """Add a INFO line to the VCF header.
376
377 Parameters
378 ----------
379 adict: dict
380 dict containing keys for ID, Number, Type, Description.
381 """
382 return self.add_to_header("##INFO=<ID={ID},Number={Number},Type={Type},Description=\"{Description}\">".format(**adict))
383
384 def add_format_to_header(self, adict):
385 """Add a FORMAT line to the VCF header.
386
387 Parameters
388 ----------
389 adict: dict
390 dict containing keys for ID, Number, Type, Description.
391 """
392 return self.add_to_header("##FORMAT=<ID={ID},Number={Number},Type={Type},Description=\"{Description}\">".format(**adict))
393
394 def add_filter_to_header(self, adict):
395 """Add a FILTER line to the VCF header.
396
397 Parameters
398 ----------
399 adict: dict
400 dict containing keys for ID, Description.
401 """
402 return self.add_to_header("##FILTER=<ID={ID},Description=\"{Description}\">".format(**adict))
403
404 def set_samples(self, samples):
405 """Set the samples to be pulled from the VCF; this must be called before any iteration.
406
407 Parameters
408 ----------
409 samples: list
410 list of samples to extract.
411 """
412 cdef bint is_null = 0
413 if samples is None:
414 samples = "-".encode()
415 if isinstance(samples, list):
416 samples = to_bytes(",".join(samples))
417 is_null = len(samples) == 0
418 else:
419 samples = to_bytes(samples)
420
421 if is_null:
422 ret = bcf_hdr_set_samples(self.hdr, NULL, 0)
423 else:
424 ret = bcf_hdr_set_samples(self.hdr, <const char *>samples, 0)
425 assert ret >= 0, ("error setting samples", ret)
426 self.n_samples = bcf_hdr_nsamples(self.hdr)
427 if ret != 0 and samples != "-":
428 s = from_bytes(samples).split(",")
429 if self.n_samples < len(s):
430 warnings.warn("not all requested samples found in VCF")
431
432
433 def update(self, id, type, number, description):
434 """Update the header with an INFO field of the given parameters.
435
436 Parameters
437 ----------
438 id: str
439 ID
440 type: str
441 valid VCF type
442 number: str
443 valid VCF number
444 description: str
445 description of added line.
446 """
447 ret = bcf_hdr_append(self.hdr, "##INFO=<ID={id},Number={number},Type={type},Description=\"{description}\">".format(id=id, type=type, number=number, description=description).encode())
448 if ret != 0:
449 raise Exception("unable to update to header: %d", ret)
450 ret = bcf_hdr_sync(self.hdr)
451 if ret != 0:
452 raise Exception("unable to update to header")
453
454 def set_index(self, index_path=""):
455 # Clear any existing indexes
456 if self.idx != NULL:
457 tbx_destroy(self.idx)
458 self.idx = NULL
459 if self.hidx != NULL:
460 hts_idx_destroy(self.hidx)
461 self.hidx = NULL
462
463 if index_path.endswith(".tbi"):
464 self.idx = tbx_index_load2(to_bytes(self.fname), to_bytes(index_path))
465 if self.idx != NULL:
466 return
467
468 self.hidx = hts_idx_load2(to_bytes(self.fname), to_bytes(index_path))
469 if self.hidx == NULL:
470 self.idx = tbx_index_load2(to_bytes(self.fname), to_bytes(index_path))
471 if self.hidx == NULL and self.idx == NULL:
472 raise OSError("unable to open index:'%s' for '%s'" % (index_path, self.fname))
473
474 def _bcf_region(VCF self, region):
475 if self.hidx == NULL:
476 self.hidx = bcf_index_load(self.fname)
477 assert self.hidx != NULL, ("error loading .csi index for %s" % self.fname)
478 cdef bcf1_t *b
479 cdef int ret
480 cdef hts_itr_t *itr
481
482 itr = bcf_itr_querys(self.hidx, self.hdr, to_bytes(region))
483 if itr == NULL:
484 warnings.warn("no intervals found for %s at %s" % (self.fname, region))
485 return
486 try:
487 while True:
488 b = bcf_init()
489 ret = bcf_itr_next(self.hts, itr, b)
490 if ret < 0:
491 bcf_destroy(b)
492 break
493 ret = bcf_subset_format(self.hdr, b)
494 assert ret == 0, ("could not subset variant", self.fname, region)
495 yield newVariant(b, self)
496 finally:
497 if itr != NULL:
498 hts_itr_destroy(itr)
499
500 def __call__(VCF self, region=None):
501 """
502 Extract the region from the VCF.
503
504 Parameters
505 ----------
506 region: str
507 region string like chr1:1234-34566 or 'chr7
508
509 Returns
510 -------
511 An Iterator over the requested region.
512
513 Notes
514 -----
515 If `region` is empty, cyvcf2 uses `HTS_IDX_START` to iterate from the
516 start of the index. This mode requires an index; without an index, the
517 iterator is empty.
518 """
519 cdef hts_itr_t *itr
520 cdef kstring_t s
521 cdef bcf1_t *b
522 cdef int slen = 1, ret = 0
523 cdef bytes bregion
524 cdef char *cregion
525
526 if not region:
527 self._open_index()
528 if self.hidx == NULL and self.idx == NULL:
529 return
530
531 if self.hidx != NULL:
532 itr = bcf_itr_queryi(self.hidx, HTS_IDX_START, 0, 0)
533 if itr == NULL:
534 return
535 try:
536 while True:
537 b = bcf_init()
538 ret = bcf_itr_next(self.hts, itr, b)
539 if ret < 0:
540 bcf_destroy(b)
541 break
542 ret = bcf_subset_format(self.hdr, b)
543 assert ret == 0, ("could not subset variant", self.fname, region)
544 yield newVariant(b, self)
545 finally:
546 hts_itr_destroy(itr)
547 return
548
549 itr = tbx_itr_queryi(self.idx, HTS_IDX_START, 0, 0)
550 if itr == NULL:
551 # no iterator was created, so there is nothing to destroy
552 return
553 s.s, s.l, s.m = NULL, 0, 0
554 try:
555 while 1:
556 with nogil:
557 slen = tbx_itr_next(self.hts, self.idx, itr, &s)
558 if slen > 0:
559 b = bcf_init()
560 ret = vcf_parse(&s, self.hdr, b)
561 if slen <= 0:
562 break
563 if ret > 0:
564 bcf_destroy(b)
565 # s.s and itr are released by the finally block
566 raise Exception("error parsing")
567 yield newVariant(b, self)
568 finally:
569 stdlib.free(s.s)
570 hts_itr_destroy(itr)
571 return
572
573 if self.fname.decode(ENC).endswith(('.bcf', '.bcf.gz')):
574 yield from self._bcf_region(region)
575 return
576
577 if self.idx == NULL:
578 self.idx = tbx_index_load(to_bytes(self.fname))
579 assert self.idx != NULL, "error loading tabix index for %s" % self.fname
580
581 bregion = to_bytes(region)
582 cregion = bregion
583
584 with nogil:
585 itr = tbx_itr_querys(self.idx, cregion)
586
587 if itr == NULL:
588 warnings.warn("no intervals found for %s at %s" % (self.fname, region))
589 return
590
591 s.s, s.l, s.m = NULL, 0, 0
592 try:
593 while 1:
594 with nogil:
595 slen = tbx_itr_next(self.hts, self.idx, itr, &s)
596 if slen > 0:
597 b = bcf_init()
598 ret = vcf_parse(&s, self.hdr, b)
599 if slen <= 0:
600 break
601 if ret > 0:
602 bcf_destroy(b)
603 # s.s and itr are released by the finally block
604 raise Exception("error parsing")
605 yield newVariant(b, self)
606 finally:
607 stdlib.free(s.s)
608 hts_itr_destroy(itr)
609
610
611 def header_iter(self):
612 """
613 Iterate over fields in the HEADER
614 """
615 cdef int i
616 for i in range(self.hdr.nhrec):
617 yield newHREC(self.hdr.hrec[i], self.hdr)
618
619 def ibd(self, int nmax=-1):
620 assert self.gts012
621 import itertools
622
623 cdef int i, rl, n_bins = 16
624
625 samples = self.samples
626 sample_to_idx = {s: samples.index(s) for s in samples}
627 sample_pairs = list(itertools.combinations(samples, 2))
628 # values of bins, run_length
629
630 cdef int n = 0
631 cdef float pi
632 cdef int[:] b
633 cdef int[:] gts
634 cdef int idx0, idx1
635 bins = np.zeros((len(sample_pairs), n_bins), dtype=np.int32)
636 rls = np.zeros(len(sample_pairs), dtype=np.int32)
637
638 for v in self:
639 if n == nmax: break
640 n += 1
641 gts = v.gt_types
642 pi = v.aaf
643 for i, (s0, s1) in enumerate(sample_pairs):
644 b = bins[i, :]
645 idx0, idx1 = sample_to_idx[s0], sample_to_idx[s1]
646 rls[i] = ibd(gts[idx0], gts[idx1], rls[i], pi, &b[0], n_bins)
647
648 return {sample_pairs[i]: bins[i, :] for i in range(len(sample_pairs))}
649
650 # pull something out of the HEADER, e.g. CSQ
651 cpdef get_header_type(self, key, order=[BCF_HL_INFO, BCF_HL_FMT]):
652 """Extract a field from the VCF header by id.
653
654 Parameters
655 ----------
656 key: str
657 ID to pull from the header.
658 Returns
659 -------
660 rec: dict
661 dictionary containing header information.
662 """
663 key = to_bytes(key)
664 cdef bcf_hrec_t *b
665 cdef int i
666 for typ in order:
667 b = bcf_hdr_get_hrec(self.hdr, typ, b"ID", key, NULL);
668 if b != NULL:
669 break
670 if b == NULL:
671 b = bcf_hdr_get_hrec(self.hdr, BCF_HL_GEN, key, NULL, NULL);
672 if b == NULL:
673 raise KeyError(key)
674 d = {from_bytes(b.key): from_bytes(b.value)}
675 else:
676 d = {from_bytes(b.keys[i]): from_bytes(b.vals[i]) for i in range(b.nkeys)}
677 #bcf_hrec_destroy(b)
678 return d
679
680 cpdef remove_header(self, key, order=[BCF_HL_INFO, BCF_HL_FMT, BCF_HL_FLT]):
681 """Remove a header record from the VCF by ID.
682
683 Parameters
684 ----------
685 key: str
686 ID to pull from the header.
687 """
688 key = to_bytes(key)
689 cdef bcf_hrec_t *b
690
691 for typ in order:
692 b = bcf_hdr_get_hrec(self.hdr, typ, b"ID", key, NULL)
693 if b != NULL:
694 break
695
696 if b == NULL:
697 raise KeyError(key)
698
699 bcf_hdr_remove(<bcf_hdr_t*>self.hdr, typ, <const char*>key)
700 bcf_hdr_sync(<bcf_hdr_t*>self.hdr)
701
702 def __getitem__(self, key):
703 return self.get_header_type(key)
704
705 def __contains__(self, key):
706 """Check if the given ID is in the header."""
707 try:
708 self[key]
709 return True
710 except KeyError:
711 return False
712
713 contains = __contains__
714
715 def __dealloc__(self):
716 if self.hdr != NULL:
717 bcf_hdr_destroy(self.hdr)
718 self.hdr = NULL
719
720 # Shouldn't call Python-space functions here
721 self._c_close()
722 if self.idx != NULL:
723 tbx_destroy(self.idx)
724 if self.hidx != NULL:
725 hts_idx_destroy(self.hidx)
726
727 def __iter__(self):
728 return self
729
730 def __next__(self):
731
732 cdef bcf1_t *b
733 cdef int ret
734 if self.hts == NULL:
735 raise Exception("attempt to iterate over closed/invalid VCF")
736 with nogil:
737 b = bcf_init()
738 ret = bcf_read(self.hts, self.hdr, b)
739 if ret >= 0 or b.errcode == BCF_ERR_CTG_UNDEF:
740 return newVariant(b, self)
741 else:
742 bcf_destroy(b)
743 if ret == -1: # end-of-file
744 raise StopIteration
745 else:
746 raise Exception("error parsing variant with `htslib::bcf_read` error-code: %d and ret: %d" % (
747 b.errcode, ret))
748
749
750 property samples:
751 "list of samples pulled from the VCF."
752 def __get__(self):
753 cdef int i
754 return [str(self.hdr.samples[i].decode('utf-8')) for i in range(self.n_samples)]
755
756 property raw_header:
757 "string of the raw header from the VCF"
758 def __get__(self):
759 cdef kstring_t s
760 s.s, s.l, s.m = NULL, 0, 0
761 bcf_hdr_format(self.hdr, 0, &s)
762
763 python_str = str(from_bytes(s.s))
764 ks_free(&s)
765 return python_str
766
767 property seqlens:
768 "list of chromosome lengths, if defined in the VCF header"
769 def __get__(self):
770 if len(self._seqlens) > 0: return self._seqlens
771 cdef int32_t nseq;
772 cdef int32_t* sls = bcf_hdr_seqlen(self.hdr, &nseq)
773 if sls == NULL or nseq <= 0:
774 raise AttributeError("no sequence lengths found in header")
775
776 self._seqlens = [sls[i] for i in range(nseq)]
777 stdlib.free(sls)
778 return self._seqlens
779
780 cdef _open_index(self):
781 """
782 Try to open an index, if not open already.
783 """
784 if self.hidx == NULL and self.idx == NULL:
785 if self.fname.decode(ENC).endswith(('.bcf', '.bcf.gz')):
786 self.hidx = bcf_index_load(self.fname)
787 else:
788 self.idx = tbx_index_load(to_bytes(self.fname))
789
790 property seqnames:
791 "list of chromosomes in the VCF"
792 def __get__(self):
793 if len(self._seqnames) > 0: return self._seqnames
794 cdef const char **cnames
795 cdef int i, n = 0
796 cnames = bcf_hdr_seqnames(self.hdr, &n)
797 if n == 0:
798 self._open_index()
799 if self.hidx != NULL:
800 cnames = bcf_index_seqnames(self.hidx, self.hdr, &n)
801 if self.idx !=NULL:
802 cnames = tbx_seqnames(self.idx, &n)
803 self._seqnames = [cnames[i].decode() for i in range(n)]
804 stdlib.free(cnames)
805 return self._seqnames
806
807 cdef _num_records(self):
808 cdef uint64_t total, records, v;
809 cdef int ret, tid, nseq;
810 cdef hts_idx_t *idx = NULL;
811
812 self._open_index()
813 if self.hidx != NULL:
814 idx = self.hidx
815 assert self.idx == NULL
816 if self.idx != NULL:
817 idx = self.idx.idx
818 assert self.hidx == NULL
819
820 if idx == NULL:
821 raise ValueError(
822 "File must be indexed to compute num_records (tip: use bcftools index)")
823
824 nseq = hts_idx_nseq(idx)
825 total = 0;
826 for tid in range(nseq):
827 # NOTE: the return value here doesn't seem to indicate an error
828 # condition, and correct values are computed when it returns < 0.
829 # bcftools index -n doesn't strictly check the output.
830 hts_idx_get_stat(idx, tid, &records, &v);
831 total += records
832 return total
833
834 property num_records:
835 """
836 The number of VCF records in the file, computed from the index.
837 If the file is not indexed (or an index has not been set using
838 ``set_index``) a ValueError is raised.
839
840 Note that incorrect values may be returned if a mismatched
841 index file (i.e., the index for a different VCF file) is used.
842 This is not detected as an error condition.
843 """
844 def __get__(self):
845 return self._num_records()
846
847 def plot_relatedness(self, riter):
848 import pandas as pd
849 from matplotlib import pyplot as plt
850 from matplotlib import gridspec
851 import seaborn as sns
852 sns.set_style("ticks")
853
854 df = []
855 for row in riter:
856 row['jtags'] = '|'.join(row['tags'])
857 df.append(row)
858
859 df = pd.DataFrame(df)
860 fig = plt.figure(figsize=(9, 9))
861
862 gs = gridspec.GridSpec(2, 1, height_ratios=[3.5, 1])
863
864 ax0, ax1 = plt.subplot(gs[0]), plt.subplot(gs[1])
865
866 if "error" in df.columns:
867 # plot all gray except points that don't match our expectation.
868 import matplotlib
869 matplotlib.rcParams['pdf.fonttype'] = 42
870 import matplotlib.colors as mc
871 colors = [mc.hex2color(h) for h in ('#b6b6b6', '#ff3333')]
872 for i, err in enumerate(("ok", "error")):
873 subset = df[df.error == err]
874 subset.plot(kind='scatter', x='rel', y='ibs0', c=colors[i],
875 edgecolor=colors[0],
876 label=err, ax=ax0, s=17 if i == 0 else 35)
877 sub = df[df.error == "error"]
878 for i, row in sub.iterrows():
879 ax0.annotate(row['sample_a'] + "\n" + row['sample_b'],
880 (row['rel'], row['ibs0']), fontsize=8)
881 else:
882 # color by the relation derived from the genotypes.
883 colors = sns.color_palette("Set1", len(set(df.jtags)))
884 for i, tag in enumerate(set(df.jtags)):
885 subset = df[df.jtags == tag]
886 subset.plot(kind='scatter', x='rel', y='ibs0', c=colors[i],
887 label=tag, ax=ax0)
888
889 ax0.legend()
890
891 ax0.set_ylim(ymin=0)
892 ax0.set_xlim(xmin=df.rel.min())
893
894 ax1.set_xlim(*ax0.get_xlim())
895 ax1.hist(df.rel, 40)
896 ax1.set_yscale('log', nonposy='clip')
897 return fig
898
899 def gen_variants(self, sites,
900 offset=0, each=1, call_rate=0.8):
901
902 seqnames = set(self.seqnames)
903
904 if sites is not None:
905 if isinstance(sites, basestring):
906 isites = []
907 for i in (x.strip().split(":") for x in open(sites)):
908 if not i[0] in seqnames and 'chr' + i[0] in seqnames:
909 i[0] = 'chr' + i[0]
910 i[1] = int(i[1])
911 isites.append(i)
912 else:
913 isites = sites
914 for i in isites:
915 if not i[0] in seqnames and 'chr' + i[0] in seqnames:
916 i[0] = 'chr' + i[0]
917
918 cdef Variant v
919 cdef int k, last_pos
920 if sites:
921 isites = isites[offset::each]
922 ref, alt = None, None
923 j = 0
924 for i, osite in enumerate(isites):
925 if len(osite) >= 4:
926 chrom, pos, ref, alt = osite[:4]
927 else:
928 chrom, pos = osite[:2]
929 for v in self("%s:%s-%s" % (chrom, pos, pos)):
930 if len(v.ALT) != 1: continue
931 if ref is not None and v.REF != ref: continue
932 if alt is not None and v.ALT[0] != alt: continue
933 if v.call_rate < call_rate: continue
934 yield i, v
935 j += 1
936 break
937 else:
938 last_pos, k = -10000, 0
939 for v in self:
940 if abs(v.POS - last_pos) < 5000: continue
941 if len(v.REF) != 1: continue
942 if len(v.ALT) != 1: continue
943 if v.call_rate < 0.5: continue
944 if not 0.03 < v.aaf < 0.6: continue
945 if np.mean(v.gt_depths > 7) < 0.5: continue
946 last_pos = v.POS
947 if k >= offset and k % each == 0:
948 yield k, v
949 k += 1
950 if k > 20000: break
951
952 def het_check(self, min_depth=8, percentiles=(10, 90), _finish=True,
953 int each=1, int offset=0,
954 sites=None):
955
956 cdef int i, k, n_samples = len(self.samples)
957 cdef Variant v
958 cdef np.ndarray het_counts = np.zeros((n_samples,), dtype=np.int32)
959
960 cdef np.ndarray sum_depths = np.zeros((n_samples,), dtype=np.int32)
961 cdef np.ndarray sum_counts = np.zeros((n_samples,), dtype=np.int32)
962 cdef int any_counts = 0
963
964 # keep the sites and gts that we used for PCA
965 used_sites, all_gt_types = [], []
966
967 mean_depths = []
968
969 maf_lists = defaultdict(list)
970 idxs = np.arange(n_samples)
971 for i, v in self.gen_variants(sites, each=each, offset=offset):
972 if v.CHROM in ('X', 'chrX'): break
973 if v.aaf < 0.01: continue
974 if v.call_rate < 0.5: continue
975 used_sites.append("%s:%d:%s:%s" % (v.CHROM, v.start + 1, v.REF, v.ALT[0]))
976 alts = v.gt_alt_depths
977 assert len(alts) == n_samples
978 depths = (alts + v.gt_ref_depths).astype(np.int32)
979 sum_depths += depths
980 sum_counts += (depths > min_depth)
981 any_counts += 1
982 mean_depths.append(depths)
983
984 mafs = alts / depths.astype(float)
985 gt_types = v.gt_types
986 hets = gt_types == 1
987 het_counts[hets] += 1
988 for k in idxs[hets]:
989 if depths[k] <= min_depth: continue
990 maf_lists[k].append(mafs[k])
991 all_gt_types.append(np.array(gt_types, dtype=np.uint8))
992
993 if _finish:
994 mean_depths = np.array(mean_depths, dtype=np.int32).T
995 return self._finish_het(mean_depths, maf_lists,
996 percentiles,
997 het_counts, sum_counts, all_gt_types,
998 used_sites, any_counts)
999 return (mean_depths, maf_lists, het_counts, sum_counts,
1000 all_gt_types, used_sites, any_counts)
1001
1002
1003 def _finish_het(self, mean_depths, maf_lists, percentiles, het_counts,
1004 sum_counts, all_gt_types, sites, any_counts):
1005
1006 sample_ranges = {}
1007 for i, sample in enumerate(self.samples):
1008 qs = np.asarray(np.percentile(maf_lists[i] or [0], percentiles))
1009 sample_ranges[sample] = dict(zip(['p' + str(p) for p in percentiles], qs))
1010 sample_ranges[sample]['range'] = qs.max() - qs.min()
1011 sample_ranges[sample]['het_ratio'] = het_counts[i] / float(any_counts)
1012 sample_ranges[sample]['het_count'] = het_counts[i]
1013 sample_ranges[sample]['sampled_sites'] = sum_counts[i]
1014 sample_ranges[sample]['mean_depth'] = np.mean(mean_depths[i])
1015 sample_ranges[sample]['median_depth'] = np.median(mean_depths[i])
1016 # used for the peddy paper.
1017 if os.environ.get('PEDDY_MAF_DUMP'):
1018 path = os.environ['PEDDY_MAF_DUMP']
1019 import cPickle
1020 cPickle.dump({s: maf_lists[i] for i, s in enumerate(self.samples)}, open(path, 'wb', -1))
1021
1022
1023 return sample_ranges, sites, np.transpose(all_gt_types)
1024
1025 def site_relatedness(self, sites=None,
1026 min_depth=5, each=1):
1027
1028 vibs, vn, vhet = self._site_relatedness(sites=sites, min_depth=min_depth, each=each)
1029 return self._relatedness_finish(vibs, vn, vhet)
1030
1031 cdef _site_relatedness(self, sites=None,
1032 int min_depth=5, int each=1, int offset=0):
1033 """
1034 sites must be an file of format: chrom:pos1:ref:alt where
1035 we match on all parts.
1036 it must have a matching file with a suffix of .bin.gz that is the binary
1037 genotype data. with 0 == hom_ref, 1 == het, 2 == hom_alt, 3 == unknown.
1038 min_depth applies per-sample
1039 """
1040 cdef int n_samples = len(self.samples)
1041 cdef int k, i
1042 assert each >= 0
1043
1044
1045 cdef int32_t[:, ::view.contiguous] ibs = np.zeros((n_samples, n_samples), np.int32)
1046 cdef int32_t[:, ::view.contiguous] n = np.zeros((n_samples, n_samples), np.int32)
1047 cdef int32_t[:] hets = np.zeros((n_samples, ), np.int32)
1048 cdef int32_t[:] gt_types = np.zeros((n_samples, ), np.int32)
1049 cdef int32_t[:] depths = np.zeros((n_samples, ), np.int32)
1050 cdef double[:] alt_freqs = np.zeros((n_samples,), np.double)
1051
1052 cdef Variant v
1053
1054 for j, (i, v) in enumerate(self.gen_variants(sites, offset=offset, each=each)):
1055 gt_types = v.gt_types
1056 alt_freqs = v.gt_alt_freqs
1057 krelated(&gt_types[0], &ibs[0, 0], &n[0, 0], &hets[0], n_samples,
1058 &alt_freqs[0])
1059
1060 return ibs, n, hets
1061
1062 def relatedness(self, int n_variants=35000, int gap=30000, float min_af=0.04,
1063 float max_af=0.8, float linkage_max=0.2, min_depth=8):
1064 cdef Variant v
1065
1066 cdef int last = -gap, nv = 0, nvt=0
1067 cdef int32_t *last_gts = NULL
1068 samples = self.samples
1069 cdef int n_samples = len(samples)
1070 cdef float aaf = 0.0
1071 cdef int n_unlinked = 0
1072
1073 cdef int32_t[:, ::view.contiguous] ibs = np.zeros((n_samples, n_samples), np.int32)
1074 cdef int32_t[:, ::view.contiguous] n = np.zeros((n_samples, n_samples), np.int32)
1075 cdef int32_t[:] hets = np.zeros((n_samples, ), np.int32)
1076 cdef int32_t[:] gt_types = np.zeros((n_samples, ), np.int32)
1077
1078 for v in self:
1079 nvt += 1
1080 if last_gts == NULL:
1081 if v._gt_types == NULL:
1082 v.gt_types
1083 last_gts = v._gt_types
1084 if v.POS - last < gap and v.POS > last:
1085 continue
1086 if v.call_rate < 0.5: continue
1087 # require half of the samples to meet the min depth
1088 if np.mean(v.gt_depths > min_depth) < 0.5: continue
1089 aaf = v.aaf
1090 if aaf < min_af: continue
1091 if aaf > max_af: continue
1092 if linkage_max < 1 and v.POS - last < 40000:
1093 if v._gt_types == NULL:
1094 v.gt_types
1095 # require 5 unlinked variants
1096 if r_unphased(last_gts, v._gt_types, 1e-5, n_samples) > linkage_max:
1097 continue
1098 n_unlinked += 1
1099 if n_unlinked < 5:
1100 continue
1101
1102 n_unlinked = 0
1103
1104 if v._gt_types == NULL:
1105 gt_types = v.gt_types
1106 last, last_gts = v.POS, v._gt_types
1107
1108 v.relatedness(ibs, n, hets)
1109 nv += 1
1110 if nv == n_variants:
1111 break
1112 warnings.warn("tested: %d variants out of %d" % (nv, nvt))
1113 return self._relatedness_finish(ibs, n, hets)
1114
1115 cdef dict _relatedness_finish(self,
1116 int32_t[:, ::view.contiguous] _ibs,
1117 int32_t[:, ::view.contiguous] _n,
1118 int32_t[:] _hets):
1119 samples = self.samples
1120 cdef int sj, sk, ns = len(samples)
1121
1122 res = {'sample_a': [], 'sample_b': [],
1123 'rel': array('f'),
1124 'hets_a': array('I'),
1125 'hets_b': array('I'),
1126 'shared_hets': array('I'),
1127 'ibs0': array('I'),
1128 'ibs2': array('I'),
1129 'n': array('I')}
1130
1131 cdef float bot
1132
1133 for sj in range(ns):
1134 sample_j = samples[sj]
1135 if _hets[sj] == 0:
1136 warnings.warn("peddy: no hets found for sample %s" % sample_j)
1137 for sk in range(sj, ns):
1138 if sj == sk: continue
1139 sample_k = samples[sk]
1140
1141 # calculate relatedness. we use the geometric mean.
1142 #bot = math.exp(0.5 * (math.log(1 + _hets[sk]) + math.log(1 + _hets[sj])))
1143 #bot = (_hets[sk] + _hets[sj])/2.0
1144 bot = min(_hets[sk], _hets[sj])
1145 if bot == 0:
1146 bot = max(_hets[sk], _hets[sj])
1147 if bot == 0:
1148 # set to negative value if we are unable to calculate it.
1149 bot = -1
1150
1151 phi = (_ibs[sk, sj] - 2.0 * _ibs[sj, sk]) / (bot)
1152
1153 res['sample_a'].append(sample_j)
1154 res['sample_b'].append(sample_k)
1155 res['hets_a'].append(_hets[sj])
1156 res['hets_b'].append(_hets[sk])
1157 res['rel'].append(phi) # rel is 2*kinship
1158 res['ibs0'].append(_ibs[sj, sk])
1159 res['shared_hets'].append(_ibs[sk, sj])
1160 res['ibs2'].append(_n[sk, sj])
1161 res['n'].append(_n[sj, sk])
1162 return res
1163
1164 cdef class Allele(object):
1165 cdef int32_t *_raw
1166 cdef int i
1167
1168 cdef int _value(self):
1169 if self._raw[self.i] < 0: return self._raw[self.i]
1170 return (self._raw[self.i] >> 1) - 1
1171
1172 @property
1173 def phased(self):
1174 return self._raw[self.i] & 1 == 1
1175
1176 @phased.setter
1177 def phased(self, bint ph):
1178 if ph:
1179 self._raw[self.i] = (self._value() + 1)<<1|1
1180 else:
1181 self._raw[self.i] = (self._value() + 1)<<1
1182
1183 @property
1184 def value(self):
1185 if self._raw[self.i] < 0: return self._raw[self.i]
1186 return (self._raw[self.i] >> 1) - 1
1187
1188 @value.setter
1189 def value(self, int value):
1190 if value < 0:
1191 self._raw[self.i] = value
1192 return
1193 if self.phased:
1194 self._raw[self.i] = (value + 1)<<1|1
1195 else:
1196 self._raw[self.i] = (value + 1)<<1
1197
1198 def __repr__(self):
1199 if self.value < 0: return "."
1200 return str(self.value) + ("|" if self.phased else "/")
1201
1202 cdef inline Allele newAllele(int32_t *raw, int i):
1203 cdef Allele a = Allele.__new__(Allele)
1204 a._raw = raw
1205 a.i = i
1206 return a
1207
1208 cdef class Genotypes(object):
1209 cdef int32_t *_raw
1210 cdef readonly int n_samples
1211 cdef readonly int ploidy
1212 def __cinit__(self):
1213 self.ploidy = 0
1214 self.n_samples = 0
1215 self._raw = NULL
1216 def __dealloc__(self):
1217 if self._raw != NULL:
1218 stdlib.free(self._raw)
1219
1220 def phased(self, int i):
1221 """
1222 a boolean indicating that the ith sample is phased.
1223 """
•1224 return (self._raw[i * self.ploidy + self.ploidy - 1] & 1) == 1
1225
1226 def alleles(self, int i):
1227 cdef list result = []
1228 cdef int32_t v
1229 for j in range(self.ploidy):
1230 v = self._raw[i * self.ploidy + j]
1231 if v != bcf_int32_vector_end:
1232 result.append((v >> 1) - 1)
1233 return result
1234
1235 def __repr__(self):
1236 return str(self.array())
1237
1238 def array(Genotypes self, int fill=-2):
1239 """
1240 array returns an int16 numpy array of shape n_samples, (ploidy + 1).
1241 The last column indicates phased (1 is phased, 0 is unphased).
1242 The other columns indicate the alleles, e.g. [0, 1, 1] is 0|1.
1243 Unknown alleles are represented by -1.
1244 If a mixture of ploidy levels are present then the array is padded
1245 with the `fill` value (default = -2) to indicate non-alleles.
1246 """
1247 cdef np.ndarray[np.int16_t, ndim=2] to_return = np.zeros((self.n_samples, self.ploidy + 1),
1248 dtype=np.int16)
1249
1250 cdef int raw
1251 cdef int ind
1252 cdef int allele
1253 cdef int p = self.ploidy + 1
1254
1255 for ind in range(self.n_samples):
1256 for allele in range(self.ploidy):
1257 raw = self._raw[ind * self.ploidy + allele]
1258 if raw == bcf_int32_vector_end:
1259 to_return[ind, allele] = fill
1260 else:
1261 to_return[ind, allele] = (raw >> 1) - 1
•1262 to_return[ind, self.ploidy] = (self._raw[ind * self.ploidy + self.ploidy - 1] & 1) == 1
1263
1264 return to_return
1265
1266 def __getitem__(self, int i):
1267 ## return the Allele objects for the i'th sample.
1268 cdef int k
1269 return [newAllele(self._raw, k) for k in range(i*self.ploidy,(i+1)*self.ploidy)]
1270
1271 cdef inline Genotypes newGenotypes(int32_t *raw, int ploidy, int n_samples):
1272 cdef Genotypes gs = Genotypes.__new__(Genotypes)
1273 gs._raw = raw
1274 gs.ploidy = ploidy
1275 gs.n_samples = n_samples
1276 return gs
1277
1278 cdef class Variant(object):
1279 """
1280 Variant represents a single VCF Record.
1281
1282 It is created internally by iterating over a VCF.
1283
1284 Attributes
1285 ----------
1286
1287 INFO: `INFO`
1288 a dictionary-like field that provides access to the VCF INFO field.
1289
1290 POS: the 1-based variant start.
1291
1292 """
1293 cdef bcf1_t *b
1294 cdef VCF vcf
1295 cdef int32_t *_gt_types
1296 cdef int *_gt_ref_depths
1297 cdef int *_gt_alt_depths
1298 cdef float *_gt_alt_freqs
1299 cdef void *fmt_buffer
1300 cdef int *_gt_phased
1301 cdef float *_gt_quals
1302 cdef int *_int_gt_quals
1303 cdef int *_gt_idxs
1304 cdef int _gt_nper
1305 cdef int *_gt_pls
1306 cdef float *_gt_gls
1307 cdef readonly INFO INFO
1308 cdef int _ploidy
1309 cdef list _genotypes
1310
1311 cdef readonly int POS
1312
1313 def __init__(self, *args, **kwargs):
1314 raise TypeError("Variant object cannot be instantiated directly.")
1315
1316 def __cinit__(self):
1317 self.b = NULL
1318 self._gt_types = NULL
1319 self._gt_phased = NULL
1320 self._gt_pls = NULL
1321 self._ploidy = -1
1322
1323 def __repr__(self):
1324 return "Variant(%s:%d %s/%s)" % (self.CHROM, self.POS, self.REF, ",".join(self.ALT))
1325
1326 def __str__(self):
1327 cdef kstring_t s
1328 s.s, s.l, s.m = NULL, 0, 0
1329 vcf_format(self.vcf.hdr, self.b, &s)
1330 try:
1331 return s.s[:s.l].decode()
1332 finally:
1333 stdlib.free(s.s)
1334
1335 def __dealloc__(self):
1336 if self.b is not NULL:
1337 bcf_destroy(self.b)
1338 self.b = NULL
1339 if self._gt_types != NULL:
1340 stdlib.free(self._gt_types)
1341 if self._gt_ref_depths != NULL:
1342 stdlib.free(self._gt_ref_depths)
1343 if self._gt_alt_depths != NULL:
1344 stdlib.free(self._gt_alt_depths)
1345 if self._gt_alt_freqs != NULL:
1346 stdlib.free(self._gt_alt_freqs)
1347 if self._gt_phased != NULL:
1348 stdlib.free(self._gt_phased)
1349 if self._gt_quals != NULL:
1350 stdlib.free(self._gt_quals)
1351 if self._int_gt_quals != NULL:
1352 stdlib.free(self._int_gt_quals)
1353 if self._gt_idxs != NULL:
1354 stdlib.free(self._gt_idxs)
1355 if self._gt_pls != NULL:
1356 stdlib.free(self._gt_pls)
1357 if self._gt_gls != NULL:
1358 stdlib.free(self._gt_gls)
1359
1360 property gt_bases:
1361 "numpy array indicating the alleles in each sample."
1362 def __get__(self):
1363 cdef np.ndarray gt_types = self.gt_types
1364 cdef int i, n = self.ploidy, j=-1, a, b
1365 cdef char **alleles = self.b.d.allele
1366 #cdef dict d = {i:alleles[i] for i in range(self.b.n_allele)}
1367 cdef list d = [from_bytes(alleles[i]) for i in range(self.b.n_allele)]
1368 d.append(".") # -1 gives .
1369 cdef list bases = ["./." for _ in range(self.vcf.n_samples)]
1370 cdef np.ndarray phased = (self.gt_phases).astype(int)
1371 cdef list lookup = ["/", "|"]
1372 cdef int unknown = 3 if self.vcf.gts012 else 2
1373 for i in range(0, n * self.vcf.n_samples, n):
1374 j += 1
1375 if n == 2:
1376 if (gt_types[j] == unknown) and (not self.vcf.strict_gt):
1377 continue
1378 else:
1379 a = self._gt_idxs[i]
1380 b = self._gt_idxs[i + 1]
1381 if a >= -1 and b >= -1:
1382 bases[j] = d[a] + lookup[phased[j]] + d[b]
1383 else:
1384 bases[j] = d[max(-1, a)]
1385 elif n == 1:
1386 bases[j] = d[self._gt_idxs[i]]
1387 else:
1388 raise Exception("gt_bases not implemented for ploidy > 2")
1389
1390 return np.array(bases, str)
1391
1392 def relatedness(self,
1393 int32_t[:, ::view.contiguous] ibs,
1394 int32_t[:, ::view.contiguous] n,
1395 int32_t[:] hets):
1396 if not self.vcf.gts012:
1397 raise Exception("must call relatedness with gts012")
1398 if self._gt_types == NULL:
1399 self.gt_types
1400 cdef double[:] alt_freqs = self.gt_alt_freqs
1401 return krelated(<int32_t *>self._gt_types, &ibs[0, 0], &n[0, 0],
1402 &hets[0], self.vcf.n_samples, &alt_freqs[0])
1403
1404 property num_called:
1405 "number of samples that were not UNKNOWN."
1406 def __get__(self):
1407 if self._gt_types == NULL:
1408 self.gt_types
1409 cdef int n = 0, i = 0
1410 if self.vcf.gts012:
1411 for i in range(self.vcf.n_samples):
1412 if self._gt_types[i] != 3:
1413 n+=1
1414 else:
1415 for i in range(self.vcf.n_samples):
1416 if self._gt_types[i] != 2:
1417 n+=1
1418 return n
1419
1420 property call_rate:
1421 "proportion of samples that were not UNKNOWN."
1422 def __get__(self):
1423 if self.vcf.n_samples > 0:
1424 return float(self.num_called) / self.vcf.n_samples
1425
1426 property aaf:
1427 "alternate allele frequency across samples in this VCF."
1428 def __get__(self):
1429 num_chroms = 2.0 * self.num_called
1430 if num_chroms == 0.0:
1431 return 0.0
1432 return float(self.num_het + 2 * self.num_hom_alt) / num_chroms
1433
1434 property nucl_diversity:
1435 def __get__(self):
1436 num_chroms = 2.0 * self.num_called
1437 p = self.aaf
1438 return (num_chroms / (num_chroms - 1.0)) * 2 * p * (1 - p)
1439
1440 property num_hom_ref:
1441 "number homozygous reference samples at this variant."
1442 def __get__(self):
1443 if self._gt_types == NULL:
1444 self.gt_types
1445 cdef int n = 0, i = 0
1446 for i in range(self.vcf.n_samples):
1447 if self._gt_types[i] == 0:
1448 n+=1
1449 return n
1450
1451 property num_het:
1452 "number heterozygous samples at this variant."
1453 def __get__(self):
1454 if self._gt_types == NULL:
1455 self.gt_types
1456 cdef int n = 0, i = 0
1457 for i in range(self.vcf.n_samples):
1458 if self._gt_types[i] == 1:
1459 n+=1
1460 return n
1461
1462 property num_hom_alt:
1463 "number homozygous alternate samples at this variant."
1464 def __get__(self):
1465 if self._gt_types == NULL:
1466 self.gt_types
1467 cdef int n = 0, i = 0
1468 if self.vcf.gts012:
1469 for i in range(self.vcf.n_samples):
1470 if self._gt_types[i] == 2:
1471 n+=1
1472 else:
1473 for i in range(self.vcf.n_samples):
1474 if self._gt_types[i] == 3:
1475 n+=1
1476 return n
1477
1478 property num_unknown:
1479 "number unknown samples at this variant."
1480 def __get__(self):
1481 if self._gt_types == NULL:
1482 self.gt_types
1483 cdef int n = 0, i = 0
1484 cdef int unknown = 3 if self.vcf.gts012 else 2
1485 for i in range(self.vcf.n_samples):
1486 n += (self._gt_types[i] == unknown)
1487 return n
1488
1489 property FORMAT:
1490 "VCF FORMAT field for this variant."
1491 def __get__(self):
1492 cdef int i
1493 cdef bcf_fmt_t fmt
1494 cdef char *key
1495 keys = []
1496 for i in range(self.b.n_fmt):
1497 fmt = self.b.d.fmt[i];
1498 key = bcf_hdr_int2id(self.vcf.hdr, BCF_DT_ID, fmt.id)
1499 keys.append(from_bytes(key))
1500 return keys
1501
1502 def format(self, field, vtype=None):
1503 """format returns a numpy array for the requested field.
1504
1505 The numpy array shape will match the requested field. E.g. if the fields
1506 has number=3, then the shape will be (n_samples, 3).
1507
1508 Parameters
1509 ----------
1510 field: str
1511 FORMAT field to get the values.
1512
1513 Returns
1514 -------
1515 numpy array.
1516 """
1517 if vtype is None:
1518 vtype = self.vcf.get_type(field)
1519
1520 cdef bytes tag = to_bytes(field)
1521 cdef bcf_fmt_t *fmt = bcf_get_fmt(self.vcf.hdr, self.b, tag)
1522 cdef int n = 0, nret
1523 cdef void *buf = NULL;
1524 cdef int typenum = 0
1525 if vtype == "Integer" or vtype == int:
1526 nret = bcf_get_format_int32(self.vcf.hdr, self.b, tag, <int **>&buf, &n)
1527 typenum = np.NPY_INT32
1528 elif vtype == "Float" or vtype == float:
1529 nret = bcf_get_format_float(self.vcf.hdr, self.b, tag, <float **>&buf, &n)
1530 typenum = np.NPY_FLOAT32
1531 elif vtype == "String" or vtype == str or vtype == "Character":
1532 vtype = str
1533 nret = bcf_get_format_string(self.vcf.hdr, self.b, tag, <char ***>&buf, &n)
1534 typenum = np.NPY_STRING
1535 else:
1536 raise Exception("type %s not supported to format()" % vtype)
1537 if nret < 0:
1538 return None
1539
1540 cdef char **dst
1541 cdef int i
1542 cdef np.npy_intp shape[2]
1543 shape[0] = <np.npy_intp> self.vcf.n_samples
1544 shape[1] = fmt.n # values per sample
1545
1546 if vtype == str:
1547 dst = <char **>buf
1548 v = [dst[i] for i in range(self.vcf.n_samples)]
1549 xret = np.array(v, dtype=str)
1550 stdlib.free(dst[0])
1551 stdlib.free(dst)
1552 return xret
1553
1554 iv = np.PyArray_SimpleNewFromData(2, shape, typenum, buf)
1555 iret = np.array(iv)
1556 stdlib.free(buf)
1557 return iret
1558
1559 @property
1560 def genotype(self):
1561 if self.vcf.n_samples == 0: return None
1562 cdef int32_t *gts = NULL
1563 cdef int ndst = 0
1564 cdef int nret = bcf_get_genotypes(self.vcf.hdr, self.b, &gts, &ndst)
1565 if nret < 0:
1566 raise Exception("couldn't get genotypes for variant")
1567 return newGenotypes(gts, int(nret/self.vcf.n_samples), self.vcf.n_samples)
1568
1569 @genotype.setter
1570 def genotype(self, Genotypes g):
1571 cdef int ret = bcf_update_genotypes(self.vcf.hdr, self.b, g._raw, self.vcf.n_samples * g.ploidy)
1572 if ret < 0:
1573 raise Exception("error setting genotypes with: %s" % g)
1574
1575 property genotypes:
1576 """genotypes returns a list for each sample Indicating the allele and phasing.
1577
1578 e.g. [0, 1, True] corresponds to 0|1
1579 while [1, 2, False] corresponds to 1/2
1580 """
1581 def __get__(self):
1582 if self.vcf.n_samples == 0: return None
1583 if self._genotypes is not None:
1584 return self._genotypes
1585 cdef int32_t *gts = NULL
1586 cdef int i, j, nret, off = 0, ndst = 0, k = 0
1587 cdef int n_samples = self.vcf.n_samples
1588 #self._genotypes = []
1589 nret = bcf_get_genotypes(self.vcf.hdr, self.b, &gts, &ndst)
1590 if nret < 0:
1591 raise Exception("error parsing genotypes")
1592 nret /= n_samples
1593 self._genotypes = [[] for _ in range(n_samples)]
1594
1595 for i in range(n_samples):
1596 k = i * nret
1597 for j in range(nret):
1598 #assert k + j < ndst
1599 if bcf_gt_is_missing(gts[k + j]):
1600 self._genotypes[i].append(-1)
1601 continue
1602 if gts[k + j] == bcf_int32_vector_end:
1603 break
1604 self._genotypes[i].append(bcf_gt_allele(gts[k + j]))
1605 self._genotypes[i].append(
•1606 bool(bcf_gt_is_phased(gts[k + nret - 1])))
1607
1608 stdlib.free(gts)
1609 return self._genotypes
1610
1611 def __set__(self, gts):
1612 cdef int n_samples = self.vcf.n_samples
1613 if len(gts) != n_samples:
1614 raise Exception("genotypes: must set with a number of gts equal the number of samples in the vcf")
1615 elif len(gts) == 0:
1616 nret = 0
1617 else:
1618 nret = max(len(gt)-1 for gt in gts)
1619 cdef int * cgts = <int *>stdlib.malloc(sizeof(int) * nret * n_samples)
1620 cdef int i, j, k
1621 self._genotypes = None
1622
1623 for i in range(n_samples):
1624 k = i * nret
1625 for j in range(nret):
1626 if j == len(gts[i]) - 1:
1627 cgts[k + j] = bcf_int32_vector_end #bcf_gt_phased(-1)
1628 break
1629 else:
1630 cgts[k + j] = bcf_gt_phased(gts[i][j]) if gts[i][-1] else bcf_gt_unphased(gts[i][j])
1631 ret = bcf_update_genotypes(self.vcf.hdr, self.b, cgts, n_samples * nret)
1632 if ret < 0:
1633 raise Exception("error setting genotypes with: %s" % gts)
1634 stdlib.free(cgts)
1635
1636 def set_pos(self, int pos0):
1637 """
1638 set the POS to the given 0-based position
1639 """
1640 self.b.pos = pos0
1641 self.POS = self.b.pos + 1
1642
1643 def set_format(self, name, np.ndarray data not None):
1644 """
1645 set the format field given by name..
1646 data must be a numpy array of type float, int or string (fixed length ASCII np.bytes_)
1647 """
1648 cdef int n_samples = self.vcf.n_samples
1649 if len(data) % n_samples != 0:
1650 raise Exception("format: len(data) must be a multiple of number of samples in vcf.")
1651
1652 cdef np.ndarray[np.float32_t, mode="c"] afloat
1653 cdef np.ndarray[np.int32_t, mode="c"] aint
1654 cdef char *bytesp
1655 cdef size_t i
1656
1657 cdef int size
1658 cdef int ret
1659 if np.issubdtype(data.dtype, np.signedinteger) or np.issubdtype(data.dtype, np.unsignedinteger):
1660 size = data.shape[0]
1661 if len((<object>data).shape) > 1:
1662 size *= data.shape[1]
1663 aint = data.astype(np.int32).reshape((size,))
1664 ret = bcf_update_format_int32(self.vcf.hdr, self.b, to_bytes(name), &aint[0], size)
1665 elif np.issubdtype(data.dtype, np.floating):
1666 size = data.shape[0]
1667 if len((<object>data).shape) > 1:
1668 size *= data.shape[1]
1669 afloat = data.astype(np.float32).reshape((size,))
1670 isnan = np.isnan(afloat)
1671 for i in range(size):
1672 if isnan[i]:
1673 bcf_float_set(&afloat[i], bcf_float_missing)
1674 ret = bcf_update_format_float(self.vcf.hdr, self.b, to_bytes(name), &afloat[0], size)
1675 elif np.issubdtype(data.dtype, np.bytes_):
1676 if len((<object>data).shape) > 1:
1677 raise Exception("Setting string type format fields with number>1 are currently not supported")
1678 if not data.flags['C_CONTIGUOUS']:
1679 data = np.ascontiguousarray(data)
1680 size = data.nbytes
1681 bytesp = <char *>data.data
1682 ret = bcf_update_format(self.vcf.hdr, self.b, to_bytes(name), bytesp, size, BCF_HT_STR)
1683 else:
1684 raise Exception("format: currently only float, int and string (fixed length ASCII np.bytes_) numpy arrays are supported. got %s", data.dtype)
1685 if ret < 0:
1686 raise Exception("error (%d) setting format with: %s" % (ret, data[:100]))
1687
1688 property gt_types:
1689 """gt_types returns a numpy array indicating the type of each sample.
1690
1691 HOM_REF=0, HET=1. For `gts012=True` HOM_ALT=2, UNKNOWN=3
1692 """
1693 def __get__(self):
1694 cdef int ndst = 0, ngts, n, i, nper, j = 0, k = 0
1695 cdef int a
1696 if self.vcf.n_samples == 0:
1697 return np.array([])
1698 if self._gt_types == NULL:
1699 self._gt_phased = <int *>stdlib.malloc(sizeof(int) * self.vcf.n_samples)
1700 ngts = bcf_get_genotypes(self.vcf.hdr, self.b, &self._gt_types, &ndst)
1701 if ngts < 0:
1702 raise Exception("error parsing genotypes; they may be absent from this record")
1703 nper = int(ngts / self.vcf.n_samples)
1704 self._ploidy = nper
1705 self._gt_idxs = <int *>stdlib.malloc(sizeof(int) * self.vcf.n_samples * nper)
1706 if ngts == 0 or nper == 0:
1707 return np.array([])
1708 for i in range(0, ngts, nper):
1709 for k in range(i, i + nper):
1710 a = self._gt_types[k]
1711 if a >= 0:
1712 self._gt_idxs[k] = bcf_gt_allele(a)
1713 else:
1714 self._gt_idxs[k] = a
1715
1716 self._gt_phased[j] = self._gt_types[i] > 0 and <int>bcf_gt_is_phased(self._gt_types[i+1])
1717 j += 1
1718
1719 if self.vcf.gts012:
1720 n = as_gts(self._gt_types, self.vcf.n_samples, nper, self.vcf.strict_gt, 2, 3)
1721 else:
1722 n = as_gts(self._gt_types, self.vcf.n_samples, nper, self.vcf.strict_gt, 3, 2)
1723 cdef np.npy_intp shape[1]
1724 shape[0] = <np.npy_intp> self.vcf.n_samples
1725 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_types)
1726
1727 property ploidy:
1728 """get the ploidy of each sample for the given record."""
1729 def __get__(self):
1730 if self._ploidy == -1:
1731 self.gt_types
1732 return self._ploidy
1733
1734 property gt_phred_ll_homref:
1735 """get the PL of Hom ref for each sample as a numpy array."""
1736 def __get__(self):
1737 if self.vcf.n_samples == 0:
1738 return []
1739 cdef int ndst = 0, nret=0, n, i, j, nper
1740
1741 cdef int imax = np.iinfo(np.int32(0)).max
1742
1743 if self._gt_pls == NULL and self._gt_gls == NULL:
1744 nret = bcf_get_format_int32(self.vcf.hdr, self.b, "PL", &self._gt_pls, &ndst)
1745 if nret < 0:
1746 nret = bcf_get_format_float(self.vcf.hdr, self.b, "GL", &self._gt_gls, &ndst)
1747 if nret < 0:
1748 return []
1749 else:
1750 for i in range(nret):
1751 if self._gt_gls[i] <= -2147483646:
1752 # this gets translated on conversion to PL
1753 self._gt_gls[i] = imax / -10.0
1754 else:
1755 for i in range(nret):
1756 if self._gt_pls[i] < 0:
1757 self._gt_pls[i] = imax
1758
1759 self._gt_nper = int(nret / self.vcf.n_samples)
1760 cdef np.npy_intp shape[1]
1761 shape[0] = <np.npy_intp> self._gt_nper * self.vcf.n_samples
1762 if self._gt_pls != NULL:
1763 pls = np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32,
1764 self._gt_pls)[::self._gt_nper]
1765 return pls
1766 else:
1767 gls = np.PyArray_SimpleNewFromData(1, shape, np.NPY_FLOAT32,
1768 self._gt_gls)[::self._gt_nper]
1769 gls = (-10 * gls).round().astype(np.int32)
1770 return gls
1771
1772 property gt_phred_ll_het:
1773 """get the PL of het for each sample as a numpy array."""
1774 def __get__(self):
1775 if self.vcf.n_samples == 0:
1776 return []
1777 if self._gt_pls == NULL and self._gt_gls == NULL:
1778 # NOTE: the missing values for all homref, het, homalt are set
1779 # by this call.
1780 self.gt_phred_ll_homref
1781 cdef np.npy_intp shape[1]
1782 shape[0] = <np.npy_intp> self._gt_nper * self.vcf.n_samples
1783 if self._gt_pls != NULL:
1784 if self._gt_nper > 1:
1785 ret = np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_pls)[1::self._gt_nper]
1786 return ret
1787
1788 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_pls)
1789 else:
1790 if self._gt_nper > 1:
1791 gls = np.PyArray_SimpleNewFromData(1, shape, np.NPY_FLOAT32,
1792 self._gt_gls)[1::self._gt_nper]
1793 else:
1794 gls = np.PyArray_SimpleNewFromData(1, shape, np.NPY_FLOAT32, self._gt_gls)
1795 gls = (-10 * gls).round().astype(np.int32)
1796 return gls
1797
1798 property gt_phred_ll_homalt:
1799 """get the PL of hom_alt for each sample as a numpy array."""
1800 def __get__(self):
1801 if self.vcf.n_samples == 0:
1802 return []
1803 if self._gt_pls == NULL and self._gt_gls == NULL:
1804 self.gt_phred_ll_homref
1805 cdef np.npy_intp shape[1]
1806 shape[0] = <np.npy_intp> self._gt_nper * self.vcf.n_samples
1807 if self._gt_pls != NULL:
1808 if self._gt_nper > 1:
1809 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32,
1810 self._gt_pls)[2::self._gt_nper]
1811 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_pls)
1812 else:
1813 if self._gt_nper > 1:
1814 gls = np.PyArray_SimpleNewFromData(1, shape, np.NPY_FLOAT32,
1815 self._gt_gls)[2::self._gt_nper]
1816 else:
1817 gls = np.PyArray_SimpleNewFromData(1, shape, np.NPY_FLOAT32,
1818 self._gt_gls)
1819 gls = (-10 * gls).round().astype(np.int32)
1820 return gls
1821
1822 property gt_ref_depths:
1823 """get the count of reference reads for a diploid sample as a numpy array."""
1824 def __get__(self):
1825 cdef int ndst, nret = 0, n, i, j = 0, nper = 0
1826 if self.vcf.n_samples == 0:
1827 return []
1828 if self._gt_ref_depths == NULL:
1829 ndst = 0
1830 # GATK
1831 nret = bcf_get_format_int32(self.vcf.hdr, self.b, "AD", &self._gt_ref_depths, &ndst)
1832 if nret > 0:
1833 nper = int(nret / self.vcf.n_samples)
1834 if nper == 1:
1835 stdlib.free(self._gt_ref_depths); self._gt_ref_depths = NULL
1836 return -1 + np.zeros(self.vcf.n_samples, np.int32)
1837
1838 for i in range(0, nret, nper):
1839 self._gt_ref_depths[j] = self._gt_ref_depths[i]
1840 j += 1
1841 elif nret == -1:
1842 # Freebayes
1843 # RO has to be 1:1
1844 nret = bcf_get_format_int32(self.vcf.hdr, self.b, "RO", &self._gt_ref_depths, &ndst)
1845 if nret < 0:
1846 stdlib.free(self._gt_ref_depths); self._gt_ref_depths = NULL
1847 return -1 + np.zeros(self.vcf.n_samples, np.int32)
1848 # TODO: add new vcf standard.
1849 else:
1850 stdlib.free(self._gt_ref_depths); self._gt_ref_depths = NULL
1851 return -1 + np.zeros(self.vcf.n_samples, np.int32)
1852
1853 for i in range(self.vcf.n_samples):
1854 if self._gt_ref_depths[i] < 0:
1855 self._gt_ref_depths[i] = -1
1856 else:
1857 pass
1858
1859 cdef np.npy_intp shape[1]
1860 shape[0] = <np.npy_intp> self.vcf.n_samples
1861 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_ref_depths)
1862
1863 property gt_alt_depths:
1864 """get the count of alternate reads for a diploid sample as a numpy array."""
1865 def __get__(self):
1866 cdef int ndst, nret = 0, n, i, j = 0, k = 0, nper = 0
1867 if self.vcf.n_samples == 0:
1868 return []
1869 if self._gt_alt_depths == NULL:
1870 ndst = 0
1871 # GATK
1872 nret = bcf_get_format_int32(self.vcf.hdr, self.b, "AD", &self._gt_alt_depths, &ndst)
1873 if nret > 0:
1874 nper = int(nret / self.vcf.n_samples)
1875 if nper == 1:
1876 stdlib.free(self._gt_alt_depths); self._gt_alt_depths = NULL
1877 return (-1 + np.zeros(self.vcf.n_samples, np.int32))
1878
1879 for i in range(0, nret, nper):
1880 self._gt_alt_depths[j] = self._gt_alt_depths[i+1]
1881 # add up all the alt alleles
1882 for k in range(2, nper):
1883 self._gt_alt_depths[j] += self._gt_alt_depths[i+k]
1884 j += 1
1885
1886 elif nret == -1:
1887 # Freebayes
1888 nret = bcf_get_format_int32(self.vcf.hdr, self.b, "AO", &self._gt_alt_depths, &ndst)
1889 nper = int(nret / self.vcf.n_samples)
1890 if nret < 0:
1891 stdlib.free(self._gt_alt_depths); self._gt_alt_depths = NULL
1892 return -1 + np.zeros(self.vcf.n_samples, np.int32)
1893 for i in range(0, nret, nper):
1894 self._gt_alt_depths[j] = self._gt_alt_depths[i]
1895 for k in range(1, nper):
1896 self._gt_alt_depths[j] += self._gt_alt_depths[i+k]
1897 j += 1
1898 else:
1899 stdlib.free(self._gt_alt_depths); self._gt_alt_depths = NULL
1900 return -1 + np.zeros(self.vcf.n_samples, np.int32)
1901
1902 # TODO: add new vcf standard.
1903 for i in range(self.vcf.n_samples):
1904 if self._gt_alt_depths[i] < 0:
1905 self._gt_alt_depths[i] = -1
1906
1907 cdef np.npy_intp shape[1]
1908 shape[0] = <np.npy_intp> self.vcf.n_samples
1909 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_alt_depths)
1910
1911 property gt_alt_freqs:
1912 """get the freq of alternate reads for a diploid sample as a numpy array."""
1913 def __get__(self):
1914 if self.vcf.n_samples == 0:
1915 return []
1916 t = np.array(self.gt_depths, float)
1917 a = np.array(self.gt_alt_depths, float)
1918
1919 # for which samples are the alt or total depths unknown?
1920 tU = t < 0
1921 aU = a < 0
1922 # for which samples is the total depth 0?
1923 t0 = t == 0
1924
1925 ## initialize
1926 alt_freq = t.astype(float)
1927
1928 # default
1929 alt_freq[t0] = 0
1930 alt_freq[aU] = 0
1931 alt_freq[tU] = -1
1932
1933 # compute the alt_freq when not unknown and no div0 error
1934 clean = ~tU & ~aU & ~t0
1935 alt_freq[clean] = (a[clean] / t[clean])
1936
1937 return alt_freq
1938
1939 property gt_quals:
1940 """get the GQ for each sample as a numpy array."""
1941 def __get__(self):
1942 if self.vcf.n_samples == 0:
1943 return []
1944 cdef int ndst = 0, nret, n, i
1945 cdef int *gq
1946 cdef np.ndarray[np.float32_t, ndim=1] a
1947 if self._gt_quals == NULL and self._int_gt_quals == NULL:
1948 nret = bcf_get_format_int32(self.vcf.hdr, self.b, "GQ", &self._int_gt_quals, &ndst)
1949 if nret == -2: # defined as int
1950 ndst = 0
1951 nret = bcf_get_format_float(self.vcf.hdr, self.b, "GQ", &self._gt_quals, &ndst)
1952 if nret < 0 and nret != -2:
1953 return -1.0 + np.zeros(self.vcf.n_samples, np.float32)
1954 cdef np.npy_intp shape[1]
1955 shape[0] = <np.npy_intp> self.vcf.n_samples
1956 if self._int_gt_quals != NULL:
1957 a = np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._int_gt_quals).astype(np.float32)
1958 a[a < 0] = -1
1959 else:
1960 a = np.PyArray_SimpleNewFromData(1, shape, np.NPY_FLOAT32, self._gt_quals)
1961 # this take up 10% of the total vcf parsing time. fix!!
1962 a[np.isnan(a)] = -1
1963 return a
1964
1965 property gt_depths:
1966 """get the read-depth for diploid samples as a numpy array."""
1967 def __get__(self):
1968 if self.vcf.n_samples == 0:
1969 return []
1970 # unfortunately need to create a new array here since we're modifying.
1971 r = np.array(self.gt_ref_depths, np.int32)
1972 a = np.array(self.gt_alt_depths, np.int32)
1973 # keep the -1 for empty.
1974 rl0 = r < 0
1975 al0 = a < 0
1976 r[rl0] = 0
1977 a[al0] = 0
1978 depth = r + a
1979 depth[rl0 & al0] = -1
1980 return depth
1981
1982 property gt_phases:
1983 """get a boolean indicating whether each sample is phased as a numpy array."""
1984 def __get__(self):
1985 # run for side-effect
1986 if self._gt_phased == NULL:
1987 self.gt_types
1988 cdef np.npy_intp shape[1]
1989 shape[0] = <np.npy_intp> self.vcf.n_samples
1990
1991 return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT32, self._gt_phased).astype(bool)
1992
1993 property REF:
1994 "the reference allele."
1995 def __get__(self):
1996 return self.b.d.allele[0].decode()
1997
1998 def __set__(self, ref):
1999 # int bcf_update_alleles_str(const bcf_hdr_t *hdr, bcf1_t *line, const char *alleles_string);
2000 alleles = (ref + "," + ",".join(self.ALT)).encode()
2001 if bcf_update_alleles_str(self.vcf.hdr, self.b, alleles) != 0:
2002 raise ValueError("couldn't set reference to:" + str(ref))
2003
2004 property ALT:
2005 "the list of alternate alleles."
2006 def __get__(self):
2007 cdef int i
2008 return [self.b.d.allele[i].decode() for i in range(1, self.b.n_allele)]
2009
2010 def __set__(self, alts):
2011 # int bcf_update_alleles_str(const bcf_hdr_t *hdr, bcf1_t *line, const char *alleles_string);
2012 if not isinstance(alts, list):
2013 alts = [alts]
2014 alleles = (self.REF + "," + ",".join(alts)).encode()
2015 if bcf_update_alleles_str(self.vcf.hdr, self.b, alleles) != 0:
2016 raise ValueError("couldn't set alternates to:" + str(alts))
2017
2018 property is_snp:
2019 "boolean indicating if the variant is a SNP."
2020 def __get__(self):
2021 cdef int i
2022 if len(self.b.d.allele[0]) > 1: return False
2023 for i in range(1, self.b.n_allele):
2024 if not self.b.d.allele[i] in (b"A", b"C", b"G", b"T"):
2025 return False
2026 return self.b.n_allele > 1
2027
2028 property is_mnp:
2029 "boolean indicating if the variant is a MNP."
2030 def __get__(self):
2031 cdef int i
2032 is_sv = self.is_sv
2033 if len(self.b.d.allele[0]) == 1 and not is_sv: return False
2034
2035 if len(self.REF) == 1 and not is_sv: return False
2036
2037 if all([len(x)==len(self.REF) for x in self.ALT]):
2038 if not is_sv:
2039 return True
2040 return False
2041
2042 property is_indel:
2043 "boolean indicating if the variant is an indel."
2044 def __get__(self):
2045 cdef int i
2046 if self.is_sv: return False
2047 if len(self.b.d.allele[0]) > 1 and self.b.d.allele[0] != b'<': return True
2048
2049 if len(self.REF) > 1: return True
2050
2051 for i in range(1, self.b.n_allele):
2052 alt = self.b.d.allele[i]
2053 if alt[0] == b'<': continue
2054 if alt == b".":
2055 return True
2056 if len(alt) > 1:
2057 return True
2058 return False
2059
2060 property is_transition:
2061 "boolean indicating if the variant is a transition."
2062 def __get__(self):
2063 if len(self.ALT) != 1: return False
2064
2065 if not self.is_snp: return False
2066 ref = self.REF
2067 # just one alt allele
2068 alt_allele = self.ALT[0]
2069 if ((ref == 'A' and alt_allele == 'G') or
2070 (ref == 'G' and alt_allele == 'A') or
2071 (ref == 'C' and alt_allele == 'T') or
2072 (ref == 'T' and alt_allele == 'C')):
2073 return True
2074 return False
2075
2076 property is_deletion:
2077 "boolean indicating if the variant is a deletion."
2078 def __get__(self):
2079 if len(self.ALT) > 1: return False
2080
2081 if not self.is_indel: return False
2082 if len(self.ALT) == 0:
2083 return True
2084 alt = self.ALT[0]
2085 if alt is None or alt == ".":
2086 return True
2087
2088 if len(self.REF) > len(alt):
2089 return True
2090 return False
2091
2092 property is_sv:
2093 "boolean indicating if the variant is an SV."
2094 def __get__(self):
2095 return self.INFO.get(b'SVTYPE') is not None
2096
2097 property CHROM:
2098 """Chromosome of the variant."""
2099 def __get__(self):
2100 return bcf_hdr_id2name(self.vcf.hdr, self.b.rid).decode()
2101
2102 def __set__(self, new_chrom):
2103 new_rid = bcf_hdr_id2int(self.vcf.hdr, BCF_DT_CTG, new_chrom.encode())
2104 if new_rid < 0:
2105 self.vcf.add_to_header("##contig=<ID={}>".format(new_chrom))
2106 new_rid = bcf_hdr_id2int(self.vcf.hdr, BCF_DT_CTG, new_chrom.encode())
2107 if new_rid < 0:
2108 raise ValueError("Unable to add {} to CHROM".format(new_chrom))
2109 warnings.warn("added new contig {} to header".format(new_chrom))
2110 self.b.rid = new_rid
2111
2112 property var_type:
2113 "type of variant (snp/indel/sv)"
2114 def __get__(self):
2115 if self.is_snp:
2116 return "snp"
2117 if self.is_mnp:
2118 return "mnp"
2119 elif self.is_indel:
2120 return "indel"
2121 elif self.is_sv:
2122 return "sv"
2123 else:
2124 return "unknown"
2125
2126 property var_subtype:
2127 def __get__(self):
2128 if self.is_snp:
2129 if self.is_transition:
2130 return "ts"
2131 if len(self.ALT) == 1:
2132 return "tv"
2133 return "unknown"
2134
2135 elif self.is_indel:
2136 if self.is_deletion:
2137 return "del"
2138 if len(self.ALT) == 1:
2139 return "ins"
2140 else:
2141 return "unknown"
2142
2143 svt = self.INFO.get("SVTYPE")
2144 if svt is None:
2145 return "unknown"
2146 if svt == "BND":
2147 return "complex"
2148 if self.INFO.get('IMPRECISE') is None:
2149 return svt
2150 return self.ALT[0].strip('<>')
2151
2152 property start:
2153 "0-based start of the variant."
2154 def __get__(self):
2155 return self.b.pos
2156
2157 property end:
2158 "end of the variant. the INFO field is parsed for SVs."
2159 def __get__(self):
2160 return self.b.pos + self.b.rlen
2161
2162 property ID:
2163 "the value of ID from the VCF field."
2164 def __get__(self):
2165 cdef char *id = self.b.d.id
2166 if id == b".": return None
2167 return from_bytes(id)
2168
2169 def __set__(self, value):
2170 sanitized = str(value) if value is not None else '.'
2171 ret = bcf_update_id(self.vcf.hdr, self.b, to_bytes(sanitized))
2172 if ret != 0:
2173 raise Exception("not able to set ID: %s", value)
2174
2175 property FILTER:
2176 """the value of FILTER from the VCF field.
2177
2178 a value of PASS or '.' in the VCF will give None for this function
2179 """
2180 def __get__(self):
2181 cdef int i
2182 cdef int n = self.b.d.n_flt
2183 if n == 1:
2184 if self.vcf.PASS != -1:
2185 if self.b.d.flt[0] == self.vcf.PASS:
2186 return None
2187 else:
2188 v = bcf_hdr_int2id(self.vcf.hdr, BCF_DT_ID, self.b.d.flt[0])
2189 if v == b"PASS":
2190 self.vcf.PASS = self.b.d.flt[0]
2191 return None
2192 return from_bytes(v)
2193 if n == 0:
2194 return None
2195 return from_bytes(b';'.join(bcf_hdr_int2id(self.vcf.hdr, BCF_DT_ID, self.b.d.flt[i]) for i in range(n)))
2196
2197 def __set__(self, filters):
2198 if isinstance(filters, basestring):
2199 filters = filters.split(";")
2200 cdef bcf_hdr_t *h = self.vcf.hdr
2201 cdef int *flt_ids = <int *>stdlib.malloc(sizeof(int) * len(filters))
2202 for i, fname in enumerate(filters):
2203 flt_ids[i] = bcf_hdr_id2int(h, BCF_DT_ID, to_bytes(fname))
2204 ret = bcf_update_filter(h, self.b, flt_ids, len(filters))
2205 stdlib.free(flt_ids)
2206 if ret != 0:
2207 raise Exception("not able to set filter: %s", filters)
2208
2209 property FILTERS:
2210 """the FILTER values as a list from the VCF field.
2211
2212 a value '.' in the VCF will return an empty list for this property
2213 """
2214 def __get__(self):
2215 cdef int i
2216 cdef int n = self.b.d.n_flt
2217 return [from_bytes(bcf_hdr_int2id(self.vcf.hdr, BCF_DT_ID, self.b.d.flt[i])) for i in range(n)]
2218
2219 property QUAL:
2220 "the float value of QUAL from the VCF field."
2221 def __get__(self):
2222 cdef float q = self.b.qual
2223 if bcf_float_is_missing(q):
2224 return None
2225 return q
2226
2227 def __set__(self, value):
2228 if value is None:
2229 bcf_float_set(&self.b.qual, bcf_float_missing)
2230 else:
2231 self.b.qual = value
2232
2233
2234 cdef inline HREC newHREC(bcf_hrec_t *hrec, bcf_hdr_t *hdr):
2235 cdef HREC h = HREC.__new__(HREC)
2236 h.hdr = hdr
2237 h.hrec = hrec
2238 return h
2239
2240
2241 cdef class HREC(object):
2242 cdef bcf_hdr_t *hdr
2243 cdef bcf_hrec_t *hrec
2244
2245 def __cinit__(HREC self):
2246 pass
2247
2248 def __dealloc__(self):
2249 #bcf_hrec_destroy(self.hrec)
2250 self.hrec = NULL
2251 self.hdr = NULL
2252
2253 @property
2254 def type(self):
2255 return ["FILTER", "INFO", "FORMAT", "CONTIG", "STR", "GENERIC"][self.hrec.type]
2256
2257 def __getitem__(self, key):
2258 key = from_bytes(key)
2259 if key == "HeaderType":
2260 return self.type
2261 cdef int i
2262 for i in range(self.hrec.nkeys):
2263 if from_bytes(self.hrec.keys[i]) == key:
2264 return from_bytes(self.hrec.vals[i])
2265 raise KeyError
2266
2267 def info(self, extra=False):
2268 """
2269 return a dict with commonly used stuffs
2270 """
2271 d = {}
2272 for k in ('Type', 'Number', 'ID', 'Description'):
2273 try:
2274 d[k] = self[k]
2275 except KeyError:
2276 continue
2277 d['HeaderType'] = self.type
2278 if extra:
2279 for i in range(self.hrec.nkeys):
2280 k = self.hrec.keys[i]
2281 if k in d: continue
2282 d[k] = self.hrec.vals[i]
2283 return d
2284
2285 def __repr__(self):
2286 return str(self.info())
2287
2288
2289 cdef class INFO(object):
2290 """
2291 INFO is create internally by accessing `Variant.INFO`
2292
2293 is acts like a dictionary where keys are expected to be in the INFO field of the Variant
2294 and values are typed according to what is specified in the VCF header
2295
2296 Items can be deleted with del v.INFO[key] and accessed with v.INFO[key] or v.INFO.get(key)
2297 """
2298 cdef bcf_hdr_t *hdr
2299 cdef bcf1_t *b
2300 cdef int _i
2301
2302 def __cinit__(INFO self):
2303 self._i = 0
2304
2305 def __delitem__(self, okey):
2306 okey = to_bytes(okey)
2307 cdef char *key = okey
2308 cdef bcf_info_t *info = bcf_get_info(self.hdr, self.b, key)
2309 if info == NULL:
2310 raise KeyError(key)
2311 cdef int htype = bcf_hdr_id2type(self.hdr, BCF_HL_INFO, info.key)
2312 cdef int ret = bcf_update_info(self.hdr, self.b, key,NULL,0,htype)
2313 if ret != 0:
2314 raise Exception("error deleting %s" % key)
2315
2316 def __setitem__(self, key, value):
2317 # only support strings for now.
2318 if value is True or value is False:
2319
2320 ret = bcf_update_info_flag(self.hdr, self.b, to_bytes(key), b"", int(value))
2321 if ret != 0:
2322 raise Exception("not able to set: %s -> %s (%d)" % (key, value, ret))
2323
2324 return
2325 cdef int32_t iint
2326 cdef float ifloat
2327 if isinstance(value, int):
2328 iint = value
2329 ret = bcf_update_info_int32(self.hdr, self.b, to_bytes(key), &iint, 1)
2330 elif isinstance(value, float):
2331 ifloat = value
2332 ret = bcf_update_info_float(self.hdr, self.b, to_bytes(key), &ifloat, 1)
2333 else:
2334 ret = bcf_update_info_string(self.hdr, self.b, to_bytes(key), to_bytes(value))
2335 if ret != 0:
2336 raise Exception("not able to set: %s -> %s (%d)", key, value, ret)
2337
2338 cdef _getval(INFO self, bcf_info_t * info, char *key):
2339
2340 if info.len == 1:
2341 if info.type == BCF_BT_INT8:
2342 if info.v1.i == INT8_MIN:
2343 return None
2344 return <int>(info.v1.i)
2345
2346 if info.type == BCF_BT_INT16:
2347 if info.v1.i == INT16_MIN:
2348 return None
2349 return <int>(info.v1.i)
2350
2351 if info.type == BCF_BT_INT32:
2352 if info.v1.i == INT32_MIN:
2353 return None
2354 return <int>(info.v1.i)
2355
2356 if info.type == BCF_BT_FLOAT:
2357 if bcf_float_is_missing(info.v1.f):
2358 return None
2359 return info.v1.f
2360
2361 if info.type == BCF_BT_CHAR:
2362 v = info.vptr[:info.vptr_len]
2363 if len(v) > 0 and v[0] == 0x7:
2364 return None
2365 return from_bytes(v)
2366
2367 # FLAG.
2368 if info.len == 0:
2369 return bcf_hdr_id2type(self.hdr, BCF_HL_INFO, info.key) == BCF_HT_FLAG
2370
2371 return bcf_array_to_object(info.vptr, info.type, info.len)
2372
2373 def __getitem__(self, okey):
2374 okey = to_bytes(okey)
2375 cdef char *key = okey
2376 cdef bcf_info_t *info = bcf_get_info(self.hdr, self.b, key)
2377 if info == NULL:
2378 raise KeyError(key)
2379 return self._getval(info, key)
2380
2381 def get(self, key, default=None):
2382 try:
2383 return self.__getitem__(key)
2384 except KeyError:
2385 return default
2386
2387 def __iter__(self):
2388 self._i = 0
2389 return self
2390
2391 def __next__(self):
2392 cdef bcf_info_t *info = NULL
2393 cdef char *name
2394 while info == NULL:
2395 if self._i >= self.b.n_info:
2396 raise StopIteration
2397 info = &(self.b.d.info[self._i])
2398 self._i += 1
2399 name = bcf_hdr_int2id(self.hdr, BCF_DT_ID, info.key)
2400 return name.decode(), self._getval(info, name)
2401
2402
2403 # this function is copied verbatim from pysam/cbcf.pyx
2404 cdef bcf_array_to_object(void *data, int type, int n, int scalar=0):
2405 cdef char *datac
2406 cdef int8_t *data8
2407 cdef int16_t *data16
2408 cdef int32_t *data32
2409 cdef float *dataf
2410 cdef int i
2411
2412 if not data or n <= 0:
2413 return None
2414
2415 if type == BCF_BT_CHAR:
2416 datac = <char *>data
2417 value = datac[:n].decode() if datac[0] != bcf_str_missing else None
2418 else:
2419 value = []
2420 if type == BCF_BT_INT8:
2421 data8 = <int8_t *>data
2422 for i in range(n):
2423 if data8[i] == bcf_int8_vector_end:
2424 break
2425 value.append(data8[i] if data8[i] != bcf_int8_missing else None)
2426 elif type == BCF_BT_INT16:
2427 data16 = <int16_t *>data
2428 for i in range(n):
2429 if data16[i] == bcf_int16_vector_end:
2430 break
2431 value.append(data16[i] if data16[i] != bcf_int16_missing else None)
2432 elif type == BCF_BT_INT32:
2433 data32 = <int32_t *>data
2434 for i in range(n):
2435 if data32[i] == bcf_int32_vector_end:
2436 break
2437 value.append(data32[i] if data32[i] != bcf_int32_missing else None)
2438 elif type == BCF_BT_FLOAT:
2439 dataf = <float *>data
2440 for i in range(n):
2441 if bcf_float_is_vector_end(dataf[i]):
2442 break
2443 value.append(dataf[i] if not bcf_float_is_missing(dataf[i]) else None)
2444 else:
2445 raise TypeError('unsupported info type code')
2446
2447 if not value:
2448 value = None
2449 elif scalar and len(value) == 1:
2450 value = value[0]
2451 else:
2452 value = tuple(value)
2453
2454 return value
2455
2456
2457 cdef inline Variant newVariant(bcf1_t *b, VCF vcf):
2458 cdef Variant v = Variant.__new__(Variant)
2459 v.b = b
2460 if not vcf.lazy:
2461 with nogil:
2462 bcf_unpack(v.b, 15)
2463 else:
2464 with nogil:
2465 bcf_unpack(v.b, 1|2|4)
2466
2467 v.vcf = vcf
2468 v.POS = v.b.pos + 1
2469 cdef INFO i = INFO.__new__(INFO)
2470 i.b = b
2471 i.hdr = vcf.hdr
2472 v.INFO = i
2473 return v
2474
2475
2476 cdef to_bytes(s, enc=ENC):
2477 if not isinstance(s, bytes):
2478 return s.encode(enc)
2479 return s
2480
2481
2482 cdef from_bytes(s):
2483 if isinstance(s, bytes):
2484 try:
2485 return s.decode(ENC)
2486 except UnicodeDecodeError:
2487 return s.decode('utf8', errors='replace')
2488 return s
2489
2490
2491 # TODO: make Writer extend HTSFile not VCF by moving common methods into HTSFile
2492 cdef class Writer(VCF):
2493 """
2494 Writer class makes a VCF Writer.
2495
2496 Parameters
2497 ----------
2498 fname: str
2499 path to file
2500 tmpl: VCF
2501 a template to use to create the output header.
2502 mode: str
2503 | Mode to use for writing the file. If ``None`` (default) is given, the mode is
2504 inferred from the filename extension. If stdout (``"-"``) is provided for ``fname``
2505 and ``mode`` is left at default, uncompressed VCF will be produced.
2506 | Valid values are:
2507 | - ``"wbu"``: uncompressed BCF
2508 | - ``"wb"``: compressed BCF
2509 | - ``"wz"``: compressed VCF
2510 | - ``"w"``: uncompressed VCF
2511 | Compression level can also be indicated by adding a single integer to one of
2512 the compressed modes (e.g. ``"wz4"`` for VCF with compressions level 4).
2513
2514 Note
2515 ----
2516 File extensions ``.bcf`` and ``.bcf.gz`` will both return compressed BCF. If you
2517 want uncompressed BCF you must explicitly provide the appropriate ``mode``.
2518
2519 Returns
2520 -------
2521 VCF object for iterating and querying.
2522 """
2523 #cdef htsFile *hts
2524 #cdef bcf_hdr_t *hdr
2525 cdef public bytes name
2526 cdef bint header_written
2527 cdef const bcf_hdr_t *ohdr
2528
2529 def __init__(Writer self, fname, VCF tmpl, mode=None):
2530 mode = self._infer_file_mode(fname, mode)
2531 self._open_htsfile(fname, mode)
2532 bcf_hdr_sync(tmpl.hdr)
2533 self.ohdr = tmpl.hdr
2534 self.hdr = bcf_hdr_dup(tmpl.hdr)
2535 bcf_hdr_sync(self.hdr)
2536 self.header_written = False
2537
2538 @staticmethod
2539 def _infer_file_mode(fname, mode=None):
2540 if mode is not None:
2541 return mode
2542
2543 from_path = isinstance(fname, (basestring, Path))
2544 if not from_path:
2545 return "w"
2546
2547 fname = str(fname)
2548 is_compressed = fname.endswith(".gz")
2549 fmt_idx = -2 if is_compressed else -1
2550 file_fmt = fname.split(".")[fmt_idx]
2551 # bcftools output write mode chars - https://github.com/samtools/bcftools/blob/76392b3014de70b7fa5c6b5c9d5bc47361951770/version.c#L64-L70
2552 inferred_mode = "w"
2553 if file_fmt == "bcf":
2554 inferred_mode += "b"
2555 if is_compressed and file_fmt == "vcf":
2556 inferred_mode += "z"
2557
2558 return inferred_mode
2559
2560 @classmethod
2561 def from_string(Writer cls, fname, header_string, mode="w"):
2562 cdef Writer self = Writer.__new__(Writer)
2563 cdef char *hmode = "w"
2564 self._open_htsfile(fname, mode)
2565 self.hdr = bcf_hdr_init(hmode)
2566 self.ohdr = bcf_hdr_dup(self.hdr)
2567 if bcf_hdr_parse(self.hdr, to_bytes(header_string)) != 0:
2568 raise Exception("error parsing header:" + header_string)
2569 if bcf_hdr_sync(self.hdr) != 0:
2570 raise Exception("error syncing header:" + header_string)
2571 self.header_written = False
2572 self.n_samples = bcf_hdr_nsamples(self.hdr)
2573 return self
2574
2575 def variant_from_string(self, variant_string):
2576 cdef bcf1_t *b = bcf_init()
2577 cdef kstring_t s
2578
2579 # vcf_parse may realloc s.s, so the memory must be created by malloc
2580 s.s = pystring_to_cstring(variant_string)
2581 if s.s == NULL:
2582 bcf_destroy(b)
2583 raise MemoryError("Failed to allocate memory")
2584
2585 # plus 1 for '\0' of cstring
2586 s.l = len(variant_string) + 1
2587 s.m = len(variant_string) + 1
2588
2589 ret = vcf_parse(&s, self.hdr, b)
2590 if ret > 0:
2591 bcf_destroy(b)
2592 ks_free(&s)
2593 raise Exception("error parsing:" + variant_string + " return value:" + ret)
2594
2595 var = newVariant(b, self)
2596 if var.b.errcode == BCF_ERR_CTG_UNDEF:
2597 self.add_to_header("##contig=<ID=%s>" % var.CHROM)
2598 var.b.errcode = 0
2599
2600 ks_free(&s)
2601 return var
2602
2603 def write_header(Writer self):
2604 bcf_hdr_write(self.hts, self.hdr)
2605 self.header_written = True
2606
2607 def write_record(Writer self, Variant var):
2608 "Write the variant to the writer."
2609 cdef bcf_hrec_t *h
2610 if not self.header_written:
2611 self.write_header()
2612 if var.b.errcode == BCF_ERR_CTG_UNDEF:
2613 h = bcf_hdr_id2hrec(bcf_hdr_dup(self.ohdr), BCF_DT_CTG, 0, var.b.rid)
2614 if h == NULL:
2615 raise Exception("contig %d unknown and not found in header" % var.b.rid)
2616 if bcf_hdr_add_hrec(self.hdr, h) < 0:
2617 raise Exception("error adding contig %d to header" % var.b.rid)
2618 bcf_hdr_sync(self.hdr)
2619 elif var.b.errcode != 0:
2620 raise Exception("variant to be written has errorcode: %d" % var.b.errcode)
2621 return bcf_write(self.hts, self.hdr, var.b)
2622
2623 def close(Writer self):
2624 if not self.header_written:
2625 self.write_header()
2626 super().close()