aboutsummaryrefslogtreecommitdiff
path: root/scripts/qc_on_rqtl2_bundle.py
blob: c3e8b6637ed5add47e87beb91e37a792654baa0b (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
"""Run Quality Control checks on R/qtl2 bundle."""
import sys
import json
from zipfile import ZipFile
from argparse import Namespace
from typing import Union, Sequence
from logging import Logger, getLogger, StreamHandler

from redis import Redis

from quality_control.errors import InvalidValue

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 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 qc_geno_errors(rconn, fqjobid, zfile, logger) -> bool:
    """Check for errors in `geno` file(s)."""
    logger.info("Checking for errors in the 'geno' file…")
    cdata = rqtl2.control_data(zfile)
    if "geno" in cdata:
        gerrs = tuple(rqc.geno_errors(zfile))
        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)."""
    logger.info("Checking for errors in the 'pheno' file…")
    cdata = rqtl2.control_data(zfile)
    if "pheno" in cdata:
        perrs = tuple(rqc.pheno_errors(zfile))
        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)."""
    logger.info("Checking for errors in the 'phenose' file…")
    cdata = rqtl2.control_data(zfile)
    if "phenose" in cdata:
        perrs = tuple(rqc.phenose_errors(zfile))
        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

        return (
            1 if any((
                qc_geno_errors(rconn, fqjobid, zfile, logger),
                qc_pheno_errors(rconn, fqjobid, zfile, logger),
                qc_phenose_errors(rconn, fqjobid, zfile, logger),
                qc_phenocovar_errors(rconn, fqjobid, zfile, logger)))
            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())