Debian Codegraph @

doc/usage.rst

raw
1 .. _Usage:
2
3 =========================================
4 Working with BAM/CRAM/SAM-formatted files
5 =========================================
6
7 Opening a file
8 ==============
9
10 To begin with, import the pysam module and open a
11 :class:`pysam.AlignmentFile`::
12
13 import pysam
14 samfile = pysam.AlignmentFile("ex1.bam", "rb")
15
16 The above command opens the file :file:`ex1.bam` for reading.
17 The ``b`` qualifier indicates that this is a :term:`BAM` file.
18 To open a :term:`SAM` file, type::
19
20 import pysam
21 samfile = pysam.AlignmentFile("ex1.sam", "r")
22
23 :term:`CRAM` files are identified by a ``c`` qualifier::
24
25 import pysam
26 samfile = pysam.AlignmentFile("ex1.cram", "rc")
27
28 Fetching reads mapped to a :term:`region`
29 =========================================
30
31 Reads are obtained through a call to the
32 :meth:`pysam.AlignmentFile.fetch` method which returns an iterator.
33 Each call to the iterator will returns a :class:`pysam.AlignedSegment`
34 object::
35
36 iter = samfile.fetch("seq1", 10, 20)
37 for x in iter:
38 print(str(x))
39
40 :meth:`pysam.AlignmentFile.fetch` returns all reads overlapping a
41 region sorted by the first aligned base in the :term:`reference`
42 sequence. Note that it will also return reads that are only partially
43 overlapping with the :term:`region`. Thus the reads returned might
44 span a region that is larger than the one queried.
45
46 Using the pileup-engine
47 =======================
48
49 In contrast to :term:`fetching`, the :term:`pileup` engine returns for
50 each base in the :term:`reference` sequence the reads that map to that
51 particular position. In the typical view of reads stacking vertically
52 on top of the reference sequence similar to a multiple alignment,
53 :term:`fetching` iterates over the rows of this implied multiple
54 alignment while a :term:`pileup` iterates over the :term:`columns<column>`.
55
56 Calling :meth:`~pysam.AlignmentFile.pileup` will return an iterator
57 over each :term:`column` (reference base) of a specified
58 :term:`region`. Each call to the iterator returns an object of the
59 type :class:`pysam.PileupColumn` that provides access to all the
60 reads aligned to that particular reference position as well as
61 some additional information::
62
63 iter = samfile.pileup('seq1', 10, 20)
64 for x in iter:
65 print(str(x))
66
67
68 Creating BAM/CRAM/SAM files from scratch
69 ========================================
70
71 The following example shows how a new :term:`BAM` file is constructed
72 from scratch. The important part here is that the
73 :class:`pysam.AlignmentFile` class needs to receive the sequence
74 identifiers. These can be given either as a dictionary in a header
75 structure, as lists of names and sizes, or from a template file.
76 Here, we use a header dictionary::
77
78 header = { 'HD': {'VN': '1.0'},
79 'SQ': [{'LN': 1575, 'SN': 'chr1'},
80 {'LN': 1584, 'SN': 'chr2'}] }
81
82 with pysam.AlignmentFile(tmpfilename, "wb", header=header) as outf:
83 a = pysam.AlignedSegment()
84 a.query_name = "read_28833_29006_6945"
85 a.query_sequence="AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG"
86 a.flag = 99
87 a.reference_id = 0
88 a.reference_start = 32
89 a.mapping_quality = 20
90 a.cigar = ((0,10), (2,1), (0,25))
91 a.next_reference_id = 0
92 a.next_reference_start=199
93 a.template_length=167
94 a.query_qualities = pysam.qualitystring_to_array("<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<")
95 a.tags = (("NM", 1),
96 ("RG", "L1"))
97 outf.write(a)
98
99 Using streams
100 =============
101
102 Pysam does not support reading and writing from true python file
103 objects, but it does support reading and writing from stdin and
104 stdout. The following example reads from stdin and writes to stdout::
105
106 infile = pysam.AlignmentFile("-", "r")
107 outfile = pysam.AlignmentFile("-", "w", template=infile)
108 for s in infile:
109 outfile.write(s)
110
111 It will also work with :term:`BAM` files. The following script
112 converts a :term:`BAM` formatted file on stdin to a :term:`SAM`
113 formatted file on stdout::
114
115 infile = pysam.AlignmentFile("-", "rb")
116 outfile = pysam.AlignmentFile("-", "w", template=infile)
117 for s in infile:
118 outfile.write(s)
119
120 Note that the file open mode needs to changed from ``r`` to ``rb``.
121
122 ==================================================
123 Using samtools and bcftools commands within Python
124 ==================================================
125
126 Commands available in `samtools`_ and `bcftools`_ are available as simple
127 function calls, with command line options provided as arguments. For
128 example::
129
130 import pysam.samtools
131 pysam.samtools.sort("-o", "output.bam", "ex1.bam", catch_stdout=False)
132
133 import pysam.bcftools
134 pysam.bcftools.index("--csi", "ex2.vcf.gz")
135
136 corresponds to the command lines::
137
138 samtools sort -o output.bam ex1.bam
139 bcftools index --csi ex2.vcf.gz
140
141 Samtools commands are also imported into the main ``pysam`` namespace.
142 For example::
143
144 pysam.sort("-m", "1000000", "-o", "output.bam", "ex1.bam", catch_stdout=False)
145
146 To make them valid Python identifiers, the functions :func:`!cram_size`
147 and :func:`!fqimport` are spelt thus, differently from their
148 corresponding commands.
149
150 In order to get usage information, try::
151
152 print(pysam.sort.usage())
153
154 Argument errors raise a :class:`pysam.SamtoolsError`::
155
156 pysam.sort()
157
158 Traceback (most recent call last):
159 File "x.py", line 12, in <module>
160 pysam.sort()
161 File "/build/lib.linux-x86_64-2.6/pysam/__init__.py", line 37, in __call__
162 if retval: raise SamtoolsError( "\n".join( stderr ) )
163 pysam.SamtoolsError: 'Usage: samtools sort [-n] [-m <maxMem>] <in.bam> <out.prefix>\n'
164
165 Messages from `samtools`_ on stderr are captured and are
166 available using the :meth:`~PysamDispatcher.get_messages` method::
167
168 pysam.sort.get_messages()
169
170 By default, pysam captures the samtools command's standard output and returns it
171 as the function's return value. To redirect stdout to a file instead, either use
172 the ``save_stdout`` keyword argument, or use ``"-o", "filename"`` in the arguments
173 and also use ``catch_stdout=False`` to prevent pysam's capturing from overriding
174 your redirection. Finally, ``catch_stdout=False`` by itself discards standard output,
175 which may help resolve problems in environments such as IPython notebooks::
176
177 # Return value
178 pileup_text = pysam.samtools.mpileup("in.bam")
179
180 # Save to file
181 pysam.samtools.mpileup("in.bam", save_stdout=pileup_filename)
182 pysam.samtools.mpileup("-o", pileup_filename, "in.bam", catch_stdout=False)
183
184 # Discard standard output
185 pysam.samtools.mpileup("in.bam", catch_stdout=False) # Returns None
186
187 For each :obj:`!command` available as a `samtools`_ subcommand,
188 the following functions are provided:
189
190 .. py:function:: pysam.samtools.command(args, *, catch_stdout=True, save_stdout=None, split_lines=False)
191
192 :param args: Arguments to be passed to the samtools subcommand.
193 :param bool catch_stdout: Whether to return stdout as the function's value.
194 :param str save_stdout: Filename to which stdout should be written.
195 :param bool split_lines: Whether to split the return value into a list of lines.
196 :returns: Standard output if it was caught, otherwise None.
197
198 If `save_stdout` is not None, the command's standard ouput is written to the
199 file specified and the function returns None.
200
201 Otherwise, if `catch_stdout` is true, the command's standard output is captured
202 and used as the function's return value --- either as a single :obj:`str` or as
203 :obj:`list[str] <list>` according to `split_lines`. If `catch_stdout` is false,
204 the command's standard output is discarded and the function returns None.
205
206 The command's standard error is always captured and made available via
207 :func:`~pysam.samtools.command.get_messages`.
208
209 .. py:function:: pysam.samtools.command.get_messages()
210
211 Returns the standard error from the most recent invocation of the particular
212 :obj:`!command`, either as a single :obj:`str` or as :obj:`list[str] <list>`
213 according to `split_lines` as specified in that invocation.
214
215 .. py:function:: pysam.samtools.command.usage()
216
217 Returns the command's usage/help message, as a single :obj:`str`.
218
219 For each :obj:`!command` available as a `bcftools`_ subcommand, the
220 :func:`!pysam.bcftools.command`, :func:`!pysam.bcftools.command.get_messages`,
221 and :func:`!pysam.bcftools.command.usage` functions operate similarly.
222
223
224 ================================
225 Working with tabix-indexed files
226 ================================
227
228 To open a tabular file that has been indexed with tabix_, use
229 :class:`~pysam.TabixFile`::
230
231 import pysam
232 tbx = pysam.TabixFile("example.bed.gz")
233
234 Similar to :class:`~pysam.AlignmentFile.fetch`, intervals within a
235 region can be retrieved by calling :meth:`~pysam.TabixFile.fetch()`::
236
237 for row in tbx.fetch("chr1", 1000, 2000):
238 print(str(row))
239
240 This will return a tuple-like data structure in which columns can
241 be retrieved by numeric index::
242
243 for row in tbx.fetch("chr1", 1000, 2000):
244 print("chromosome is", row[0])
245
246 By providing a parser to :class:`~pysam.AlignmentFile.fetch`
247 or :class:`~pysam.TabixFile`, the data will we presented in parsed
248 form::
249
250 for row in tbx.fetch("chr1", 1000, 2000, parser=pysam.asTuple()):
251 print("chromosome is", row.contig)
252 print("first field (chrom)=", row[0])
253
254 Pre-built parsers are available for :term:`bed`
255 (:class:`~pysam.asBed`) formatted files and :term:`gtf`
256 (:class:`~pysam.asGTF`) formatted files. Thus, additional fields
257 become available through named access, for example::
258
259 for row in tbx.fetch("chr1", 1000, 2000, parser=pysam.asBed()):
260 print("name is", row.name)
261
262
263 .. Currently inactivated as pileup deprecated
264 .. Using the samtools SNP caller
265 .. -----------------------------
266
267 .. There are two ways to access the samtools SNP caller. The :class:`pysam.IteratorSNPCalls`
268 .. is appropriate when calling many consecutive SNPs, while :class:`pysam.SNPCaller` is
269 .. best when calling SNPs at non-consecutive genomic positions. Each snp caller returns objects of
270 .. type :class:`pysam.SNPCall`.
271
272 .. To use :class:`pysam.IteratorSNPCalls`, associate it with a :class:`pysam.IteratorColumn`::
273
274 .. samfile = pysam.AlignmentFile( "ex1.bam", "rb")
275 .. fastafile = pysam.Fastafile( "ex1.fa" )
276 .. pileup_iter = samfile.pileup( stepper = "samtools", fastafile = fastafile )
277 .. sncpall_iter = pysam.IteratorSNPCalls(pileup_iter)
278 .. for call in snpcall_iter:
279 .. print(str(call))
280
281 .. Usage of :class:`pysam.SNPCaller` is similar::
282
283 .. samfile = pysam.AlignmentFile( "ex1.bam", "rb")
284 .. fastafile = pysam.Fastafile( "ex1.fa" )
285 .. pileup_iter = samfile.pileup( stepper = "samtools", fastafile = fastafile )
286 .. snpcaller = pysam.SNPCaller.call(pileup_iter)
287 .. print(snpcaller( "chr1", 100 ))
288
289 .. Note the use of the option *stepper* to control which reads are included in the
290 .. in the :term:`pileup`. The ``samtools`` stepper implements the same read selection
291 .. and processing as in the samtools pileup command.
292
293 .. Calling indels works along the same lines, using the :class:`pysam.IteratorIndelCalls`
294 .. and :class:`pysam.IteratorIndelCaller`.
295
296
297 ====================================
298 Working with VCF/BCF formatted files
299 ====================================
300
301 To iterate through a VCF/BCF formatted file use
302 :class:`~pysam.VariantFile`::
303
304 from pysam import VariantFile
305
306 bcf_in = VariantFile("test.bcf") # auto-detect input format
307 bcf_out = VariantFile('-', 'w', header=bcf_in.header)
308
309 for rec in bcf_in.fetch('chr1', 100000, 200000):
310 bcf_out.write(rec)
311
312 :meth:`_pysam.VariantFile.fetch()` iterates over
313 :class:`~pysam.VariantRecord` objects which provides access to
314 simple variant attributes such as :class:`~pysam.VariantRecord.contig`,
315 :class:`~pysam.VariantRecord.pos`, :class:`~pysam.VariantRecord.ref`::
316
317 for rec in bcf_in.fetch():
318 print(rec.pos)
319
320 but also to complex attributes such as the contents to the
321 :class:`~pysam.VariantRecord.info`, :class:`~pysam.VariantRecord.format`
322 and :term:`genotype` columns. These
323 complex attributes are views on the underlying htslib data structures
324 and provide dictionary-like access to the data::
325
326 for rec in bcf_in.fetch():
327 print(rec.info)
328 print(rec.info.keys())
329 print(rec.info["DP"])
330
331 The :py:attr:`~pysam.VariantFile.header` attribute
332 (:class:`~pysam.VariantHeader`) provides access information
333 stored in the :term:`vcf` header. The complete header can be printed::
334
335 >>> print(bcf_in.header)
336 ##fileformat=VCFv4.2
337 ##FILTER=<ID=PASS,Description="All filters passed">
338 ##fileDate=20090805
339 ##source=myImputationProgramV3.1
340 ##reference=1000GenomesPilot-NCBI36
341 ##phasing=partial
342 ##INFO=<ID=NS,Number=1,Type=Integer,Description="Number of Samples
343 With Data">
344 ##INFO=<ID=DP,Number=1,Type=Integer,Description="Total Depth">
345 ##INFO=<ID=AF,Number=.,Type=Float,Description="Allele Frequency">
346 ##INFO=<ID=AA,Number=1,Type=String,Description="Ancestral Allele">
347 ##INFO=<ID=DB,Number=0,Type=Flag,Description="dbSNP membership, build
348 129">
349 ##INFO=<ID=H2,Number=0,Type=Flag,Description="HapMap2 membership">
350 ##FILTER=<ID=q10,Description="Quality below 10">
351 ##FILTER=<ID=s50,Description="Less than 50% of samples have data">
352 ##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
353 ##FORMAT=<ID=GQ,Number=1,Type=Integer,Description="Genotype Quality">
354 ##FORMAT=<ID=DP,Number=1,Type=Integer,Description="Read Depth">
355 ##FORMAT=<ID=HQ,Number=2,Type=Integer,Description="Haplotype Quality">
356 ##contig=<ID=M>
357 ##contig=<ID=17>
358 ##contig=<ID=20>
359 ##bcftools_viewVersion=1.3+htslib-1.3
360 ##bcftools_viewCommand=view -O b -o example_vcf42.bcf
361 example_vcf42.vcf.gz
362 #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NA00001 NA00002 NA0000
363
364 Individual contents such as contigs, info fields, samples, formats can
365 be retrieved as attributes from :py:attr:`~pysam.VariantFile.header`::
366
367 >>> print(bcf_in.header.contigs)
368 <pysam.cbcf.VariantHeaderContigs object at 0xf250f8>
369
370 To convert these views to native python types, iterate through the views::
371
372 >>> print(list((bcf_in.header.contigs)))
373 ['M', '17', '20']
374 >>> print(list((bcf_in.header.filters)))
375 ['PASS', 'q10', 's50']
376 >>> print(list((bcf_in.header.info)))
377 ['NS', 'DP', 'AF', 'AA', 'DB', 'H2']
378 >>> print(list((bcf_in.header.samples)))
379 ['NA00001', 'NA00002', 'NA00003']
380
381 Alternatively, it is possible to iterate through all records in the
382 header returning objects of type :py:class:`~pysam.VariantHeaderRecord`:: ::
383
384 >>> for x in bcf_in.header.records:
385 >>> print(x)
386 >>> print(x.type, x.key)
387 GENERIC fileformat
388 FILTER FILTER
389 GENERIC fileDate
390 GENERIC source
391 GENERIC reference
392 GENERIC phasing
393 INFO INFO
394 INFO INFO
395 INFO INFO
396 INFO INFO
397 INFO INFO
398 INFO INFO
399 FILTER FILTER
400 FILTER FILTER
401 FORMAT FORMAT
402 FORMAT FORMAT
403 FORMAT FORMAT
404 FORMAT FORMAT
405 CONTIG contig
406 CONTIG contig
407 CONTIG contig
408 GENERIC bcftools_viewVersion
409 GENERIC bcftools_viewCommand
410
411 ===============
412 Extending pysam
413 ===============
414
415 Using pyximport_, it is (relatively) straight-forward to access pysam
416 internals and the underlying `samtools`_ library. An example is provided
417 in the :file:`tests` directory. The example emulates the samtools
418 flagstat command and consists of three files:
419
420 1. The main script :file:`pysam_flagstat.py`. The important lines in
421 this script are::
422
423 import pyximport
424 pyximport.install()
425 import _pysam_flagstat
426
427 ...
428
429 flag_counts = _pysam_flagstat.count(pysam_in)
430
431 The first part imports, sets up pyximport_ and imports the cython
432 module :file:`_pysam_flagstat`. The second part calls the
433 ``count`` method in :file:`_pysam_flagstat`.
434
435 2. The cython implementation :file:`_pysam_flagstat.pyx`. This script
436 imports the pysam API via::
437
438 from pysam.libcalignmentfile cimport AlignmentFile, AlignedSegment
439
440 This statement imports, amongst others, :class:`AlignedSegment`
441 into the namespace. Speed can be gained from declaring
442 variables. For example, to efficiently iterate over a file, an
443 :class:`AlignedSegment` object is declared::
444
445 # loop over samfile
446 cdef AlignedSegment read
447 for read in samfile:
448 ...
449
450 3. A :file:`pyxbld` providing pyximport_ with build information.
451 Required are the locations of the samtools and pysam header
452 libraries of a source installation of pysam plus the
453 :file:`csamtools.so` shared library. For example::
454
455 def make_ext(modname, pyxfilename):
456 from distutils.extension import Extension
457 import pysam
458 return Extension(name=modname,
459 sources=[pyxfilename],
460 extra_link_args=pysam.get_libraries(),
461 include_dirs=pysam.get_include(),
462 define_macros=pysam.get_defines())
463
464 If the script :file:`pysam_flagstat.py` is called the first time,
465 pyximport_ will compile the cython_ extension
466 :file:`_pysam_flagstat.pyx` and make it available to the
467 script. Compilation requires a working compiler and cython_
468 installation. Each time :file:`_pysam_flagstat.pyx` is modified, a
469 new compilation will take place.
470
471 pyximport_ comes with cython_.
472