aboutsummaryrefslogtreecommitdiff
path: root/qc_app/samples.py
blob: d27164e8cc1873a83a2a90bb89e60293fbd12bc6 (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
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
"""Code regarding samples"""
import os
import sys
import csv
import uuid
from pathlib import Path
from typing import Iterator

import MySQLdb as mdb
from redis import Redis
from MySQLdb.cursors import DictCursor
from flask import (
    flash,
    request,
    url_for,
    redirect,
    Blueprint,
    render_template,
    current_app as app)

from quality_control.parsing import take

from qc_app import jobs
from qc_app.files import save_file
from qc_app.dbinsert import species_by_id, groups_by_species
from qc_app.db_utils import (
    with_db_connection,
    database_connection,
    with_redis_connection)

samples = Blueprint("samples", __name__)

@samples.route("/upload/species", methods=["POST"])
def select_species():
    """Select the species."""
    index_page = redirect(url_for("entry.upload_file"))
    species_id = request.form.get("species_id")
    if bool(species_id):
        species_id = int(species_id)
        species = with_db_connection(
            lambda conn: species_by_id(conn, species_id))
        if bool(species):
            return render_template(
                "samples/select-population.html",
                species=species,
                populations=groups_by_species(species_id))
        flash("Invalid species selected!", "alert-error")
    flash("You need to select a species", "alert-error")
    return index_page

def save_population(conn: mdb.Connection, population_details: dict) -> int:
    """Save the population details to the db."""
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute("SELECT MAX(Id) AS last_id FROM InbredSet")
        new_id = cursor.fetchone()["last_id"] + 1
        cursor.execute(
            "INSERT INTO InbredSet("
            "Id, InbredSetId, InbredSetName, Name, SpeciesId, FullName, "
            "MenuOrderId, Description"
            ") "
            "VALUES ("
            "%(Id)s, %(InbredSetId)s, %(InbredSetName)s, %(Name)s, "
            "%(SpeciesId)s, %(FullName)s, %(MenuOrderId)s, %(Description)s"
            ")",
            {
                "Id": new_id,
                "InbredSetId": new_id,
                "MenuOrderId": 0,
                **population_details
            })
        return new_id

def population_by_id(conn: mdb.Connection, population_id: int) -> dict:
    """Get the grouping/population by id."""
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute("SELECT * FROM InbredSet WHERE InbredSetId=%s",
                       (population_id,))
        return cursor.fetchone()

@samples.route("/upload/create-population", methods=["POST"])
def create_population():
    """Create new grouping/population."""
    species_page = redirect(url_for("samples.select_species"), code=307)
    with database_connection(app.config["SQL_URI"]) as conn:
        species = species_by_id(conn, request.form.get("species_id"))
        pop_name = request.form.get("inbredset_name").strip()
        pop_fullname = request.form.get("inbredset_fullname").strip()

        if not bool(species):
            flash("Invalid species!", "alert-error error-create-population")
            return species_page
        if (not bool(pop_name)) or (not bool(pop_fullname)):
            flash("You *MUST* provide a grouping/population name",
                  "alert-error error-create-population")
            return species_page

        pop_id = save_population(conn, {
            "SpeciesId": species["SpeciesId"],
            "Name": pop_name,
            "InbredSetName": pop_fullname,
            "FullName": pop_fullname,
            "Family": request.form.get("inbredset_family") or None,
            "Description": request.form.get("description") or None
        })

    flash("Grouping/Population created successfully.", "alert-success")
    return render_template(
        "samples/upload-samples.html",
        species=species,
        population=with_db_connection(
            lambda conn: population_by_id(conn, pop_id)))

@samples.route("/upload/select-population", methods=["POST"])
def select_population():
    """Select from existing groupings/populations."""
    species_page = redirect(url_for("samples.select_species"), code=307)
    with database_connection(app.config["SQL_URI"]) as conn:
        species = species_by_id(conn, request.form.get("species_id"))
        pop_id = int(request.form.get("inbredset_id"))
        population = with_db_connection(lambda conn: population_by_id(conn, pop_id))

    if not bool(species):
        flash("Invalid species!", "alert-error error-select-population")
        return species_page

    if not bool(population):
        flash("Invalid grouping/population!",
              "alert-error error-select-population")
        return species_page

    return render_template("samples/upload-samples.html",
                           species=species,
                           population=population)

def read_samples_file(filepath, separator: str, firstlineheading: bool, **kwargs) -> Iterator[dict]:
    """Read the samples file."""
    with open(filepath, "r", encoding="utf-8") as inputfile:
        reader = csv.DictReader(
            inputfile,
            fieldnames=(
                None if firstlineheading
                else ("Name", "Name2", "Symbol", "Alias")),
            delimiter=separator,
            quotechar=kwargs.get("quotechar", '"'))
        for row in reader:
            yield row

def save_samples_data(conn: mdb.Connection,
                      speciesid: int,
                      file_data: Iterator[dict]):
    """Save the samples to DB."""
    data = ({**row, "SpeciesId": speciesid} for row in file_data)
    total = 0
    with conn.cursor() as cursor:
        while True:
            batch = take(data, 5000)
            if len(batch) == 0:
                break
            cursor.executemany(
                "INSERT INTO Strain(Name, Name2, SpeciesId, Symbol, Alias) "
                "VALUES("
                "    %(Name)s, %(Name2)s, %(SpeciesId)s, %(Symbol)s, %(Alias)s"
                ") ON DUPLICATE KEY UPDATE Name=Name",
                batch)
            total += len(batch)
            print(f"\tSaved {total} samples total so far.")

def cross_reference_samples(conn: mdb.Connection,
                            species_id: int,
                            population_id: int,
                            strain_names: Iterator[str]):
    """Link samples to their population."""
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            "SELECT MAX(OrderId) AS loid FROM StrainXRef WHERE InbredSetId=%s",
            (population_id,))
        last_order_id = (cursor.fetchone()["loid"] or 10)
        total = 0
        while True:
            batch = take(strain_names, 5000)
            if len(batch) == 0:
                break
            params_str = ", ".join(["%s"] * len(batch))
            ## This query is slow -- investigate.
            cursor.execute(
                "SELECT s.Id FROM Strain AS s LEFT JOIN StrainXRef AS sx "
                "ON s.Id = sx.StrainId WHERE s.SpeciesId=%s AND s.Name IN "
                f"({params_str}) AND sx.StrainId IS NULL",
                (species_id,) + tuple(batch))
            strain_ids = (sid["Id"] for sid in cursor.fetchall())
            params = tuple({
                "pop_id": population_id,
                "strain_id": strain_id,
                "order_id": last_order_id + (order_id * 10),
                "mapping": "N",
                "pedigree": None
            } for order_id, strain_id in enumerate(strain_ids, start=1))
            cursor.executemany(
                "INSERT INTO StrainXRef( "
                "  InbredSetId, StrainId, OrderId, Used_for_mapping, PedigreeStatus"
                ")"
                "VALUES ("
                "  %(pop_id)s, %(strain_id)s, %(order_id)s, %(mapping)s, "
                "  %(pedigree)s"
                ")",
                params)
            last_order_id += (len(params) * 10)
            total += len(batch)
            print(f"\t{total} total samples cross-referenced to the population "
                  "so far.")

def build_sample_upload_job(# pylint: disable=[too-many-arguments]
        speciesid: int,
        populationid: int,
        samplesfile: Path,
        separator: str,
        firstlineheading: bool,
        quotechar: str):
    """Define the async command to run the actual samples data upload."""
    return [
        sys.executable, "-m", "scripts.insert_samples", app.config["SQL_URI"],
        str(speciesid), str(populationid), str(samplesfile.absolute()),
        separator, f"--redisuri={app.config['REDIS_URL']}",
        f"--quotechar={quotechar}"
    ] + (["--firstlineheading"] if firstlineheading else [])

@samples.route("/upload/samples", methods=["POST"])
def upload_samples():
    """Upload the samples."""
    samples_uploads_page = redirect(url_for("samples.select_population"),
                                    code=307)

    with database_connection(app.config["SQL_URI"]) as conn:
        species = species_by_id(conn, request.form.get("species_id"))
        if not bool(species):
            flash("Invalid species!", "alert-error")
            return samples_uploads_page

        population = with_db_connection(
            lambda conn: population_by_id(
                conn, int(request.form.get("inbredset_id"))))
        if not bool(population):
            flash("Invalid grouping/population!", "alert-error")
            return samples_uploads_page

        samples_file = save_file(request.files["samples_file"], Path(app.config["UPLOAD_FOLDER"]))
        if not bool(samples_file):
            flash("You need to provide a file with the samples data.")
            return samples_uploads_page

        firstlineheading = (request.form.get("first_line_heading") == "on")

        separator = request.form.get("separator")
        if separator == "other":
            separator = request.form.get("other_separator")
        if not bool(separator):
            flash("You need to provide a separator character.", "alert-error")
            return samples_uploads_page

        quotechar = (request.form.get("field_delimiter", '"') or '"')

        redisuri = app.config["REDIS_URL"]
        with Redis.from_url(redisuri, decode_responses=True) as rconn:
            the_job = jobs.launch_job(
                jobs.initialise_job(
                    rconn,
                    str(uuid.uuid4()),
                    build_sample_upload_job(
                        species["SpeciesId"],
                        population["InbredSetId"],
                        samples_file,
                        separator,
                        firstlineheading,
                        quotechar),
                    "samples_upload",
                    app.config["JOBS_TTL_SECONDS"],
                    {"job_name": f"Samples Upload: {samples_file.name}"}),
                redisuri,
                f"{app.config['UPLOAD_FOLDER']}/job_errors")
            return redirect(url_for(
                "samples.upload_status", job_id=the_job["job_id"]))

@samples.route("/upload/status/<uuid:job_id>", methods=["GET"])
def upload_status(job_id: uuid.UUID):
    """Check on the status of a samples upload job."""
    job = with_redis_connection(lambda rconn: jobs.job(rconn, str(job_id)))
    if job:
        status = job["status"]
        if status == "success":
            return render_template("samples/upload-success.html", job=job)

        if status == "error":
            return redirect(url_for("samples.upload_failure", job_id=job_id))

        error_filename = Path(jobs.error_filename(
            job_id, f"{app.config['UPLOAD_FOLDER']}/job_errors"))
        if error_filename.exists():
            stat = os.stat(error_filename)
            if stat.st_size > 0:
                return redirect(url_for(
                    "samples.upload_failure", job_id=job_id))

        return render_template(
            "samples/upload-progress.html",
            job=job) # maybe also handle this?

    return render_template("no_such_job.html", job_id=job_id), 400

@samples.route("/upload/failure/<uuid:job_id>", methods=["GET"])
def upload_failure(job_id: uuid.UUID):
    """Display the errors of the samples upload failure."""
    job = with_redis_connection(lambda rconn: jobs.job(rconn, str(job_id)))
    if not bool(job):
        return render_template("no_such_job.html", job_id=job_id), 400

    error_filename = Path(jobs.error_filename(
        job_id, f"{app.config['UPLOAD_FOLDER']}/job_errors"))
    if error_filename.exists():
        stat = os.stat(error_filename)
        if stat.st_size > 0:
            return render_template("worker_failure.html", job_id=job_id)

    return render_template("samples/upload-failure.html", job=job)