Debian Codegraph @

test/test_gather_bigwig.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import logging
2 import os.path as op
3 import subprocess
4 import sys
5 import tempfile
6
7 import pytest
8
9 from pbcommand.pb_io.common import load_pipeline_chunks_from_json, \
10 write_pipeline_chunks
11 from pbcommand.pb_io.report import load_report_from_json
12 from pbcommand.models import PipelineChunk
13
14 from kineticsTools.tasks.gather_bigwig import gather_bigwig
15
16 log = logging.getLogger(__name__)
17
18
19 def _generate_chunk_output_file(i=None):
20 import pyBigWig
21 records = [
22 ("chr1", 4, 5, 0.45),
23 ("chr2", 8, 9, 1.0),
24 ("chr2", 9, 10, 6.7),
25 ("chr1", 1, 2, 1.5),
26 ("chr1", 2, 3, 4.5),
27 ("chr1", 3, 4, 1.9)
28 ]
29 fn = tempfile.NamedTemporaryFile(suffix=".bw").name
30 _records = records[(i * 3):(i * 3) + 3]
31 assert len(_records) == 3
32 ranges = {}
33 for rec in _records:
34 seqid = rec[0]
35 pos = rec[1]
36 ranges.setdefault(seqid, (sys.maxsize, 0))
37 ranges[seqid] = (min(ranges[seqid][0], pos),
38 max(ranges[seqid][1], pos))
39 bw = pyBigWig.open(fn, "w")
40 regions = [(s, ranges[s][1] + 1) for s in sorted(ranges.keys())]
41 bw.addHeader(regions)
42 bw.addEntries([rec[0] for rec in _records],
43 [rec[1] - 1 for rec in _records],
44 ends=[rec[2] - 1 for rec in _records],
45 values=[rec[3] for rec in _records])
46 bw.close()
47 return fn
48
49
50 @pytest.mark.pybigwig
51 class TestGatherBigwig:
52 NCHUNKS = 2
53
54 @classmethod
55 def setup_class(cls):
56 cls._data_files = [_generate_chunk_output_file(i=i)
57 for i in range(cls.NCHUNKS)]
58
59 def validate_output(self, output_file):
60 import pyBigWig
61 bw = pyBigWig.open(output_file)
62 nrec = bw.header()["nBasesCovered"]
63 assert nrec == 6
64 assert pytest.approx(bw.stats("chr1", 2, 3)[0]) == 1.9
65 assert pytest.approx(bw.stats("chr2", 7, 8)[0]) == 1.0
66
67 def test_gather_bigwig(self):
68 ofn = tempfile.NamedTemporaryFile(suffix=".bw").name
69 rc = gather_bigwig(self._data_files, ofn)
70 self.validate_output(ofn)
71
72 def test_gather_bigwig_cli(self):
73 tmp_dir = tempfile.mkdtemp()
74 ofn = op.join(tmp_dir, "gathered.bw")
75 args = ["python", "-m", "kineticsTools.tasks.gather_bigwig",
76 ofn] + self._data_files
77 log.info("Output will be in %s", tmp_dir)
78 with open(op.join(tmp_dir, "stdout"), "w") as stdout:
79 with open(op.join(tmp_dir, "stderr"), "w") as stderr:
80 subprocess.check_call(args, stdout=stdout, stderr=stderr)
81 self.validate_output(ofn)