aboutsummaryrefslogtreecommitdiff
path: root/scripts/qc_on_rqtl2_bundle.py
blob: d77b6c20de3b770f80c2ab3f551b23f0c5ece79a (plain)
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
"""Run Quality Control checks on R/qtl2 bundle."""
import sys
import json
from time import sleep
from zipfile import ZipFile
from functools import partial
from argparse import Namespace
import multiprocessing as mproc
from logging import Logger, getLogger, StreamHandler
from typing import Union, Sequence, Callable, Iterator

from redis import Redis

from quality_control.errors import InvalidValue
from quality_control.checks import decimal_points_error

from qc_app import jobs
from qc_app.db_utils import database_connection
from qc_app.check_connections import check_db, check_redis

from r_qtl import errors as rqe
from r_qtl import r_qtl2 as rqtl2
from r_qtl import r_qtl2_qc as rqc
from r_qtl import fileerrors as rqfe

from scripts.cli_parser import init_cli_parser
from scripts.process_rqtl2_bundle import parse_job
from scripts.redis_logger import setup_redis_logger

def dict2tuple(dct: dict) -> tuple:
    """Utility to convert items in dicts to pairs of tuples."""
    return tuple((key, val) for key,val in dct.items())

def add_to_errors(rconn: Redis,
                  fqjobid: str,
                  key: str,
                  errors: Sequence[Union[InvalidValue, rqfe.MissingFile]]):
    """Add `errors` to a given list of errors"""
    errs = tuple(dict(item) for item in set(
        [dict2tuple(old) for old in
         json.loads(rconn.hget(fqjobid, key) or "[]")] +
        [dict2tuple({"type": type(error).__name__, **error._asdict()})
         for error in errors]))
    rconn.hset(fqjobid, key, json.dumps(errs))

def qc_missing_files(rconn: Redis,
                     fqjobid: str,
                     zfile: ZipFile,
                     logger: Logger) -> bool:
    """Run QC for files listed in control file that don't exist in bundle."""
    logger.info("Checking for missing files…")
    missing = rqc.missing_files(zfile)
    add_to_errors(rconn, fqjobid, "errors-generic", tuple(
        rqfe.MissingFile(
            mfile[0], mfile[1], (
                f"File '{mfile[1]}' is listed in the control file under "
                f"the '{mfile[0]}' key, but it does not actually exist in "
                "the bundle."))
        for mfile in missing))
    if len(missing) > 0:
        logger.error("Missing files in the bundle!")
        return True
    return False

def compute_filesize(zfile: ZipFile, filetype: str) -> int:
    """Compute the total file size."""
    cdata = rqtl2.control_data(zfile)
    if isinstance(cdata[filetype], str):
        return zfile.getinfo(cdata[filetype]).file_size

    return sum(zfile.getinfo(afile).file_size for afile in cdata[filetype])

def retrieve_errors_with_progress(rconn: Redis,#pylint: disable=[too-many-locals]
                                  fqjobid: str,
                                  zfile: ZipFile,
                                  filetype: str,
                                  checkers: tuple[Callable]) -> Iterator[Union[
                                      InvalidValue, rqfe.MissingFile]]:
    """Filter the errors while also counting the number of lines in the file."""
    assert filetype in rqtl2.FILE_TYPES, f"Invalid file type {filetype}."
    count = 0
    checked = 0
    cdata = rqtl2.control_data(zfile)
    rconn.hset(fqjobid, f"{filetype}-filesize", compute_filesize(zfile, filetype))
    def __update_processed__(value):
        nonlocal checked
        checked = checked + len(value)
        rconn.hset(fqjobid, f"{filetype}-checked", checked)

    try:# pylint: disable=[too-many-nested-blocks]
        for lineno, row in enumerate(
                rqtl2.file_data(zfile, filetype, cdata), start=1):
            count = count + 1
            for field, value in row.items():
                if field == "id":
                    __update_processed__(value)
                    continue
                if value is not None:
                    for checker in checkers:
                        error = checker(lineno, field, value)
                        if bool(error):
                            yield error
                        __update_processed__(value)

        rconn.hset(fqjobid, f"{filetype}-linecount", count)
    except rqe.MissingFileError:
        fname = cdata.get(filetype)
        yield rqfe.MissingFile(filetype, fname, (
            f"The file '{fname}' does not exist in the bundle despite it being "
            f"listed under '{filetype}' in the control file."))

def qc_geno_errors(rconn, fqjobid, zfile, logger) -> bool:
    """Check for errors in `geno` file(s)."""
    cdata = rqtl2.control_data(zfile)
    if "geno" in cdata:
        logger.info("Checking for errors in the 'geno' file…")
        gerrs = tuple(retrieve_errors_with_progress(
            rconn, fqjobid, zfile, "geno",
            (rqc.make_genocode_checker(cdata.get("genotypes", {})),)))
        add_to_errors(rconn, fqjobid, "errors-generic", tuple(
            err for err in gerrs if isinstance(err, rqfe.MissingFile)))
        add_to_errors(rconn, fqjobid, "errors-geno", tuple(
            err for err in gerrs if not isinstance(err, rqfe.MissingFile)))
        if len(gerrs) > 0:
            logger.error("The 'geno' file has errors.")
            return True
        logger.info("No errors found in the 'geno' file.")

    return False

def qc_pheno_errors(rconn, fqjobid, zfile, logger) -> bool:
    """Check for errors in `pheno` file(s)."""
    cdata = rqtl2.control_data(zfile)
    if "pheno" in cdata:
        logger.info("Checking for errors in the 'pheno' file…")
        perrs = tuple(retrieve_errors_with_progress(
            rconn,fqjobid, zfile, "pheno",
            (partial(decimal_points_error, mini=3),)))
        add_to_errors(rconn, fqjobid, "errors-generic", tuple(
            err for err in perrs if isinstance(err, rqfe.MissingFile)))
        add_to_errors(rconn, fqjobid, "errors-pheno", tuple(
            err for err in perrs if not isinstance(err, rqfe.MissingFile)))
        if len(perrs) > 0:
            logger.error("The 'pheno' file has errors.")
            return True
        logger.info("No errors found in the 'pheno' file.")

    return False

def qc_phenose_errors(rconn, fqjobid, zfile, logger) -> bool:
    """Check for errors in `phenose` file(s)."""
    cdata = rqtl2.control_data(zfile)
    if "phenose" in cdata:
        logger.info("Checking for errors in the 'phenose' file…")
        perrs = tuple(retrieve_errors_with_progress(
            rconn,fqjobid, zfile, "phenose",
            (partial(decimal_points_error, mini=6),)))
        add_to_errors(rconn, fqjobid, "errors-generic", tuple(
            err for err in perrs if isinstance(err, rqfe.MissingFile)))
        add_to_errors(rconn, fqjobid, "errors-phenose", tuple(
            err for err in perrs if not isinstance(err, rqfe.MissingFile)))
        if len(perrs) > 0:
            logger.error("The 'phenose' file has errors.")
            return True
        logger.info("No errors found in the 'phenose' file.")

    return False

def qc_phenocovar_errors(_rconn, _fqjobid, _zfile, _logger) -> bool:
    """Check for errors in `phenocovar` file(s)."""
    return False

def run_qc(rconn: Redis,
           args: Namespace,
           logger: Logger) -> int:
    """Run the QC programs."""
    fqjobid = jobs.job_key(args.redisprefix, args.jobid)
    thejob = parse_job(rconn, args.redisprefix, args.jobid)
    jobmeta = thejob["job-metadata"]

    with ZipFile(jobmeta["rqtl2-bundle-file"], "r") as zfile:
        if qc_missing_files(rconn, fqjobid, zfile, logger):
            return 1

    def with_zipfile(rconn, fqjobid, filename, logger, func):
        with ZipFile(filename, "r") as zfile:
            return func(rconn, fqjobid, zfile, logger)

    def buildargs(func):
        return (rconn, fqjobid, jobmeta["rqtl2-bundle-file"], logger, func)
    processes = [
        mproc.Process(target=with_zipfile, args=buildargs(qc_geno_errors,)),
        mproc.Process(target=with_zipfile, args=buildargs(qc_pheno_errors,)),
        mproc.Process(target=with_zipfile, args=buildargs(qc_phenose_errors,)),
        mproc.Process(target=with_zipfile, args=buildargs(qc_phenocovar_errors,))
    ]
    for process in processes:
        process.start()

    while True:
        processes_running = any(
            (process.is_alive() for process in processes))
        if not processes_running:
            break
        sleep(2)

    if any((process.exitcode for process in processes)):
        # at least one process failed for some reason...
        return 1

    def __fetch_errors__(rkey: str) -> tuple:
        return tuple(json.loads(rconn.hget(fqjobid, rkey) or "[]"))

    return (1 if any((
        bool(__fetch_errors__(key))
        for key in
        ("errors-geno", "errors-pheno", "errors-phenos", "errors-phenocovar")))
            else 0)

if __name__ == "__main__":
    def main():
        """Enter R/qtl2 bundle QC runner."""
        args = init_cli_parser(
            "qc-on-rqtl2-bundle", "Run QC on R/qtl2 bundle.").parse_args()
        check_redis(args.redisuri)
        check_db(args.databaseuri)

        logger = getLogger("qc-on-rqtl2-bundle")
        logger.addHandler(StreamHandler(stream=sys.stderr))
        logger.setLevel("DEBUG")

        fqjobid = jobs.job_key(args.redisprefix, args.jobid)
        with (database_connection(args.databaseuri) as _dbconn,
              Redis.from_url(args.redisuri, decode_responses=True) as rconn):
            logger.addHandler(setup_redis_logger(
                rconn, fqjobid, f"{fqjobid}:log-messages",
                args.redisexpiry))

            exitcode = run_qc(rconn, args, logger)
            rconn.hset(
                jobs.job_key(args.redisprefix, args.jobid), "exitcode", exitcode)
            return exitcode

    sys.exit(main())