-
Notifications
You must be signed in to change notification settings - Fork 271
/
calignmentfile.pyx
2438 lines (1949 loc) · 79.8 KB
/
calignmentfile.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# cython: embedsignature=True
# cython: profile=True
########################################################
########################################################
# Cython wrapper for SAM/BAM/CRAM files based on htslib
########################################################
# The principal classes defined in this module are:
#
# class AlignmentFile read/write access to SAM/BAM/CRAM formatted files
#
# class IndexedReads index a SAM/BAM/CRAM file by query name while keeping
# the original sort order intact
#
# Additionally this module defines numerous additional classes that are part
# of the internal API. These are:
#
# Various iterator classes to iterate over alignments in sequential (IteratorRow)
# or in a stacked fashion (IteratorColumn):
#
# class IteratorRow
# class IteratorRowRegion
# class IteratorRowHead
# class IteratorRowAll
# class IteratorRowAllRefs
# class IteratorRowSelection
# class IteratorColumn
# class IteratorColumnRegion
# class IteratorColumnAllRefs
#
########################################################
#
# The MIT License
#
# Copyright (c) 2015 Andreas Heger
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
########################################################
import os
import collections
import re
import warnings
import array
from cpython cimport array as c_array
from cpython.version cimport PY_MAJOR_VERSION
from cutils cimport force_bytes, force_str, charptr_to_str
from cutils cimport encode_filename, from_string_and_size
from calignedsegment cimport makeAlignedSegment, makePileupColumn
cimport cython
########################################################
## Constants and global variables
# defines imported from samtools
DEF SEEK_SET = 0
DEF SEEK_CUR = 1
DEF SEEK_END = 2
# maximum genomic coordinace
cdef int MAX_POS = 2 << 29
# valid types for SAM headers
VALID_HEADER_TYPES = {"HD" : dict,
"SQ" : list,
"RG" : list,
"PG" : list,
"CO" : list}
# order of records within SAM headers
VALID_HEADERS = ("HD", "SQ", "RG", "PG", "CO")
# default type conversions within SAM header records
VALID_HEADER_FIELDS = {"HD" : {"VN" : str, "SO" : str, "GO" : str},
"SQ" : {"SN" : str, "LN" : int, "AS" : str,
"M5" : str, "SP" : str, "UR" : str,},
"RG" : {"ID" : str, "CN" : str, "DS" : str,
"DT" : str, "FO" : str, "KS" : str,
"LB" : str, "PG" : str, "PI" : str,
"PL" : str, "PU" : str, "SM" : str,},
"PG" : {"ID" : str, "PN" : str, "CL" : str,
"PP" : str, "DS" : str, "VN" : str,},}
# output order of fields within records
VALID_HEADER_ORDER = {"HD" : ("VN", "SO", "GO"),
"SQ" : ("SN", "LN", "AS", "M5",
"UR", "SP"),
"RG" : ("ID", "SM", "LB", "DS",
"PU", "PI", "CN", "DT",
"PL", "FO", "KS", "PG"),
"PG" : ("PN", "ID", "VN", "CL",
"PP"),}
def build_header_line(fields, record):
'''build a header line from `fields` dictionary for `record`'''
# TODO: add checking for field and sort order
line = ["@%s" % record]
# comment
if record == "CO":
line.append(fields)
# user tags
elif record.islower():
for key in sorted(fields):
line.append("%s:%s" % (key, str(fields[key])))
# defined tags
else:
# write fields of the specification
for key in VALID_HEADER_ORDER[record]:
if key in fields:
line.append("%s:%s" % (key, str(fields[key])))
# write user fields
for key in fields:
if not key.isupper():
line.append("%s:%s" % (key, str(fields[key])))
return "\t".join(line)
cdef bam_hdr_t * build_header(new_header):
'''return a new header built from a dictionary in `new_header`.
This method inserts the text field, target_name and target_len.
'''
lines = []
# check if hash exists
# create new header and copy old data
cdef bam_hdr_t * dest
dest = bam_hdr_init()
# first: defined tags
for record in VALID_HEADERS:
if record in new_header:
ttype = VALID_HEADER_TYPES[record]
data = new_header[record]
if type(data) != type(ttype()):
raise ValueError(
"invalid type for record %s: %s, expected %s" %
(record, type(data), type(ttype())))
if type(data) is dict:
lines.append(build_header_line(data, record))
else:
for fields in new_header[record]:
lines.append(build_header_line(fields, record))
# then: user tags (lower case), sorted alphabetically
for record, data in sorted(new_header.items()):
if record in VALID_HEADERS: continue
if type(data) is dict:
lines.append(build_header_line(data, record))
else:
for fields in new_header[record]:
lines.append(build_header_line(fields, record))
text = "\n".join(lines) + "\n"
if dest.text != NULL: free( dest.text )
dest.text = <char*>calloc(len(text), sizeof(char))
dest.l_text = len(text)
cdef bytes btext = text.encode('ascii')
strncpy(dest.text, btext, dest.l_text)
cdef bytes bseqname
# collect targets
if "SQ" in new_header:
seqs = []
for fields in new_header["SQ"]:
try:
seqs.append( (fields["SN"], fields["LN"] ) )
except KeyError:
raise KeyError( "incomplete sequence information in '%s'" % str(fields))
dest.n_targets = len(seqs)
dest.target_name = <char**>calloc(dest.n_targets, sizeof(char*))
dest.target_len = <uint32_t*>calloc(dest.n_targets, sizeof(uint32_t))
for x from 0 <= x < dest.n_targets:
seqname, seqlen = seqs[x]
dest.target_name[x] = <char*>calloc(
len(seqname) + 1, sizeof(char))
bseqname = seqname.encode('ascii')
strncpy(dest.target_name[x], bseqname,
len(seqname) + 1)
dest.target_len[x] = seqlen
return dest
cdef class AlignmentFile:
"""
AlignmentFile(filepath_or_object, mode=None, template=None,
reference_names=None, reference_lengths=None, text=NULL,
header=None, add_sq_text=False, check_header=True, check_sq=True)
A :term:`SAM`/:term:`BAM` formatted file.
If `filepath_or_object` is a string, the file is automatically
opened. If `filepath_or_object` is a python File object, the
already opened file will be used.
If the file is opened for reading an index for a BAM file exists
(.bai), it will be opened automatically. Without an index random
access via :meth:`~pysam.AlignmentFile.fetch` and
:meth:`~pysam.AlignmentFile.pileup` is disabled.
For writing, the header of a :term:`SAM` file/:term:`BAM` file can
be constituted from several sources (see also the samtools format
specification):
1. If `template` is given, the header is copied from a another
`AlignmentFile` (`template` must be a
:class:`~pysam.AlignmentFile`).
2. If `header` is given, the header is built from a
multi-level dictionary.
3. If `text` is given, new header text is copied from raw
text.
4. The names (`reference_names`) and lengths
(`reference_lengths`) are supplied directly as lists.
For writing a CRAM file, the filename of the reference can be
added through a fasta formatted file (`reference_filename`)
By default, if a file is opened in mode 'r', it is checked
for a valid header (`check_header` = True) and a definition of
chromosome names (`check_sq` = True).
Parameters
----------
mode : string
`mode` should be ``r`` for reading or ``w`` for writing. The
default is text mode (:term:`SAM`). For binary (:term:`BAM`) I/O
you should append ``b`` for compressed or ``u`` for uncompressed
:term:`BAM` output. Use ``h`` to output header information in
text (:term:`TAM`) mode.
If ``b`` is present, it must immediately follow ``r`` or ``w``.
Valid modes are ``r``, ``w``, ``wh``, ``rb``, ``wb``, ``wbu`` and
``wb0``. For instance, to open a :term:`BAM` formatted file for
reading, type::
f = pysam.AlignmentFile('ex1.bam','rb')
If mode is not specified, the method will try to auto-detect
in the order 'rb', 'r', thus both the following should work::
f1 = pysam.AlignmentFile('ex1.bam')
f2 = pysam.AlignmentFile('ex1.sam')
template : AlignmentFile
when writing, copy header frem `template`.
header : dict
when writing, build header from a multi-level dictionary. The
first level are the four types ('HD', 'SQ', ...). The
second level are a list of lines, with each line being a
list of tag-value pairs. The header is constructed first
from all the defined fields, followed by user tags in
alphabetical order.
text : string
when writing, use the string provided as the header
reference_names : list
see referece_lengths
reference_lengths : list
when writing, build header from list of chromosome names and lengths.
By default, 'SQ' and 'LN' tags will be added to the header
text. This option can be changed by unsetting the flag
`add_sq_text`.
add_sq_text : bool
do not add 'SQ' and 'LN' tags to header. This option permits construction
:term:`SAM` formatted files without a header.
check_header : bool
when reading, check if header is present (default=True)
check_sq : bool
when reading, check if SQ entries are present in header (default=True)
"""
def __cinit__(self, *args, **kwargs):
self.htsfile = NULL
self._filename = None
self.is_bam = False
self.is_stream = False
self.is_cram = False
self.is_remote = False
self._open(*args, **kwargs)
# allocate memory for iterator
self.b = <bam1_t*>calloc(1, sizeof(bam1_t))
def is_open(self):
'''return true if htsfile has been opened.'''
return self.htsfile != NULL
def has_index(self):
"""return true if htsfile has an existing (and opened) index.
"""
return self.index != NULL
def check_index(self):
"""return True if index is present.
Raises
------
AttributeError
if htsfile is :term:`SAM` formatted and thus has no index.
ValueError
if htsfile is closed or index could not be opened.
"""
if not self.is_open():
raise ValueError("I/O operation on closed file")
if not self.is_bam and not self.is_cram:
raise AttributeError(
"AlignmentFile.mapped only available in bam files")
if self.index == NULL:
raise ValueError(
"mapping information not recorded in index "
"or index not available")
def _open(self,
filepath_or_object,
mode=None,
AlignmentFile template=None,
reference_names=None,
reference_lengths=None,
reference_filename=None,
text=None,
header=None,
port=None,
add_sq_text=True,
check_header=True,
check_sq=True,
referencenames=None,
referencelengths=None):
'''open a sam, bam or cram formatted file.
If _open is called on an existing file, the current file
will be closed and a new file will be opened.
'''
cdef char *cfilename
cdef char *cmode
# for backwards compatibility:
if referencenames is not None:
reference_names = referencenames
if referencelengths is not None:
reference_lengths = referencelengths
# read mode autodetection
if mode is None:
try:
self._open(filepath_or_object,
'rb',
template=template,
reference_names=reference_names,
reference_lengths=reference_lengths,
reference_filename=reference_filename,
text=text,
header=header,
port=port,
check_header=check_header,
check_sq=check_sq)
return
except ValueError, msg:
pass
self._open(filepath_or_object,
'r',
template=template,
reference_names=reference_names,
reference_lengths=reference_lengths,
reference_filename=reference_filename,
text=text,
header=header,
port=port,
check_header=check_header,
check_sq=check_sq)
return
assert mode in ("r", "w", "rb", "wb", "wh",
"wbu", "rU", "wb0",
"rc", "wc"), \
"invalid file opening mode `%s`" % mode
# close a previously opened file
if self.htsfile != NULL:
self.close()
# check if we are working with a File object
if hasattr(filepath_or_object, "fileno"):
filename = filepath_or_object.name
if filepath_or_object.closed:
raise ValueError('I/O operation on closed file')
else:
filename = filepath_or_object
# for htslib, wbu seems to not work
if mode == "wbu":
mode = "wb0"
cdef bytes bmode = mode.encode('ascii')
self._filename = filename = encode_filename(filename)
# FIXME: Use htsFormat when it is available
self.is_bam = len(mode) > 1 and mode[1] == 'b'
self.is_cram = len(mode) > 1 and mode[1] == 'c'
self.is_stream = filename == b"-"
self.is_remote = filename.startswith(b"http:") or \
filename.startswith(b"ftp:")
cdef char * ctext
cdef hFILE * fp
ctext = NULL
if mode[0] == 'w':
# open file for writing
# header structure (used for writing)
if template:
self.header = bam_hdr_dup(template.header)
elif header:
self.header = build_header(header)
else:
# build header from a target names and lengths
assert reference_names and reference_lengths, \
("either supply options `template`, `header` "
"or both `reference_names` and `reference_lengths` "
"for writing")
assert len(reference_names) == len(reference_lengths), \
"unequal names and lengths of reference sequences"
# allocate and fill header
reference_names = [force_bytes(ref) for ref in reference_names]
self.header = bam_hdr_init()
self.header.n_targets = len(reference_names)
n = 0
for x in reference_names:
n += len(x) + 1
self.header.target_name = <char**>calloc(
n, sizeof(char*))
self.header.target_len = <uint32_t*>calloc(
n, sizeof(uint32_t))
for x from 0 <= x < self.header.n_targets:
self.header.target_len[x] = reference_lengths[x]
name = reference_names[x]
self.header.target_name[x] = <char*>calloc(
len(name) + 1, sizeof(char))
strncpy(self.header.target_name[x], name, len(name))
# Optionally, if there is no text, add a SAM
# compatible header to output file.
if text is None and add_sq_text:
text = []
for x from 0 <= x < self.header.n_targets:
text.append("@SQ\tSN:%s\tLN:%s\n" % \
(force_str(reference_names[x]),
reference_lengths[x]))
text = ''.join(text)
if text is not None:
# copy without \0
text = force_bytes(text)
ctext = text
self.header.l_text = strlen(ctext)
self.header.text = <char*>calloc(
strlen(ctext), sizeof(char))
memcpy(self.header.text, ctext, strlen(ctext))
# open file (hts_open is synonym with sam_open)
cfilename, cmode = filename, bmode
if hasattr(filepath_or_object, "fileno"):
fp = hdopen(filepath_or_object.fileno(), cmode)
with nogil:
self.htsfile = hts_hopen(fp, cfilename, cmode)
else:
with nogil:
self.htsfile = hts_open(cfilename, cmode)
# set filename with reference sequences. If no filename
# is given, the CRAM reference arrays will be built from
# the @SQ header in the header
if self.is_cram and reference_filename:
# note that fn_aux takes ownership, so create
# a copy
fn = encode_filename(reference_filename)
self.htsfile.fn_aux = strdup(fn)
# write header to htsfile
if self.is_bam or self.is_cram or "h" in mode:
with nogil:
sam_hdr_write(self.htsfile, self.header)
elif mode[0] == "r":
# open file for reading
if (filename != b"-"
and not self.is_remote
and not os.path.exists(filename)):
raise IOError("file `%s` not found" % filename)
# open file (hts_open is synonym with sam_open)
cfilename, cmode = filename, bmode
if hasattr(filepath_or_object, "fileno"):
fp = hdopen(filepath_or_object.fileno(), cmode)
with nogil:
self.htsfile = hts_hopen(fp, cfilename, cmode)
else:
with nogil:
self.htsfile = hts_open(cfilename, cmode)
if self.htsfile == NULL:
raise ValueError(
"could not open file (mode='%s') - "
"is it SAM/BAM format?" % mode)
# bam files require a valid header
if self.is_bam or self.is_cram:
with nogil:
self.header = sam_hdr_read(self.htsfile)
if self.header == NULL:
raise ValueError(
"file does not have valid header (mode='%s') "
"- is it BAM format?" % mode )
else:
# in sam files it is optional (htsfile full of
# unmapped reads)
if check_header:
with nogil:
self.header = sam_hdr_read(self.htsfile)
if self.header == NULL:
raise ValueError(
"file does not have valid header (mode='%s') "
"- is it SAM format?" % mode )
# self.header.ignore_sam_err = True
# disabled for autodetection to work needs to be disabled
# so that reading from sam-files without headers works
if check_sq and self.header.n_targets == 0:
raise ValueError(
("file header is empty (mode='%s') - "
"is it SAM/BAM format?") % mode)
if self.htsfile == NULL:
raise IOError("could not open file `%s`" % filename )
# check for index and open if present
cdef int format_index = -1
if self.is_bam:
format_index = HTS_FMT_BAI
elif self.is_cram:
format_index = HTS_FMT_CRAI
if mode[0] == "r" and (self.is_bam or self.is_cram):
# open index for remote files
if self.is_remote:
cfilename = filename
with nogil:
self.index = hts_idx_load(cfilename, format_index)
if self.index == NULL:
warnings.warn(
"unable to open remote index for '%s'" % filename)
else:
if self.is_bam \
and not os.path.exists(filename + b".bai") \
and not os.path.exists(filename[:-4] + b".bai"):
self.index = NULL
elif self.is_cram \
and not os.path.exists(filename + b".crai") \
and not os.path.exists(filename[:-4] + b".crai"):
self.index = NULL
else:
# returns NULL if there is no index or index could
# not be opened
cfilename = filename
with nogil:
self.index = sam_index_load(self.htsfile,
cfilename)
if self.index == NULL:
raise IOError(
"error while opening index for '%s'" %
filename)
# save start of data section
if not self.is_stream:
self.start_offset = self.tell()
def get_tid(self, reference):
"""
return the numerical :term:`tid` corresponding to
:term:`reference`
returns -1 if reference is not known.
"""
if not self.is_open():
raise ValueError("I/O operation on closed file")
reference = force_bytes(reference)
return bam_name2id(self.header, reference)
def get_reference_name(self, tid):
"""
return :term:`reference` name corresponding to numerical :term:`tid`
"""
if not self.is_open():
raise ValueError("I/O operation on closed file")
if not 0 <= tid < self.header.n_targets:
raise ValueError("reference_id %i out of range 0<=tid<%i" %
(tid, self.header.n_targets))
return charptr_to_str(self.header.target_name[tid])
def parse_region(self,
reference=None,
start=None,
end=None,
region=None,
tid=None):
"""parse alternative ways to specify a genomic region. A region can
either be specified by :term:`reference`, `start` and
`end`. `start` and `end` denote 0-based, half-open
intervals.
Alternatively, a samtools :term:`region` string can be
supplied.
If any of the coordinates are missing they will be replaced by the
minimum (`start`) or maximum (`end`) coordinate.
Note that region strings are 1-based, while `start` and `end` denote
an interval in python coordinates.
Returns
-------
tuple : a tuple of `flag`, :term:`tid`, `start` and `end`. The
flag indicates whether no coordinates were supplied and the
genomic region is the complete genomic space.
Raises
------
ValueError
for invalid or out of bounds regions.
"""
cdef int rtid
cdef long long rstart
cdef long long rend
rtid = -1
rstart = 0
rend = MAX_POS
if start != None:
try:
rstart = start
except OverflowError:
raise ValueError('start out of range (%i)' % start)
if end != None:
try:
rend = end
except OverflowError:
raise ValueError('end out of range (%i)' % end)
if region:
region = force_str(region)
parts = re.split("[:-]", region)
reference = parts[0]
if len(parts) >= 2:
rstart = int(parts[1]) - 1
if len(parts) >= 3:
rend = int(parts[2])
if not reference:
return 0, 0, 0, 0
if tid is not None:
rtid = tid
else:
rtid = self.gettid(reference)
if rtid < 0:
raise ValueError(
"invalid reference `%s`" % reference)
if rstart > rend:
raise ValueError(
'invalid coordinates: start (%i) > end (%i)' % (rstart, rend))
if not 0 <= rstart < MAX_POS:
raise ValueError('start out of range (%i)' % rstart)
if not 0 <= rend <= MAX_POS:
raise ValueError('end out of range (%i)' % rend)
return 1, rtid, rstart, rend
def reset(self):
"""reset file position to beginning of file just after
the header.
Returns
-------
The file position after moving the file pointer.
"""
return self.seek(self.start_offset, 0)
def seek(self, uint64_t offset, int where=0):
"""move file pointer to position `offset`, see
:meth:`pysam.AlignmentFile.tell`.
Parameters
----------
offset : int
position of the read/write pointer within the file.
where :
optional and defaults to 0 which means absolute file
positioning, other values are 1 which means seek relative to
the current position and 2 means seek relative to the file's
end.
Returns
-------
the file position after moving the file pointer
"""
if not self.is_open():
raise ValueError("I/O operation on closed file")
if not self.is_bam:
raise NotImplementedError(
"seek only available in bam files")
if self.is_stream:
raise OSError("seek no available in streams")
cdef uint64_t pos
with nogil:
pos = bgzf_seek(hts_get_bgzfp(self.htsfile), offset, where)
return pos
def tell(self):
"""
return current file position.
"""
if not self.is_open():
raise ValueError("I/O operation on closed file")
if not (self.is_bam or self.is_cram):
raise NotImplementedError(
"seek only available in bam files")
cdef uint64_t pos
with nogil:
pos = bgzf_tell(hts_get_bgzfp(self.htsfile))
return pos
def fetch(self,
reference=None,
start=None,
end=None,
region=None,
tid=None,
until_eof=False,
multiple_iterators=False):
"""fetch reads aligned in a :term:`region`.
See :meth:`AlignmentFile.parse_region` for more information
on genomic regions.
Without a `reference` or `region` all mapped reads in the file
will be fetched. The reads will be returned ordered by reference
sequence, which will not necessarily be the order within the
file.
If only `reference` is set, all reads aligned to `reference`
will be fetched.
Note that a :term:`SAM` file does not allow random access. If
`region` or `reference` are given, an exception is raised.
:class:`~pysam.FastaFile`
:class:`~pysam.IteratorRow`
:class:`~pysam.IteratorRow`
:class:`~IteratorRow`
:class:`IteratorRow`
Parameters
----------
until_eof : bool
If `until_eof` is True, all reads from the current file
position will be returned in order as they are within the
file. Using this option will also fetch unmapped reads.
multiple_iterators : bool
If `multiple_iterators` is True (default) multiple
iterators on the same file can be used at the same time. The
iterator returned will receive its own copy of a filehandle to
the file effectively re-opening the file. Re-opening a file
creates some overhead, so beware.
Returns
-------
An iterator over a collection of reads.
Raises
------
ValueError
if the genomic coordinates are out of range or invalid or the
file does not permit random access to genomic coordinates.
"""
cdef int rtid, rstart, rend, has_coord
if not self.is_open():
raise ValueError( "I/O operation on closed file" )
has_coord, rtid, rstart, rend = self.parse_region(
reference,
start,
end,
region,
tid)
# Turn of re-opening if htsfile is a stream
if self.is_stream:
multiple_iterators = False
if self.is_bam or self.is_cram:
if not until_eof and not self.is_remote:
if not self.has_index():
raise ValueError(
"fetch called on bamfile without index")
if has_coord:
return IteratorRowRegion(
self, rtid, rstart, rend,
multiple_iterators=multiple_iterators)
else:
if until_eof:
return IteratorRowAll(
self,
multiple_iterators=multiple_iterators)
else:
# AH: check - reason why no multiple_iterators for
# AllRefs?
return IteratorRowAllRefs(
self,
multiple_iterators=multiple_iterators)
else:
if has_coord:
raise ValueError(
"fetching by region is not available for sam files")
if self.header == NULL:
raise ValueError(
"fetch called for htsfile without header")
# check if targets are defined
# give warning, sam_read1 segfaults
if self.header.n_targets == 0:
warnings.warn("fetch called for htsfile without header")
return IteratorRowAll(self,
multiple_iterators=multiple_iterators)
def head(self, n, multiple_iterators=True):
'''return an iterator over the first n alignments.
This iterator is is useful for inspecting the bam-file.
Parameters
----------
multiple_iterators : bool
is set to True by default in order to
avoid changing the current file position.
Returns
-------
an iterator over a collection of reads
'''
return IteratorRowHead(self, n,
multiple_iterators=multiple_iterators)
def mate(self, AlignedSegment read):
'''return the mate of :class:`~pysam.AlignedSegment` `read`.
.. note::
Calling this method will change the file position.
This might interfere with any iterators that have
not re-opened the file.
.. note::
This method is too slow for high-throughput processing.
If a read needs to be processed with its mate, work
from a read name sorted file or, better, cache reads.
Returns
-------
:class:`~pysam.AlignedSegment` : the mate
Raises
------
ValueError
if the read is unpaired or the mate is unmapped
'''
cdef uint32_t flag = read._delegate.core.flag
if flag & BAM_FPAIRED == 0:
raise ValueError("read %s: is unpaired" %
(read.query_name))
if flag & BAM_FMUNMAP != 0:
raise ValueError("mate %s: is unmapped" %
(read.query_name))
# xor flags to get the other mate
cdef int x = BAM_FREAD1 + BAM_FREAD2
flag = (flag ^ x) & x
# Make sure to use a separate file to jump around
# to mate as otherwise the original file position
# will be lost
# The following code is not using the C API and
# could thus be made much quicker, for example
# by using tell and seek.
for mate in self.fetch(
read._delegate.core.mpos,
read._delegate.core.mpos + 1,
tid=read._delegate.core.mtid,
multiple_iterators=True):
if mate.flag & flag != 0 and \
mate.query_name == read.query_name:
break
else:
raise ValueError("mate not found")
return mate
def pileup(self,
reference=None,
start=None,
end=None,
region=None,
**kwargs):
"""perform a :term:`pileup` within a :term:`region`. The region is
specified by :term:`reference`, 'start' and 'end' (using
0-based indexing). Alternatively, a samtools 'region' string
can be supplied.
Without 'reference' or 'region' all reads will be used for the
pileup. The reads will be returned ordered by
:term:`reference` sequence, which will not necessarily be the