aboutsummaryrefslogtreecommitdiff
path: root/gn3/api/gemma.py
blob: 21c4cf56c24581b909b821383febcba8c074516b (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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
"""Endpoints for running the gemma cmd"""
import os
import redis

from flask import Blueprint
from flask import current_app
from flask import jsonify
from flask import request

from gn3.commands import queue_cmd
from gn3.commands import run_cmd
from gn3.file_utils import jsonfile_to_dict
from gn3.computations.gemma import generate_gemma_cmd
from gn3.computations.gemma import do_paths_exist
from gn3.computations.gemma import generate_hash_of_string
from gn3.computations.gemma import generate_pheno_txt_file
from gn3.computations.gemma import generate_gemma_computation_cmd

gemma = Blueprint("gemma", __name__)


@gemma.route("/version")
def get_version():
    """Display the installed version of gemma-wrapper"""
    gemma_cmd = current_app.config["GEMMA_WRAPPER_CMD"]
    return jsonify(run_cmd(f"{gemma_cmd} -v | head -n 1"))


@gemma.route("/status/<unique_id>", methods=["GET"])
def check_cmd_status(unique_id):
    """Given a (url-encoded) UNIQUE-ID which is returned when hitting any of the
gemma endpoints, return the status of the command

    """
    status = redis.Redis().hget(name=unique_id, key="status")
    if not status:
        return jsonify(status=128,
                       error="The unique id you used does not exist!"), 500
    return jsonify(status=status.decode("utf-8"))


@gemma.route("/k-compute/<token>", methods=["POST"])
def compute_k(token):
    """Given a genofile, traitfile, snpsfile, and the token, compute the k-valuen
and return <hash-of-inputs>.json with a UNIQUE-ID of the job. The genofile,
traitfile, and snpsfile are extracted from a metadata.json file.

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {"g": genofile, "p": phenofile, "a": snpsfile}
        results = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs)
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=results.get("gemma_cmd")),
                       status="queued",
                       output_file=results.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/k-compute/loco/<chromosomes>/<token>", methods=["POST"])
def compute_k_loco(chromosomes, token):
    """Similar to 'compute_k' with the extra option of using loco given chromosome
values.

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {"g": genofile, "p": phenofile, "a": snpsfile}
        results = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            chromosomes=chromosomes)
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=results.get("gemma_cmd")),
                       status="queued",
                       output_file=results.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/gwa-compute/<k_filename>/<token>", methods=["POST"])
def compute_gwa(k_filename, token):
    """Compute GWA values. No loco no covariates provided.

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps"]
        ]
        gemma_kwargs = {
            "g": genofile,
            "p": phenofile,
            "a": snpsfile,
            "lmm": _dict.get("lmm", 9)
        }
        results = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "input": os.path.join(working_dir, k_filename)
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=results.get("gemma_cmd")),
                       status="queued",
                       output_file=results.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/gwa-compute/covars/<k_filename>/<token>", methods=["POST"])
def compute_gwa_with_covar(k_filename, token):
    """Compute GWA values. No Loco; Covariates provided.

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile, covarfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps", "covar"]
        ]
        gemma_kwargs = {
            "g": genofile,
            "p": phenofile,
            "a": snpsfile,
            "c": covarfile,
            "lmm": _dict.get("lmm", 9)
        }
        results = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "input": os.path.join(working_dir, k_filename)
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=results.get("gemma_cmd")),
                       status="queued",
                       output_file=results.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/gwa-compute/<k_filename>/loco/maf/<maf>/<token>",
             methods=["POST"])
def compute_gwa_with_loco_maf(k_filename, maf, token):
    """Compute GWA values. No Covariates provided. Only loco and maf vals given.

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {
            "g": genofile,
            "p": phenofile,
            "a": snpsfile,
            "lmm": _dict.get("lmm", 9),
            'maf': float(maf)
        }
        results = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "loco": f"--input {os.path.join(working_dir, k_filename)}"
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=results.get("gemma_cmd")),
                       status="queued",
                       output_file=results.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/gwa-compute/<k_filename>/loco/covariates/maf/<maf>/<token>",
             methods=["POST"])
def compute_gwa_with_loco_covar(k_filename, maf, token):
    """Compute GWA values. No Covariates provided. Only loco and maf vals given.

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile, covarfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps", "covar"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile, covarfile]):
            raise FileNotFoundError
        gemma_kwargs = {
            "g": genofile,
            "p": phenofile,
            "a": snpsfile,
            "c": covarfile,
            "lmm": _dict.get("lmm", 9),
            "maf": float(maf)
        }
        results = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "loco": f"--input {os.path.join(working_dir, k_filename)}"
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=results.get("gemma_cmd")),
                       status="queued",
                       output_file=results.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/k-gwa-compute/<token>", methods=["POST"])
def compute_k_gwa(token):
    """Given a genofile, traitfile, snpsfile, and the token, compute the k-values
and return <hash-of-inputs>.json with a UNIQUE-ID of the job. The genofile,
traitfile, and snpsfile are extracted from a metadata.json file. No Loco no
covars; lmm defaults to 9!

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {"g": genofile, "p": phenofile, "a": snpsfile}
        gemma_k_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs)
        gemma_kwargs["lmm"] = _dict.get("lmm", 9)
        gemma_gwa_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "input": os.path.join(working_dir,
                                      gemma_k_cmd.get("output_file"))
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=(f"{gemma_k_cmd.get('gemma_cmd')} && "
                 f"{gemma_gwa_cmd.get('gemma_cmd')}")),
                       status="queued",
                       output_file=gemma_gwa_cmd.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/k-gwa-compute/covars/<token>", methods=["POST"])
def compute_k_gwa_with_covars_only(token):
    """Given a genofile, traitfile, snpsfile, and the token, compute the k-values
and return <hash-of-inputs>.json with a UNIQUE-ID of the job. The genofile,
traitfile, and snpsfile are extracted from a metadata.json file. No Loco no
covars; lmm defaults to 9!

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile, covarfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps", "covar"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {"g": genofile, "p": phenofile, "a": snpsfile}
        gemma_k_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs)
        gemma_kwargs["c"] = covarfile
        gemma_kwargs["lmm"] = _dict.get("lmm", 9)
        gemma_gwa_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "input": os.path.join(working_dir,
                                      gemma_k_cmd.get("output_file"))
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=(f"{gemma_k_cmd.get('gemma_cmd')} && "
                 f"{gemma_gwa_cmd.get('gemma_cmd')}")),
                       status="queued",
                       output_file=gemma_gwa_cmd.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/k-gwa-compute/loco/<chromosomes>/maf/<maf>/<token>",
             methods=["POST"])
def compute_k_gwa_with_loco_only(chromosomes, maf, token):
    """k-gwa-compute; Loco no covars; lmm defaults to 9!

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {"g": genofile, "p": phenofile, "a": snpsfile}
        gemma_k_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            chromosomes=chromosomes)
        gemma_kwargs["maf"] = float(maf)
        gemma_kwargs["lmm"] = _dict.get("lmm", 9)
        gemma_gwa_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "loco":
                ("--input "
                 f"{os.path.join(working_dir, gemma_k_cmd.get('output_file'))}"
                 )
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=(f"{gemma_k_cmd.get('gemma_cmd')} && "
                 f"{gemma_gwa_cmd.get('gemma_cmd')}")),
                       status="queued",
                       output_file=gemma_gwa_cmd.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")


@gemma.route("/k-gwa-compute/covars/loco/<chromosomes>/maf/<maf>/<token>",
             methods=["POST"])
def compute_k_gwa_with_loco_and_cavar(chromosomes, maf, token):
    """k-gwa-compute; Loco with covars; lmm defaults to 9!

    """
    working_dir = os.path.join(current_app.config.get("TMPDIR"), token)
    _dict = jsonfile_to_dict(os.path.join(working_dir, "metadata.json"))
    try:
        genofile, phenofile, snpsfile, covarfile = [
            os.path.join(working_dir, _dict.get(x))
            for x in ["geno", "pheno", "snps", "covar"]
        ]
        if not do_paths_exist([genofile, phenofile, snpsfile]):
            raise FileNotFoundError
        gemma_kwargs = {"g": genofile, "p": phenofile, "a": snpsfile}
        gemma_k_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            chromosomes=chromosomes)
        gemma_kwargs["c"] = covarfile
        gemma_kwargs["maf"] = float(maf)
        gemma_kwargs["lmm"] = _dict.get("lmm", 9)
        gemma_gwa_cmd = generate_gemma_cmd(
            gemma_cmd=current_app.config.get("GEMMA_"
                                             "WRAPPER_CMD"),
            output_dir=current_app.config.get('TMPDIR'),
            token=token,
            gemma_kwargs=gemma_kwargs,
            gemma_wrapper_kwargs={
                "loco":
                ("--input "
                 f"{os.path.join(working_dir, gemma_k_cmd.get('output_file'))}"
                 )
            })
        return jsonify(unique_id=queue_cmd(
            conn=redis.Redis(),
            email=(request.get_json() or {}).get('email'),
            job_queue=current_app.config.get("REDIS_JOB_QUEUE"),
            cmd=(f"{gemma_k_cmd.get('gemma_cmd')} && "
                 f"{gemma_gwa_cmd.get('gemma_cmd')}")),
                       status="queued",
                       output_file=gemma_gwa_cmd.get("output_file"))
    # pylint: disable=W0703
    except Exception:
        return jsonify(
            status=128,
            # use better message
            message="Metadata file non-existent!")