File: AlignmentFileHeader_test.py

package info (click to toggle)
python-pysam 0.15.4%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 27,992 kB
  • sloc: ansic: 140,738; python: 7,881; sh: 265; makefile: 223; perl: 41
file content (330 lines) | stat: -rw-r--r-- 12,294 bytes parent folder | download | duplicates (2)
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python
'''unit testing code for pysam.

Execute in the :file:`tests` directory as it requires the Makefile
and data files located there.
'''

import unittest
import os
import sys
import re
import copy
from collections import OrderedDict as odict
import pysam
import pysam.samtools
from TestUtils import get_temp_filename, BAM_DATADIR

if sys.version_info.major >= 3:
    from io import StringIO
else:
    from StringIO import StringIO


class TestHeaderConstruction(unittest.TestCase):
    """testing header construction."""

    header_dict = odict(
        [('SQ', [odict([('LN', 1575), ('SN', 'chr1'), ('AH', 'chr1:5000000-5010000')]),
                 odict([('LN', 1584), ('SN', 'chr2'), ('AH', '*')])]),
         ('RG', [odict([('LB', 'SC_1'), ('ID', 'L1'), ('SM', 'NA12891'),
                        ('PU', 'SC_1_10'), ("CN", "name:with:colon")]),
                 odict([('LB', 'SC_2'), ('ID', 'L2'), ('SM', 'NA12891'),
                        ('PU', 'SC_2_12'), ("CN", "name:with:colon")])]),
         ('PG', [odict([('ID', 'P1'), ('VN', '1.0')]),
                 odict([('ID', 'P2'), ('VN', '1.1')])]),
         ('HD', odict([('VN', '1.0')])),
         ('CO', ['this is a comment', 'this is another comment']),
        ])

    header_text = ("@HD\tVN:1.0\n"
                   "@SQ\tSN:chr1\tLN:1575\tAH:chr1:5000000-5010000\n"
                   "@SQ\tSN:chr2\tLN:1584\tAH:*\n"
                   "@RG\tID:L1\tPU:SC_1_10\tLB:SC_1\tSM:NA12891\tCN:name:with:colon\n"
                   "@RG\tID:L2\tPU:SC_2_12\tLB:SC_2\tSM:NA12891\tCN:name:with:colon\n"
                   "@PG\tID:P1\tVN:1.0\n"
                   "@PG\tID:P2\tVN:1.1\n"
                   "@CO\tthis is a comment\n"
                   "@CO\tthis is another comment\n")


    header_from_references = odict(
        [('SQ', [odict([('LN', 1575), ('SN', 'chr1')]),
                 odict([('LN', 1584), ('SN', 'chr2')])]),
         ('RG', [odict([('LB', 'SC_1'), ('ID', 'L1'), ('SM', 'NA12891'),
                        ('PU', 'SC_1_10'), ("CN", "name:with:colon")]),
                 odict([('LB', 'SC_2'), ('ID', 'L2'), ('SM', 'NA12891'),
                        ('PU', 'SC_2_12'), ("CN", "name:with:colon")])]),
         ('PG', [odict([('ID', 'P1'), ('VN', '1.0')]),
                 odict([('ID', 'P2'), ('VN', '1.1')])]),
         ('HD', odict([('VN', '1.0')])),
         ('CO', ['this is a comment', 'this is another comment']),
        ])

    header_without_text = odict(
        [('SQ', [odict([('LN', 1575), ('SN', 'chr1')]),
                 odict([('LN', 1584), ('SN', 'chr2')])]),
        ])
    
    def compare_headers(self, test_header, ref_header=None):
        '''compare two headers a and b.'''
        test_header_dict = test_header.as_dict()
        if ref_header is None:
            ref_header = self.header_dict
            
        for ak, av in test_header_dict.items():
            self.assertTrue(ak in self.header_dict, "key '%s' not in '%s' " % (ak, ref_header))
            self.assertEqual(av, ref_header[ak])
        for ak, av in ref_header.items():
            self.assertTrue(ak in test_header_dict, "key '%s' not in '%s' " % (ak, test_header_dict))
            self.assertEqual(av, test_header_dict[ak])

    def check_name_mapping(self, test_header):
        for x, y in enumerate(("chr1", "chr2")):
            tid = test_header.get_tid(y)
            ref = test_header.get_reference_name(x)
            self.assertEqual(tid, x)
            self.assertEqual(ref, y)

        self.assertEqual(test_header.get_tid("chr?"), -1)
        self.assertRaises(ValueError, test_header.get_reference_name, 2)
            
    def test_header_constructed_from_dict(self):
        header = pysam.AlignmentHeader.from_dict(self.header_dict)
        self.compare_headers(header)
        self.check_name_mapping(header)
        
    def test_header_constructed_from_text(self):
        header = pysam.AlignmentHeader.from_text(self.header_text)
        self.compare_headers(header)
        self.check_name_mapping(header)
        
    def test_header_constructed_from_header(self):
        header = pysam.AlignmentHeader.from_text(self.header_text)
        self.compare_headers(header.copy())
        self.check_name_mapping(header)

    def test_header_constructed_from_references(self):
        text = re.sub("@SQ[^\n]+\n", "", self.header_text)
        assert "@SQ" not in text
        header = pysam.AlignmentHeader.from_references(
            reference_names=["chr1", "chr2"],
            reference_lengths=[1575, 1584],
            text=text)
        self.compare_headers(header, self.header_from_references)
        self.check_name_mapping(header)

    def test_header_constructed_from_references_without_text(self):
        header = pysam.AlignmentHeader.from_references(
            reference_names=["chr1", "chr2"],
            reference_lengths=[1575, 1584])
        self.compare_headers(header, self.header_without_text)
        self.check_name_mapping(header)


class TestHeaderSAM(unittest.TestCase):
    """testing header manipulation"""

    header = {'SQ': [{'LN': 1575, 'SN': 'chr1', 'AH': 'chr1:5000000-5010000'},
                     {'LN': 1584, 'SN': 'chr2', 'AH': '*'}],
              'RG': [{'LB': 'SC_1', 'ID': 'L1', 'SM': 'NA12891',
                      'PU': 'SC_1_10', "CN": "name:with:colon"},
                     {'LB': 'SC_2', 'ID': 'L2', 'SM': 'NA12891',
                      'PU': 'SC_2_12', "CN": "name:with:colon"}],
              'PG': [{'ID': 'P1', 'VN': '1.0'}, {'ID': 'P2', 'VN': '1.1'}],
              'HD': {'VN': '1.0'},
              'CO': ['this is a comment', 'this is another comment'],
              }

    def compare_headers(self, a, b):
        '''compare two headers a and b.'''
        for ak, av in a.items():
            self.assertTrue(ak in b, "key '%s' not in '%s' " % (ak, b))
            self.assertEqual(av, b[ak])

    def setUp(self):
        self.samfile = pysam.AlignmentFile(
            os.path.join(BAM_DATADIR, "ex3.sam"),
            "r")

    def test_header_content_is_as_expected(self):
        self.compare_headers(self.header, self.samfile.header.to_dict())
        self.compare_headers(self.samfile.header.to_dict(), self.header)

    def test_text_access_works(self):
        self.assertEqual(self.samfile.text, self.samfile.header.__str__())
        
    def test_name_mapping(self):
        for x, y in enumerate(("chr1", "chr2")):
            tid = self.samfile.gettid(y)
            ref = self.samfile.getrname(x)
            self.assertEqual(tid, x)
            self.assertEqual(ref, y)

        self.assertEqual(self.samfile.gettid("chr?"), -1)
        self.assertRaises(ValueError, self.samfile.getrname, 2)

    def test_dictionary_access_works(self):
        for key in self.header.keys():
            self.compare_headers({key: self.header[key]},
                                 {key: self.samfile.header[key]})

    def test_dictionary_setting_raises_error(self):
        self.assertRaises(TypeError,
                          self.samfile.header.__setitem__,
                          "CO",
                          ["This is a final comment"])

    def test_dictionary_len_works(self):
        self.assertEqual(len(self.header), len(self.samfile.header))

    def test_dictionary_keys_works(self):
        # sort for py2.7
        self.assertEqual(sorted(self.header.keys()),
                         sorted(self.samfile.header.keys()))

    def test_dictionary_values_works(self):
        self.assertEqual(len(self.header.values()), len(self.samfile.header.values()))
        
    def test_dictionary_get_works(self):
        self.assertEqual(self.header.get("HD"), {'VN': '1.0'})
        self.assertEqual(self.header.get("UK", "xyz"), "xyz")
        self.assertEqual(self.header.get("UK"), None)

    def test_dictionary_contains_works(self):
        self.assertTrue("HD" in self.header)
        self.assertFalse("UK" in self.header)

    def tearDown(self):
        self.samfile.close()


class TestHeaderBAM(TestHeaderSAM):

    def setUp(self):
        self.samfile = pysam.AlignmentFile(
            os.path.join(BAM_DATADIR, "ex3.bam"),
            "rb")


class TestHeaderCRAM(TestHeaderSAM):

    def setUp(self):
        self.samfile = pysam.AlignmentFile(
            os.path.join(BAM_DATADIR, "ex3.cram"),
            "rc")

    def compare_headers(self, a, b):
        '''compare two headers a and b.'''
        def _strip(dd):
            for x in dd:
                for y in ("M5", "UR"):
                    if y in x:
                        del x[y]
        for ak, av in a.items():
            _strip(av)
            self.assertTrue(ak in b, "key '%s' not in '%s' " % (ak, b))
            _strip(b[ak])

            self.assertEqual(av, b[ak])


class TestHeaderFromRefs(unittest.TestCase):
    '''see issue 144

    reference names need to be converted to string for python 3
    '''

    # def testHeader( self ):
    #     refs = ['chr1', 'chr2']
    #     tmpfile = "tmp_%i" % id(self)
    #     s = pysam.AlignmentFile(tmpfile, 'wb',
    #                       referencenames=refs,
    #                       referencelengths=[100]*len(refs))
    #     s.close()

    #     self.assertTrue( checkBinaryEqual( 'issue144.bam', tmpfile ),
    #                      'bam files differ')
    #     os.unlink( tmpfile )



class TestHeaderWriteRead(unittest.TestCase):
    header = {'SQ': [{'LN': 1575, 'SN': 'chr1'},
                     {'LN': 1584, 'SN': 'chr2'}],
              'RG': [{'LB': 'SC_1', 'ID': 'L1', 'SM': 'NA12891',
                      'PU': 'SC_1_10', "CN": "name:with:colon"},
                     {'LB': 'SC_2', 'ID': 'L2', 'SM': 'NA12891',
                      'PU': 'SC_2_12', "CN": "name:with:colon"}],
              'PG': [{'ID': 'P1', 'VN': '1.0', 'CL': 'tool'},
                     {'ID': 'P2', 'VN': '1.1', 'CL': 'tool with in option -R a\tb',
                      'PP': 'P1'}],
              'HD': {'VN': '1.0'},
              'CO': ['this is a comment', 'this is another comment'],
              }

    def compare_headers(self, a, header_b):
        '''compare two headers a and b.

        Ignore M5 and UR field as they are set application specific.
        '''
        b = header_b.to_dict()
        for ak, av in a.items():
            self.assertTrue(ak in b, "key '%s' not in '%s' " % (ak, b))
            self.assertEqual(
                len(av), len(b[ak]),
                "unequal number of entries for key {}: {} vs {}"
                .format(ak, av, b[ak]))

            for row_a, row_b in zip(av, b[ak]):
                if isinstance(row_b, dict):
                    for x in ["M5", "UR"]:
                        try:
                            del row_b[x]
                        except KeyError:
                            pass
                self.assertEqual(row_a, row_b)

    def check_read_write(self, flag_write, header):

        fn = get_temp_filename()
        print(fn)
        with pysam.AlignmentFile(
                fn,
                flag_write,
                header=header,
                reference_filename=os.path.join(BAM_DATADIR, "ex1.fa")) as outf:
            a = pysam.AlignedSegment()
            a.query_name = "abc"
            outf.write(a)

        with pysam.AlignmentFile(fn) as inf:
            read_header = inf.header

        # os.unlink(fn)
        self.compare_headers(header, read_header)
        expected_lengths = dict([(x["SN"], x["LN"]) for x in header["SQ"]])
        self.assertEqual(expected_lengths,
                         dict(zip(read_header.references,
                                  read_header.lengths)))

    def test_SAM(self):
        self.check_read_write("wh", self.header)

    def test_BAM(self):
        self.check_read_write("wb", self.header)
        
    def test_CRAM(self):
        header = copy.copy(self.header)
        if "PG" in header:
            # for CRAM, \t needs to be quoted:
            header['PG'][1]['CL'] = re.sub(r"\t", r"\\\\t", header['PG'][1]['CL'])
        self.check_read_write("wc", header)


class TestHeaderLargeContigs(TestHeaderWriteRead):
    """see issue 741"""

    header = {'SQ': [{'LN': 2147483647, 'SN': 'chr1'},
                     {'LN': 1584, 'SN': 'chr2'}],
              'HD': {'VN': '1.0'}}