File: test_genomic.py

package info (click to toggle)
htseq 2.0.9%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 103,476 kB
  • sloc: python: 6,280; sh: 211; cpp: 147; makefile: 80
file content (239 lines) | stat: -rw-r--r-- 8,138 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import pytest
import sys
import os
import glob
import sysconfig
from pathlib import Path
import unittest
import pytest
import conftest

build_dir = "build/lib.%s-%s" % (sysconfig.get_platform(), sys.version[0:3])

sys.path.insert(0, os.path.join(os.getcwd(), build_dir))
import HTSeq

try:
    import pyBigWig
except ImportError:
    pyBigWig = None


data_folder = conftest.get_data_folder()


class TestGenomicInterval(unittest.TestCase):
    def test_init(self):
        iv = HTSeq.GenomicInterval(
            'chr1', 100, 200, ".",
        )


class TestChromVector(unittest.TestCase):
    def test_init_step(self):
        # Autoallocation
        cv = HTSeq.ChromVector.create(
            HTSeq.GenomicInterval('chr1', 100, 200, "."),
            typecode='d',
            storage='step',
        )

    def test_init_stretch(self):
        # Autoallocation
        cv = HTSeq.ChromVector.create(
            HTSeq.GenomicInterval('chr1', 100, 200, "."),
            typecode='d',
            storage='stretch',
        )

    def test_steps_stretch(self):
        cv = HTSeq.ChromVector.create(
            HTSeq.GenomicInterval('chr1', 100, 200, "."),
            typecode='d',
            storage='stretch',
        )
        cv[120:130] = 45
        cv[129:140] = 89
        cv[180: 182] = 1
        steps = list(cv.steps())
        self.assertEqual(steps[0][0], HTSeq.GenomicInterval('chr1', 120, 129))
        self.assertEqual(steps[1][0], HTSeq.GenomicInterval('chr1', 129, 140))
        self.assertEqual(steps[2][0], HTSeq.GenomicInterval('chr1', 180, 182))
        self.assertEqual(steps[0][1], 45)
        self.assertEqual(steps[1][1], 89)
        self.assertEqual(steps[2][1], 1)


class TestGenomicArray(unittest.TestCase):
    def test_init(self):
        # Autoallocation
        ga = HTSeq.GenomicArray("auto")

        # Infinite length chromosomes
        ga = HTSeq.GenomicArray(['1', '2'])

        # Fixed chromosomes
        ga = HTSeq.GenomicArray({
            '1': 5898,
            '2': 4876,
        })

        # Store: ndarray
        ga = HTSeq.GenomicArray({
            '1': 5898,
            '2': 4876,
            },
            storage='ndarray',
        )

        # Store: memmap
        ga = HTSeq.GenomicArray({
            '1': 5898,
            '2': 4876,
            },
            storage='memmap',
            memmap_dir='.',
        )

    def test_steps(self):
        for storage in ['step', 'ndarray']:
            ga = HTSeq.GenomicArray({
                '1': 5898,
                '2': 4876,
                },
                storage=storage,
            )
            steps = ga.steps()
            steps_exp = [
                (HTSeq.GenomicInterval('1', 0, 5898, strand='+'), 0),
                (HTSeq.GenomicInterval('1', 0, 5898, strand='-'), 0),
                (HTSeq.GenomicInterval('2', 0, 4876, strand='+'), 0),
                (HTSeq.GenomicInterval('2', 0, 4876, strand='-'), 0),
            ]
            for step, step_exp in zip(steps, steps_exp):
                self.assertEqual(step, step_exp)

    def test_access_out_of_range(self):
        """ Ensure chromosomes are made with infinite size, which can be accessed  """

        def _get_arrays():
            return {
                "Provided chrom": HTSeq.GenomicArray(["1"], typecode='O'),
                "Auto chrom": HTSeq.GenomicArray("auto", typecode='O'),
            }

        # Test we can access unknown regions without error
        unknown_iv = HTSeq.GenomicInterval('1', 200, 300, "+")
        for name, genomic_array in _get_arrays().items():
            step = list(genomic_array[unknown_iv].steps())[0]
            unknown_value = step[1]
            self.assertIsNone(unknown_value, msg="Access unknown in " + name)

        # Test accessing unknown regions works the same even if we call setter first
        known_iv = HTSeq.GenomicInterval('1', 0, 100, strand='+')
        for name, genomic_array in _get_arrays().items():
            # Call setter first before getter
            genomic_array[known_iv] = "test"
            step = list(genomic_array[unknown_iv].steps())[0]
            unknown_value = step[1]
            self.assertIsNone(unknown_value, msg="Access unknown after calling setter in " + name)

    def test_bedgraph(self):
        def compare_bedgraph_line(line1, line2):
            fields1 = line1.split()
            fields2 = line2.split()
            # Chromosome
            self.assertEqual(fields1[0], fields2[0])
            # Start-end
            self.assertEqual(int(fields1[1]), int(fields2[1]))
            self.assertEqual(int(fields1[2]), int(fields2[2]))
            # Value
            self.assertEqual(float(fields1[3]), float(fields2[3]))

        ga = HTSeq.GenomicArray.from_bedgraph_file(
            data_folder+'example_bedgraph.bedgraph',
            strand='.',
        )

        steps = []
        for iv, value in ga.steps():
            steps.append((iv.chrom, iv.start, iv.end, value))

        steps_exp = [
            ('chr19', 49302000, 49302300, -1.0),
            ('chr19', 49302300, 49302600, -0.75),
            ('chr19', 49302600, 49302900, -0.50),
            ('chr19', 49302900, 49303200, -0.25),
            ('chr19', 49303200, 49303500, 0.0),
            ('chr19', 49303500, 49303800, 0.25),
            ('chr19', 49303800, 49304100, 0.50),
            ('chr19', 49304100, 49304400, 0.75),
            ('chr19', 49304400, 49304700, 1.00),
        ]
        self.assertEqual(steps, steps_exp)

        ga.write_bedgraph_file(
            'test_output.bedgraph',
            track_options='name="BedGraph Format" description="BedGraph format" visibility=full color=200,100,0 altColor=0,100,200 priority=20',
            separator=' ',
        )
        with open(data_folder+'example_bedgraph.bedgraph') as f1, \
             open('test_output.bedgraph') as f2:
            header_found = False
            for line1, line2 in zip(f1, f2):
                if not header_found:
                    self.assertEqual(line1, line2)
                else:
                    compare_bedgraph_line(line1, line2)
                if 'track type' in line1:
                    header_found = True

    @unittest.skipIf(pyBigWig is None, "test case depends on pyBigWig")
    def test_bigwig(self):
        ga = HTSeq.GenomicArray.from_bigwig_file(
            data_folder+'example_bigwig.bw',
        )
        ga.write_bigwig_file(
            'test_output.bw',
        )

        import pyBigWig
        with pyBigWig.open(data_folder+'example_bigwig.bw') as bw1, \
                pyBigWig.open('test_output.bw') as bw2:
            self.assertEqual(bw1.chroms(), bw2.chroms())
            for chrom in bw1.chroms():
                self.assertEqual(
                    bw1.intervals(chrom),
                    bw2.intervals(chrom),
                )

    def test_access_out_of_range(self):
        """ Ensure chromosomes are made with infinite size, which can be accessed  """

        def _get_arrays():
            return {
                "Provided chrom": HTSeq.GenomicArray(["1"], typecode='O'),
                "Auto chrom": HTSeq.GenomicArray("auto", typecode='O'),
            }

        # Test we can access unknown regions without error
        unknown_iv = HTSeq.GenomicInterval('1', 200, 300, "+")
        for name, genomic_array in _get_arrays().items():
            step = list(genomic_array[unknown_iv].steps())[0]
            unknown_value = step[1]
            self.assertIsNone(unknown_value, msg="Access unknown in " + name)

        # Test accessing unknown regions works the same even if we call setter first
        known_iv = HTSeq.GenomicInterval('1', 0, 100, strand='+')
        for name, genomic_array in _get_arrays().items():
            # Call setter first before getter
            genomic_array[known_iv] = "test"
            step = list(genomic_array[unknown_iv].steps())[0]
            unknown_value = step[1]
            self.assertIsNone(unknown_value, msg="Access unknown after calling setter in " + name)


if __name__ == '__main__':

    suite = TestGenomicArray()
    suite.test_init()