aboutsummaryrefslogtreecommitdiff
path: root/scripts/rqtl2/install_genotypes.py
blob: a1609a037b0ccc1d07fd2714ed888b92cb9036ed (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
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
"""Load genotypes from R/qtl2 bundle into the database."""
import sys
import uuid
import logging
import traceback
from pathlib import Path
from zipfile import ZipFile
from functools import reduce
from typing import Union, Iterator
from argparse import ArgumentParser

import MySQLdb as mdb
from redis import Redis
from MySQLdb.cursors import DictCursor

from r_qtl import r_qtl2 as rqtl2

from quality_control.parsing import take

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

from scripts.redis_logger import RedisLogger

stderr_handler = logging.StreamHandler(stream=sys.stderr)
logger = logging.getLogger("install_genotypes")
logger.addHandler(stderr_handler)

def insert_markers(dbconn: mdb.Connection,
                   speciesid: int,
                   markers: tuple[str, ...],
                   pmapdata: Union[Iterator[dict], None]) -> int:
    """Insert genotype and genotype values into the database."""
    mdata = reduce(#type: ignore[var-annotated]
        lambda acc, row: ({#type: ignore[arg-type, return-value]
            **acc, row["id"]: {
                key: val
                for key,val in row.items()
                if key != "id"
            }
        }),
        (pmapdata or tuple()),
        {})
    with dbconn.cursor() as cursor:
        cursor.executemany(
            "INSERT INTO Geno(SpeciesId, Name, Marker_Name, Chr, Mb) "
            "VALUES (%(speciesid)s, %(marker)s, %(marker)s, %(chr)s, %(pos)s) "
            "ON DUPLICATE KEY UPDATE SpeciesId=SpeciesId",
            tuple({
                "speciesid": speciesid,
                "marker": marker,
                "chr": mdata.get(marker, {}).get("chr"),
                "pos": mdata.get(marker, {}).get("pos")
            } for marker in markers))
        return cursor.rowcount

def insert_individuals(dbconn: mdb.Connection,
                       speciesid: int,
                       individuals: tuple[str, ...]) -> int:
    """Insert individuals/samples into the database."""
    with dbconn.cursor() as cursor:
        cursor.executemany(
            "INSERT INTO Strain(Name, Name2, SpeciesId) "
            "VALUES(%(id)s, %(id)s, %(speciesid)s) "
            "ON DUPLICATE KEY UPDATE Name=Name",
            tuple({"speciesid": speciesid, "id": individual}
                  for individual in individuals))
        return cursor.rowcount

def cross_reference_individuals(dbconn: mdb.Connection,
                                speciesid: int,
                                populationid: int,
                                individuals: tuple[str, ...]) -> int:
    """Cross reference any inserted individuals."""
    with dbconn.cursor(cursorclass=DictCursor) as cursor:
        paramstr = ", ".join(["%s"] * len(individuals))
        cursor.execute("SELECT Id FROM Strain "
                       f"WHERE SpeciesId=%s AND Name IN ({paramstr})",
                       (speciesid,) + individuals)
        ids = ({"popid": populationid, "indid": row["Id"]}
               for row in cursor.fetchall())
        cursor.executemany(
            "INSERT INTO StrainXRef(InbredSetId, StrainId) "
            "VALUES(%(popid)s, %(indid)s) "
            "ON DUPLICATE KEY UPDATE InbredSetId=InbredSetId",
            tuple(ids))
        return cursor.rowcount

def insert_genotype_data(dbconn: mdb.Connection,
                         speciesid: int,
                         genotypes: tuple[dict, ...],
                         individuals: tuple[str, ...]) -> tuple[
                             int, tuple[dict, ...]]:
    """Insert the genotype data values into the database."""
    with dbconn.cursor(cursorclass=DictCursor) as cursor:
        paramstr = ", ".join(["%s"] * len(individuals))
        cursor.execute(
            f"SELECT Id, Name FROM Strain WHERE Name IN ({paramstr})",
            individuals)
        indids = {row["Name"]: row["Id"] for row in cursor.fetchall()}
        markers = tuple(key for key in genotypes[0].keys() if key != "id")
        paramstr = ", ".join(["%s"] * len(markers))
        cursor.execute(
            f"SELECT Id, Name FROM Geno WHERE SpeciesId=%s AND Name IN ({paramstr})",
            (speciesid,)+markers)
        markerids = {row["Name"]: row["Id"] for row in cursor.fetchall()}
        cursor.execute("SELECT MAX(Id) AS lastid FROM GenoData")
        lastid = cursor.fetchone()["lastid"]
        data = tuple(
            {**row, "gid": gid}
            for gid, row in enumerate(
                    ({
                        "value": innerrow[marker],
                        "indid": indids[innerrow["id"]],
                        "markerid": markerids[marker]
                    } for innerrow in genotypes for marker in
                     (key for key in innerrow.keys() if key != "id")),
                    start=lastid+1))
        cursor.executemany(
            "INSERT INTO GenoData(Id, StrainId, value) "
            "VALUES(%(gid)s, %(indid)s, %(value)s)",
            data)
        return cursor.rowcount, tuple({
            "dataid": row["gid"],
            "markerid": row["markerid"]
        } for row in data)

def cross_reference_genotypes(dbconn: mdb.Connection,
                              speciesid: int,
                              datasetid: int,
                              dataids: tuple[dict, ...],
                              gmapdata: Union[Iterator[dict], None]) -> int:
    """Cross-reference the data to the relevant dataset."""
    _rows, markers, mdata = reduce(#type: ignore[var-annotated]
        lambda acc, row: (#type: ignore[return-value,arg-type]
            (acc[0] + (row,)), (acc[1] + (row["id"],)),
            {
                **acc[2], row["id"]: {
                    key: val
                    for key,val in row.items()
                    if key != "id"
                }
            }),
        (gmapdata or tuple()),
        (tuple(), tuple(), {}))

    with dbconn.cursor(cursorclass=DictCursor) as cursor:
        paramstr = ", ".join(["%s"] * len(markers))
        cursor.execute("SELECT Id, Name FROM Geno "
                       f"WHERE SpeciesId=%s AND Name IN ({paramstr})",
                       (speciesid,) + markers)
        markersdict = {row["Id"]: row["Name"] for row in cursor.fetchall()}
        cursor.executemany(
            "INSERT INTO GenoXRef(GenoFreezeId, GenoId, DataId, cM) "
            "VALUES(%(datasetid)s, %(markerid)s, %(dataid)s, %(pos)s) "
            "ON DUPLICATE KEY UPDATE GenoFreezeId=GenoFreezeId",
            tuple({
                **row,
                "datasetid": datasetid,
                "pos": mdata.get(markersdict.get(
                    row.get("markerid"), {}), {}).get("pos")
            } for row in dataids))
        return cursor.rowcount

def install_genotypes(dbconn: mdb.Connection,
                      speciesid: int,
                      populationid: int,
                      datasetid: int,
                      rqtl2bundle: Path) -> int:
    """Load any existing genotypes into the database."""
    count = 0
    with ZipFile(str(rqtl2bundle.absolute()), "r") as zfile:
        try:
            logger.info("Validating bundle")
            rqtl2.validate_bundle(zfile)
            logger.info("Bundle validated successfully.")
            logger.info(("Loading genotypes. This could take a while. "
                         "Please be patient."))

            cdata = rqtl2.control_data(zfile)
            genotypes = rqtl2.genotype_data(zfile)
            while True:
                batch = tuple(take(genotypes, 5000))
                if len(batch) == 0:
                    logger.info("Loading Genotypes complete!")
                    logger.info(
                        "Total rows processed: %s", count)
                    break

                insert_markers(
                    dbconn,
                    speciesid,
                    tuple(key for key in batch[0].keys() if key != "id"),
                    (rqtl2.file_data(zfile, "pmap", cdata) if "pmap" in cdata
                     else None))
                individuals = tuple(row["id"] for row in batch)
                insert_individuals(dbconn, speciesid, individuals)
                cross_reference_individuals(
                    dbconn, speciesid, populationid, individuals)
                _num_rows, dataids = insert_genotype_data(
                    dbconn, speciesid, batch, individuals)
                cross_reference_genotypes(
                    dbconn,
                    speciesid,
                    datasetid,
                    dataids,
                    (rqtl2.file_data(zfile, "gmap", cdata)
                     if "gmap" in cdata else None))
                count = count + len(batch)
        except rqtl2.InvalidFormat as exc:
            logger.error(str(exc))
            logger.info("There are no genotypes to load.")
        except Exception as _exc:# pylint: disable=[broad-except]
            # Narrow this exception with time.
            logger.error("Failing with exception: %s", traceback.format_exc())
            return 3

    return 0

if __name__ == "__main__":

    def cli_args():
        """Process command-line arguments for install_genotypes"""
        parser = ArgumentParser(
            prog="install_genotypes",
            description="Parse genotypes from R/qtl2 bundle into the database.")

        parser.add_argument("databaseuri", help="URL to MariaDB")
        parser.add_argument("redisuri", help="URL to Redis")
        parser.add_argument("jobid",
                            help="Job ID that this belongs to.",
                            type=uuid.UUID)

        parser.add_argument("speciesid",
                            help="Species to which bundle relates.")
        parser.add_argument("populationid",
                            help="Population to group data under")
        parser.add_argument("datasetid",
                            help="The dataset to which the data belongs.")
        parser.add_argument("rqtl2bundle",
                            help="Path to R/qtl2 bundle zip file.",
                            type=Path)

        parser.add_argument("--redisexpiry",
                            help="How long to keep any redis keys around.",
                            type=int,
                            default=86400)

        return parser.parse_args()

    def main():
        """Run `install_genotypes` scripts."""
        args = cli_args()
        check_db(args.databaseuri)
        check_redis(args.redisuri)
        if not args.rqtl2bundle.exists():
            logging.error("File not found: '%s'.", args.rqtl2bundle)
            return 2

        with (Redis.from_url(args.redisuri, decode_responses=True) as rconn,
              database_connection(args.databaseuri) as dbconn):
            formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s: %(message)s")
            job_messagelist = f"{str(args.jobid)}:log-messages"
            rconn.hset(name=str(args.jobid),
                       key="log-messagelist",
                       value=job_messagelist)
            redislogger = RedisLogger(
                rconn, args.jobid, expiry=args.redisexpiry)
            redislogger.setFormatter(formatter)
            logger.addHandler(redislogger)
            logger.setLevel("INFO")
            return install_genotypes(dbconn,
                                     args.speciesid,
                                     args.populationid,
                                     args.datasetid,
                                     args.rqtl2bundle)

    sys.exit(main())