Debian Codegraph @

doc/faq.rst

raw
1 ===
2 FAQ
3 ===
4
5 How should I cite pysam
6 =======================
7
8 Pysam has not been published in print. When referring to pysam, please
9 use the github URL: https://github.com/pysam-developers/pysam.
10 As pysam is a wrapper around htslib and the samtools package, I
11 suggest citing [Li.2009]_, [Bonfield.2021]_, and/or [Danecek.2021]_,
12 as appropriate.
13
14 Is pysam thread-safe?
15 =====================
16
17 Pysam is a mix of python and C code. Instructions within python are
18 generally made thread-safe through python's `global interpreter lock`_
19 (:dfn:`GIL`). This ensures that python data structures will always be in a
20 consistent state.
21
22 If an external function outside python is called, the programmer has a
23 choice to keep the GIL in place or to release it. Keeping the GIL in
24 place will make sure that all python threads wait until the external
25 function has completed. This is a safe option and ensures
26 thread-safety.
27
28 Alternatively, the GIL can be released while the external function is
29 called. This will allow other threads to run concurrently. This can be
30 beneficial if the external function is expected to halt, for example
31 when waiting for data to read or write. However, to achieve
32 thread-safety, the external function needs to be implemented with
33 thread-safety in mind. This means that there can be no shared state
34 between threads, or if there is shared, it needs to be controlled to
35 prevent any access conflicts.
36
37 Pysam generally uses the latter option and aims to release the GIL for
38 I/O intensive tasks. This is generally fine, but thread-safety of all
39 parts have not been fully tested.
40
41 A related issue is when different threads read from the same file
42 object - or the same thread uses two iterators over a file. There is
43 only a single file-position for each opened file. To prevent this from
44 happening, use the option ``multiple_iterators=True`` when calling
45 a fetch() method. This will return an iterator on a newly opened
46 file.
47
48 pysam coordinates are wrong
49 ===========================
50
51 pysam uses 0-based coordinates and the half-open notation for ranges
52 as does python. Coordinates and intervals reported from pysam always
53 follow that convention.
54
55 Confusion might arise as different file formats might have different
56 conventions. For example, the SAM format is 1-based while the BAM
57 format is 0-based. It is important to remember that pysam will always
58 conform to the python convention and translate to/from the file format
59 automatically.
60
61 The only exception is the :term:`region` string in the
62 :meth:`~pysam.AlignmentFile.fetch` and
63 :meth:`~pysam.AlignmentFile.pileup` methods. This string follows the
64 convention of the samtools command line utilities. The same is true
65 for any coordinates passed to the samtools command utilities directly,
66 such as :meth:`pysam.mpileup`.
67
68 Calling pysam.fetch() confuses existing iterators
69 =================================================
70
71 The following code will cause unexpected behaviour::
72
73 samfile = pysam.AlignmentFile("pysam_ex1.bam", "rb")
74
75 iter1 = samfile.fetch("chr1")
76 print(next(iter1).reference_id)
77 iter2 = samfile.fetch("chr2")
78 print(next(iter2).reference_id)
79 print(next(iter1).reference_id)
80
81 This will give the following output::
82
83 0
84 1
85 Traceback (most recent call last):
86 File "xx.py", line 8, in <module>
87 print(next(iter1).reference_id)
88 File "libcalignmentfile.pyx", line 2103,
89 in pysam.libcalignmentfile.IteratorRowRegion.__next__
90 StopIteration
91
92 Note how the second iterator stops as the file pointer has moved to
93 chr2. The correct way to work with multiple iterators is::
94
95 samfile = pysam.AlignmentFile("pysam_ex1.bam", "rb")
96
97 iter1 = samfile.fetch("chr1", multiple_iterators=True)
98 print(next(iter1).reference_id)
99 iter2 = samfile.fetch("chr2")
100 print(next(iter2).reference_id)
101 print(next(iter1).reference_id)
102
103 Here, the output is::
104
105 0
106 1
107 0
108
109 The reason for this behaviour is that every iterator needs to keep
110 track of its current position in the file. Within pysam, each opened
111 file can only keep track of one file position and hence there can only
112 be one iterator per file. Using the option ``multiple_iterators=True``
113 will return an iterator within a newly opened file. This iterator will
114 not interfere with existing iterators as it has its own file handle
115 associated with it.
116
117 Note that re-opening files incurs a performance penalty which can
118 become severe when calling :meth:`~pysam.AlignmentFile.fetch` often.
119 Thus, ``multiple_iterators`` is set to ``False`` by default.
120
121 AlignmentFile.fetch does not show unmapped reads
122 ================================================
123
124 By default, :meth:`~pysam.AlignmentFile.fetch` will only iterate over
125 placed alignments in the SAM/BAM/CRAM file. Thus the following always
126 works::
127
128 f = pysam.AlignmentFile(fname, "r")
129 for r in f.fetch():
130 assert r.reference_name is not None
131
132 If the file contains unaligned reads, they can be included
133 in the iteration by adding the ``until_eof=True`` flag::
134
135 f = pysam.AlignmentFile(fname, "r")
136 for r in f.fetch(until_eof=True):
137 if r.is_unmapped:
138 print("read is unmapped")
139
140 See also :meth:`fetch("*") <pysam.AlignmentFile.fetch>` which iterates
141 only over the unplaced unmapped reads at the end of the file.
142
143 I can't call AlignmentFile.fetch on a file without an index
144 ===========================================================
145
146 :meth:`~pysam.AlignmentFile.fetch` requires an index when
147 iterating over a SAM/BAM file. To iterate over a file without an
148 index, use ``until_eof=True``::
149
150 bf = pysam.AlignmentFile(fname, "rb")
151 for r in bf.fetch(until_eof=True):
152 print(r)
153
154
155 BAM files with a large number of reference sequences are slow
156 =============================================================
157
158 If you have many reference sequences in a BAM file, the following
159 might be slow::
160
161 track = pysam.AlignmentFile(fname, "rb")
162 for aln in track.fetch():
163 pass
164
165 The reason is that track.fetch() will iterate through the BAM file
166 for each reference sequence in the order as it is defined in the
167 header. This might require a lot of jumping around in the file. To
168 avoid this, use::
169
170 track = pysam.AlignmentFile(fname, "rb")
171 for aln in track.fetch(until_eof=True):
172 pass
173
174 This will iterate through reads as they appear in the file.
175
176 Weirdness with spliced reads in samfile.pileup(chr,start,end) given spliced alignments from an RNA-seq bam file
177 ===============================================================================================================
178
179 Spliced reads are reported within samfile.pileup. To ignore these
180 in your analysis, test the flags ``is_del == True and indel == 0``
181 in the :class:`~.PileupRead` object.
182
183 I can't edit quality scores in place
184 ====================================
185
186 Editing reads in-place generally works, though there is one
187 quirk to be aware of. Assigning to AlignedSegment.query_sequence will invalidate
188 any quality scores in AlignedSegment.query_qualities. The reason is that samtools
189 manages the memory of the sequence and quality scores together
190 and thus requires them to always be of the same length or 0.
191
192 Thus, to in-place edit the sequence and quality scores, copies of
193 the quality scores need to be taken. Consider trimming for example::
194
195 quals = read.query_qualities
196 read.query_sequence = read.query_sequence[5:10]
197 read.query_qualities = quals[5:10]
198
199 Why is there no SNPCaller class anymore?
200 =========================================
201
202 SNP calling is highly complex and heavily parameterized. There was a
203 danger that the pysam implementations might show different behaviour from the
204 samtools implementation, which would have caused a lot of confusion.
205
206 The best way to use samtools SNP calling from python is to use the
207 :meth:`pysam.mpileup` command and parse the output directly.
208
209 I get an error 'PileupProxy accessed after iterator finished'
210 =============================================================
211
212 Pysam works by providing proxy objects to objects defined within
213 the C-samtools package. Thus, some attention must be paid to the
214 lifetime of objects. The following to code snippets will cause an
215 error::
216
217 s = AlignmentFile('ex1.bam')
218 for p in s.pileup('chr1', 1000,1010):
219 pass
220
221 for pp in p.pileups:
222 print(pp)
223
224 The iteration has finished, thus the contents of ``p`` are invalid. Another
225 variation of this::
226
227 p = next(AlignmentFile('ex1.bam').pileup('chr1', 1000, 1010))
228 for pp in p.pileups:
229 print(pp)
230
231 Again, the iteration finishes as the temporary iterator created
232 by pileup goes out of scope. The solution is to keep a handle
233 to the iterator that remains alive::
234
235 i = AlignmentFile('ex1.bam').pileup('chr1', 1000, 1010)
236 p = next(i)
237 for pp in p.pileups:
238 print(pp)
239
240 Pysam won't compile
241 ===================
242
243 Compiling pysam can be tricky as there are numerous variables that
244 differ between build environments such as OS, version, python version,
245 and compiler. It is difficult to build software that builds cleanly
246 on all systems and the process might fail. Please see the
247 `pysam user group
248 <https://groups.google.com/forum/#!forum/pysam-user-group>`_
249 for common issues.
250
251 If there is a build issue, read the generated output carefully -
252 generally the cause of the problem is among the first errors to be
253 reported. For example, you will need to have the development version
254 of python installed that includes the header files such as
255 :file:`Python.h`. If that file is missing, the compiler will report
256 this at the very top of its error messages but will follow it
257 with any unknown function or variable definition it encounters later
258 on.
259
260 General advice is to always use the latest version on python_ and
261 cython_ when building pysam. There are some known incompatibilities:
262
263 * Python 3.4 requires cython 0.20.2 or later (see `here
264 <https://github.com/pysam-developers/pysam/issues/37>`_)
265
266 .. _global interpreter lock: https://en.wikipedia.org/wiki/Global_interpreter_lock
267
268 ImportError: cannot import name csamtools
269 =========================================
270
271 In version 0.10.0 and onwards, all pysam extension modules contain a
272 ``lib``-prefix. This facilates linking against pysam extension modules
273 with compilers that require to start with ``lib``. As a consequence,
274 all code using pysam extension modules directly will need to be
275 adapted. For example,::
276
277 cimport pysam.csamtools
278
279 will become::
280
281 cimport pysam.libcsamtools
282