Debian Codegraph @

tests/AlignmentFile_test.py

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