Debian Codegraph @

tests/tabix_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 os
9 import shutil
10 import gzip
11 import pysam
12 import unittest
13 import glob
14 import re
15 from TestUtils import checkBinaryEqual, checkGZBinaryEqual, check_url, \
16 load_and_convert, make_data_files, TABIX_DATADIR, get_temp_filename
17
18
19 def setUpModule():
20 make_data_files(TABIX_DATADIR)
21
22
23 def myzip_open(infile, mode="r"):
24 '''open compressed file and decode.'''
25
26 def _convert(f):
27 for l in f:
28 yield l.decode("ascii")
29
30 if mode == "r":
31 return _convert(gzip.open(infile, "r"))
32
33
34 def splitToBytes(s):
35 '''split string and return list of bytes.'''
36 return [x.encode("ascii") for x in s.split("\t")]
37
38
39 class TestIndexing(unittest.TestCase):
40 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
41 filename_idx = os.path.join(TABIX_DATADIR, "example.gtf.gz.tbi")
42
43 def setUp(self):
44
45 self.tmpfilename = get_temp_filename(suffix="gtf.gz")
46 shutil.copyfile(self.filename, self.tmpfilename)
47
48 def test_indexing_with_preset_works(self):
49 '''test indexing via preset.'''
50
51 pysam.tabix_index(self.tmpfilename, preset="gff")
52 self.assertTrue(checkGZBinaryEqual(
53 self.tmpfilename + ".tbi", self.filename_idx))
54
55 def test_indexing_to_custom_location_works(self):
56 '''test indexing a file with a non-default location.'''
57
58 index_path = get_temp_filename(suffix='custom.tbi')
59 pysam.tabix_index(self.tmpfilename, preset="gff",
60 index=index_path, force=True)
61 self.assertTrue(checkGZBinaryEqual(index_path, self.filename_idx))
62 os.unlink(index_path)
63
64 def test_indexing_with_explict_columns_works(self):
65 '''test indexing via preset.'''
66
67 pysam.tabix_index(self.tmpfilename,
68 seq_col=0,
69 start_col=3,
70 end_col=4,
71 line_skip=0,
72 zerobased=False)
73 self.assertTrue(checkGZBinaryEqual(
74 self.tmpfilename + ".tbi", self.filename_idx))
75
76 def test_indexing_with_lineskipping_works(self):
77 '''test indexing via preset and lineskip.'''
78 pysam.tabix_index(self.tmpfilename,
79 seq_col=0,
80 start_col=3,
81 end_col=4,
82 line_skip=1,
83 zerobased=False)
84 self.assertFalse(checkGZBinaryEqual(
85 self.tmpfilename + ".tbi", self.filename_idx))
86
87 def tearDown(self):
88 os.unlink(self.tmpfilename)
89 if os.path.exists(self.tmpfilename + ".tbi"):
90 os.unlink(self.tmpfilename + ".tbi")
91
92
93 class TestCompression(unittest.TestCase):
94 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
95 filename_idx = os.path.join(TABIX_DATADIR, "example.gtf.gz.tbi")
96 preset = "gff"
97
98 def setUp(self):
99 self.tmpfilename = get_temp_filename(suffix="gtf")
100 with gzip.open(self.filename, "rb") as infile, \
101 open(self.tmpfilename, "wb") as outfile:
102 outfile.write(infile.read())
103
104 def testCompression(self):
105 '''see also issue 106'''
106 pysam.tabix_compress(self.tmpfilename, self.tmpfilename + ".gz")
107 checkBinaryEqual(self.tmpfilename, self.tmpfilename + ".gz")
108
109 def testIndexPresetUncompressed(self):
110 '''test indexing via preset.'''
111
112 pysam.tabix_index(self.tmpfilename, preset=self.preset)
113 # check if uncompressed file has been removed
114 self.assertEqual(os.path.exists(self.tmpfilename), False)
115 checkBinaryEqual(self.tmpfilename + ".gz", self.filename)
116 checkBinaryEqual(self.tmpfilename + ".gz.tbi", self.filename_idx)
117
118 def testIndexPresetCompressed(self):
119 '''test indexing via preset.'''
120
121 pysam.tabix_compress(self.tmpfilename, self.tmpfilename + ".gz")
122 pysam.tabix_index(self.tmpfilename + ".gz", preset=self.preset)
123 checkBinaryEqual(self.tmpfilename + ".gz", self.filename)
124 checkBinaryEqual(self.tmpfilename + ".gz.tbi", self.filename_idx)
125
126 def tearDown(self):
127 if os.path.exists(self.tmpfilename):
128 os.unlink(self.tmpfilename)
129 if os.path.exists(self.tmpfilename + ".gz"):
130 os.unlink(self.tmpfilename + ".gz")
131 if os.path.exists(self.tmpfilename + ".gz.tbi"):
132 os.unlink(self.tmpfilename + ".gz.tbi")
133
134
135 class TestCompressionSam(TestCompression):
136 filename = os.path.join(TABIX_DATADIR, "example.sam.gz")
137 filename_index = os.path.join(TABIX_DATADIR, "example.sam.gz.tbi")
138 preset = "sam"
139
140
141 class TestCompressionBed(TestCompression):
142 filename = os.path.join(TABIX_DATADIR, "example.bed.gz")
143 filename_index = os.path.join(TABIX_DATADIR, "example.bed.gz.tbi")
144 preset = "bed"
145
146
147 class TestCompressionVCF(TestCompression):
148 filename = os.path.join(TABIX_DATADIR, "example.vcf.gz")
149 filename_index = os.path.join(TABIX_DATADIR, "example.vcf.gz.tbi")
150 preset = "vcf"
151
152
153 class IterationTest(unittest.TestCase):
154
155 with_comments = False
156
157 def setUp(self):
158
159 lines = []
160 with gzip.open(self.filename, "rb") as inf:
161 for line in inf:
162 line = line.decode('ascii')
163 if line.startswith("#"):
164 if not self.with_comments:
165 continue
166 lines.append(line)
167
168 # creates index of contig, start, end, adds content without newline.
169 self.compare = [
170 (x[0][0], int(x[0][3]), int(x[0][4]), x[1])
171 for x in [(y.split("\t"), y[:-1]) for y in lines
172 if not y.startswith("#")]]
173
174 self.comments = [x[:-1] for x in lines if x.startswith("#")]
175
176 def getSubset(self, contig=None, start=None, end=None):
177
178 if contig is None:
179 # all lines
180 subset = [x[3] for x in self.compare]
181 else:
182 if start is not None and end is None:
183 # until end of contig
184 subset = [x[3]
185 for x in self.compare if x[0] == contig and
186 x[2] > start]
187 elif start is None and end is not None:
188 # from start of contig
189 subset = [x[3]
190 for x in self.compare if x[0] == contig and
191 x[1] <= end]
192 elif start is None and end is None:
193 subset = [x[3] for x in self.compare if x[0] == contig]
194 else:
195 # all within interval
196 subset = [x[3] for x in self.compare if x[0] == contig and
197 min(x[2], end) - max(x[1], start) > 0]
198
199 if self.with_comments:
200 subset.extend(self.comments)
201
202 return subset
203
204 def checkPairwise(self, result, ref):
205 '''check pairwise results.
206 '''
207 result.sort()
208 ref.sort()
209 a = set(result)
210 b = set(ref)
211
212 self.assertEqual(
213 len(result), len(ref),
214 "unexpected number of results: "
215 "result=%i, expected ref=%i, differences are %s: %s"
216 % (len(result), len(ref),
217 a.difference(b),
218 b.difference(a)))
219
220 for x, d in enumerate(list(zip(result, ref))):
221 self.assertEqual(
222 d[0], d[1],
223 "unexpected results in pair %i:\n'%s', expected\n'%s'" %
224 (x, d[0], d[1]))
225
226
227 class TestGZFile(IterationTest):
228
229 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
230 with_comments = True
231
232 def setUp(self):
233 super().setUp()
234 self.gzfile = pysam.GZIterator(self.filename)
235
236 def testAll(self):
237 result = list(self.gzfile)
238 ref = self.getSubset()
239 self.checkPairwise(result, ref)
240
241
242 class TestIterationWithoutComments(IterationTest):
243
244 '''test iterating with TabixFile.fetch() when
245 there are no comments in the file.'''
246
247 filename = os.path.join(TABIX_DATADIR,
248 "example.gtf.gz")
249
250 def setUp(self):
251 super().setUp()
252 self.tabix = pysam.TabixFile(self.filename)
253
254 def tearDown(self):
255 self.tabix.close()
256
257 def testRegionStrings(self):
258 """test if access with various region strings
259 works"""
260
261 self.assertEqual(218, len(list(
262 self.tabix.fetch("chr1"))))
263 self.assertEqual(218, len(list(
264 self.tabix.fetch("chr1", 1000))))
265 self.assertEqual(218, len(list(
266 self.tabix.fetch("chr1", end=1000000))))
267 self.assertEqual(218, len(list(
268 self.tabix.fetch("chr1", 1000, 1000000))))
269
270 def testAll(self):
271 result = list(self.tabix.fetch())
272 ref = self.getSubset()
273 self.checkPairwise(result, ref)
274
275 def testPerContig(self):
276 for contig in ("chr1", "chr2", "chr1", "chr2"):
277 result = list(self.tabix.fetch(contig))
278 ref = self.getSubset(contig)
279 self.checkPairwise(result, ref)
280
281 def testPerContigToEnd(self):
282
283 end = None
284 for contig in ("chr1", "chr2", "chr1", "chr2"):
285 for start in range(0, 200000, 1000):
286 result = list(self.tabix.fetch(contig, start, end))
287 ref = self.getSubset(contig, start, end)
288 self.checkPairwise(result, ref)
289
290 def testPerContigFromStart(self):
291
292 start = None
293 for contig in ("chr1", "chr2", "chr1", "chr2"):
294 for end in range(0, 200000, 1000):
295 result = list(self.tabix.fetch(contig, start, end))
296 ref = self.getSubset(contig, start, end)
297 self.checkPairwise(result, ref)
298
299 def testPerContig2(self):
300
301 start, end = None, None
302 for contig in ("chr1", "chr2", "chr1", "chr2"):
303 result = list(self.tabix.fetch(contig, start, end))
304 ref = self.getSubset(contig, start, end)
305 self.checkPairwise(result, ref)
306
307 def testPerInterval(self):
308
309 start, end = None, None
310 for contig in ("chr1", "chr2", "chr1", "chr2"):
311 for start in range(0, 200000, 2000):
312 for end in range(start, start + 2000, 500):
313 result = list(self.tabix.fetch(contig, start, end))
314 ref = self.getSubset(contig, start, end)
315 self.checkPairwise(result, ref)
316
317 def testInvalidIntervals(self):
318
319 # invalid intervals (start > end)
320 self.assertRaises(ValueError, self.tabix.fetch, "chr1", 0, -10)
321 self.assertRaises(ValueError, self.tabix.fetch, "chr1", 200, 0)
322
323 # out of range intervals
324 self.assertRaises(ValueError, self.tabix.fetch, "chr1", -10, 200)
325 self.assertRaises(ValueError, self.tabix.fetch, "chr1", -10, -20)
326
327 # unknown chromosome
328 self.assertRaises(ValueError, self.tabix.fetch, "chrUn")
329
330 # out of range access
331 # to be implemented
332 # self.assertRaises(IndexError, self.tabix.fetch, "chr1", 1000000, 2000000)
333
334 # raise no error for empty intervals
335 self.tabix.fetch("chr1", 100, 100)
336
337 def testGetContigs(self):
338 self.assertEqual(sorted(self.tabix.contigs), ["chr1", "chr2"])
339 # check that contigs is read-only
340 self.assertRaises(
341 AttributeError, setattr, self.tabix, "contigs", ["chr1", "chr2"])
342
343 def testHeader(self):
344 ref = []
345 with gzip.open(self.filename) as inf:
346 for x in inf:
347 x = x.decode("ascii")
348 if not x.startswith("#"):
349 break
350 ref.append(x[:-1])
351
352 header = list(self.tabix.header)
353 self.assertEqual(ref, header)
354
355 def testReopening(self):
356 '''test repeated opening of the same file.'''
357 def func1():
358 # opens any tabix file
359 with pysam.TabixFile(self.filename) as inf:
360 pass
361
362 for i in range(1000):
363 func1()
364
365
366 class TestIterationWithComments(TestIterationWithoutComments):
367
368 '''test iterating with TabixFile.fetch() when
369 there are comments in the file.
370
371 Tests will create plenty of warnings on stderr.
372 '''
373
374 filename = os.path.join(TABIX_DATADIR, "example_comments.gtf.gz")
375
376
377 class TestIterators(unittest.TestCase):
378 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
379
380 iterator = pysam.tabix_generic_iterator
381 parser = pysam.asTuple
382 is_compressed = False
383
384 def setUp(self):
385
386 self.tabix = pysam.TabixFile(self.filename)
387 self.compare = load_and_convert(self.filename)
388 self.tmpfilename_uncompressed = 'tmp_TestIterators'
389 with gzip.open(self.filename, "rb") as infile, \
390 open(self.tmpfilename_uncompressed, "wb") as outfile:
391 outfile.write(infile.read())
392
393 def tearDown(self):
394 self.tabix.close()
395 os.unlink(self.tmpfilename_uncompressed)
396
397 def open(self):
398
399 if self.is_compressed:
400 infile = gzip.open(self.filename)
401 else:
402 infile = open(self.tmpfilename_uncompressed)
403 return infile
404
405 def testIteration(self):
406
407 with self.open() as infile:
408 for x, r in enumerate(self.iterator(infile, self.parser())):
409 self.assertEqual(self.compare[x], list(r))
410 self.assertEqual(len(self.compare[x]), len(r))
411
412 # test indexing
413 for c in range(0, len(r)):
414 self.assertEqual(self.compare[x][c], r[c])
415
416 # test slicing access
417 for c in range(0, len(r) - 1):
418 for cc in range(c + 1, len(r)):
419 self.assertEqual(self.compare[x][c:cc],
420 r[c:cc])
421
422 def testClosedFile(self):
423 '''test for error when iterating from closed file.'''
424 infile = self.open()
425 infile.close()
426
427 # iterating from a closed file should raise a value error
428 self.assertRaises(ValueError, self.iterator, infile, self.parser())
429
430 def testClosedFileIteration(self):
431 '''test for error when iterating from file that has been closed'''
432
433 infile = self.open()
434
435 i = self.iterator(infile, self.parser())
436 x = next(i)
437 infile.close()
438 # Not implemented
439 # self.assertRaises(ValueError, i.next)
440
441
442 class TestIteratorsGenericCompressed(TestIterators):
443 is_compressed = True
444
445
446 class TestIteratorsFileCompressed(TestIterators):
447 iterator = pysam.tabix_file_iterator
448 is_compressed = True
449
450
451 class TestIteratorsFileUncompressed(TestIterators):
452 iterator = pysam.tabix_file_iterator
453 is_compressed = False
454
455
456 class TestIterationMalformattedGTFFiles(unittest.TestCase):
457
458 '''test reading from malformatted gtf files.'''
459
460 iterator = pysam.tabix_generic_iterator
461 parser = pysam.asGTF
462
463 def testGTFTooManyFields(self):
464
465 with gzip.open(os.path.join(
466 TABIX_DATADIR,
467 "gtf_toomany_fields.gtf.gz")) as infile:
468 iterator = self.iterator(
469 infile,
470 parser=self.parser())
471 self.assertRaises(ValueError, iterator.__next__)
472
473 def testGTFTooFewFields(self):
474
475 with gzip.open(os.path.join(
476 TABIX_DATADIR,
477 "gtf_toofew_fields.gtf.gz")) as infile:
478 iterator = self.iterator(
479 infile,
480 parser=self.parser())
481 self.assertRaises(ValueError, iterator.__next__)
482
483
484 class TestBed(unittest.TestCase):
485 filename = os.path.join(TABIX_DATADIR, "example.bed.gz")
486
487 def setUp(self):
488
489 self.tabix = pysam.TabixFile(self.filename)
490 self.compare = load_and_convert(self.filename)
491
492 def tearDown(self):
493 self.tabix.close()
494
495 def testRead(self):
496
497 for x, r in enumerate(self.tabix.fetch(parser=pysam.asBed())):
498 c = self.compare[x]
499 self.assertEqual(len(c), len(r))
500 self.assertEqual(c, str(r).split("\t"))
501 self.assertEqual(c[0], r.contig)
502 self.assertEqual(int(c[1]), r.start)
503 self.assertEqual(int(c[2]), r.end)
504 # Needs lambda so that the property getter isn't called too soon
505 self.assertRaises(KeyError, lambda: r.name)
506 self.assertRaises(KeyError, lambda: r.score)
507 self.assertEqual(list(c), list(r))
508 self.assertEqual("\t".join(map(str, c)),
509 str(r))
510
511 def testWrite(self):
512
513 for x, r in enumerate(self.tabix.fetch(parser=pysam.asBed())):
514 c = self.compare[x]
515 self.assertEqual(c, str(r).split("\t"))
516 self.assertEqual(list(c), list(r))
517
518 r.contig = "test"
519 self.assertEqual("test", r.contig)
520 self.assertEqual("test", r[0])
521
522 r.start += 1
523 self.assertEqual(int(c[1]) + 1, r.start)
524 self.assertEqual(str(int(c[1]) + 1), r[1])
525
526 r.end += 1
527 self.assertEqual(int(c[2]) + 1, r.end)
528 self.assertEqual(str(int(c[2]) + 1), r[2])
529
530 with self.assertRaises(IndexError):
531 r.name = "test"
532
533 with self.assertRaises(IndexError):
534 r.score = 1
535
536
537 class TestVCF(unittest.TestCase):
538
539 filename = os.path.join(TABIX_DATADIR, "example.vcf40")
540
541 def setUp(self):
542 self.tmpfilename = get_temp_filename(suffix="vcf")
543 shutil.copyfile(self.filename, self.tmpfilename)
544 pysam.tabix_index(self.tmpfilename, preset="vcf")
545
546 def tearDown(self):
547 os.unlink(self.tmpfilename + ".gz")
548 if os.path.exists(self.tmpfilename + ".gz.tbi"):
549 os.unlink(self.tmpfilename + ".gz.tbi")
550
551
552 class TestUnicode(unittest.TestCase):
553
554 '''test reading from a file with non-ascii characters.'''
555
556 filename = os.path.join(TABIX_DATADIR, "example_unicode.vcf")
557
558 def setUp(self):
559 self.tmpfilename = get_temp_filename(suffix="vcf")
560 shutil.copyfile(self.filename, self.tmpfilename)
561 pysam.tabix_index(self.tmpfilename, preset="vcf")
562
563 def tearDown(self):
564 os.unlink(self.tmpfilename + ".gz")
565 if os.path.exists(self.tmpfilename + ".gz.tbi"):
566 os.unlink(self.tmpfilename + ".gz.tbi")
567
568 def testFromTabix(self):
569
570 # use ascii encoding - should raise error
571 with pysam.TabixFile(
572 self.tmpfilename + ".gz", encoding="ascii") as t:
573 results = list(t.fetch(parser=pysam.asVCF()))
574 self.assertRaises(UnicodeDecodeError,
575 getattr, results[1], "id")
576
577 with pysam.TabixFile(
578 self.tmpfilename + ".gz", encoding="utf-8") as t:
579 results = list(t.fetch(parser=pysam.asVCF()))
580 self.assertEqual(getattr(results[1], "id"), u"Rene\xe9")
581
582 def testFromVCF(self):
583 self.vcf = pysam.VCF()
584 self.assertRaises(
585 UnicodeDecodeError,
586 self.vcf.connect,
587 self.tmpfilename + ".gz",
588 "ascii")
589 self.vcf.connect(self.tmpfilename + ".gz", encoding="utf-8")
590 v = self.vcf.getsamples()[0]
591
592
593 class TestVCFFromTabix(TestVCF):
594
595 columns = ("contig", "pos", "id",
596 "ref", "alt", "qual",
597 "filter", "info", "format")
598
599 def setUp(self):
600 super().setUp()
601
602 self.tabix = pysam.TabixFile(self.tmpfilename + ".gz")
603 self.compare = load_and_convert(self.filename)
604
605 def tearDown(self):
606 self.tabix.close()
607 super().tearDown()
608
609 def testRead(self):
610
611 ncolumns = len(self.columns)
612
613 for x, r in enumerate(self.tabix.fetch(parser=pysam.asVCF())):
614 c = self.compare[x]
615 for y, field in enumerate(self.columns):
616 # it is ok to have a missing format column
617 if y == 8 and y == len(c):
618 continue
619 if field == "pos":
620 self.assertEqual(int(c[y]) - 1, getattr(r, field))
621 self.assertEqual(int(c[y]) - 1, r.pos)
622 else:
623 self.assertEqual(c[y], getattr(r, field),
624 "mismatch in field %s: %s != %s" %
625 (field, c[y], getattr(r, field)))
626 if len(c) == 8:
627 self.assertEqual(0, len(r))
628 else:
629 self.assertEqual(len(c), len(r) + ncolumns)
630
631 for y in range(len(c) - ncolumns):
632 self.assertEqual(c[ncolumns + y], r[y])
633 self.assertEqual("\t".join(map(str, c)),
634 str(r))
635
636 def testWrite(self):
637
638 ncolumns = len(self.columns)
639
640 for x, r in enumerate(self.tabix.fetch(parser=pysam.asVCF())):
641 c = self.compare[x]
642 # check unmodified string
643 cmp_string = str(r)
644 ref_string = "\t".join([x for x in c])
645
646 self.assertEqual(ref_string, cmp_string)
647
648 # set fields and compare field-wise
649 for y, field in enumerate(self.columns):
650 # it is ok to have a missing format column
651 if y == 8 and y == len(c):
652 continue
653 if field == "pos":
654 rpos = getattr(r, field)
655 self.assertEqual(int(c[y]) - 1, rpos)
656 self.assertEqual(int(c[y]) - 1, r.pos)
657 # increment pos by 1
658 setattr(r, field, rpos + 1)
659 self.assertEqual(getattr(r, field), rpos + 1)
660 c[y] = str(int(c[y]) + 1)
661 else:
662 setattr(r, field, "test_%i" % y)
663 c[y] = "test_%i" % y
664 self.assertEqual(c[y], getattr(r, field),
665 "mismatch in field %s: %s != %s" %
666 (field, c[y], getattr(r, field)))
667
668 if len(c) == 8:
669 self.assertEqual(0, len(r))
670 else:
671 self.assertEqual(len(c), len(r) + ncolumns)
672
673 for y in range(len(c) - ncolumns):
674 c[ncolumns + y] = "test_%i" % y
675 r[y] = "test_%i" % y
676 self.assertEqual(c[ncolumns + y], r[y])
677
678
679 class TestVCFFromVCF(TestVCF):
680
681 columns = ("chrom", "pos", "id",
682 "ref", "alt", "qual",
683 "filter", "info", "format")
684
685 # tests failing while parsing
686 fail_on_parsing = (
687 (5, "Flag fields should not have a value"),
688 (9, "aouao"),
689 (12, "Error BAD_NUMBER_OF_PARAMETERS"),
690 (13, "aoeu"),
691 (18, "Error BAD_NUMBER_OF_PARAMETERS"),
692 (24, "Error HEADING_NOT_SEPARATED_BY_TABS"))
693
694 # tests failing on opening
695 fail_on_opening = ((24, "Error HEADING_NOT_SEPARATED_BY_TABS"),
696 )
697
698 fail_on_samples = []
699
700 check_samples = False
701 coordinate_offset = 1
702
703 # value returned for missing values
704 missing_value = "."
705 missing_quality = -1
706
707 def setUp(self):
708 super().setUp()
709
710 self.vcf = pysam.VCF()
711 self.compare = load_and_convert(self.filename, encode=False)
712
713 def tearDown(self):
714 super().tearDown()
715 self.vcf.close()
716
717 def open_vcf(self, fn):
718 return self.vcf.connect(fn)
719
720 def get_failure_stage(self):
721
722 fn = os.path.basename(self.filename)
723 for x, msg in self.fail_on_opening:
724 if "{}.vcf".format(x) == fn:
725 return "opening"
726
727 for x, msg in self.fail_on_parsing:
728 if "{}.vcf".format(x) == fn:
729 return "parsing"
730
731 for x, msg in self.fail_on_samples:
732 if "{}.vcf".format(x) == fn:
733 return "samples"
734
735 return None
736
737 def testConnecting(self):
738
739 if self.get_failure_stage() == "opening":
740 self.assertRaises(ValueError,
741 self.open_vcf,
742 self.tmpfilename + ".gz")
743 else:
744 self.open_vcf(self.tmpfilename + ".gz")
745
746 def get_iterator(self):
747
748 with open(self.filename) as f:
749 fn = os.path.basename(self.filename)
750 return list(self.vcf.parse(f))
751
752 def get_field_value(self, record, field):
753 return record[field]
754
755 def sample2value(self, r, v):
756 return r, v
757
758 def alt2value(self, r, v):
759 if r == ".":
760 return [], v
761 else:
762 return r.split(","), list(v)
763
764 def filter2value(self, r, v):
765 if r == "PASS":
766 return [], v
767 elif r == ".":
768 return [], v
769 else:
770 return r.split(";"), v
771
772 def testParsing(self):
773
774 if self.get_failure_stage() in ("opening", "parsing"):
775 return
776
777 itr = self.get_iterator()
778 if itr is None:
779 return
780
781 fn = os.path.basename(self.filename)
782
783 check_samples = self.check_samples
784 for vcf_code, msg in self.fail_on_samples:
785 if "%i.vcf" % vcf_code == fn:
786 check_samples = False
787
788 for x, r in enumerate(itr):
789 c = self.compare[x]
790 for y, field in enumerate(self.columns):
791 # it is ok to have a missing format column
792 if y == 8 and y == len(c):
793 continue
794
795 val = self.get_field_value(r, field)
796 if field == "pos":
797 self.assertEqual(int(c[y]) - self.coordinate_offset,
798 val)
799 elif field == "alt" or field == "alts":
800 cc, vv = self.alt2value(c[y], val)
801 if cc != vv:
802 # import pdb; pdb.set_trace()
803 pass
804 self.assertEqual(
805 cc, vv,
806 "mismatch in field %s: expected %s, got %s" %
807 (field, cc, vv))
808
809 elif field == "filter":
810 cc, vv = self.filter2value(c[y], val)
811 self.assertEqual(
812 cc, vv,
813 "mismatch in field %s: expected %s, got %s" %
814 (field, cc, vv))
815
816 elif field == "info":
817 # tests for info field not implemented
818 pass
819
820 elif field == "qual" and c[y] == ".":
821 self.assertEqual(
822 self.missing_quality, val,
823 "mismatch in field %s: expected %s, got %s" %
824 (field, c[y], val))
825
826 elif field == "format":
827 # format field converted to list
828 self.assertEqual(
829 c[y].split(":"), list(val),
830 "mismatch in field %s: expected %s, got %s" %
831 (field, c[y], val))
832
833 elif type(val) in (int, float):
834 if c[y] == ".":
835 self.assertEqual(
836 None, val,
837 "mismatch in field %s: expected %s, got %s" %
838 (field, c[y], val))
839 else:
840 self.assertAlmostEqual(
841 float(c[y]), float(val), 2,
842 "mismatch in field %s: expected %s, got %s" %
843 (field, c[y], val))
844 else:
845 if c[y] == ".":
846 ref_val = self.missing_value
847 else:
848 ref_val = c[y]
849 self.assertEqual(
850 ref_val, val,
851 "mismatch in field %s: expected %s(%s), got %s(%s)" %
852 (field, ref_val, type(ref_val), val, type(val)))
853 # parse samples
854 if check_samples:
855 if len(c) == 8:
856 for x, s in enumerate(r.samples):
857 self.assertEqual(
858 [], r.samples[s].values(),
859 "mismatch in sample {}: "
860 "expected [], got {}, src={}, line={}".format(
861 s, r.samples[s].values(),
862 r.samples[s].items(), r))
863 else:
864 for x, s in enumerate(r.samples):
865 ref, comp = self.sample2value(
866 c[9 + x],
867 r.samples[s])
868 self.compare_samples(ref, comp, s, r)
869
870 def compare_samples(self, ref, comp, s, r):
871
872 if ref != comp:
873
874 # check if GT not at start, not VCF conform and
875 # not supported by cbcf.pyx
876 k = r.format.keys()
877 if "GT" in k and k[0] != "GT":
878 return
879
880 # perform an element-wise checto work around rounding differences
881 for a, b in zip(re.split("[:,;]", ref),
882 re.split("[:,;]", comp)):
883 is_float = True
884 try:
885 a = float(a)
886 b = float(b)
887 except ValueError:
888 is_float = False
889
890 if is_float:
891 self.assertAlmostEqual(
892 a, b, 2,
893 "mismatch in sample {}: "
894 "expected {}, got {}, src={}, line={}"
895 .format(
896 s, ref, comp,
897 r.samples[s].items(), r))
898 else:
899 self.assertEqual(
900 a, b,
901 "mismatch in sample {}: "
902 "expected {}, got {}, src={}, line={}"
903 .format(
904 s, ref, comp,
905 r.samples[s].items(), r))
906
907
908 ############################################################################
909 # create a test class for each example vcf file.
910 # Two samples are created -
911 # 1. Testing pysam/tabix access
912 # 2. Testing the VCF class
913 vcf_files = glob.glob(os.path.join(TABIX_DATADIR, "vcf", "*.vcf"))
914
915 for vcf_file in vcf_files:
916 n = "VCFFromTabixTest_%s" % os.path.basename(vcf_file[:-4])
917 globals()[n] = type(n, (TestVCFFromTabix,), dict(filename=vcf_file,))
918 n = "VCFFromVCFTest_%s" % os.path.basename(vcf_file[:-4])
919 globals()[n] = type(n, (TestVCFFromVCF,), dict(filename=vcf_file,))
920
921
922 class TestVCFFromVariantFile(TestVCFFromVCF):
923
924 columns = ("chrom", "pos", "id",
925 "ref", "alts", "qual",
926 "filter", "info", "format")
927
928 fail_on_parsing = [
929 (24, 'Could not parse the "#CHROM.." line'),
930 ("issue85", "empty VCF"),
931 ]
932 fail_on_opening = [
933 (24, 'Could not parse the "#CHROM.." line'),
934 ("issue85", "empty VCF"),
935 ]
936 coordinate_offset = 0
937 check_samples = True
938 fail_on_samples = [
939 (9, "PL field not defined. Expected to be scalar, but is array"),
940 (12, "PL field not defined. Expected to be scalar, but is array"),
941 (18, "PL field not defined. Expected to be scalar, but is array"),
942 ]
943
944 # value returned for missing values
945 missing_value = None
946 missing_quality = None
947
948 vcf = None
949
950 def filter2value(self, r, v):
951 if r == "PASS":
952 return ["PASS"], list(v)
953 elif r == ".":
954 return [], list(v)
955 else:
956 return r.split(";"), list(v)
957
958 def alt2value(self, r, v):
959 if r == ".":
960 return None, v
961 else:
962 return r.split(","), list(v)
963
964 def sample2value(self, r, smp):
965
966 def convert_field(f):
967 if f is None:
968 return "."
969 elif isinstance(f, tuple):
970 return ",".join(map(convert_field, f))
971 else:
972 return str(f)
973
974 v = smp.values()
975
976 if 'GT' in smp:
977 alleles = [
978 str(a) if a is not None else '.' for a in smp.allele_indices]
979 v[0] = '/|'[smp.phased].join(alleles)
980
981 comp = ":".join(map(convert_field, v))
982
983 if comp.endswith(":."):
984 comp = comp[:-2]
985
986 return r, comp
987
988 def setUp(self):
989 TestVCF.setUp(self)
990 self.compare = load_and_convert(self.filename, encode=False)
991
992 def tearDown(self):
993 if self.vcf:
994 self.vcf.close()
995 self.vcf = None
996 TestVCF.tearDown(self)
997
998 def get_iterator(self):
999 self.vcf = pysam.VariantFile(self.filename)
1000 return self.vcf.fetch()
1001
1002 def get_field_value(self, record, field):
1003 return getattr(record, field)
1004
1005 def open_vcf(self, fn):
1006 with pysam.VariantFile(fn) as inf:
1007 pass
1008
1009
1010 for vcf_file in vcf_files:
1011 p = os.path.basename(vcf_file[:-4])
1012 n = "TestVCFFromVariantFile_%s" % p
1013 globals()[n] = type(n, (TestVCFFromVariantFile,), dict(filename=vcf_file,))
1014
1015
•1016 @unittest.skip
1017 class TestRemoteFileHTTP(unittest.TestCase):
1018
1019 url = "http://genserv.anat.ox.ac.uk/downloads/pysam/test/example.gtf.gz"
1020 region = "chr1:1-1000"
1021 local = os.path.join(TABIX_DATADIR, "example.gtf.gz")
1022
1023 def setUp(self):
1024 if not getattr(pysam.config, "HAVE_LIBCURL", 0) or not check_url(self.url):
1025 self.remote_file = None
1026 else:
1027 self.remote_file = pysam.TabixFile(self.url, "r")
1028
1029 self.local_file = pysam.TabixFile(self.local, "r")
1030
1031 def tearDown(self):
1032 if self.remote_file is None:
1033 return
1034
1035 self.remote_file.close()
1036 self.local_file.close()
1037
1038 def testFetchAll(self):
1039 if self.remote_file is None:
1040 return
1041
1042 remote_result = list(self.remote_file.fetch())
1043 local_result = list(self.local_file.fetch())
1044
1045 self.assertEqual(len(remote_result), len(local_result))
1046 for x, y in zip(remote_result, local_result):
1047 self.assertEqual(x, y)
1048
1049 def testHeader(self):
1050 if self.remote_file is None:
1051 return
1052
1053 self.assertEqual(list(self.local_file.header), [])
1054
1055
•1056 #@unittest.skip # this leads to
1057 # E TypeError: Error when calling the metaclass bases
1058 # E function() argument 1 must be code, not str
1059 #class TestRemoteFileHTTPWithHeader(TestRemoteFileHTTP):
1060 #
1061 # url = "http://genserv.anat.ox.ac.uk/downloads/pysam/test/example_comments.gtf.gz"
1062 # region = "chr1:1-1000"
1063 # local = os.path.join(TABIX_DATADIR, "example_comments.gtf.gz")
1064 #
1065 # def setUp(self):
1066 # if not getattr(pysam.config, "HAVE_LIBCURL", 0) or not check_url(self.url):
1067 # self.remote_file = None
1068 # else:
1069 # self.remote_file = pysam.TabixFile(self.url, "r")
1070 # self.local_file = pysam.TabixFile(self.local, "r")
1071 #
1072 # def testHeader(self):
1073 # if self.remote_file is None:
1074 # return
1075 #
1076 # self.assertEqual(list(self.local_file.header), ["# comment at start"])
1077 # self.assertEqual(list(self.local_file.header), self.remote_file.header)
1078
1079
1080 class TestIndexArgument(unittest.TestCase):
1081
1082 filename_src = os.path.join(TABIX_DATADIR, "example.vcf.gz")
1083 filename_dst = "tmp_example.vcf.gz"
1084 index_src = os.path.join(TABIX_DATADIR, "example.vcf.gz.tbi")
1085 index_dst = "tmp_index_example.vcf.gz.tbi"
1086 index_dst_dat = "tmp_index_example.vcf.gz.tbi.dat"
1087 preset = "vcf"
1088
1089 def testFetchAll(self):
1090 shutil.copyfile(self.filename_src, self.filename_dst)
1091 shutil.copyfile(self.index_src, self.index_dst)
1092
1093 with pysam.TabixFile(
1094 self.filename_src, "r", index=self.index_src) as same_basename_file:
1095 same_basename_results = list(same_basename_file.fetch())
1096
1097 with pysam.TabixFile(
1098 self.filename_dst, "r", index=self.index_dst) as diff_index_file:
1099 diff_index_result = list(diff_index_file.fetch())
1100
1101 self.assertEqual(len(same_basename_results), len(diff_index_result))
1102 for x, y in zip(same_basename_results, diff_index_result):
1103 self.assertEqual(x, y)
1104
1105 os.unlink(self.filename_dst)
1106 os.unlink(self.index_dst)
1107
1108 def testLoadIndexWithoutTbiExtension(self):
1109 shutil.copyfile(self.filename_src, self.filename_dst)
1110 shutil.copyfile(self.index_src, self.index_dst_dat)
1111
1112 with pysam.TabixFile(
1113 self.filename_src, "r", index=self.index_src) as same_basename_file:
1114 same_basename_results = list(same_basename_file.fetch())
1115
1116 with pysam.TabixFile(
1117 self.filename_dst, "r", index=self.index_dst_dat) as diff_index_file:
1118 diff_index_result = list(diff_index_file.fetch())
1119
1120 self.assertEqual(len(same_basename_results), len(diff_index_result))
1121 for x, y in zip(same_basename_results, diff_index_result):
1122 self.assertEqual(x, y)
1123
1124 os.unlink(self.filename_dst)
1125 os.unlink(self.index_dst_dat)
1126
1127
1128 def _TestMultipleIteratorsHelper(filename, multiple_iterators):
1129 '''open file within scope, return iterator.'''
1130
1131 tabix = pysam.TabixFile(filename)
1132 iterator = tabix.fetch(parser=pysam.asGTF(),
1133 multiple_iterators=multiple_iterators)
1134 tabix.close()
1135 return iterator
1136
1137
1138 class TestBackwardsCompatibility(unittest.TestCase):
1139 """check if error is raised if a tabix file from an
1140 old version is accessed from pysam"""
1141
1142 def check(self, filename, raises=None):
1143 with pysam.TabixFile(filename) as tf:
1144 ref = load_and_convert(filename)
1145 if raises is None:
1146 self.assertEqual(len(list(tf.fetch())), len(ref))
1147 else:
1148 self.assertRaises(raises, tf.fetch)
1149
1150 def testVCF0v23(self):
1151 self.check(os.path.join(TABIX_DATADIR, "example_0v23.vcf.gz"),
1152 ValueError)
1153
1154 def testBED0v23(self):
1155 self.check(os.path.join(TABIX_DATADIR, "example_0v23.bed.gz"),
1156 ValueError)
1157
1158 def testVCF0v26(self):
1159 self.check(os.path.join(TABIX_DATADIR, "example_0v26.vcf.gz"),
1160 ValueError)
1161
1162 def testBED0v26(self):
1163 self.check(os.path.join(TABIX_DATADIR, "example_0v26.bed.gz"),
1164 ValueError)
1165
1166 def testVCF(self):
1167 self.check(os.path.join(TABIX_DATADIR, "example.vcf.gz"))
1168
1169 def testBED(self):
1170 self.check(os.path.join(TABIX_DATADIR, "example.bed.gz"))
1171
1172 def testEmpty(self):
1173 self.check(os.path.join(TABIX_DATADIR, "empty.bed.gz"))
1174
1175
1176 class TestMultipleIterators(unittest.TestCase):
1177
1178 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
1179
1180 def testJoinedIterators(self):
1181
1182 # two iterators working on the same file
1183 with pysam.TabixFile(self.filename) as tabix:
1184 a = next(tabix.fetch(parser=pysam.asGTF()))
1185 b = next(tabix.fetch(parser=pysam.asGTF()))
1186 # the first two lines differ only by the feature field
1187 self.assertEqual(a.feature, "UTR")
1188 self.assertEqual(b.feature, "exon")
1189 self.assertEqual(re.sub("UTR", "", str(a)),
1190 re.sub("exon", "", str(b)))
1191
1192 def testDisjointIterators(self):
1193 # two iterators working on the same file
1194 with pysam.TabixFile(self.filename) as tabix:
1195 a = next(tabix.fetch(parser=pysam.asGTF(), multiple_iterators=True))
1196 b = next(tabix.fetch(parser=pysam.asGTF(), multiple_iterators=True))
1197 # both iterators are at top of file
1198 self.assertEqual(str(a), str(b))
1199
1200 def testScope(self):
1201 # technically it does not really test if the scope is correct
1202 i = _TestMultipleIteratorsHelper(self.filename,
1203 multiple_iterators=True)
1204 self.assertTrue(next(i))
1205 i = _TestMultipleIteratorsHelper(self.filename,
1206 multiple_iterators=False)
1207 self.assertRaises(IOError, i.__next__)
1208
1209 def testDoubleFetch(self):
1210
1211 with pysam.TabixFile(self.filename) as f:
1212
1213 for a, b in zip(f.fetch(multiple_iterators=True),
1214 f.fetch(multiple_iterators=True)):
1215 self.assertEqual(str(a), str(b))
1216
1217
1218 class TestContextManager(unittest.TestCase):
1219
1220 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
1221
1222 def testManager(self):
1223
1224 with pysam.TabixFile(self.filename) as tabixfile:
1225 tabixfile.fetch()
1226 self.assertEqual(tabixfile.closed, True)
1227
1228
1229 class TestMultithreadTabixFile(unittest.TestCase):
1230
1231 filename = os.path.join(TABIX_DATADIR, "example.gtf.gz")
1232
1233 def testMultithreadEqualsSinglethread(self):
1234 with pysam.TabixFile(self.filename) as tabixfile:
1235 single = [r for r in tabixfile.fetch()]
1236 with pysam.TabixFile(self.filename, threads=2) as tabixfile:
1237 multi = [r for r in tabixfile.fetch()]
1238 for r1, r2 in zip(single, multi):
1239 assert str(r1) == str(r2)
1240
1241
1242 if __name__ == "__main__":
1243 unittest.main()