4 # Copyright (c) 2011 Seoul National University.
6 # Permission is hereby granted, free of charge, to any person obtaining
7 # a copy of this software and associated documentation files (the
8 # "Software"), to deal in the Software without restriction, including
9 # without limitation the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the Software, and to
11 # permit persons to whom the Software is furnished to do so, subject to
12 # the following conditions:
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 # Contact: Hyeshik Chang <hyeshik@snu.ac.kr>
33 EXAMPLEFILE = '../example.gtf.gz'
35 def load_example_regions(path):
37 for line in gzip.GzipFile(EXAMPLEFILE):
38 fields = line.decode('ascii')[:-1].split('\t')
40 begin = int(fields[3])
42 alldata.append((seqid, begin, end, fields[:7]))
46 def does_overlap(A, B, C, D):
47 return (A <= D <= B) or (C <= B <= D)
49 def sample_test_dataset(regions, ntests):
50 seqids = [seqid for seqid, _, _, _ in regions]
51 lowerbound = max(0, min(begin for _, begin, _, _ in regions) - 1000)
52 upperbound = max(end for _, _, end, _ in regions) + 1000
55 for i in range(ntests):
56 seqid = random.choice(seqids)
57 low = random.randrange(lowerbound, upperbound)
58 high = random.randrange(low, upperbound)
60 # for 1-based both-end inclusive intervals
61 matches = [info for seq, begin, end, info in regions
62 if seqid == seq and does_overlap(begin, end, low, high)]
64 tests.append((seqid, low, high, matches))
68 def tbresult2excerpt(tbmatches):
69 return [fields[:7] for fields in tbmatches]
71 class TabixTest(unittest.TestCase):
72 regions = load_example_regions(EXAMPLEFILE)
73 testset = sample_test_dataset(regions, 500)
76 self.tb = tabix.Tabix(EXAMPLEFILE)
79 for seqid, low, high, matches in self.testset:
80 tbresult = tbresult2excerpt(self.tb.query(seqid, low, high))
81 self.assertEqual(tbresult, matches)
84 for seqid, low, high, matches in self.testset:
85 tbresult = tbresult2excerpt(self.tb.querys('%s:%d-%d' %
87 self.assertEqual(tbresult, matches)
90 if __name__ == '__main__':