Debian Codegraph @

tests/AlignmentFile_test.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 '''unit testing code for pysam.
3
4 Execute in the :file:`tests` directory as it requires the Makefile
5 and data files located there.
6 '''
7
8 import unittest
9 import pytest
10 import os
11 import shutil
12 import collections
13 import subprocess
14 import logging
15 import array
16 from io import StringIO
17
18 from functools import partial
19
20 import pysam
21 import pysam.samtools
22 from TestUtils import checkBinaryEqual, checkGZBinaryEqual, check_url, \
23 check_samtools_view_equal, checkFieldEqual, force_str, \
24 get_temp_filename, make_data_files, BAM_DATADIR
25
26
27 def setUpModule():
28 make_data_files(BAM_DATADIR)
29
30
31 ##################################################
32 #
33 # Detailed test of file contents
34 #
35 # Data are read either through file based iterator
36 # access (BasicTestBAMFromFile) or by calling fetch
37 # without coordinates (BasicTestBAMFromFetch)
38 ##################################################
39 class BasicTestBAMFromFetch(unittest.TestCase):
40
41 '''basic first test - detailed testing
42 if information in file is consistent
43 with information in AlignedSegment object.'''
44
45 def setUp(self):
46 self.samfile = pysam.AlignmentFile(
47 os.path.join(BAM_DATADIR, "ex3.bam"),
48 "rb")
49 self.reads = list(self.samfile.fetch())
50
51 def tearDown(self):
52 self.samfile.close()
53
54 def testARqname(self):
55 self.assertEqual(self.reads[0].query_name,
56 "read_28833_29006_6945")
57 self.assertEqual(self.reads[1].query_name,
58 "read_28701_28881_323b")
59
60 def testARflag(self):
61 self.assertEqual(self.reads[0].flag, 99)
62 self.assertEqual(self.reads[1].flag, 147)
63
64 def testARrname(self):
65 self.assertEqual(self.reads[0].reference_id, 0)
66 self.assertEqual(self.reads[1].reference_id, 1)
67
68 def testARpos(self):
69 self.assertEqual(self.reads[0].reference_start, 33 - 1)
70 self.assertEqual(self.reads[1].reference_start, 88 - 1)
71
72 def testARmapq(self):
73 self.assertEqual(self.reads[0].mapping_quality, 20)
74 self.assertEqual(self.reads[1].mapping_quality, 30)
75
76 def testARcigar(self):
77 self.assertEqual(self.reads[0].cigartuples, [(0, 10), (2, 1), (0, 25)])
78 self.assertEqual(self.reads[1].cigartuples, [(0, 35)])
79
80 def testARcigarstring(self):
81 self.assertEqual(self.reads[0].cigarstring, '10M1D25M')
82 self.assertEqual(self.reads[1].cigarstring, '35M')
83
84 def testARmrnm(self):
85 self.assertEqual(self.reads[0].next_reference_id, 0)
86 self.assertEqual(self.reads[1].next_reference_id, 1)
87 self.assertEqual(self.reads[0].next_reference_id, 0)
88 self.assertEqual(self.reads[1].next_reference_id, 1)
89
90 def testARmpos(self):
91 self.assertEqual(self.reads[0].next_reference_start, 200 - 1)
92 self.assertEqual(self.reads[1].next_reference_start, 500 - 1)
93 self.assertEqual(self.reads[0].next_reference_start, 200 - 1)
94 self.assertEqual(self.reads[1].next_reference_start, 500 - 1)
95
96 def testARQueryLength(self):
97 self.assertEqual(
98 self.reads[0].query_length, 35,
99 "insert size mismatch in read 1: %s != %s" %
100 (self.reads[0].query_length, 35))
101 self.assertEqual(
102 self.reads[1].query_length, 35,
103 "insert size mismatch in read 2: %s != %s" %
104 (self.reads[1].query_length, 35))
105 self.assertEqual(
106 self.reads[0].query_length, 35,
107 "insert size mismatch in read 1: %s != %s" %
108 (self.reads[0].query_length, 35))
109 self.assertEqual(
110 self.reads[1].query_length, 35,
111 "insert size mismatch in read 2: %s != %s" %
112 (self.reads[1].query_length, 35))
113
114 def testARseq(self):
115 self.assertEqual(
116 self.reads[0].query_sequence,
117 "AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG")
118 self.assertEqual(
119 self.reads[1].query_sequence,
120 "ACCTATATCTTGGCCTTGGCCGATGCGGCCTTGCA")
121 self.assertEqual(
122 self.reads[3].query_sequence,
123 "AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG")
124
125 def testARqual(self):
126 self.assertEqual(
127 pysam.qualities_to_qualitystring(self.reads[0].query_qualities),
128 "<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<")
129 self.assertEqual(
130 pysam.qualities_to_qualitystring(self.reads[1].query_qualities),
131 "<<<<<;<<<<7;:<<<6;<<<<<<<<<<<<7<<<<")
132 self.assertEqual(
133 pysam.qualities_to_qualitystring(self.reads[3].query_qualities),
134 "<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<")
135
136 def testARquery(self):
137 self.assertEqual(
138 self.reads[0].query_alignment_sequence,
139 "AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG",
140 "query mismatch in read 1: %s != %s" %
141 (self.reads[0].query_alignment_sequence,
142 "AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG"))
143 self.assertEqual(
144 self.reads[1].query_alignment_sequence,
145 "ACCTATATCTTGGCCTTGGCCGATGCGGCCTTGCA",
146 "query size mismatch in read 2: %s != %s" %
147 (self.reads[1].query_alignment_sequence,
148 "ACCTATATCTTGGCCTTGGCCGATGCGGCCTTGCA"))
149 self.assertEqual(
150 self.reads[3].query_alignment_sequence,
151 "TAGCTAGCTACCTATATCTTGGTCTT",
152 "query mismatch in read 4: %s != %s" %
153 (self.reads[3].query_alignment_sequence,
154 "TAGCTAGCTACCTATATCTTGGTCTT"))
155
156 def testARqqual(self):
157 self.assertEqual(
158 pysam.qualities_to_qualitystring(
159 self.reads[0].query_alignment_qualities),
160 "<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<",
161 "qquality string mismatch in read 1: %s != %s" %
162 (pysam.qualities_to_qualitystring(self.reads[0].query_alignment_qualities),
163 "<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<"))
164 self.assertEqual(
165 pysam.qualities_to_qualitystring(
166 self.reads[1].query_alignment_qualities),
167 "<<<<<;<<<<7;:<<<6;<<<<<<<<<<<<7<<<<",
168 "qquality string mismatch in read 2: %s != %s" %
169 (pysam.qualities_to_qualitystring(self.reads[1].query_alignment_qualities),
170 "<<<<<;<<<<7;:<<<6;<<<<<<<<<<<<7<<<<"))
171 self.assertEqual(
172 pysam.qualities_to_qualitystring(
173 self.reads[3].query_alignment_qualities),
174 "<<<<<<<<<<<<<<<<<:<9/,&,22",
175 "qquality string mismatch in read 3: %s != %s" %
176 (pysam.qualities_to_qualitystring(self.reads[3].query_alignment_qualities),
177 "<<<<<<<<<<<<<<<<<:<9/,&,22"))
178
179 def testPresentOptionalFields(self):
180 self.assertEqual(
181 self.reads[0].opt('NM'), 22,
182 "optional field mismatch in read 1, NM: %s != %s" %
183 (self.reads[0].opt('NM'), 22))
184 self.assertEqual(
185 self.reads[0].opt('RG'), 'L1',
186 "optional field mismatch in read 1, RG: %s != %s" %
187 (self.reads[0].opt('RG'), 'L1'))
188 self.assertEqual(
189 self.reads[1].opt('RG'), 'L2',
190 "optional field mismatch in read 2, RG: %s != %s" %
191 (self.reads[1].opt('RG'), 'L2'))
192 self.assertEqual(
193 self.reads[1].opt('MF'), 18,
194 "optional field mismatch in read 2, MF: %s != %s" %
195 (self.reads[1].opt('MF'), 18))
196
197 def testPairedBools(self):
198 self.assertEqual(self.reads[0].is_paired, True, "is paired mismatch in read 1: %s != %s" % (
199 self.reads[0].is_paired, True))
200 self.assertEqual(self.reads[1].is_paired, True, "is paired mismatch in read 2: %s != %s" % (
201 self.reads[1].is_paired, True))
202 self.assertEqual(self.reads[0].is_proper_pair, True, "is proper pair mismatch in read 1: %s != %s" % (
203 self.reads[0].is_proper_pair, True))
204 self.assertEqual(self.reads[1].is_proper_pair, True, "is proper pair mismatch in read 2: %s != %s" % (
205 self.reads[1].is_proper_pair, True))
206
207 def testTags(self):
208 self.assertEqual(self.reads[0].tags,
209 [('NM', 22), ('RG', 'L1'),
210 ('PG', 'P1'), ('XT', 'U')])
211 self.assertEqual(self.reads[1].tags,
212 [('MF', 18), ('RG', 'L2'),
213 ('PG', 'P2'), ('XT', 'R')])
214
215 def testOpt(self):
216 self.assertEqual(self.reads[0].opt("XT"), "U")
217 self.assertEqual(self.reads[1].opt("XT"), "R")
218
219
220 class BasicTestSAMFromFetch(BasicTestBAMFromFetch):
221
222 def setUp(self):
223 self.samfile = pysam.AlignmentFile(
224 os.path.join(BAM_DATADIR, "ex3.sam"),
225 "r")
226 self.reads = list(self.samfile.fetch())
227
228
229 class BasicTestCRAMFromFetch(BasicTestBAMFromFetch):
230
231 def setUp(self):
232 self.samfile = pysam.AlignmentFile(
233 os.path.join(BAM_DATADIR, "ex3.cram"),
234 "rc")
235 self.reads = list(self.samfile.fetch())
236
237 def testTags(self):
238 self.assertEqual(
239 sorted(self.reads[0].tags),
240 sorted([('RG', 'L1'),
241 ('NM', 22),
242 ('MD', '0C0T1G1C0C0A1G0^G0C1C1G1A0T2G0G0G0A1C1G1G1A2C0'),
243 ('PG', 'P1'),
244 ('XT', 'U'),
245 ]))
246 self.assertEqual(
247 sorted(self.reads[1].tags),
248 sorted([('RG', 'L2'),
249 ('NM', 26),
250 ('MD',
251 '1G0A0A1G1G0G2C0A0G0A0A0C0T0T0G0A0A0G0A0C0A0A1T2C0T0T1'),
252 ('MF', 18),
253 ('PG', 'P2'),
254 ('XT', 'R')]))
255
256 def testPresentOptionalFields(self):
257 self.assertEqual(
258 self.reads[0].opt('NM'), 22,
259 "optional field mismatch in read 1, NM: %s != %s" %
260 (self.reads[0].opt('NM'), 22))
261 self.assertEqual(
262 self.reads[0].opt('RG'), 'L1',
263 "optional field mismatch in read 1, RG: %s != %s" %
264 (self.reads[0].opt('RG'), 'L1'))
265 self.assertEqual(
266 self.reads[1].opt('RG'), 'L2',
267 "optional field mismatch in read 2, RG: %s != %s" %
268 (self.reads[1].opt('RG'), 'L2'))
269 self.assertEqual(
270 self.reads[1].opt('MF'), 18,
271 "optional field mismatch in read 2, MF: %s != %s" %
272 (self.reads[1].opt('MF'), 18))
273
274
275 class BasicTestSAMFromFilename(BasicTestBAMFromFetch):
276
277 def setUp(self):
278 self.samfile = pysam.AlignmentFile(
279 os.path.join(BAM_DATADIR, "ex3.sam"),
280 "r")
281 self.reads = [r for r in self.samfile]
282
283
284 class BasicTestCRAMFromFilename(BasicTestCRAMFromFetch):
285
286 def setUp(self):
287 self.samfile = pysam.AlignmentFile(
288 os.path.join(BAM_DATADIR, "ex3.cram"),
289 "rc")
290 self.reads = [r for r in self.samfile]
291
292
293 class BasicTestBAMFromFilename(BasicTestBAMFromFetch):
294
295 def setUp(self):
296 self.samfile = pysam.AlignmentFile(
297 os.path.join(BAM_DATADIR, "ex3.bam"),
298 "rb")
299 self.reads = [r for r in self.samfile]
300
301
302 class BasicTestBAMFromFile(BasicTestBAMFromFetch):
303
304 def setUp(self):
305 with open(os.path.join(BAM_DATADIR, "ex3.bam")) as f:
306 self.samfile = pysam.AlignmentFile(
307 f, "rb")
308 self.reads = [r for r in self.samfile]
309
310
311 class BasicTestBAMFromFileNo(BasicTestBAMFromFetch):
312
313 def setUp(self):
314 with open(os.path.join(BAM_DATADIR, "ex3.bam")) as f:
315 self.samfile = pysam.AlignmentFile(
316 f.fileno(), "rb")
317 self.reads = [r for r in self.samfile]
318
319
320 class BasicTestSAMFromFile(BasicTestBAMFromFetch):
321
322 def setUp(self):
323 with open(os.path.join(BAM_DATADIR, "ex3.sam")) as f:
324 self.samfile = pysam.AlignmentFile(
325 f, "r")
326 self.reads = [r for r in self.samfile]
327
328
329 class BasicTestSAMFromFileNo(BasicTestBAMFromFetch):
330
331 def setUp(self):
332 with open(os.path.join(BAM_DATADIR, "ex3.sam")) as f:
333 self.samfile = pysam.AlignmentFile(
334 f.fileno(), "r")
335 self.reads = [r for r in self.samfile]
336
337
338 class BasicTestCRAMFromFile(BasicTestCRAMFromFetch):
339
340 def setUp(self):
341 with open(os.path.join(BAM_DATADIR, "ex3.cram")) as f:
342 self.samfile = pysam.AlignmentFile(f, "rc")
343 self.reads = [r for r in self.samfile]
344
345
346 class BasicTestCRAMFromFileNo(BasicTestCRAMFromFetch):
347
348 def setUp(self):
349 with open(os.path.join(BAM_DATADIR, "ex3.cram")) as f:
350 self.samfile = pysam.AlignmentFile(
351 f.fileno(), "rc")
352 self.reads = [r for r in self.samfile]
353
354
355 class BasicTestSAMFromStringIO(BasicTestBAMFromFetch):
356
357 def testRaises(self):
358 statement = "samtools view -h {}".format(
359 os.path.join(BAM_DATADIR, "ex3.bam"))
360 stdout = subprocess.check_output(statement.split(" "), encoding="ascii")
361 bam = StringIO()
362 bam.write(stdout)
363 bam.seek(0)
364 self.assertRaises(NotImplementedError,
365 pysam.AlignmentFile, bam)
366 # self.reads = [r for r in samfile]
367
368
369 ##################################################
370 #
371 # Test of basic File I/O
372 #
373 # * format conversions
374 # * reading with/without index
375 # * reading from closed files
376 #
377 ##################################################
378 class TestIO(unittest.TestCase):
379
380 '''check if reading samfile and writing a samfile
381 are consistent.'''
382
383 def checkEcho(self,
384 input_filename,
385 reference_filename,
386 output_filename,
387 input_mode,
388 output_mode,
389 sequence_filename=None,
390 use_template=True,
391 checkf=checkBinaryEqual,
392 **kwargs):
393 '''iterate through *input_filename* writing to
394 *output_filename* and comparing the output to
395 *reference_filename*.
396
397 The files are opened according to the *input_mode* and
398 *output_mode*.
399
400 If *use_template* is set, the header is copied from infile
401 using the template mechanism, otherwise target names and
402 lengths are passed explicitly.
403
404 The *checkf* is used to determine if the files are
405 equal.
406 '''
407
408 with pysam.AlignmentFile(
409 os.path.join(BAM_DATADIR, input_filename),
410 input_mode) as infile:
411
412 if "b" in input_mode:
413 self.assertTrue(infile.is_bam)
414 self.assertFalse(infile.is_cram)
415 elif "c" in input_mode:
416 self.assertFalse(infile.is_bam)
417 self.assertTrue(infile.is_cram)
418 else:
419 self.assertFalse(infile.is_cram)
420 self.assertFalse(infile.is_bam)
421
422 if use_template:
423 outfile = pysam.AlignmentFile(
424 output_filename,
425 output_mode,
426 reference_filename=sequence_filename,
427 template=infile, **kwargs)
428 else:
429 outfile = pysam.AlignmentFile(
430 output_filename,
431 output_mode,
432 reference_names=infile.references,
433 reference_lengths=infile.lengths,
434 reference_filename=sequence_filename,
435 add_sq_text=False,
436 **kwargs)
437
438 iter = infile.fetch()
439
440 for x in iter:
441 outfile.write(x)
442
443 outfile.close()
444
445 self.assertTrue(checkf(
446 os.path.join(BAM_DATADIR, reference_filename),
447 output_filename),
448 "files %s and %s are not the same" %
449 (reference_filename,
450 output_filename))
451
452 os.unlink(output_filename)
453
454 def testSAM2SAM(self):
455 self.checkEcho("ex2.sam",
456 "ex2.sam",
457 "tmp_ex2.sam",
458 "r", "wh")
459
460 def testSAM2SAMWithoutHeader(self):
461 self.checkEcho("ex2.sam",
462 "ex1.sam",
463 "tmp_ex2.sam",
464 "r", "w",
465 add_sam_header=False)
466
467 def testBAM2BAM(self):
468 self.checkEcho("ex2.bam",
469 "ex2.bam",
470 "tmp_ex2.bam",
471 "rb", "wb",
472 checkf=checkGZBinaryEqual)
473
474 def testCRAM2CRAM(self):
475 # in some systems different reference sequence paths might be
476 # embedded in the CRAM files which will result in different headers
477 # see #542
478 self.checkEcho("ex2.cram",
479 "ex2.cram",
480 "tmp_ex2.cram",
481 "rc", "wc",
482 sequence_filename=os.path.join(BAM_DATADIR, "ex1.fa"),
483 checkf=partial(
484 check_samtools_view_equal,
485 without_header=True))
486
487 def testSAM2BAM(self):
488 self.checkEcho("ex2.sam",
489 "ex2.bam",
490 "tmp_ex2.bam",
491 "r", "wb",
492 checkf=checkGZBinaryEqual)
493
494 def testBAM2SAM(self):
495 self.checkEcho("ex2.bam",
496 "ex2.sam",
497 "tmp_ex2.sam",
498 "rb", "wh")
499
500 def testBAM2CRAM(self):
501 # ignore header (md5 sum)
502 self.checkEcho("ex2.bam",
503 "ex2.cram",
504 "tmp_ex2.cram",
505 "rb", "wc",
506 sequence_filename=os.path.join(BAM_DATADIR, "ex1.fa"),
507 checkf=partial(
508 check_samtools_view_equal,
509 without_header=True))
510
511 def testCRAM2BAM(self):
512 # ignore header (md5 sum)
513 self.checkEcho("ex2.cram",
514 "ex2.bam",
515 "tmp_ex2.bam",
516 "rc", "wb",
517 sequence_filename=os.path.join(BAM_DATADIR, "ex1.fa"),
518 checkf=partial(
519 check_samtools_view_equal,
520 without_header=True))
521
522 def testSAM2CRAM(self):
523 self.checkEcho("ex2.sam",
524 "ex2.cram",
525 "tmp_ex2.cram",
526 "r", "wc",
527 sequence_filename=os.path.join(BAM_DATADIR, "ex1.fa"),
528 checkf=partial(
529 check_samtools_view_equal,
530 without_header=True))
531
532 def testCRAM2SAM(self):
533 self.checkEcho("ex2.cram",
534 "ex2.sam",
535 "tmp_ex2.sam",
536 "rc", "wh",
537 sequence_filename=os.path.join(BAM_DATADIR, "ex1.fa"),
538 checkf=partial(
539 check_samtools_view_equal,
540 without_header=True))
541
542 # Disabled - should work, files are not binary equal, but are
543 # non-binary equal:
544 # diff <(samtools view pysam_ex1.bam) <(samtools view pysam_data/ex1.bam)
545 # def testReadWriteBamWithTargetNames(self):
546 # input_filename = "ex1.bam"
547 # output_filename = "pysam_ex1.bam"
548 # reference_filename = "ex1.bam"
549
550 # self.checkEcho(input_filename, reference_filename, output_filename,
551 # "rb", "wb", use_template=False)
552
553 def testReadSamWithoutTargetNames(self):
554 '''see issue 104.'''
555 input_filename = os.path.join(
556 BAM_DATADIR,
557 "example_unmapped_reads_no_sq.sam")
558
559 # raise exception in default mode
560 self.assertRaises(ValueError,
561 pysam.AlignmentFile,
562 input_filename,
563 "r")
564
565 # raise exception if no SQ files
566 self.assertRaises(ValueError,
567 pysam.AlignmentFile,
568 input_filename, "r",
569 check_header=True)
570
571 with pysam.AlignmentFile(
572 input_filename,
573 check_header=False,
574 check_sq=False) as infile:
575 result = list(infile.fetch(until_eof=True))
576 self.assertEqual(2, len(result))
577
578 def testReadBamWithoutTargetNames(self):
579 '''see issue 104.'''
580 input_filename = os.path.join(
581 BAM_DATADIR, "example_unmapped_reads_no_sq.bam")
582
583 # raise exception in default mode
584 self.assertRaises(ValueError,
585 pysam.AlignmentFile,
586 input_filename,
587 "r")
588
589 # raise exception if no SQ files
590 self.assertRaises(ValueError,
591 pysam.AlignmentFile,
592 input_filename,
593 "r",
594 check_header=True)
595
596 with pysam.AlignmentFile(
597 input_filename, check_sq=False) as infile:
598 result = list(infile.fetch(until_eof=True))
599
600 def test_fail_read_sam_without_header(self):
601 input_filename = os.path.join(BAM_DATADIR, "ex1.sam")
602
603 self.assertRaises(ValueError,
604 pysam.AlignmentFile,
605 input_filename,
606 "r")
607
608 def test_pass_read_sam_without_header_with_refs(self):
609 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.sam"),
610 "r",
611 reference_names=["chr1", "chr2"],
612 reference_lengths=[1575, 1584]) as samfile:
613 self.assertEqual(len(list(samfile.fetch(until_eof=True))), 3270)
614
615 def test_pass_read_sam_with_header_without_header_check(self):
616 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex2.sam"),
617 "r", check_header=False) as samfile:
618 self.assertEqual(len(list(samfile.fetch(until_eof=True))), 3270)
619
620 def test_fail_when_reading_unformatted_files(self):
621 '''test reading from a file that is not bam/sam formatted'''
622 input_filename = os.path.join(BAM_DATADIR, 'Makefile')
623
624 self.assertRaises(ValueError,
625 pysam.AlignmentFile,
626 input_filename,
627 "rb")
628
629 self.assertRaises(ValueError,
630 pysam.AlignmentFile,
631 input_filename,
632 "r")
633
634 def testBAMWithoutAlignedSegments(self):
635 '''see issue 117'''
636 input_filename = os.path.join(BAM_DATADIR, "test_unaligned.bam")
637 samfile = pysam.AlignmentFile(input_filename,
638 "rb",
639 check_sq=False)
640 samfile.fetch(until_eof=True)
641
642 def testBAMWithShortBAI(self):
643 '''see issue 116'''
644 input_filename = os.path.join(BAM_DATADIR, "example_bai.bam")
645 samfile = pysam.AlignmentFile(input_filename,
646 "rb",
647 check_sq=False)
648 samfile.fetch('chr2')
649
650 def testFetchFromClosedFile(self):
651
652 samfile = pysam.AlignmentFile(
653 os.path.join(BAM_DATADIR, "ex1.bam"),
654 "rb")
655 samfile.close()
656 self.assertRaises(ValueError, samfile.fetch, 'chr1', 100, 120)
657
658 def testFetchFromClosedFileObject(self):
659
660 f = open(os.path.join(BAM_DATADIR, "ex1.bam"))
661 samfile = pysam.AlignmentFile(f, "rb")
662 f.close()
663 self.assertTrue(f.closed)
664 # access to Samfile still works
665 self.checkEcho("ex1.bam",
666 "ex1.bam",
667 "tmp_ex1.bam",
668 "rb", "wb",
669 checkf=checkGZBinaryEqual)
670
671 f = open(os.path.join(BAM_DATADIR, "ex1.bam"))
672 samfile = pysam.AlignmentFile(f, "rb")
673 self.assertFalse(f.closed)
674 samfile.close()
675 # python file needs to be closed separately
676 self.assertFalse(f.closed)
677
678 def test_accessing_attributes_in_closed_file_raises_errors(self):
679 '''test that access to a closed samfile raises ValueError.'''
680
681 samfile = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"),
682 "rb")
683 samfile.close()
684
685 self.assertRaises(ValueError, samfile.fetch, 'chr1', 100, 120)
686 self.assertRaises(ValueError, samfile.pileup, 'chr1', 100, 120)
687 self.assertRaises(ValueError, samfile.getrname, 0)
688 # TODO
689 self.assertRaises(ValueError, samfile.tell)
690 self.assertRaises(ValueError, samfile.seek, 0)
691 self.assertRaises(ValueError, getattr, samfile, "nreferences")
692 self.assertRaises(ValueError, getattr, samfile, "references")
693 self.assertRaises(ValueError, getattr, samfile, "lengths")
694
695 self.assertEqual(samfile.header, None)
696 # write on closed file
697 self.assertEqual(0, samfile.write(None))
698
699 def test_header_available_after_closing_file(self):
700
701 def load_bam():
702 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"), "rb") as inf:
703 header = inf.header
704 return header
705
706 header = load_bam()
707 self.assertTrue(header)
708 self.assertEqual(header.nreferences, 2)
709 self.assertEqual(header.references, ("chr1", "chr2"))
710
711 def test_reference_name_available_after_closing_file(self):
712 """read tids can be mapped to references after AlignmentFile has been closed.
713
714 see issue #517"""
715
716 def load_bam():
717 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"), "rb") as inf:
718 read = next(inf)
719 return read
720
721 read = load_bam()
722 self.assertEqual(read.reference_name, "chr1")
723
724 # TODO
725 # def testReadingFromSamFileWithoutHeader(self):
726 # '''read from samfile without header.
727 # '''
728 # samfile = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex7.sam"),
729 # check_header=False,
730 # check_sq=False)
731 # self.assertRaises(NotImplementedError, samfile.__iter__)
732
733 def testReadingFromFileWithoutIndex(self):
734 '''read from bam file without index.'''
735
736 dest = get_temp_filename("tmp_ex2.bam")
737 shutil.copyfile(os.path.join(BAM_DATADIR, "ex2.bam"),
738 dest)
739 samfile = pysam.AlignmentFile(dest,
740 "rb")
741 self.assertRaises(ValueError, samfile.fetch)
742 self.assertEqual(
743 len(list(samfile.fetch(until_eof=True))),
744 3270)
745 os.unlink(dest)
746
747 # def testReadingUniversalFileMode(self):
748 # '''read from samfile without header.
749 # '''
750
751 # input_filename = "ex2.sam"
752 # output_filename = "pysam_ex2.sam"
753 # reference_filename = "ex1.sam"
754
755 # self.checkEcho(input_filename,
756 # reference_filename,
757 # output_filename,
758 # "rU", "w")
759
760 def testHead(self):
761 '''test IteratorRowHead'''
762 samfile = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"),
763 "rb")
764 l10 = list(samfile.head(10))
765 l100 = list(samfile.head(100))
766 self.assertEqual(len(l10), 10)
767 self.assertEqual(len(l100), 100)
768 self.assertEqual(list(map(str, l10)),
769 list(map(str, l100[:10])))
770
771 def testWriteUncompressedBAMFile(self):
772 '''read from uncompressed BAM file, see issue #43'''
773
774 input_filename = "ex2.sam"
775 output_filename = "pysam_uncompressed.bam"
776 reference_filename = "uncompressed.bam"
777
778 self.checkEcho(input_filename,
779 reference_filename,
780 output_filename,
781 "r", "wb0")
782
783 self.checkEcho(input_filename,
784 reference_filename,
785 output_filename,
786 "r", "wbu")
787
788 def testEmptyBAM(self):
789 samfile = pysam.Samfile(os.path.join(BAM_DATADIR, "empty.bam"),
790 "rb")
791 self.assertEqual(samfile.mapped, 0)
792 self.assertEqual(samfile.unmapped, 0)
793 self.assertEqual(samfile.nocoordinate, 0)
794
795 def testEmptyWithHeaderBAM(self):
796 self.assertRaises(
797 ValueError,
798 pysam.Samfile,
799 os.path.join(BAM_DATADIR, "example_empty_with_header.bam"),
800 "rb")
801
802 samfile = pysam.Samfile(
803 os.path.join(BAM_DATADIR, "example_empty_with_header.bam"),
804 "rb",
805 check_sq=False)
806 self.assertEqual(samfile.mapped, 0)
807 self.assertEqual(samfile.unmapped, 0)
808 self.assertEqual(samfile.nocoordinate, 0)
809 self.assertEqual([], list(samfile.fetch()))
810
811 def testOpenFromFilename(self):
812
813 samfile = pysam.AlignmentFile(
814 filename=os.path.join(BAM_DATADIR, "ex1.bam"),
815 mode="rb")
816 self.assertEqual(len(list(samfile.fetch())), 3270)
817
818 def testBAMWithCSIIndex(self):
819 '''see issue 116'''
820 input_filename = os.path.join(BAM_DATADIR, "ex1_csi.bam")
821 samfile = pysam.AlignmentFile(input_filename,
822 "rb",
823 check_sq=False)
824 samfile.fetch('chr2')
825
826 def test_fetch_by_tid(self):
827 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"), "rb") as samfile:
828 self.assertEqual(len(list(samfile.fetch('chr1'))),
829 len(list(samfile.fetch(tid=0))))
830 self.assertEqual(len(list(samfile.fetch('chr2'))),
831 len(list(samfile.fetch(tid=1))))
832 self.assertRaises(
833 IndexError,
834 samfile.fetch,
835 tid=2)
836 self.assertRaises(
837 IndexError,
838 samfile.fetch,
839 tid=-1)
840 self.assertEqual(len(list(samfile.fetch('chr1', start=1000, end=2000))),
841 len(list(samfile.fetch(tid=0, start=1000, end=2000))))
842
843 def test_write_bam_to_unknown_path_fails(self):
844 '''see issue 116'''
845 input_filename = os.path.join(BAM_DATADIR, "ex1.bam")
846 with pysam.AlignmentFile(input_filename) as inf:
847 self.assertRaises(IOError,
848 pysam.AlignmentFile,
849 "missing_directory/new_file.bam",
850 "wb",
851 template=inf)
852
853
854 class TestAutoDetect(unittest.TestCase):
855
856 def testSAM(self):
857 """test SAM autodetection."""
858
859 with pysam.AlignmentFile(
860 os.path.join(BAM_DATADIR, "ex3.sam")) as inf:
861 self.assertFalse(inf.is_bam)
862 self.assertFalse(inf.is_cram)
863
864 self.assertRaises(ValueError, inf.fetch, 'chr1')
865
866 def testBAM(self):
867 """test BAM autodetection."""
868
869 with pysam.AlignmentFile(
870 os.path.join(BAM_DATADIR, "ex3.bam")) as inf:
871 self.assertTrue(inf.is_bam)
872 self.assertFalse(inf.is_cram)
873 self.assertEqual(len(list(inf.fetch('chr1'))), 1)
874 self.assertEqual(len(list(inf.fetch('chr2'))), 3)
875
876 def testCRAM(self):
877 """test CRAM autodetection."""
878
879 with pysam.AlignmentFile(
880 os.path.join(BAM_DATADIR, "ex3.cram")) as inf:
881 self.assertFalse(inf.is_bam)
882 self.assertTrue(inf.is_cram)
883 self.assertEqual(len(list(inf.fetch('chr1'))), 1)
884 self.assertEqual(len(list(inf.fetch('chr2'))), 3)
885
886
887 ##################################################
888 #
889 # Random access iterator tests
890 #
891 ##################################################
892 class TestIteratorRowBAM(unittest.TestCase):
893
894 filename = os.path.join(BAM_DATADIR, "ex2.bam")
895 mode = "rb"
896 reference_filename = None
897
898 def setUp(self):
899 self.samfile = pysam.AlignmentFile(
900 self.filename,
901 self.mode,
902 reference_filename=self.reference_filename,
903 )
904
905 def tearDown(self):
906 self.samfile.close()
907
908 def checkRange(self, rnge):
909 '''compare results from iterator with those from samtools.'''
910 ps = list(self.samfile.fetch(region=rnge))
911 sa = force_str(
912 pysam.samtools.view(
913 self.filename,
914 rnge,
915 raw=True)).splitlines(True)
916 self.assertEqual(
917 len(ps), len(sa),
918 "unequal number of results for range %s: %i != %i" %
919 (rnge, len(ps), len(sa)))
920 # check if the same reads are returned and in the same order
921 for line, (a, b) in enumerate(list(zip(ps, sa))):
922 d = b.split("\t")
923 self.assertEqual(
924 a.query_name, d[0],
925 "line %i: read id mismatch: %s != %s" %
926 (line, a.reference_id, d[0]))
927 self.assertEqual(
928 a.reference_start,
929 int(d[3]) - 1,
930 "line %i: read position mismatch: %s != %s, \n%s\n%s\n" %
931 (line, a.reference_start, int(d[3]) - 1,
932 str(a), str(d)))
933 qual = d[10]
934 self.assertEqual(
935 pysam.qualities_to_qualitystring(a.query_qualities),
936 qual,
937 "line %i: quality mismatch: %s != %s, \n%s\n%s\n" %
938 (line, pysam.qualities_to_qualitystring(a.query_qualities), qual,
939 str(a), str(d)))
940
941 def testIteratePerContig(self):
942 '''check random access per contig'''
943 for contig in self.samfile.references:
944 self.checkRange(contig)
945
946 def testIterateRanges(self):
947 '''check random access per range'''
948 for contig, length in zip(self.samfile.references,
949 self.samfile.lengths):
950 for start in range(1, length, 90):
951 # this includes empty ranges
952 self.checkRange("%s:%i-%i" %
953 (contig, start, start + 90))
954
955
956 class TestIteratorRowAllBAM(unittest.TestCase):
957
958 filename = os.path.join(BAM_DATADIR, "ex2.bam")
959 mode = "rb"
960
961 def setUp(self):
962 self.samfile = pysam.AlignmentFile(
963 self.filename,
964 self.mode)
965
966 def testIterate(self):
967 '''compare results from iterator with those from samtools.'''
968 ps = list(self.samfile.fetch())
969 sa = pysam.samtools.view(self.filename,
970 raw=True).splitlines()
971 self.assertEqual(
972 len(ps), len(sa),
973 "unequal number of results: %i != %i" %
974 (len(ps), len(sa)))
975 # check if the same reads are returned
976 for line, pair in enumerate(list(zip(ps, sa))):
977 data = force_str(pair[1]).split("\t")
978 self.assertEqual(
979 pair[0].query_name,
980 data[0],
981 "read id mismatch in line %i: %s != %s" %
982 (line, pair[0].reference_id, data[0]))
983
984 def tearDown(self):
985 self.samfile.close()
986
987
988 class TestIteratorRowCRAM(TestIteratorRowBAM):
989 filename = os.path.join(BAM_DATADIR, "ex2.cram")
990 mode = "rc"
991
992
993 class TestIteratorRowCRAMWithReferenceFilename(TestIteratorRowCRAM):
994 reference_filename = os.path.join(BAM_DATADIR, "ex1.fa")
995
996
997 # needs to be implemented
998 # class TestAlignedSegmentFromSamWithoutHeader(TestAlignedSegmentFromBam):
999 #
1000 # def setUp(self):
1001 # self.samfile=pysam.AlignmentFile( "ex7.sam","r" )
1002 # self.reads=list(self.samfile.fetch())
1003
1004
1005 class TestFloatTagBug(unittest.TestCase):
1006
1007 '''see issue 71'''
1008
1009 def testFloatTagBug(self):
1010 '''a float tag before another exposed a parsing bug in bam_aux_get.
1011
1012 Fixed in 0.1.19
1013 '''
1014 samfile = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "tag_bug.bam"))
1015 read = next(samfile.fetch(until_eof=True))
1016 self.assertTrue(('XC', 1) in read.tags)
1017 self.assertEqual(read.opt('XC'), 1)
1018
1019
1020 class TestLargeFieldBug(unittest.TestCase):
1021
1022 '''see issue 100'''
1023
1024 def testLargeFileBug(self):
1025 '''when creating a read with a large entry in the tag field
1026 causes an error:
1027 NotImplementedError: tags field too large
1028 '''
1029 samfile = pysam.AlignmentFile(
1030 os.path.join(BAM_DATADIR, "issue100.bam"))
1031 read = next(samfile.fetch(until_eof=True))
1032 new_read = pysam.AlignedSegment()
1033 new_read.tags = read.tags
1034 self.assertEqual(new_read.tags, read.tags)
1035
1036
1037 class TestClipping(unittest.TestCase):
1038
1039 def testClipping(self):
1040
1041 self.samfile = pysam.AlignmentFile(
1042 os.path.join(BAM_DATADIR, "softclip.bam"),
1043 "rb")
1044
1045 for read in self.samfile:
1046
1047 if read.query_name == "r001":
1048 self.assertEqual(read.query_sequence, 'AAAAGATAAGGATA')
1049 self.assertEqual(read.query_alignment_sequence, 'AGATAAGGATA')
1050 self.assertEqual(pysam.qualities_to_qualitystring(read.query_qualities),
1051 None)
1052 self.assertEqual(
1053 pysam.qualities_to_qualitystring(
1054 read.query_alignment_qualities),
1055 None)
1056
1057 elif read.query_name == "r002":
1058
1059 self.assertEqual(read.query_sequence, 'GCCTAAGCTAA')
1060 self.assertEqual(read.query_alignment_sequence, 'AGCTAA')
1061 self.assertEqual(
1062 pysam.qualities_to_qualitystring(read.query_qualities),
1063 '01234567890')
1064 self.assertEqual(
1065 pysam.qualities_to_qualitystring(
1066 read.query_alignment_qualities),
1067 '567890')
1068
1069 elif read.query_name == "r003":
1070
1071 self.assertEqual(read.query_sequence, 'GCCTAAGCTAA')
1072 self.assertEqual(read.query_alignment_sequence, 'GCCTAA')
1073 self.assertEqual(
1074 pysam.qualities_to_qualitystring(read.query_qualities),
1075 '01234567890')
1076 self.assertEqual(
1077 pysam.qualities_to_qualitystring(
1078 read.query_alignment_qualities),
1079 '012345')
1080
1081 elif read.query_name == "r004":
1082
1083 self.assertEqual(read.query_sequence, 'TAGGC')
1084 self.assertEqual(read.query_alignment_sequence, 'TAGGC')
1085 self.assertEqual(
1086 pysam.qualities_to_qualitystring(read.query_qualities),
1087 '01234')
1088 self.assertEqual(
1089 pysam.qualities_to_qualitystring(
1090 read.query_alignment_qualities),
1091 '01234')
1092
1093
1094 class TestUnmappedReadsRetrieval(unittest.TestCase):
1095
1096 def test_fetch_from_sam_with_until_eof_reads_unmapped_reads(self):
1097 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex5.sam"),
1098 "rb") as samfile:
1099 self.assertEqual(len(list(samfile.fetch(until_eof=True))), 2)
1100
1101 def test_fetch_from_bam_with_until_eof_reads_unmapped_reads(self):
1102 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex5.bam"),
1103 "rb") as samfile:
1104 self.assertEqual(len(list(samfile.fetch(until_eof=True))), 2)
1105
1106 def test_fetch_with_asterisk_only_returns_unmapped_reads(self):
1107 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "test_mapped_unmapped.bam"),
1108 "rb") as samfile:
1109 self.assertEqual(len(list(samfile.fetch(region="*"))), 4)
1110
1111 def test_fetch_with_asterisk_only_returns_unmapped_reads_by_contig(self):
1112 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "test_mapped_unmapped.bam"),
1113 "rb") as samfile:
1114 self.assertEqual(len(list(samfile.fetch(contig="*"))), 4)
1115
1116
1117 class TestContextManager(unittest.TestCase):
1118
1119 def testManager(self):
1120 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, 'ex1.bam'),
1121 'rb') as samfile:
1122 samfile.fetch()
1123 self.assertEqual(samfile.closed, True)
1124
1125
1126 class TestMultiThread(unittest.TestCase):
1127
1128 def testSingleThreadEqualsMultithread(self):
1129 input_bam = os.path.join(BAM_DATADIR, 'ex1.bam')
1130 single_thread_out = get_temp_filename("tmp_single.bam")
1131 multi_thread_out = get_temp_filename("tmp_multi.bam")
1132 with pysam.AlignmentFile(input_bam,
1133 'rb') as samfile:
1134 reads = [r for r in samfile]
1135 with pysam.AlignmentFile(single_thread_out,
1136 mode='wb',
1137 template=samfile,
1138 threads=1) as single_out:
1139 [single_out.write(r) for r in reads]
1140 with pysam.AlignmentFile(multi_thread_out,
1141 mode='wb',
1142 template=samfile,
1143 threads=2) as multi_out:
1144 [single_out.write(r) for r in reads]
1145 with pysam.AlignmentFile(input_bam) as inp, \
1146 pysam.AlignmentFile(single_thread_out) as single, \
1147 pysam.AlignmentFile(multi_thread_out) as multi:
1148 for r1, r2, r3 in zip(inp, single, multi):
1149 assert r1.to_string == r2.to_string == r3.to_string
1150
1151 def TestNoMultiThreadingWithIgnoreTruncation(self):
1152 self.assertRaises(
1153 ValueError, pysam.AlignmentFile(os.path.join(BAM_DATADIR, 'ex1.bam'),
1154 threads=2,
1155 ignore_truncation=True)
1156 )
1157
1158
1159 class TestExceptions(unittest.TestCase):
1160
1161 def setUp(self):
1162 self.samfile = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"),
1163 "rb")
1164
1165 def testMissingFile(self):
1166
1167 self.assertRaises(
1168 IOError, pysam.AlignmentFile, "exdoesntexist.bam", "rb")
1169 self.assertRaises(
1170 IOError, pysam.AlignmentFile, "exdoesntexist.sam", "r")
1171 self.assertRaises(
1172 IOError, pysam.AlignmentFile, "exdoesntexist.bam", "r")
1173 self.assertRaises(
1174 IOError, pysam.AlignmentFile, "exdoesntexist.sam", "rb")
1175
1176 def testBadContig(self):
1177 self.assertRaises(ValueError, self.samfile.fetch, "chr88")
1178
1179 def testMeaninglessCrap(self):
1180 self.assertRaises(ValueError, self.samfile.fetch, "skljf")
1181
1182 def testBackwardsOrderNewFormat(self):
1183 self.assertRaises(ValueError, self.samfile.fetch, 'chr1', 100, 10)
1184
1185 def testBackwardsOrderOldFormat(self):
1186 self.assertRaises(ValueError, self.samfile.fetch, region="chr1:100-10")
1187
1188 def testOutOfRangeNegativeNewFormat(self):
1189 self.assertRaises(ValueError, self.samfile.fetch, "chr1", 5, -10)
1190 self.assertRaises(ValueError, self.samfile.fetch, "chr1", 5, 0)
1191 self.assertRaises(ValueError, self.samfile.fetch, "chr1", -5, -10)
1192
1193 self.assertRaises(ValueError, self.samfile.count, "chr1", 5, -10)
1194 self.assertRaises(ValueError, self.samfile.count, "chr1", 5, 0)
1195 self.assertRaises(ValueError, self.samfile.count, "chr1", -5, -10)
1196
1197 def testOutOfRangeNegativeOldFormat(self):
1198 self.assertRaises(ValueError, self.samfile.fetch, region="chr1:-5-10")
1199 self.assertRaises(ValueError, self.samfile.fetch, region="chr1:-5-0")
1200 self.assertRaises(ValueError, self.samfile.fetch, region="chr1:-5--10")
1201
1202 self.assertRaises(ValueError, self.samfile.count, region="chr1:-5-10")
1203 self.assertRaises(ValueError, self.samfile.count, region="chr1:-5-0")
1204 self.assertRaises(ValueError, self.samfile.count, region="chr1:-5--10")
1205
1206 def testOutOfRangNewFormat(self):
1207 self.assertRaises(
1208 ValueError, self.samfile.fetch, "chr1", 9999999999, 99999999999)
1209 self.assertRaises(
1210 ValueError, self.samfile.count, "chr1", 9999999999, 99999999999)
1211
1212 def testOutOfRangeLargeNewFormat(self):
1213 self.assertRaises(ValueError, self.samfile.fetch, "chr1",
1214 9999999999999999999999999999999, 9999999999999999999999999999999999999999)
1215 self.assertRaises(ValueError, self.samfile.count, "chr1",
1216 9999999999999999999999999999999, 9999999999999999999999999999999999999999)
1217
1218 def testOutOfRangeLargeOldFormat(self):
1219 self.assertRaises(
1220 ValueError, self.samfile.fetch, "chr1:99999999999999999-999999999999999999")
1221 self.assertRaises(
1222 ValueError, self.samfile.count, "chr1:99999999999999999-999999999999999999")
1223
1224 def testZeroToZero(self):
1225 '''see issue 44'''
1226 self.assertEqual(len(list(self.samfile.fetch('chr1', 0, 0))), 0)
1227
1228 def tearDown(self):
1229 self.samfile.close()
1230
1231
1232 class TestWrongFormat(unittest.TestCase):
1233
1234 '''test cases for opening files not in bam/sam format.'''
1235
1236 def testOpenSamAsBam(self):
1237 self.assertRaises(ValueError,
1238 pysam.AlignmentFile,
1239 os.path.join(BAM_DATADIR, 'ex1.sam'),
1240 'rb')
1241
1242 def testOpenBamAsSam(self):
1243 # test fails, needs to be implemented.
1244 # sam.fetch() fails on reading, not on opening
1245 # self.assertRaises(ValueError, pysam.AlignmentFile,
1246 # os.path.join(BAM_DATADIR, 'ex1.bam'),
1247 # 'r')
1248 pass
1249
1250 def testOpenFastaAsSam(self):
1251 # test fails, needs to be implemented.
1252 # sam.fetch() fails on reading, not on opening
1253 # self.assertRaises( ValueError, pysam.AlignmentFile, 'ex1.fa', 'r' )
1254 pass
1255
1256 def testOpenFastaAsBam(self):
1257 self.assertRaises(ValueError,
1258 pysam.AlignmentFile,
1259 os.path.join(BAM_DATADIR, 'ex1.fa'),
1260 'rb')
1261
1262
1263 class TestRegionParsing(unittest.TestCase):
1264
1265 def test_dash_in_chr(self):
1266 with pysam.AlignmentFile(
1267 os.path.join(BAM_DATADIR, "example_dash_in_chr.bam")) as inf:
1268 self.assertEqual(len(list(inf.fetch(contig="chr-1"))), 1)
1269 self.assertEqual(len(list(inf.fetch(contig="chr2"))), 1)
1270 self.assertEqual(len(list(inf.fetch(region="chr-1"))), 1)
1271 self.assertEqual(len(list(inf.fetch(region="chr2"))), 1)
1272
1273
1274 class TestDeNovoConstruction(unittest.TestCase):
1275
1276 '''check BAM/SAM file construction using ex6.sam
1277
1278 (note these are +1 coordinates):
1279
1280 read_28833_29006_6945 99 chr1 33 20 10M1D25M = 200 167 AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG <<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<< NM:i:1 RG:Z:L1
1281 read_28701_28881_323b 147 chr2 88 30 35M = 500 412 ACCTATATCTTGGCCTTGGCCGATGCGGCCTTGCA <<<<<;<<<<7;:<<<6;<<<<<<<<<<<<7<<<< MF:i:18 RG:Z:L2
1282 ''' # noqa
1283
1284 header = {'HD': {'VN': '1.0'},
1285 'SQ': [{'LN': 1575, 'SN': 'chr1'},
1286 {'LN': 1584, 'SN': 'chr2'}], }
1287
1288 bamfile = os.path.join(BAM_DATADIR, "ex6.bam")
1289 samfile = os.path.join(BAM_DATADIR, "ex6.sam")
1290
1291 def setUp(self):
1292
1293 header = pysam.AlignmentHeader.from_dict(self.header)
1294
1295 a = pysam.AlignedSegment(header)
1296 a.query_name = "read_28833_29006_6945"
1297 a.query_sequence = "AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG"
1298 a.flag = 99
1299 a.reference_id = 0
1300 a.reference_start = 32
1301 a.mapping_quality = 20
1302 a.cigartuples = ((0, 10), (2, 1), (0, 25))
1303 a.next_reference_id = 0
1304 a.next_reference_start = 199
1305 a.template_length = 167
1306 a.query_qualities = pysam.qualitystring_to_array(
1307 "<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<")
1308 a.tags = (("NM", 1),
1309 ("RG", "L1"))
1310
1311 b = pysam.AlignedSegment(header)
1312 b.query_name = "read_28701_28881_323b"
1313 b.query_sequence = "ACCTATATCTTGGCCTTGGCCGATGCGGCCTTGCA"
1314 b.flag = 147
1315 b.reference_id = 1
1316 b.reference_start = 87
1317 b.mapping_quality = 30
1318 b.cigartuples = ((0, 35), )
1319 b.next_reference_id = 1
1320 b.next_reference_start = 499
1321 b.template_length = 412
1322 b.query_qualities = pysam.qualitystring_to_array(
1323 "<<<<<;<<<<7;:<<<6;<<<<<<<<<<<<7<<<<")
1324 b.tags = (("MF", 18),
1325 ("RG", "L2"))
1326
1327 self.reads = (a, b)
1328
1329 # TODO
1330 # def testSAMWholeFile(self):
1331
1332 # tmpfilename = "tmp_%i.sam" % id(self)
1333
1334 # outfile = pysam.AlignmentFile(tmpfilename,
1335 # "wh",
1336 # header=self.header)
1337
1338 # for x in self.reads:
1339 # outfile.write(x)
1340 # outfile.close()
1341 # self.assertTrue(checkBinaryEqual(tmpfilename, self.samfile),
1342 # "mismatch when construction SAM file, see %s %s" % (tmpfilename, self.samfile))
1343
1344 # os.unlink(tmpfilename)
1345
1346 def test_pass_if_reads_binary_equal(self):
1347 '''check if individual reads are binary equal.'''
1348 infile = pysam.AlignmentFile(self.bamfile, "rb")
1349
1350 references = list(infile)
1351 for denovo, reference in zip(references, self.reads):
1352 checkFieldEqual(self, reference, denovo)
1353 self.assertEqual(reference.compare(denovo), 0)
1354
1355 # TODO
1356 # def testSAMPerRead(self):
1357 # '''check if individual reads are binary equal.'''
1358 # infile = pysam.AlignmentFile(self.samfile, "r")
1359
1360 # others = list(infile)
1361 # for denovo, other in zip(others, self.reads):
1362 # checkFieldEqual(self, other, denovo)
1363 # self.assertEqual(other.compare(denovo), 0)
1364
1365 def testBAMWholeFile(self):
1366
1367 tmpfilename = "tmp_%i.bam" % id(self)
1368
1369 outfile = pysam.AlignmentFile(tmpfilename, "wb", header=self.header)
1370
1371 for x in self.reads:
1372 outfile.write(x)
1373 outfile.close()
1374
1375 self.assertTrue(
1376 checkGZBinaryEqual(tmpfilename, self.bamfile),
1377 "mismatch when construction BAM file, see %s %s" %
1378 (tmpfilename, self.bamfile))
1379
1380 os.unlink(tmpfilename)
1381
1382
1383 class TestEmptyHeader(unittest.TestCase):
1384 '''see issue 84.'''
1385
1386 def testEmptyHeader(self):
1387 s = pysam.AlignmentFile(os.path.join(BAM_DATADIR,
1388 'example_empty_header.bam'))
1389 self.assertEqual(s.header.to_dict(), {'SQ': [{'LN': 1000, 'SN': 'chr1'}]})
1390
1391 def test_bam_without_seq_in_header(self):
1392 s = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "0example_no_seq_in_header.bam"))
1393 self.assertTrue("SQ" in s.header.to_dict())
1394 self.assertTrue("@SQ" in str(s.header))
1395
1396 def test_bam_without_seq_with_null_bytes_in_header(self):
1397 s = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "0example_no_seq_in_header_null_bytes.bam"))
1398 self.assertTrue("SQ" in s.header.to_dict())
1399 self.assertTrue("@SQ" in str(s.header))
1400
1401
1402 class TestMismatchingHeader(unittest.TestCase):
1403 '''see issue 716.'''
1404
1405 def testMismatchingHeader(self):
1406 # Note: no chr2
1407 header = {
1408 'SQ': [{'SN': 'chr1', 'LN': 1575}],
1409 'PG': [{'ID': 'bwa', 'PN': 'bwa', 'VN': '0.7.15', 'CL': 'bwa mem xx -'}],
1410 }
1411
1412 dest = get_temp_filename("tmp_ex3.bam")
1413 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, 'ex3.bam')) as inf:
1414 with pysam.AlignmentFile(dest, mode="wb", header=header) as outf:
1415 for read in inf:
1416 if read.reference_name == "chr1":
1417 outf.write(read)
1418 else:
1419 self.assertRaises(ValueError,
1420 outf.write,
1421 read)
1422 os.unlink(dest)
1423
1424
1425 class TestHeaderWithProgramOptions(unittest.TestCase):
1426
1427 '''see issue 39.'''
1428
1429 def testHeader(self):
1430 s = pysam.AlignmentFile(os.path.join(BAM_DATADIR,
1431 'rg_with_tab.bam'))
1432 self.assertEqual(
1433 s.header.to_dict(),
1434 {'SQ': [{'LN': 1575, 'SN': 'chr1'},
1435 {'LN': 1584, 'SN': 'chr2'}],
1436 'PG': [{'PN': 'bwa',
1437 'ID': 'bwa',
1438 'VN': '0.7.9a-r786',
1439 'CL': 'bwa mem -p -t 8 -M -R '
1440 '@RG ID:None SM:None /mnt/data/hg19.fa '
1441 '/mnt/analysis/default-0.fastq'}]})
1442
1443
1444 class TestTruncatedBAM(unittest.TestCase):
1445
1446 '''see pull request 50.'''
1447
1448 def testTruncatedBam2(self):
1449 self.assertRaises(IOError,
1450 pysam.AlignmentFile,
1451 os.path.join(BAM_DATADIR, 'ex2_truncated.bam'))
1452
1453 @pytest.mark.filterwarnings('ignore:no BGZF EOF marker')
1454 def testTruncatedBamIterator(self):
1455 s = pysam.AlignmentFile(os.path.join(BAM_DATADIR, 'ex2_truncated.bam'),
1456 ignore_truncation=True)
1457
1458 def iterall(x):
1459 return len([a for a in x])
1460 self.assertRaises(IOError, iterall, s)
1461
1462 # Ignore closing errors, as s is now in an error state
1463 try:
1464 s.close()
1465 except IOError:
1466 pass
1467
1468
1469 class TestCorruptBAM(unittest.TestCase):
1470 """See pull request 1035."""
1471
1472 def testCorruptBamIterator(self):
1473 s = pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex2_corrupt.bam"))
1474
1475 def iterall(x):
1476 return len([a for a in x])
1477
1478 self.assertRaises(IOError, iterall, s)
1479
1480
1481 COMPARE_BTAG = [100, 1, 91, 0, 7, 101, 0, 201, 96, 204,
1482 0, 0, 87, 109, 0, 7, 97, 112, 1, 12, 78,
1483 197, 0, 7, 100, 95, 101, 202, 0, 6, 0, 1,
1484 186, 0, 84, 0, 244, 0, 0, 324, 0, 107, 195,
1485 101, 113, 0, 102, 0, 104, 3, 0, 101, 1, 0,
1486 212, 6, 0, 0, 1, 0, 74, 1, 11, 0, 196, 2,
1487 197, 103, 0, 108, 98, 2, 7, 0, 1, 2, 194,
1488 0, 180, 0, 108, 0, 203, 104, 16, 5, 205,
1489 0, 0, 0, 1, 1, 100, 98, 0, 0, 204, 6, 0,
1490 79, 0, 0, 101, 7, 109, 90, 265, 1, 27, 10,
1491 109, 102, 9, 0, 292, 0, 110, 0, 0, 102,
1492 112, 0, 0, 84, 100, 103, 2, 81, 126, 0, 2,
1493 90, 0, 15, 96, 15, 1, 0, 2, 0, 107, 92, 0,
1494 0, 101, 3, 98, 15, 102, 13, 116, 116, 90, 93,
1495 198, 0, 0, 0, 199, 92, 26, 495, 100, 5, 0,
1496 100, 5, 209, 0, 92, 107, 90, 0, 0, 0, 0, 109,
1497 194, 7, 94, 200, 0, 40, 197, 0, 11, 0, 0, 112,
1498 110, 6, 4, 200, 28, 0, 196, 0, 203, 1, 129,
1499 0, 0, 1, 0, 94, 0, 1, 0, 107, 5, 201, 3, 3, 100,
1500 0, 121, 0, 7, 0, 1, 105, 306, 3, 86, 8, 183, 0,
1501 12, 163, 17, 83, 22, 0, 0, 1, 8, 109, 103, 0, 0,
1502 295, 0, 200, 16, 172, 3, 16, 182, 3, 11, 0, 0,
1503 223, 111, 103, 0, 5, 225, 0, 95]
1504
1505
1506 class TestBTagSam(unittest.TestCase):
1507
1508 '''see issue 81.'''
1509
1510 compare = [COMPARE_BTAG,
1511 [-100, 200, -300, -400],
1512 [-100, 12],
1513 [12, 15],
1514 [-1.0, 5.0, 2.5]]
1515
1516 filename = os.path.join(BAM_DATADIR, 'example_btag.sam')
1517
1518 read0 = [('RG', 'QW85I'),
1519 ('PG', 'tmap'),
1520 ('MD', '140'),
1521 ('NM', 0),
1522 ('AS', 140),
1523 ('FZ', array.array('H', COMPARE_BTAG)),
1524 ('XA', 'map2-1'),
1525 ('XS', 53),
1526 ('XT', 38),
1527 ('XF', 1),
1528 ('XE', 0)]
1529
1530 def testReadTags(self):
1531
1532 s = pysam.AlignmentFile(self.filename)
1533 for x, read in enumerate(s):
1534 tags = read.tags
1535 if x == 0:
1536 self.assertEqual(tags, self.read0)
1537
1538 fz = list(dict(tags)["FZ"])
1539 self.assertEqual(fz, self.compare[x])
1540 self.assertEqual(list(read.opt("FZ")), self.compare[x])
1541 self.assertEqual(tags, read.get_tags())
1542 for tag, value in tags:
1543 self.assertEqual(value, read.get_tag(tag))
1544
1545 def testReadWriteTags(self):
1546
1547 s = pysam.AlignmentFile(self.filename)
1548 for read in s:
1549 before = read.tags
1550 read.tags = before
1551 self.assertEqual(read.tags, before)
1552
1553 read.set_tags(before)
1554 self.assertEqual(read.tags, before)
1555
1556 for tag, value in before:
1557 read.set_tag(tag, value)
1558 self.assertEqual(value, read.get_tag(tag))
1559
1560
1561 class TestBTagBam(TestBTagSam):
1562 filename = os.path.join(BAM_DATADIR, 'example_btag.bam')
1563
1564
1565 class TestDoubleFetchBAM(unittest.TestCase):
1566 '''check if two iterators on the same bamfile are independent.'''
1567
1568 filename = os.path.join(BAM_DATADIR, 'ex1.bam')
1569 mode = "rb"
1570
1571 def testDoubleFetch(self):
1572
1573 with pysam.AlignmentFile(self.filename, self.mode) as samfile1:
1574 for a, b in zip(samfile1.fetch(multiple_iterators=True),
1575 samfile1.fetch(multiple_iterators=True)):
1576 self.assertEqual(a.compare(b), 0)
1577
1578 def testDoubleFetchWithRegionTrueTrue(self):
1579
1580 with pysam.AlignmentFile(self.filename, self.mode) as samfile1:
1581 contig, start, stop = 'chr2', 200, 3000000
1582 # just making sure the test has something to catch
1583 self.assertTrue(len(list(samfile1.fetch(contig, start, stop))) > 0)
1584
1585 for a, b in zip(samfile1.fetch(contig, start, stop,
1586 multiple_iterators=True),
1587 samfile1.fetch(contig, start, stop,
1588 multiple_iterators=True)):
1589 self.assertEqual(a.compare(b), 0)
1590
1591 def testDoubleFetchWithRegionFalseTrue(self):
1592 with pysam.AlignmentFile(self.filename, self.mode) as samfile1:
1593 contig, start, stop = 'chr2', 200, 3000000
1594 # just making sure the test has something to catch
1595 self.assertTrue(len(list(samfile1.fetch(contig, start, stop))) > 0)
1596
1597 for a, b in zip(samfile1.fetch(contig, start, stop,
1598 multiple_iterators=False),
1599 samfile1.fetch(contig, start, stop,
1600 multiple_iterators=True)):
1601 self.assertEqual(a.compare(b), 0)
1602
1603 def testDoubleFetchWithRegionTrueFalse(self):
1604 with pysam.AlignmentFile(self.filename, self.mode) as samfile1:
1605 contig, start, stop = 'chr2', 200, 3000000
1606 # just making sure the test has something to catch
1607 self.assertTrue(len(list(samfile1.fetch(contig, start, stop))) > 0)
1608
1609 for a, b in zip(samfile1.fetch(contig, start, stop,
1610 multiple_iterators=True),
1611 samfile1.fetch(contig, start, stop,
1612 multiple_iterators=False)):
1613 self.assertEqual(a.compare(b), 0)
1614
1615 def testDoubleFetchUntilEOF(self):
1616
1617 with pysam.AlignmentFile(self.filename, self.mode) as samfile1:
1618
1619 for a, b in zip(samfile1.fetch(until_eof=True),
1620 samfile1.fetch(until_eof=True,
1621 multiple_iterators=True)):
1622 self.assertEqual(a.compare(b), 0)
1623
1624
1625 class TestDoubleFetchCRAM(TestDoubleFetchBAM):
1626 filename = os.path.join(BAM_DATADIR, 'ex2.cram')
1627 mode = "rc"
1628
1629
1630 class TestDoubleFetchCRAMWithReference(TestDoubleFetchBAM):
1631 filename = os.path.join(BAM_DATADIR, 'ex2.cram')
1632 mode = "rc"
1633 reference_filename = os.path.join(BAM_DATADIR, 'ex1.fa')
1634
1635
1636 class TestRemoteFileFTP(unittest.TestCase):
1637
1638 '''test remote access.
1639
1640 '''
1641
1642 # Need to find an ftp server without password on standard
1643 # port.
1644
1645 url = "ftp://ftp.sanger.ac.uk/pub/rd/humanSequences/CV.bam"
1646 region = "1:1-1000"
1647
1648 def testFTPView(self):
1649 return
1650 if not check_url(self.url):
1651 return
1652
1653 result = pysam.samtools.view(self.url, self.region)
1654 self.assertEqual(len(result), 36)
1655
1656 def testFTPFetch(self):
1657 return
1658 if not check_url(self.url):
1659 return
1660
1661 samfile = pysam.AlignmentFile(self.url, "rb")
1662 result = list(samfile.fetch(region=self.region))
1663 self.assertEqual(len(result), 36)
1664
1665
1666 class TestRemoteFileHTTP(unittest.TestCase):
1667
1668 url = "http://genserv.anat.ox.ac.uk/downloads/pysam/test/ex1.bam"
1669 region = "chr1:1-1000"
1670 local = os.path.join(BAM_DATADIR, "ex1.bam")
1671
1672 def testView(self):
1673 if not check_url(self.url):
1674 return
1675
1676 samfile_local = pysam.AlignmentFile(self.local, "rb")
1677 ref = list(samfile_local.fetch(region=self.region))
1678
1679 result = pysam.samtools.view(self.url, self.region)
1680 self.assertEqual(len(result.splitlines()), len(ref))
1681
1682 def testFetch(self):
1683 if not check_url(self.url):
1684 return
1685
1686 with pysam.AlignmentFile(self.url, "rb") as samfile:
1687 result = list(samfile.fetch(region=self.region))
1688
1689 with pysam.AlignmentFile(self.local, "rb") as samfile_local:
1690 ref = list(samfile_local.fetch(region=self.region))
1691
1692 self.assertEqual(len(ref), len(result))
1693 for x, y in zip(result, ref):
1694 self.assertEqual(x.compare(y), 0)
1695
1696 def testFetchAll(self):
1697 if not check_url(self.url):
1698 return
1699
1700 with pysam.AlignmentFile(self.url, "rb") as samfile:
1701 result = list(samfile.fetch())
1702
1703 with pysam.AlignmentFile(self.local, "rb") as samfile_local:
1704 ref = list(samfile_local.fetch())
1705
1706 self.assertEqual(len(ref), len(result))
1707 for x, y in zip(result, ref):
1708 self.assertEqual(x.compare(y), 0)
1709
1710
1711 class TestLargeOptValues(unittest.TestCase):
1712
1713 ints = (65536, 214748, 2147484, 2147483647)
1714 floats = (65536.0, 214748.0, 2147484.0)
1715
1716 def check(self, samfile):
1717
1718 i = samfile.fetch()
1719 for exp in self.ints:
1720 rr = next(i)
1721 obs = rr.opt("ZP")
1722 self.assertEqual(exp, obs,
1723 "expected %s, got %s\n%s" %
1724 (str(exp), str(obs), str(rr)))
1725
1726 for exp in [-x for x in self.ints]:
1727 rr = next(i)
1728 obs = rr.opt("ZP")
1729 self.assertEqual(exp, obs,
1730 "expected %s, got %s\n%s" %
1731 (str(exp), str(obs), str(rr)))
1732
1733 for exp in self.floats:
1734 rr = next(i)
1735 obs = rr.opt("ZP")
1736 self.assertEqual(exp, obs,
1737 "expected %s, got %s\n%s" %
1738 (str(exp), str(obs), str(rr)))
1739
1740 for exp in [-x for x in self.floats]:
1741 rr = next(i)
1742 obs = rr.opt("ZP")
1743 self.assertEqual(exp, obs, "expected %s, got %s\n%s" %
1744 (str(exp), str(obs), str(rr)))
1745
1746 def testSAM(self):
1747 samfile = pysam.AlignmentFile(
1748 os.path.join(BAM_DATADIR, "ex10.sam"),
1749 "r")
1750 self.check(samfile)
1751
1752 def testBAM(self):
1753 samfile = pysam.AlignmentFile(
1754 os.path.join(BAM_DATADIR, "ex10.bam"),
1755 "rb")
1756 self.check(samfile)
1757
1758
1759 class TestCountCoverage(unittest.TestCase):
1760
1761 samfilename = os.path.join(BAM_DATADIR, "ex1.bam")
1762 fastafilename = os.path.join(BAM_DATADIR, "ex1.fa")
1763
1764 def setUp(self):
1765
1766 self.fastafile = pysam.Fastafile(self.fastafilename)
1767 self.tmpfilename = get_temp_filename(".bam")
1768
1769 with pysam.AlignmentFile(self.samfilename) as inf:
1770 with pysam.AlignmentFile(
1771 self.tmpfilename,
1772 'wb',
1773 template=inf) as outf:
1774 for ii, read in enumerate(inf.fetch()):
1775 # if ii % 2 == 0: # setting BFUNMAP makes no sense...
1776 #read.flag = read.flag | 0x4
1777 if ii % 3 == 0:
1778 read.flag = read.flag | 0x100
1779 if ii % 5 == 0:
1780 read.flag = read.flag | 0x200
1781 if ii % 7 == 0:
1782 read.flag = read.flag | 0x400
1783 outf.write(read)
1784 pysam.samtools.index(self.tmpfilename)
1785
1786 def tearDown(self):
1787 self.fastafile.close()
1788 os.unlink(self.tmpfilename)
1789 os.unlink(self.tmpfilename + ".bai")
1790
1791 def count_coverage_python(self,
1792 bam, chrom, start, stop,
1793 read_callback,
1794 quality_threshold=15):
1795 stop = min(stop, bam.get_reference_length(chrom))
1796 l = stop - start
1797 count_a = array.array('L', [0] * l)
1798 count_c = array.array('L', [0] * l)
1799 count_g = array.array('L', [0] * l)
1800 count_t = array.array('L', [0] * l)
1801 for p in bam.pileup(chrom, start, stop,
1802 truncate=True,
1803 stepper='nofilter',
1804 min_base_quality=quality_threshold,
1805 ignore_overlaps=False):
1806 rpos = p.reference_pos - start
1807 for read in p.pileups:
1808 if not read.is_del and not read.is_refskip and \
1809 read_callback(read.alignment):
1810 try:
1811 if read.alignment.query_qualities[read.query_position] \
1812 >= quality_threshold:
1813 letter = read.alignment.query[read.query_position]
1814 if letter == 'A':
1815 count_a[rpos] += 1
1816 elif letter == 'C':
1817 count_c[rpos] += 1
1818 elif letter == 'G':
1819 count_g[rpos] += 1
1820 elif letter == 'T':
1821 count_t[rpos] += 1
1822 except IndexError:
1823 pass
1824 return count_a, count_c, count_g, count_t
1825
1826 def test_count_coverage_with_coordinates_works(self):
1827
1828 with pysam.AlignmentFile(self.samfilename) as inf:
1829 c = inf.count_coverage("chr1")
1830 self.assertEqual(len(c[0]), inf.get_reference_length("chr1"))
1831 self.assertEqual(len(c[0]), 1575)
1832
1833 c = inf.count_coverage("chr1", 100)
1834 self.assertEqual(len(c[0]), inf.get_reference_length("chr1") - 100)
1835
1836 c = inf.count_coverage("chr1", 100, 200)
1837 self.assertEqual(len(c[0]), 200 - 100)
1838
1839 c = inf.count_coverage("chr1", None, 200)
1840 self.assertEqual(len(c[0]), 200)
1841
1842 c = inf.count_coverage("chr1", None, inf.get_reference_length("chr1") + 10000)
1843 self.assertEqual(len(c[0]), inf.get_reference_length("chr1"))
1844
1845 def test_count_coverage_without_coordinates_fails(self):
1846 with pysam.AlignmentFile(self.samfilename) as inf:
1847 self.assertRaises(TypeError, inf.count_coverage)
1848
1849 def test_count_coverage_wrong_coordinates_fails(self):
1850 with pysam.AlignmentFile(self.samfilename) as inf:
1851 self.assertRaises(ValueError, inf.count_coverage, "chr1", 200, 100)
1852 self.assertRaises(KeyError, inf.count_coverage, "chrUnknown", 100, 200)
1853
1854 def test_counting_the_same_region_works(self):
1855
1856 with pysam.AlignmentFile(self.samfilename) as inf:
1857 c1 = inf.count_coverage("chr1")
1858 c2 = inf.count_coverage("chr1")
1859 self.assertEqual(c1, c2)
1860
1861 def test_count_coverage_counts_as_expected(self):
1862 chrom = 'chr1'
1863 start = 0
1864 stop = 1000
1865
1866 with pysam.AlignmentFile(self.samfilename) as inf:
1867 manual_counts = self.count_coverage_python(
1868 inf, chrom, start, stop,
1869 lambda read: True,
1870 quality_threshold=0)
1871
1872 fast_counts = inf.count_coverage(
1873 chrom, start, stop,
1874 read_callback=lambda read: True,
1875 quality_threshold=0)
1876
1877 self.assertEqual(list(fast_counts[0]), list(manual_counts[0]))
1878 self.assertEqual(list(fast_counts[1]), list(manual_counts[1]))
1879 self.assertEqual(list(fast_counts[2]), list(manual_counts[2]))
1880 self.assertEqual(list(fast_counts[3]), list(manual_counts[3]))
1881
1882 def test_count_coverage_quality_filter(self):
1883 chrom = 'chr1'
1884 start = 0
1885 stop = 1000
1886 with pysam.AlignmentFile(self.samfilename) as inf:
1887 manual_counts = self.count_coverage_python(
1888 inf, chrom, start, stop,
1889 lambda read: True,
1890 quality_threshold=0)
1891 fast_counts = inf.count_coverage(
1892 chrom, start, stop,
1893 read_callback=lambda read: True,
1894 quality_threshold=15)
1895
1896 # we filtered harder, should be less
1897 for i in range(4):
1898 for r in range(start, stop):
1899 self.assertTrue(fast_counts[i][r] <= manual_counts[i][r])
1900
1901 def test_count_coverage_read_callback(self):
1902 chrom = 'chr1'
1903 start = 0
1904 stop = 1000
1905 with pysam.AlignmentFile(self.samfilename) as inf:
1906 manual_counts = self.count_coverage_python(
1907 inf, chrom, start, stop,
1908 lambda read: read.flag & 0x10,
1909 quality_threshold=0)
1910 fast_counts = inf.count_coverage(
1911 chrom, start, stop,
1912 read_callback=lambda read: True,
1913 quality_threshold=0)
1914
1915 for i in range(4):
1916 for r in range(start, stop):
1917 self.assertTrue(fast_counts[i][r] >= manual_counts[i][r])
1918
1919 fast_counts = inf.count_coverage(
1920 chrom, start, stop,
1921 read_callback=lambda read: read.flag & 0x10,
1922 quality_threshold=0)
1923
1924 self.assertEqual(fast_counts[0], manual_counts[0])
1925 self.assertEqual(fast_counts[1], manual_counts[1])
1926 self.assertEqual(fast_counts[2], manual_counts[2])
1927 self.assertEqual(fast_counts[3], manual_counts[3])
1928
1929 def test_count_coverage_read_all(self):
1930
1931 chrom = 'chr1'
1932 start = 0
1933 stop = 1000
1934
1935 def filter(read):
1936 return not (read.flag & (0x4 | 0x100 | 0x200 | 0x400))
1937
1938 with pysam.AlignmentFile(self.tmpfilename) as samfile:
1939 fast_counts = samfile.count_coverage(
1940 chrom, start, stop,
1941 read_callback='all',
1942 # read_callback = lambda read: ~(read.flag & (0x4 | 0x100 | 0x200 | 0x400)),
1943 quality_threshold=0)
1944 manual_counts = samfile.count_coverage(
1945 chrom, start, stop,
1946 read_callback=lambda read: not(
1947 read.flag & (0x4 | 0x100 | 0x200 | 0x400)),
1948 quality_threshold=0)
1949
1950 self.assertEqual(fast_counts[0], manual_counts[0])
1951 self.assertEqual(fast_counts[1], manual_counts[1])
1952 self.assertEqual(fast_counts[2], manual_counts[2])
1953 self.assertEqual(fast_counts[3], manual_counts[3])
1954
1955 def test_count_coverage_nofilter(self):
1956
1957 with pysam.AlignmentFile(self.samfilename) as inf:
1958 with pysam.AlignmentFile(
1959 self.tmpfilename, 'wb', template=inf) as outf:
1960
1961 for ii, read in enumerate(inf.fetch()):
1962 # if ii % 2 == 0: # setting BFUNMAP makes no sense...
1963 # read.flag = read.flag | 0x4
1964 if ii % 3 == 0:
1965 read.flag = read.flag | 0x100
1966 if ii % 5 == 0:
1967 read.flag = read.flag | 0x200
1968 if ii % 7 == 0:
1969 read.flag = read.flag | 0x400
1970 outf.write(read)
1971
1972 pysam.samtools.index(self.tmpfilename)
1973 chr = 'chr1'
1974 start = 0
1975 stop = 1000
1976
1977 with pysam.AlignmentFile(self.tmpfilename) as inf:
1978 fast_counts = inf.count_coverage(chr, start, stop,
1979 read_callback='nofilter',
1980 quality_threshold=0)
1981
1982 manual_counts = self.count_coverage_python(inf, chr, start, stop,
1983 read_callback=lambda x: True,
1984 quality_threshold=0)
1985
1986 self.assertEqual(fast_counts[0], manual_counts[0])
1987 self.assertEqual(fast_counts[1], manual_counts[1])
1988 self.assertEqual(fast_counts[2], manual_counts[2])
1989 self.assertEqual(fast_counts[3], manual_counts[3])
1990
1991
1992 class TestFindIntrons(unittest.TestCase):
1993 samfilename = os.path.join(BAM_DATADIR, "ex_spliced.bam")
1994
1995 def setUp(self):
1996 self.samfile = pysam.AlignmentFile(self.samfilename)
1997
1998 def tearDown(self):
1999 self.samfile.close()
2000
2001 def test_total(self):
2002 all_read_counts = self.samfile.count()
2003 splice_sites = self.samfile.find_introns(self.samfile.fetch())
2004 # there is a single unspliced read and a single unmapped read in there
2005 self.assertEqual(sum(splice_sites.values()), all_read_counts - 2)
2006
2007 def test_first(self):
2008 reads = list(self.samfile.fetch())[:10]
2009 splice_sites = self.samfile.find_introns(reads)
2010 starts = [14792 + 38 - 1]
2011 stops = [14792 + 38 + 140 - 1]
2012 self.assertEqual(len(splice_sites), 1)
2013 self.assertTrue((starts[0], stops[0]) in splice_sites)
2014 # first one is the unspliced read
2015 self.assertEqual(splice_sites[(starts[0], stops[0])], 9)
2016
2017 def test_all(self):
2018 reads = list(self.samfile.fetch())
2019 splice_sites = self.samfile.find_introns(reads)
2020 should = collections.Counter({
2021 (14829, 14969): 33,
2022 (15038, 15795): 24,
2023 (15947, 16606): 3,
2024 (16765, 16857): 9,
2025 (16765, 16875): 1,
2026 (17055, 17232): 19,
2027 (17055, 17605): 3,
2028 (17055, 17914): 1,
2029 (17368, 17605): 7,
2030 })
2031 self.assertEqual(should, splice_sites)
2032
2033
2034 class TestLogging(unittest.TestCase):
2035
2036 '''test around bug issue 42,
2037
2038 failed in versions < 0.4
2039 '''
2040
2041 def check(self, bamfile, log):
2042
2043 if log:
2044 logger = logging.getLogger('franklin')
2045 logger.setLevel(logging.INFO)
2046 formatter = logging.Formatter(
2047 '%(asctime)s %(levelname)s %(message)s')
2048 log_hand = logging.FileHandler('log.txt')
2049 log_hand.setFormatter(formatter)
2050 logger.addHandler(log_hand)
2051
2052 with pysam.AlignmentFile(bamfile, 'rb') as bam:
2053 cols = bam.pileup()
2054 self.assertTrue(True)
2055
2056 def tearDown(self):
2057 if os.path.exists('log.txt'):
2058 os.unlink('log.txt')
2059
2060 def testFail1(self):
2061 self.check(os.path.join(BAM_DATADIR, "ex9_fail.bam"),
2062 False)
2063 self.check(os.path.join(BAM_DATADIR, "ex9_fail.bam"),
2064 True)
2065
2066 def testNoFail1(self):
2067 self.check(os.path.join(BAM_DATADIR, "ex9_nofail.bam"),
2068 False)
2069 self.check(os.path.join(BAM_DATADIR, "ex9_nofail.bam"),
2070 True)
2071
2072 def testNoFail2(self):
2073 self.check(os.path.join(BAM_DATADIR, "ex9_nofail.bam"),
2074 True)
2075 self.check(os.path.join(BAM_DATADIR, "ex9_nofail.bam"),
2076 True)
2077
2078 # TODOS
2079 # 1. finish testing all properties within pileup objects
2080 # 2. check exceptions and bad input problems (missing files, optional fields that aren't present, etc...)
2081 # 3. check: presence of sequence
2082
2083
2084 class TestAlignmentFileUtilityFunctions(unittest.TestCase):
2085
2086 def testCount(self):
2087
2088 with pysam.AlignmentFile(
2089 os.path.join(BAM_DATADIR, "ex1.bam"),
2090 "rb") as samfile:
2091
2092 for contig in ("chr1", "chr2"):
2093 for start in range(0, 2000, 100):
2094 end = start + 1
2095 self.assertEqual(
2096 len(list(samfile.fetch(contig, start, end))),
2097 samfile.count(contig, start, end),
2098 'number mismatch for %s:%i-%i %i != %i' % (
2099 contig, start, end,
2100 len(list(samfile.fetch(contig, start, end))),
2101 samfile.count(contig, start, end)))
2102
2103 # test empty intervals
2104 self.assertEqual(
2105 len(list(samfile.fetch(contig, start, start))),
2106 samfile.count(contig, start, start),
2107 'number mismatch for %s:%i-%i %i != %i' % (
2108 contig, start, start,
2109 len(list(samfile.fetch(contig, start, start))),
2110 samfile.count(contig, start, start)))
2111
2112 # test half empty intervals
2113 self.assertEqual(len(list(samfile.fetch(contig, start))),
2114 samfile.count(contig, start))
2115
2116 self.assertEqual(
2117 len(list(samfile.fetch(contig, start))),
2118 samfile.count(contig, start),
2119 'number mismatch for %s:%i %i != %i' % (
2120 contig, start,
2121 len(list(samfile.fetch(contig, start))),
2122 samfile.count(contig, start)))
2123
2124 def testMate(self):
2125 '''test mate access.'''
2126
2127 with open(os.path.join(BAM_DATADIR, "ex1.sam"), "rb") as inf:
2128 readnames = [x.decode("ascii").split("\t")[0] for x in inf.readlines()]
2129
2130 counts = collections.defaultdict(int)
2131 for x in readnames:
2132 counts[x] += 1
2133
2134 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"),
2135 "rb") as samfile:
2136
2137 for read in samfile.fetch():
2138 if not read.is_paired:
2139 self.assertRaises(ValueError, samfile.mate, read)
2140 elif read.mate_is_unmapped:
2141 self.assertRaises(ValueError, samfile.mate, read)
2142 else:
2143 if counts[read.query_name] == 1:
2144 self.assertRaises(ValueError, samfile.mate, read)
2145 else:
2146 mate = samfile.mate(read)
2147 self.assertEqual(read.query_name, mate.query_name)
2148 self.assertEqual(read.is_read1, mate.is_read2)
2149 self.assertEqual(read.is_read2, mate.is_read1)
2150 self.assertEqual(
2151 read.reference_start, mate.next_reference_start)
2152 self.assertEqual(
2153 read.next_reference_start, mate.reference_start)
2154
2155 def testIndexStats(self):
2156 '''test if total number of mapped/unmapped reads is correct.'''
2157
2158 with pysam.AlignmentFile(os.path.join(BAM_DATADIR, "ex1.bam"),
2159 "rb") as samfile:
2160 self.assertEqual(samfile.mapped, 3235)
2161 self.assertEqual(samfile.unmapped, 35)
2162 self.assertEqual(samfile.nocoordinate, 0)
2163
2164
2165 class TestMappedUnmapped(unittest.TestCase):
2166 filename = "test_mapped_unmapped.bam"
2167
2168 def test_counts_of_mapped_and_unmapped_are_correct(self):
2169
2170 with pysam.AlignmentFile(os.path.join(BAM_DATADIR,
2171 self.filename)) as inf:
2172 unmapped_flag = 0
2173 unmapped_nopos = 0
2174 mapped_flag = 0
2175 for x in inf.fetch(until_eof=True):
2176 if x.is_unmapped:
2177 if x.reference_id < 0:
2178 unmapped_nopos += 1
2179 else:
2180 unmapped_flag += 1
2181 else:
2182 mapped_flag += 1
2183
2184 self.assertEqual(inf.mapped, mapped_flag)
2185 self.assertEqual(inf.unmapped, unmapped_flag + unmapped_nopos)
2186
2187 inf.reset()
2188 self.assertEqual(inf.count(),
2189 inf.mapped + unmapped_flag)
2190
2191 inf.reset()
2192 self.assertEqual(inf.count(until_eof=True),
2193 inf.mapped + unmapped_flag + unmapped_nopos)
2194
2195 inf.reset()
2196 self.assertEqual(inf.count(read_callback="all"),
2197 inf.mapped)
2198
2199 inf.reset()
2200 self.assertEqual(inf.count(until_eof=True, read_callback="all"),
2201 inf.mapped)
2202
2203 def test_counts_of_mapped_and_unmapped_are_correct_per_chromosome(self):
2204
2205 with pysam.AlignmentFile(os.path.join(BAM_DATADIR,
2206 self.filename)) as inf:
2207
2208 counts = inf.get_index_statistics()
2209
2210 counts_contigs = [x.contig for x in counts]
2211 self.assertEqual(sorted(counts_contigs),
2212 sorted(inf.references))
2213
2214 for contig in inf.references:
2215 unmapped_flag = 0
2216 unmapped_nopos = 0
2217 mapped_flag = 0
2218 for x in inf.fetch(contig=contig):
2219 if x.is_unmapped:
2220 unmapped_flag += 1
2221 else:
2222 mapped_flag += 1
2223
2224 cc = [c for c in counts if c.contig == contig][0]
2225 self.assertEqual(cc.mapped, mapped_flag)
2226 self.assertEqual(cc.unmapped, unmapped_flag)
2227 self.assertEqual(cc.total, mapped_flag + unmapped_flag)
2228
2229
2230 class TestSamtoolsProxy(unittest.TestCase):
2231
2232 '''tests for sanity checking access to samtools functions.'''
2233
2234 def testIndex(self):
2235 self.assertRaises(IOError, pysam.samtools.index, "missing_file")
2236
2237 def testView(self):
2238 # note that view still echos "open: No such file or directory"
2239 self.assertRaises(pysam.SamtoolsError,
2240 pysam.samtools.view,
2241 "missing_file")
2242
2243 def testSort(self):
2244 self.assertRaises(pysam.SamtoolsError,
2245 pysam.samtools.sort,
2246 "missing_file")
2247
2248
2249 class TestAlignmentFileIndex(unittest.TestCase):
2250
2251 def testIndex(self):
2252 samfile = pysam.AlignmentFile(
2253 os.path.join(BAM_DATADIR, "ex1.bam"),
2254 "rb")
2255 index = pysam.IndexedReads(samfile)
2256 index.build()
2257 reads = collections.defaultdict(int)
2258
2259 for read in samfile:
2260 reads[read.query_name] += 1
2261
2262 for qname, counts in reads.items():
2263 found = list(index.find(qname))
2264 self.assertEqual(len(found), counts)
2265 for x in found:
2266 self.assertEqual(x.query_name, qname)
2267
2268
2269 class TestExplicitIndex(unittest.TestCase):
2270
2271 def testExplicitIndexBAM(self):
2272 with pysam.AlignmentFile(
2273 os.path.join(BAM_DATADIR, "explicit_index.bam"),
2274 "rb",
2275 filepath_index=os.path.join(BAM_DATADIR, 'ex1.bam.bai')) as samfile:
2276 samfile.fetch("chr1")
2277
2278 def testExplicitIndexCRAM(self):
2279 with pysam.AlignmentFile(
2280 os.path.join(BAM_DATADIR, "explicit_index.cram"),
2281 "rc",
2282 filepath_index=os.path.join(BAM_DATADIR, 'ex1.cram.crai')) as samfile:
2283 samfile.fetch("chr1")
2284
2285 def testRemoteExplicitIndexBAM(self):
2286 if not check_url(
2287 "http://genserv.anat.ox.ac.uk/downloads/pysam/test/noindex.bam"):
2288 return
2289
2290 with pysam.AlignmentFile(
2291 "http://genserv.anat.ox.ac.uk/downloads/pysam/test/noindex.bam",
2292 "rb",
2293 filepath_index=os.path.join(BAM_DATADIR, 'ex1.bam.bai')) as samfile:
2294 samfile.fetch("chr1")
2295
2296
2297 class TestVerbosity(unittest.TestCase):
2298
2299 '''test if setting/getting of verbosity works.'''
2300
2301 def testVerbosity(self):
2302 self.assertEqual(pysam.get_verbosity(), 3)
2303 old = pysam.set_verbosity(0)
2304 self.assertEqual(pysam.get_verbosity(), 0)
2305 new = pysam.set_verbosity(old)
2306 self.assertEqual(new, 0)
2307 self.assertEqual(pysam.get_verbosity(), 3)
2308
2309
2310 class TestSanityCheckingBAM(unittest.TestCase):
2311
2312 mode = "wb"
2313
2314 def check_write(self, read):
2315
2316 fn = "tmp_test_sanity_check.bam"
2317 names = ["chr1"]
2318 lengths = [10000]
2319 with pysam.AlignmentFile(
2320 fn,
2321 self.mode,
2322 reference_names=names,
2323 reference_lengths=lengths) as outf:
2324 outf.write(read)
2325
2326 if os.path.exists(fn):
2327 os.unlink(fn)
2328
2329 def test_empty_read_gives_value_error(self):
2330 read = pysam.AlignedSegment()
2331 self.check_write(read)
2332
2333
2334 class TestLargeCigar(unittest.TestCase):
2335
2336 def setUp(self):
2337 self.read_length = 70000
2338 self.header = pysam.AlignmentHeader.from_references(
2339 ["chr1", "chr2"],
2340 [self.read_length * 2, self.read_length * 2])
2341
2342 def build_read(self):
2343 '''build an example read.'''
2344
2345 a = pysam.AlignedSegment(self.header)
2346 l = self.read_length
2347 a.query_name = "read_12345"
2348 a.query_sequence = "A" * (l + 1)
2349 a.flag = 0
2350 a.reference_id = 0
2351 a.reference_start = 20
2352 a.mapping_quality = 20
2353 a.cigarstring = "1M1D" * l + "1M"
2354 self.assertEqual(len(a.cigartuples), 2 * l + 1)
2355 a.next_reference_id = 0
2356 a.next_reference_start = 0
2357 a.template_length = l
2358 a.query_qualities = pysam.qualitystring_to_array("1") * (l + 1)
2359 return a
2360
2361 def check_read(self, read, mode="bam"):
2362 fn = get_temp_filename("tmp_largecigar.{}".format(mode))
2363 fn_reference = get_temp_filename("tmp_largecigar.fa")
2364
2365 nrows = int(self.read_length * 2 / 80)
2366
2367 s = "\n".join(["A" * 80 for x in range(nrows)])
2368 with open(fn_reference, "w") as outf:
2369 outf.write(">chr1\n{seq}\n>chr2\n{seq}\n".format(
2370 seq=s))
2371
2372 if mode == "bam":
2373 write_mode = "wb"
2374 elif mode == "sam":
2375 write_mode = "w"
2376 elif mode == "cram":
2377 write_mode = "wc"
2378
2379 with pysam.AlignmentFile(fn, write_mode,
2380 header=self.header,
2381 reference_filename=fn_reference) as outf:
2382 outf.write(read)
2383 with pysam.AlignmentFile(fn) as inf:
2384 ref_read = next(inf)
2385
2386 if mode == "cram":
2387 # in CRAM, the tag field is kept, while it is emptied by the BAM/SAM reader
2388 self.assertEqual(read.cigarstring, ref_read.cigarstring)
2389 else:
2390 self.assertEqual(read, ref_read)
2391
2392 os.unlink(fn)
2393 os.unlink(fn_reference)
2394
2395 def test_reading_writing_sam(self):
2396 read = self.build_read()
2397 self.check_read(read, mode="sam")
2398
2399 def test_reading_writing_bam(self):
2400 read = self.build_read()
2401 self.check_read(read, mode="bam")
2402
2403 @unittest.skip("fails on linux - https issue?")
2404 def test_reading_writing_cram(self):
2405 # The following test fails with htslib 1.9, but worked with previous versions.
2406 # Error is:
2407 # [W::find_file_url] Failed to open reference "https://www.ebi.ac.uk/ena/cram/md5/ac9fac7c3e9c476f74f1d0e47abc8be2": Input/output error
2408 # Error can be reproduced using samtools 1.9 command line.
2409 # Could be a conda configuration issue, see
2410 # https://github.com/bioconda/bioconda-recipes/issues/9056
2411 return
2412 read = self.build_read()
2413 self.check_read(read, mode="cram")
2414
2415 # SAM writing fails, as query length is 0
2416 # class TestSanityCheckingSAM(TestSanityCheckingSAM):
2417 # mode = "w"
2418
2419 if __name__ == "__main__":
2420 print("starting tests")
2421 unittest.main()
2422 print("completed tests")