-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.py
2062 lines (1860 loc) · 102 KB
/
main.py
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request, redirect, url_for, json, jsonify, flash
#from src.job import Job
import src.queue as q
import os
import signal
import base64
from celery import Celery
import subprocess
from src.system import System
from celery.utils.log import get_task_logger
import random
import time
import fnmatch
import subprocess
from subprocess import Popen, PIPE, CalledProcessError
import sys
import re
import threading
import gzip
import glob
import argparse
import redis
import traceback
import functools
import inspect
import pandas as pd
import numpy as np
VERSION = "0.4.4"
ARTIC_VERSION = "1.2.1"
DOCS = "/static/site/index.html"
print(DOCS)
pd.set_option('display.width', 1000)
pd.set_option('colheader_justify', 'center')
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
redis_port = sys.argv[1]
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
# Celery configuration
# app.config['CELERY_BROKER_URL'] = 'redis://localhost:7777/0'
# app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:7777/0'
app.config['CELERY_BROKER_URL'] = 'redis://localhost:{}/0'.format(redis_port)
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:{}/0'.format(redis_port)
app.secret_key = "shhhh"
# Initialize Celery
# celery = Celery(app.name)
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
logger = get_task_logger(__name__)
#Define maximum queue size
max_queue_size = 10
#Create a System object with a queue of length maximum_queue_size
qSys = System(max_queue_size)
if fnmatch.fnmatch(sys.argv[0], "*celery"):
test_arg = False
for a in sys.argv:
if a == "-b":
test_arg = True
continue
if test_arg:
redis_port_arg = a
break
# worker_port = int(sys.argv[5].split(":")[2].split("/")[0])
worker_port = int(redis_port_arg.split(":")[2].split("/")[0])
red = redis.StrictRedis(host='localhost', port=worker_port, db=0)
#Global variable for base filepath
#initialised as /user/data
# plot_file = os.path.dirname(os.path.realpath(__file__))+'/plots.py'
config_file = os.path.dirname(os.path.realpath(__file__))+'/config.init'
primer_folder = os.path.dirname(os.path.realpath(__file__))+'/primer-schemes'
with open(config_file) as f:
data = json.load(f)
input_filepath = data['data-folder']
sample_csv = data['sample-barcode-csvs']
schemes = {}
# nCoV-2019 schemes
schemes['nCoV_2019_eden_V1_scheme'] = os.path.join(primer_folder, "eden")
schemes['nCoV_2019_eden_V1_scheme_name'] = "nCoV-2019/V1"
schemes['nCoV_2019_midnight_V1_scheme'] = os.path.join(primer_folder, "midnight")
schemes['nCoV_2019_midnight_V1_scheme_name'] = "nCoV-2019/V1"
schemes['nCoV_2019_artic_V1_scheme'] = os.path.join(primer_folder, "artic")
schemes['nCoV_2019_artic_V1_scheme_name'] = "nCoV-2019/V1"
schemes['nCoV_2019_artic_V2_scheme'] = os.path.join(primer_folder, "artic")
schemes['nCoV_2019_artic_V2_scheme_name'] = "nCoV-2019/V2"
schemes['nCoV_2019_artic_V3_scheme'] = os.path.join(primer_folder, "artic")
schemes['nCoV_2019_artic_V3_scheme_name'] = "nCoV-2019/V3"
schemes['nCoV_2019_artic_V4_scheme'] = os.path.join(primer_folder, "artic")
schemes['nCoV_2019_artic_V4_scheme_name'] = "nCoV-2019/V4"
# ZaireEbola shemes
schemes['IturiEBOV_artic_V1_scheme'] = os.path.join(primer_folder, "artic")
schemes['IturiEBOV_artic_V1_scheme_name'] = "IturiEBOV/V1"
@app.route('/getCheckTasksUrl', methods = ['POST'])
def getCheckTasksUrl():
return jsonify({}), 202, {'Location': url_for('checkTasks')}
@app.route('/checkTasks')
def checkTasks():
queueList = []
completedList = []
changed = False
for job in qSys.queue.getItems():
if job.task_id:
task = executeJob.AsyncResult(job.task_id)
if task.ready():
qSys.moveJobToComplete(job.job_name)
changed = True
#Don't add this job to queueList (we don't want it to display in the queue)
continue
queueList.append({job.job_name : url_for('progress', job_name=job.job_name, task_id = job.task_id)})
for job in qSys.completed:
completedList.append({job.job_name : url_for('delete', job_name=job.job_name)})
queueDict = {'jobs': queueList}
for key, value in queueDict.items():
print(key, value)
completedDict = {'jobs': completedList}
for key, value in completedDict.items():
print(key, value)
return json.htmlsafe_dumps({'changed': changed, 'queue': queueDict, 'completed': completedDict})
def check_override(output_folder, override_data, skip):
print("Checking output folder:::", output_folder)
if(not os.path.exists(output_folder)):
if skip > 0:
return False
return True
dir_files = os.listdir(output_folder)
if len(dir_files) > 1 and override_data is False:
if skip > 0:
return False
return True
elif len(dir_files) == 1 and dir_files[0] == "all_cmds_log.txt":
print("checking files:::",dir_files)
if os.path.getsize(output_folder+"/all_cmds_log.txt") > 0:
if skip > 0:
return False
return True
return False
@celery.task(bind=True)
def executeJob(self, job_name, gather_cmd, guppyplex_cmd, demult_cmd, min_cmd, plot_cmd, step):
logger.info("In celery task, executing job...")
logger.info("executing job_name: {}".format(job_name))
logger.info("Starting from step: {}".format(step))
# Step is a debug command to start at 0, 1, 2, 3 in the commands list with
# an existing job_name, as it should build all the commands as usual
# but not execute them, so if I just want to do plots, I can use skip=3
# group ID to kill children
# {"job_name": #####}
Anakin = {}
self.update_state(state='PROGRESS', meta={'current':10, 'status':'Beginning execution'})
if guppyplex_cmd != "":
sys.stderr.write("guppyplex_cmd detected\n")
commands = [guppyplex_cmd, min_cmd, plot_cmd]
else:
sys.stderr.write("guppyplex_cmd NOT detected\n")
# sys.stderr.write(guppyplex_cmd+"\n")
commands = [gather_cmd, demult_cmd, min_cmd, plot_cmd]
for i, cmd in enumerate(commands[step:]):
po = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
Anakin[job_name] = po.pid
rval = json.dumps(Anakin)
red.set(str(job_name), rval)
# k = ["{}: {}".format(key, Anakin[key]) for key in Anakin.keys()]
# sys.stderr.write(",".join(k))
# sys.stderr.write("\n")
stdout, stderr = po.communicate()
#self.update_state(state='PROGRESS')
po.wait()
if i == 0:
status = "Successfully ran gather"
n = 50
else:
status = "Successfully ran minion"
n = 90
self.update_state(state='PROGRESS', meta={'current': n, 'status': status, 'command': cmd})
returnCode = po.returncode
if returnCode != 0:
self.update_state(state='FAILURE', meta={'exc_type': "STAND IN TYPE", 'exc_message': traceback.format_exc().split('\n'), 'current': n, 'status': 'Command failed', 'command': cmd})
raise Exception("Command {} got return code {}.\nSTDOUT: {}\nSTDERR: {}".format(cmd, returnCode, stdout, stderr))
break
print("JOB CMD {} RETURNED: {}".format(cmd, returnCode))
self.update_state(state='FINISHED', meta={'current': 100, 'status': 'Finishing', 'result': returnCode}) #Don't know if this is actually used
return {'current': 100, 'total': 100, 'status': 'Task completed!', 'result': returnCode}
@celery.task(bind=True)
def killJob(self, job_name):
logger.info("In celery task, executing job...")
logger.info("killing job_name: {}".format(job_name))
pidss = red.get(str(job_name))
Anakin = json.loads(pidss)
if not Anakin:
sys.stderr.write("ANAKIN EMPTY!!!\n")
else:
# k = ["{}: {}".format(key, Anakin[key]) for key in Anakin.keys()]
# sys.stderr.write(",".join(k))
try:
# k = ["{}: {}".format(key, Anakin[key]) for key in Anakin.keys()]
# sys.stderr.write(",".join(k))
group_pid = Anakin[job_name]
sys.stderr.write("killing PID: {}\n".format(group_pid))
os.killpg(group_pid, signal.SIGTERM)
except:
traceback.print_exc()
sys.stderr.write("killJob FAILED - 1")
sys.stderr.write("\n")
return 1
sys.stderr.write("killJob SUCCESS - 0")
sys.stderr.write("\n")
return 0
sys.stderr.write("killJob FAILED (ANAKIN EMPTY) - 1")
sys.stderr.write("\n")
return 1
@celery.task(bind=True)
def getVersions(self, from_file=False):
root = os.path.join(os.path.dirname(os.path.realpath(__file__)))
bin_path = os.path.join(root, "artic_bin", "bin")
logger.info("In celery task, getting software versions...")
version_file = os.path.join(root, "version_dump.txt")
logger.info(version_file)
version_dic = {"interartic": VERSION,
"artic": "UNKNOWN",
"medaka": "UNKNOWN",
"nanopolish": "UNKNOWN",
"minimap2": "UNKNOWN",
"samtools": "UNKNOWN",
"bcftools": "UNKNOWN",
"muscle": "UNKNOWN",
"longshot": "UNKNOWN"}
def _versions():
cmd_list = ["{}/artic --version | cut -d ' ' -f2 | awk '{}' >> {}".format(bin_path, '{print "artic " $1}', os.path.join(root, "version_dump.txt")),
"{}/medaka --version | cut -d ' ' -f2 | awk '{}' >> {}".format(bin_path, '{print "medaka " $1}', os.path.join(root, "version_dump.txt")),
"{}/nanopolish --version | head -1 | cut -d ' ' -f3 | awk '{}' >> {}".format(bin_path, '{print "nanopolish " $1}', os.path.join(root, "version_dump.txt")),
"{}/minimap2 --version | awk '{}' >> {}".format(bin_path, '{print "minimap2 " $1}', os.path.join(root, "version_dump.txt")),
"{}/samtools --version | head -1 | cut -d ' ' -f2 | awk '{}' >> {}".format(bin_path, '{print "samtools " $1}', os.path.join(root, "version_dump.txt")),
"{}/bcftools --version | head -1 | cut -d ' ' -f2 | awk '{}' >> {}".format(bin_path, '{print "bcftools " $1}', os.path.join(root, "version_dump.txt")),
"{}/muscle --version 2>&1 | head -3 | tail -1 | cut -d ' ' -f2 | awk '{}' >> {}".format(bin_path, '{print "muscle " $1}', os.path.join(root, "version_dump.txt")),
"{}/longshot --version 2>&1 | tail -1 | cut -d ' ' -f2 | awk '{}' >> {}".format(bin_path, '{print "longshot " $1}', os.path.join(root, "version_dump.txt")),
]
for cmd in cmd_list:
os.system(cmd)
if not from_file:
if os.path.isfile(version_file):
# remove and re-make
logger.info("File found and deleting")
os.remove(version_file)
logger.info("File being re-made")
_versions()
if not os.path.isfile(version_file):
logger.info("File not found, building..")
_versions()
# final check to see if the file was made
if not os.path.isfile(version_file):
# error making file
logger.info("File STILL not found, error")
flash("WARNING: Could not construct software version table in: {}".format(version_file))
if os.path.isfile(version_file):
# read file
logger.info("Reading file")
with open(version_file, 'r') as f:
for l in f:
l = l.strip("\n")
l = l.split(" ")
if len(l) > 1:
name = l[0]
version = l[1]
if name in list(version_dic.keys()):
if version == "1:":
continue
version_dic[name] = version
else:
if os.path.isfile(version_file):
# read file
logger.info("Reading file")
with open(version_file, 'r') as f:
for l in f:
l = l.strip("\n")
l = l.split(" ")
if len(l) > 1:
name = l[0]
version = l[1]
if name in list(version_dic.keys()):
if version == "1:":
continue
version_dic[name] = version
return version_dic
@app.route('/task/<job_name>', methods = ['POST'])
def task(job_name):
job = qSys.getJobByName(job_name)
return jsonify({}), 202, {'Location': url_for('task_status', task_id = job.task_id, job_name = job.job_name)}
@app.route('/status/<task_id>')
def task_status(task_id):
task = executeJob.AsyncResult(task_id)
print("TASK.READY: ", task.ready())
if task.state == 'PENDING':
response = {
'state': task.state,
'current': 0,
'total': 100,
'status': 'Pending...'
}
elif task.state != 'FAILURE':
response = {
'state': task.state,
'current': task.info.get('current', 0),
'total': 100,
'status': task.info.get('status', '')
}
if 'result' in task.info:
response['result'] = task.info['result']
else:
# something went wrong in the background job
response = {
'state': task.state,
'current': 1,
'total': 100,
'status': str(task.info), # this is the exception raised
}
return json.htmlsafe_dumps(response)
@app.route("/")
def route():
return redirect(url_for('home'))
@app.route("/home",methods = ["POST", "GET"])
def home():
errors = {}
if request.method == "POST":
# get global variables
search_input = request.form.get('file_path')
search_csv = request.form.get('csv_folder')
# error checking here
if not os.path.isdir(search_input):
errors['invalid_input_file_path'] = "File path entered is not valid"
if not os.path.isdir(search_csv):
errors['invalid_csv_file_path'] = "File path entered is not valid"
# sys.stderr.write("errors:\n")
# k = ["{}: {}".format(key, errors[key]) for key in errors.keys()]
# sys.stderr.write(",".join(k))
# sys.stderr.write("\n")
# sys.stderr.write("search_input: {}\n".format(request.form.get('search_input')))
# sys.stderr.write("add_job: {}\n".format(request.form.get('add_job')))
if request.form.get('search_input') == 'Confirm':
if len(errors) != 0:
return render_template("home.html", input_folder=search_input, errors=errors, csv_folder=search_csv, search_csv=search_csv, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
global input_filepath
input_filepath = search_input
global sample_csv
sample_csv = search_csv
# Save config if paths all work
with open(os.path.dirname(os.path.realpath(__file__))+"/config.init", 'w') as c:
c.write("{\n")
c.write('\t"data-folder": "{}",\n'.format(search_input))
c.write('\t"sample-barcode-csvs": "{}"'.format(search_csv))
c.write('}\n')
if request.form.get('add_job') == "Add Job":
if len(errors) != 0:
flash("WARNING:File paths entered are not valid")
return render_template("home.html", input_folder=search_input, errors=errors, csv_folder=search_csv, search_csv=search_csv, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
else:
return redirect(url_for('parameters'))
# return render_template("home.html", input_folder=input_filepath, csv_folder=sample_csv, eden_folder=schemes['eden_scheme'], eden_name=schemes['eden_scheme_name'], midnight_folder=schemes['midnight_scheme'], midnight_name=schemes['midnight_scheme_name'], artic_folder=schemes['artic_scheme'], artic_name=schemes['artic_scheme_name'])
return render_template("home.html", input_folder=input_filepath, csv_folder=sample_csv, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
@app.route("/about")
def about():
# Get version info to display on about page
tasks_running = False
for job in qSys.queue.getItems():
if job.task_id:
tasks_running = True
if tasks_running:
res = getVersions(from_file=True)
version_dic = res
else:
res = getVersions.delay()
version_dic = res.get()
return render_template("about.html", VERSION_DIC=version_dic, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
def check_special_characters(func):
@functools.wraps(func)
def wraper_check_char(*args, **kwargs):
"""
check input args for special characters
return error dic handled after call
"""
def _detect_special_characer(pass_string, filename=False):
ret = False
if filename:
# regex= re.compile('^[a-zA-Z0-9._/-]+$')
char_set = set("<>,?:;|}{][+=)(*&^%$#@! ")
for e in pass_string:
if e in char_set:
sys.stderr.write("this character fails: {}\n".format(e))
ret = True
else:
# regex= re.compile('^[a-zA-Z0-9_/-]+$')
char_set = set("<>,?:;|}{][+=)(*&^%$#@! ")
for e in pass_string:
if e in char_set:
sys.stderr.write("this character fails: {}\n".format(e))
ret = True
return ret
# gets names of arguments
args_name = inspect.getargspec(func)[0]
# argnames: values into dic
args_dict = dict(zip(args_name, args))
errors = {}
for arg in args_dict:
a = args_dict[arg]
if a:
# sys.stderr.write(str(a))
# sys.stderr.write("\n")
if arg == "csv_filepath":
if _detect_special_characer(str(a), filename=True):
errors["char_error_{}".format(arg)] = "Invalid character in {}: ' {} ', please use utf-8 alpha/numerical or . _ - /".format(arg, str(a))
continue
if _detect_special_characer(str(a)):
errors["char_error_{}".format(arg)] = "Invalid character in {}: ' {} ', please use utf-8 alpha/numerical or _ - /".format(arg, str(a))
if len(errors) != 0:
return errors, args[1]
return func(*args, **kwargs)
return wraper_check_char
@check_special_characters
def checkInputs(input_folder, output_folder, primer_scheme_dir, read_file, pipeline, override_data, min_length, max_length, job_name, output_input, csv_filepath, skip, num_samples):
errors = {}
#Check of jobname is used
if qSys.getJobByName(job_name) is not None:
errors['job_name'] = "Job Name has already been used."
flash("Warning: Job Name has already been used.")
return errors, output_folder
if not input_folder:
errors['input_folder'] = "Input Directory does not exist"
flash("Warning: Input folder does not exist, please check input and try again")
return errors, output_folder
if num_samples == "multiple":
if not os.path.isfile(csv_filepath):
errors['csv_file'] = "csv file does not exist"
flash("Warning: CSV file does not exist, please check input and try again")
return errors, output_folder
#give error if input folder path is empty
if len(os.listdir(input_folder)) == 0:
errors['input_folder'] = "Directory is empty."
flash("Warning: Input folder contains no data, please check input and try again")
return errors, output_folder
io_check = output_input.strip("/")
if_check = input_folder.strip("/")
sys.stderr.write("io_check: {}\n".format(io_check))
sys.stderr.write("if_check: {}\n".format(if_check))
if io_check == if_check:
errors['input_output_folder'] = "Output directory will be in the same folder as data"
flash("Warning: Output directory will be in the same folder as data, please check data structure info in documentation.")
return errors, output_folder
#if no output folder entered, creates one inside of input folder
if not output_folder and not os.path.isdir(output_input):
errors['input_output_folder'] = "Input and output don't exist"
flash("Warning: Input and output don't exist!")
return errors, output_folder
elif not output_folder and os.path.isdir(output_input):
output_folder = output_input + "/output"
elif output_folder and os.path.isdir(output_input):
if output_folder[0] == "/":
check_out = "/".join(output_folder.split("/")[:-1])
if not os.path.isdir(check_out):
errors['output_folder'] = "Parent directory of new output folder ( {} ) does not exist".format(check_out)
flash("Warning: Parent directory of new output folder ( {} ) does not exist".format(check_out))
return errors, output_folder
else:
output_folder = output_input + "/" + output_folder
else:
errors['input_folder'] = "Input folder does not exist, pleas check: {}".format(output_input)
flash("Warning: Input folder does not exist, pleas check: {}".format(output_input))
return errors, output_folder
if output_folder[-1] == "/":
output_folder = output_folder[:-1]
if primer_scheme_dir[-1] == "/":
primer_scheme_dir = primer_scheme_dir[:-1]
#give error if primer schemes folder path is invalid or empty
if not os.path.isdir(primer_scheme_dir):
errors['primer_scheme_dir'] = "Invalid path."
flash("Warning: primer_scheme_dir does not exist, pleas check: {}".format(primer_scheme_dir))
return errors, output_folder
elif len(os.listdir(primer_scheme_dir)) == 0:
errors['primer_scheme_dir'] = "Directory is empty."
flash("Warning: Primer_scheme_dir is empty, pleas check: {}".format(primer_scheme_dir))
return errors, output_folder
#if read file is specified by user
if read_file:
if not os.path.isfile(read_file):
errors['read_file'] = "Invalid path/file."
else:
#to be filled later
read_file = ""
# if pipeline in ["both", "nanopolish"]:
# # check for sequencing summary file for nanopolish
# seq_sum_found = False
# for file in os.listdir(input_folder):
# if fnmatch.fnmatch(file, "*sequencing_summary*.txt"):
# seq_sum_found = True
# if not seq_sum_found:
# flash("Warning: sequencing_summary.txt file not found in input folder structure")
# errors['input_folder'] = "sequencing_summary.txt file not found"
# return errors, output_folder
#both pipelines running
if pipeline == "both":
# TODO: check all os.system() calls
if not os.path.exists(output_folder):
make_dir = 'mkdir ' + output_folder
if os.system(make_dir) != 0:
errors['mkdir'] = "Failed to create output directory, please check parent path exists and has write permission"
flash("Warning: Failed to create output directory, please check parent path exists and has write permission")
return errors, output_folder
if override_data is True and os.path.exists(output_folder):
# remove = "rm -r " + output_folder + "/all_cmds_log.txt"
remove = "rm -r " + output_folder
if os.system(remove) !=0:
errors['remove_folder'] = "Could not detele output_directory"
flash("Warning: Could not delete {}".format(output_folder))
return errors, output_folder
make_dir = 'mkdir ' + output_folder
if os.system(make_dir) != 0:
errors['mkdir'] = "Failed to create output directory, please check parent path exists and has write permission"
flash("Warning: Failed to create output directory, please check parent path exists and has write permission")
return errors, output_folder
elif check_override(output_folder, override_data, skip) and os.path.exists(output_input):
errors['override'] = True
flash("Warning: Output folder is NOT empty. Please choose another folder or delete/move files in it.")
return errors, output_folder
#if the output folder does not exist, it is created
if not os.path.exists(output_folder + "/medaka"):
# make_dir = 'mkdir ' + output_folder
# if os.system(make_dir) != 0:
# errors['mkdir_m1'] = "Failed to create output directory, please check parent path exists and has write permission"
# flash("Warning: Could not mkdir {}".format(output_folder))
# return errors, output_folder
make_dir_m = 'mkdir ' + output_folder + '/medaka'
if os.system(make_dir_m) != 0:
errors['mkdir_m2'] = "Failed to create medaka directory, please check parent path exists and has write permission"
flash("Warning: Could not mkdir {}/medaka".format(output_folder))
return errors, output_folder
#if the output folder does not exist, it is created
if not os.path.exists(output_folder + "/nanopolish"):
# make_dir = 'mkdir ' + output_folder
# # os.system(make_dir)
# if os.system(make_dir) != 0:
# errors['mkdir_n1'] = "Failed to create output directory, please check parent path exists and has write permission"
# flash("Warning: Could not mkdir {}".format(output_folder))
# return errors, output_folder
make_dir_n = 'mkdir ' + output_folder + '/nanopolish'
if os.system(make_dir_n) != 0:
errors['mkdir_n2'] = "Failed to create nanopolish directory, please check parent path exists and has write permission"
flash("Warning: Could not mkdir {}/nanopolish".format(output_folder))
return errors, output_folder
if check_override(output_folder + "/medaka", override_data, skip) and os.path.exists(output_input):
flash("Warning: Output folder is NOT empty. Please choose another folder or delete/move files in it.")
errors['override'] = True
return errors, output_folder
if check_override(output_folder + "/nanopolish", override_data, skip) and os.path.exists(output_input):
flash("Warning: Output folder is NOT empty. Please choose another folder or delete/move files in it.")
errors['override'] = True
return errors, output_folder
# Make empty log file for initial progress rendering
make_log_m = 'touch \"' + output_folder + '\"/medaka/all_cmds_log.txt'
make_log_n = 'touch \"' + output_folder + '\"/nanopolish/all_cmds_log.txt'
if os.system(make_log_m) != 0:
errors['touch_m'] = "Failed to write to output directory, please check path exists and has write permission"
flash("Warning: Failed to write to output directory, please check path exists and has write permission")
return errors, output_folder
if os.system(make_log_n) != 0:
errors['touch_n'] = "Failed to write to output directory, please check path exists and has write permission"
flash("Warning: Failed to write to output directory, please check path exists and has write permission")
return errors, output_folder
else:
#TODO: if not "both" still make the folders medaka | nanopolish based on selection
#if the output folder does not exist, it is created
if not os.path.exists(output_folder):
make_dir = 'mkdir ' + output_folder
if os.system(make_dir) != 0:
errors['mkdir'] = "Failed to create output directory, please check parent path exists and has write permission"
flash("Warning: Failed to create output directory, please check parent path exists and has write permission")
return errors, output_folder
if override_data is True:
# remove = "rm -r " + output_folder + "/all_cmds_log.txt"
remove = "rm -r " + output_folder
if os.system(remove) !=0:
errors['remove_folder'] = "Could not detele output_directory"
flash("Warning: Could not delete {}".format(output_folder))
return errors, output_folder
make_dir = 'mkdir ' + output_folder
if os.system(make_dir) != 0:
errors['mkdir'] = "Failed to create output directory, please check parent path exists and has write permission"
flash("Warning: Failed to create output directory, please check parent path exists and has write permission")
return errors, output_folder
elif check_override(output_folder, override_data, skip) and os.path.exists(output_input):
errors['override'] = True
flash("Warning: Output folder is NOT empty. Please choose another folder or delete/move files in it.")
return errors, output_folder
# Make empty log file for initial progress rendering
make_log = 'touch \"' + output_folder + '\"/all_cmds_log.txt'
if os.system(make_log) != 0:
errors['touch'] = "Failed to write to output directory, please check path exists and has write permission"
flash("Warning: Failed to create log file, please check parent path exists and has write permission")
return errors, output_folder
#check length parameters are valid
if min_length.isdigit() == False:
errors['invalid_length'] = "Invalid minimum length."
if max_length.isdigit() == False:
errors['invalid_length'] = "Invalid maximum and minimum length."
elif max_length.isdigit() == False:
errors['invalid_length'] = "Invalid maximum length."
elif int(max_length) < int(min_length):
errors['invalid_length'] = "Invalid parameters: Maximum length smaller than minimum length."
return errors, output_folder
def getInputFolders(filepath):
# find all the current input folders
checkFoldersCmd = "cd && cd " + filepath + " && ls"
print("check folders command")
print(checkFoldersCmd)
folders = subprocess.check_output(checkFoldersCmd, shell=True, stderr=subprocess.STDOUT).decode("utf8").split("\n")
# folders = subprocess.check_output(checkFoldersCmd, shell=True, stderr=subprocess.STDOUT).decode("ascii").split("\n")
return folders
@app.route("/parameters", methods = ["POST","GET"])
def parameters():
# get global variables for use
global input_filepath
global sample_csv
global schemes
# get a list of all the folders in the input and csv folders to be displayed to the user
folders = getInputFolders(input_filepath)
csvs = getInputFolders(sample_csv)
if request.method == "POST":
# get curr queue
queueList = []
if not qSys.queue.empty():
for item in qSys.queue.getItems():
queueList.append({item._job_name : url_for('progress', job_name=item._job_name, task_id = item._task_id)})
queueDict = {'jobs': queueList}
displayQueue = json.htmlsafe_dumps(queueDict)
#get parameters
job_name = request.form.get('job_name')
input_folder = request.form.get('input_folder')
read_file = request.form.get('read_file')
primer_scheme_dir = request.form.get('primer_scheme_dir')
primer_scheme = request.form.get('primer_scheme')
primer_type = request.form.get('primer_type')
other_primer_type = request.form.get('other_primer_type')
output_folder = request.form.get('output_folder')
normalise = request.form.get('normalise')
num_threads = request.form.get('num_threads')
pipeline = request.form.get('pipeline')
num_samples = request.form.get('num_samples')
min_length = request.form.get('min_length')
max_length = request.form.get('max_length')
bwa = request.form.get('bwa')
skip_nanopolish = request.form.get('skip_nanopolish')
dry_run = request.form.get('dry_run')
# num_samples = request.form.get('num_samples')
guppyplex = request.form.get('guppyplex')
barcode_type = request.form.get('barcode_type')
csv_file = request.form.get('csv_file')
virus = request.form.get('virus')
override_data = request.form.get('override_data')
# DEBUG
step = int(request.form.get('step'))
sys.stderr.write("override_data: {}\n".format(override_data))
sys.stderr.write("guppyplex: {}\n".format(guppyplex))
# set correct primer_type - if primer type is other, get the correct primer type from the tet input
# primer_select is so that on reload, the correct radio button will be selected
primer_select = primer_type
if virus == 'custom':
if other_primer_type:
primer_type = other_primer_type
else:
primer_type = "Custom-primer-scheme"
# store input_name
input_name = input_folder
#csv filepath
csv_filepath = sample_csv + '/' + csv_file
# concat /data to input folder
# global input_filepath
input_folder = input_filepath + '/' + input_folder
filename = os.path.dirname(os.path.realpath(__file__))
# if no output folder entered, creates one inside of input folder
# Do this to put output above input folder to stop fastq cross talk
# if not output_folder:
# output_folder = input_folder + "/output"
# else:
# if output_folder[0] != "/":
# output_folder = input_folder + output_folder
if not os.path.isdir(input_folder):
input_folder = ""
output_input = ""
else:
os.chdir(input_folder)
tmp_oi = os.getcwd()
output_input = tmp_oi
# get the correct input folder filepath from user input
# path = glob.glob(input_folder + '/*/*')[0]
# use fnmatch with walk to get fastq_pass, fastq_fail folders
# then split off the last bit to get the top folder for the gather command
tmp_folder_list = []
for dName, sdName, fList in os.walk(input_folder):
for fileName in sdName:
if fnmatch.fnmatch(fileName, "fastq*"):
tmp_folder_list.append(os.path.join(dName, fileName))
elif fnmatch.fnmatch(fileName, "barcode*"):
tmp_folder_list.append(os.path.join(dName, fileName))
if len(tmp_folder_list) == 0:
queueList = []
flash("Warning: Could not locate fastq files in {}. Check the file names, demultiplexing options and the directory structure is compatible".format(input_folder))
errors = {}
if qSys.queue.empty():
return render_template("parameters.html", job_name=job_name, queue=None,
input_name=input_name, input_folder=input_folder,
output_folder=output_folder, virus=virus,
pipeline=pipeline, min_length=min_length,
max_length=max_length, primer_scheme=primer_scheme,
primer_type=primer_type, num_samples=num_samples,
primer_scheme_dir=primer_scheme_dir, guppyplex=guppyplex, barcode_type=barcode_type,
errors=errors, folders=folders, csvs=csvs, csv_name=csv_file,
other_primer_type=other_primer_type, primer_select=primer_select,
schemes=schemes, override_data=override_data, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
return render_template("parameters.html", job_name=job_name, queue=displayQueue,
input_name=input_name, input_folder=input_folder,
output_folder=output_folder, virus=virus,
pipeline=pipeline, min_length=min_length,
max_length=max_length, primer_scheme=primer_scheme,
primer_type=primer_type, num_samples=num_samples,
primer_scheme_dir=primer_scheme_dir, guppyplex=guppyplex, barcode_type=barcode_type,
errors=errors,folders=folders, csvs=csvs, csv_name=csv_file,
other_primer_type=other_primer_type, primer_select=primer_select,
schemes=schemes, override_data=override_data, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
# this takes the first encountered (so fastq_pass or a barcode folder depending on how the user demuxed or not)
# It looks at sdName above, not filenames!!!! so here when it splits, it keeps all BUT the sdName, so it gets the containing parent directory
tmp_path = tmp_folder_list[0].split("/")[:-1]
path = "/".join(tmp_path)
os.chdir(path)
input_folder = os.getcwd()
#if user agrees output can override files with the same name in output folder
if request.form.get('override_data'):
override_data = True
else:
override_data = False
# check errors
errors = {}
errors, output_folder_checked = checkInputs(input_folder, output_folder, primer_scheme_dir,
read_file, pipeline, override_data, min_length,
max_length, job_name, output_input, csv_filepath, step, num_samples)
# if an output folder does not exist, make one
# if not output_folder:
# output_folder = output_folder_checked
output_folder = output_folder_checked
# validate csv contents.
# No special characters -
# comma separated -
# 2 columns -
# 2nd column should have NB or RB or BC-
def _detect_special(pass_string):
regex= re.compile('^[a-zA-Z0-9,_-]+$')
if(regex.search(pass_string) == None):
ret = True
else:
ret = False
return ret
sys.stderr.write("checking CSV file: {}\n".format(csv_filepath))
if os.path.isfile(csv_filepath):
sys.stderr.write("csv file exists\n")
with open(csv_filepath, 'r') as c:
for l in c:
l = l.strip("\n")
if _detect_special(l):
flash("Warning: csv file malformed: special characters detected ")
errors['csv_malformed'] = "csv is malformed, special characters detected a-zA-Z0-9,_- only"
break
l = l.split(",")
if len(l) != 2:
errors['csv_malformed'] = "csv is malformed, more or less than 2 columns"
flash("Warning: csv file malformed: more or less than 2 columns")
break
else:
if l[1][:2] not in ["NB", "RB", "BC"]:
errors['csv_malformed'] = "csv is malformed, not NB or RB or BC for barcode"
flash("Warning: csv file malformed: not NB or RB or BC for barcode")
break
sys.stderr.write("printing errors:\n")
k = ["{}: {}".format(key, errors[key]) for key in errors.keys()]
sys.stderr.write(",".join(k))
sys.stderr.write("\n")
# if queue is full, add an error to the list
if qSys.queue.full():
errors['full_queue'] = "Job queue is full."
# display errors if errors exist
if len(errors) != 0:
# k = ["{}: {}".format(key, errors[key]) for key in errors.keys()]
# sys.stderr.write(",".join(k))
# sys.stderr.write("\n")
#Update displayed queue on home page
queueList = []
if qSys.queue.empty():
return render_template("parameters.html", job_name=job_name, queue=None,
input_name=input_name, input_folder=input_folder,
output_folder=output_folder, virus=virus,
pipeline=pipeline, min_length=min_length,
max_length=max_length, primer_scheme=primer_scheme,
primer_type=primer_type, num_samples=num_samples,
primer_scheme_dir=primer_scheme_dir, guppyplex=guppyplex, barcode_type=barcode_type,
errors=errors, folders=folders, csvs=csvs, csv_name=csv_file,
other_primer_type=other_primer_type, primer_select=primer_select,
schemes=schemes, override_data=override_data, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
return render_template("parameters.html", job_name=job_name, queue=displayQueue,
input_name=input_name, input_folder=input_folder,
output_folder=output_folder, virus=virus,
pipeline=pipeline, min_length=min_length,
max_length=max_length, primer_scheme=primer_scheme,
primer_type=primer_type, num_samples=num_samples,
primer_scheme_dir=primer_scheme_dir, guppyplex=guppyplex, barcode_type=barcode_type,
errors=errors,folders=folders, csvs=csvs, csv_name=csv_file,
other_primer_type=other_primer_type, primer_select=primer_select,
schemes=schemes, override_data=override_data, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
#no spaces in the job name - messes up commands
job_name = job_name.replace(" ", "_")
# create new jobs
if pipeline != "both":
#Create a new instance of the Job class
new_job = qSys.newJob(job_name, input_folder, read_file, primer_scheme_dir, primer_scheme, primer_type, output_folder, normalise, num_threads, pipeline, min_length, max_length, bwa, skip_nanopolish, dry_run, override_data, num_samples, guppyplex, barcode_type, input_name, csv_filepath, primer_select, input_name)
#Add job to queue
qSys.addJob(new_job)
print("qSys has jobs: ", qSys.printQueue())
new_task = executeJob.apply_async(args=[new_job.job_name, new_job.gather_cmd, new_job.guppyplex_cmd, new_job.demult_cmd, new_job.min_cmd, new_job.plot_cmd, step])
new_job.task_id = new_task.id
#if both pipelines
else:
#Create a new medaka instance of the Job class
new_job_m = qSys.newJob(job_name + "_medaka", input_folder, read_file, primer_scheme_dir, primer_scheme, primer_type, output_folder + "/medaka", normalise, num_threads, "medaka", min_length, max_length, bwa, skip_nanopolish, dry_run, override_data, num_samples, guppyplex, barcode_type, input_name, csv_filepath, primer_select, input_name)
#Create a new nanopolish instance of the Job class
new_job_n = qSys.newJob(job_name + "_nanopolish", input_folder, read_file, primer_scheme_dir, primer_scheme, primer_type, output_folder + "/nanopolish", normalise, num_threads, "nanopolish", min_length, max_length, bwa, skip_nanopolish, dry_run, override_data, num_samples, guppyplex, barcode_type, input_name, csv_filepath, primer_select, input_name)
#Add medaka job to queue
qSys.addJob(new_job_m)
task_m = executeJob.apply_async(args=[new_job_m.job_name, new_job_m.gather_cmd, new_job_m.guppyplex_cmd, new_job_m.demult_cmd, new_job_m.min_cmd, new_job_m.plot_cmd, step])
new_job_m.task_id = task_m.id
#Add nanopolish job to queue
qSys.addJob(new_job_n)
task_n = executeJob.apply_async(args=[new_job_n.job_name, new_job_n.gather_cmd, new_job_n.guppyplex_cmd, new_job_n.demult_cmd, new_job_n.min_cmd, new_job_n.plot_cmd, step])
new_job_n.task_id = task_n.id
# redirect to the progress page
if pipeline == "both":
return redirect(url_for('progress', job_name=job_name+"_medaka"))
else:
return redirect(url_for('progress', job_name=job_name))
#Update displayed queue on home page
queueList = []
if qSys.queue.empty():
return render_template("parameters.html", queue=None, folders=folders, csvs=csvs, schemes=schemes, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
for item in qSys.queue.getItems():
queueList.append({item._job_name : url_for('progress', job_name=item._job_name, task_id = item._task_id)})
queueDict = {'jobs': queueList}
displayQueue = json.htmlsafe_dumps(queueDict)
return render_template("parameters.html", queue = displayQueue, folders=folders, csvs=csvs, schemes=schemes, VERSION=VERSION, ARTIC_VERSION=ARTIC_VERSION, DOCS=DOCS)
# error page, accessed if a user wants to re-run a job if an error occurs during a run
# @app.route("/error/<job_name>", methods = ["POST","GET"])
# def error(job_name):
# # get the job that needs to be re-run
# job = qSys.getJobByName(job_name)
#
# # get global variables
# global input_filepath
# global sample_csv
# folders = getInputFolders(input_filepath)
# csvs = getInputFolders(sample_csv)
#
# # if the job exists, get all the parameters used in the initial run so that they can be rendered for the user
# if job != None:
# input_folder = job.input_folder
# input_name = job.input_name
# output_folder = job.output_folder
# read_file = job.read_file
# pipeline = job.pipeline
# min_length = job.min_length