forked from appliedbinf/pima_md
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pima.py
3567 lines (2661 loc) · 154 KB
/
pima.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
#!/usr/bin/env python
import copy
import csv
import datetime
import glob
import locale
import logging
import os
import re
import shutil
import statistics
import subprocess
import sys
import time
from argparse import ArgumentParser, HelpFormatter
import numpy
import pandas as pd
import numpy as np
import joblib
import Bio.SeqIO
import pathos.multiprocessing as mp
from dna_features_viewer import GraphicFeature, GraphicRecord
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from MarkdownReport import PimaReport
#from ba_report import PimaReport
pd.set_option('display.max_colwidth', 200)
VERSION=1.1
pima_path = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(pima_path, 'data')
amr_database_default = os.path.join(pima_path, 'data/amr.fasta')
amr_gene_drug_tsv = os.path.join(pima_path, 'data/gene_drug.tsv')
amr_default_color = '#FED976'
inc_database_default = os.path.join(pima_path, 'data/inc.fasta')
inc_default_color = '#0570B0'
included_databases = [amr_database_default, inc_database_default]
plasmid_database_default_fasta = os.path.join(pima_path, 'data/plasmids_and_vectors.fasta')
kraken_database_default = os.path.join(pima_path, 'data/kraken2')
reference_dir_default = os.path.join(pima_path, 'data/reference_sequences')
pima_css = os.path.join(pima_path,'data/pima.css')
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def nicenumber(x, round):
exp = np.floor(np.log10(x))
f = x / 10**exp
if round:
if f < 1.5:
nf = 1.
elif f < 3.:
nf = 2.
elif f < 7.:
nf = 5.
else:
nf = 10.
else:
if f <= 1.:
nf = 1.
elif f <= 2.:
nf = 2.
elif f <= 5.:
nf = 5.
else:
nf = 10.
return nf * 10.**exp
def pretty(low, high, n):
range = nicenumber(high - low, False)
d = nicenumber(range / (n-1), True)
miny = np.floor(low / d) * d
maxy = np.ceil (high / d) * d
return np.arange(miny, maxy+0.5*d, d)
def format_kmg(number, decimals = 0) :
if number == 0 :
return('0')
magnitude_powers = [10**9, 10**6, 10**3, 1]
magnitude_units = ['G', 'M', 'K', '']
for i in range(len(magnitude_units)) :
if number >= magnitude_powers[i] :
magnitude_power = magnitude_powers[i]
magnitude_unit = magnitude_units[i]
return(('{:0.' + str(decimals) + 'f}').format(number / magnitude_power) + magnitude_unit)
class Analysis :
def __init__(self, opts = None, unknown_args = None) :
# The actual steps to carry out in the analysis held as a list
self.analysis = []
# Verbosity levels and colors
self.error_color = Colors.FAIL
self.main_process_verbosity = 1
self.warning_color = Colors.WARNING
self.warning_verbosity = 1
self.main_process_color = Colors.OKGREEN
self.sub_process_verbosity = 2
self.sub_process_color = Colors.OKBLUE
self.command_verbosity = 3
self.errors = []
self.warnings = []
# Watch options
self.ont_watch = None
self.ont_watch_reads_min = 200000
self.ont_watch_time_max = 1 * 60 * 60
self.ont_watch_between_max = 10 * 60
self.ont_watch_sleep_time = 10
# ONT FASTQ input
self.ont_fastq = None
self.ont_raw_fastq = self.ont_fastq
self.ont_read_count = None
self.ont_read_lengths = None
self.will_have_ont_fastq = False
self.ont_read_lengths = []
# Basecalling
self.ont_fast5 = None
self.basecaller = 'guppy'
self.ont_fastq_dir = None
self.only_basecall = False
self.did_guppy_ont_fast5 = False
# Read metadata
self.read_metadata = pd.Series(dtype = object)
# Demultiplexing
self.multiplexed = None
self.is_barcode = False
self.barcode_min_fraction = 0.025
self.did_qcat_ont_fastq = False
self.barcodes = pd.Series(dtype = object)
self.barcode_summary = None
self.error_correct = False
# Contamination
self.contam_check = False
self.kraken_fracs = pd.Series(dtype = object)
self.kraken_database = kraken_database_default
self.did_contamination_check = False
# Genome FASTA input
self.genome_fasta = None
self.will_have_genome_fasta = False
# Illumina FASTQ input
self.illumina_fastq = None
self.pilon_coverage_min = 25
self.did_spades_illumina_fastq = False
self.did_pilon_ont_assembly = False
# Output options
self.output_dir = None
self.overwrite = False
# Assembly options
self.assembler = 'flye'
self.genome_assembly_size = None
self.genome_assembly_raw_size = None
self.assembly_coverage = None
self.racon = False
self.racon_rounds = None
self.no_medaka = False
self.ont_n50 = None
self.ont_n50_min = 2500
self.ont_coverage_min = 30
self.only_assemble = False
self.no_assembly = False
self.did_flye_ont_fastq = False
self.did_medaka_ont_assembly = False
self.will_have_ont_assembly = False
# Feature options
self.amr_database = amr_database_default
self.no_amr = False
self.inc_database = inc_database_default
self.no_inc = False
self.feature_fastas = None
self.feature_hits = pd.Series(dtype = object)
self.feature_plots = pd.Series(dtype = object)
self.feature_dirs = []
self.feature_names = []
self.feature_colors = []
self.did_blast_feature_sets = False
# Download options
self.download = False
# Reference options
self.reference_dir = None
self.organism = None
self.organism_dir = None
self.auto_reference = False
self.will_have_reference_fasta = False
self.reference_fasta = None
self.reference = None
self.mutation_region_bed = None
self.amr_mutations = pd.Series(dtype = object)
self.did_call_mutations = False
self.amr_deletions = pd.DataFrame()
self.did_call_large_indels = False
# How much stuff to print
self.verbosity = 1
# Files to remove when done
self.files_to_clean = []
# Plasmid options
self.plasmids = False
self.plasmid_database = plasmid_database_default_fasta
self.did_call_plasmids = False
# Notes for different sections of the analysis
self.assembly_notes = pd.Series(dtype = object)
self.alignment_notes = pd.Series(dtype = object)
self.contig_alignment = pd.Series(dtype = object)
self.versions = pd.Series(dtype = object)
self.logging_handle = None
self.fake_run = False
self.bundle = None
self.report = pd.Series(dtype = object)
if opts is None or unknown_args is None :
return
# Date-time information
self.start_time = datetime.datetime.now().strftime("%Y-%m-%d")
# Logging information
self.logging_file = None
self.logging_handle = None
# Watch options
self.ont_watch = opts.ont_watch
self.ont_watch_reads_min = opts.ont_watch_min_reads
self.ont_watch_time_max = opts.ont_watch_max_time * 60 * 60
self.ont_watch_between_max = opts.ont_watch_between_time * 60
self.ont_watch_sleep_time = 10
# Basecalling
self.ont_fast5 = opts.ont_fast5
self.basecaller = opts.basecaller
self.only_basecall = opts.only_basecall
# ONT FASTQ input
self.ont_fastq = opts.ont_fastq
self.ont_raw_fastq = self.ont_fastq
# Demultiplexing
self.multiplexed = opts.multiplexed
self.barcodes = pd.Series(dtype='float64')
self.barcode_min_fraction = 0.025
self.error_correct = opts.error_correct
# Contamination
self.contam_check = opts.contamination
self.did_contamination_check = False
# Illumina FASTQ input
self.illumina_fastq = opts.illumina_fastq
# Genome FASTA input
self.genome_fasta = opts.genome
# Output options
self.output_dir = opts.output
self.overwrite = opts.overwrite
# Assembly options
self.assembler = opts.assembler
self.genome_assembly_size = opts.genome_size
self.assembly_coverage = opts.assembly_coverage
self.racon = opts.racon
self.racon_rounds = opts.racon_rounds
self.no_medaka = opts.no_medaka
self.only_assemble = opts.only_assemble
self.no_assembly = opts.no_assembly
# Illumina metrics
self.illumina_length_mean = None
self.illumina_coverage_min = 30
self.did_pilon_ont_assembly = False
# The assembly itself
self.genome = None
self.contig_info = None
# Vs. reference options
self.reference_identity_min = 98.
self.reference_alignment_min = 97.
# Plasmid and feature options
self.plasmids = opts.plasmids
self.plasmid_database = opts.plasmid_database
self.did_call_plasmids = False
self.no_drawing = opts.no_drawing
self.amr_database = opts.amr_database
self.no_amr = opts.no_amr
self.inc_database = opts.inc_database
self.no_inc = opts.no_inc
self.feature_fastas = opts.feature
self.feature_hits = pd.Series(dtype='float64')
self.feature_plots = pd.Series(dtype='float64')
self.feature_dirs = []
self.feature_names = []
self.feature_colors = []
self.download = opts.download
# Reference options
self.reference_dir = opts.reference_dir
self.organism = opts.organism
self.auto_reference = opts.auto_reference
self.reference_fasta = opts.reference_genome
self.mutation_region_bed = opts.mutation_regions
self.threads = opts.threads
# How much stuff to print
self.verbosity = opts.verbosity
# Files to remove when done
self.files_to_clean = []
# Don't actully run any commands
self.fake_run = opts.fake_run
# Reporting
self.no_report = False
self.bundle = opts.bundle
self.analysis_name = opts.name
self.mutation_title = 'Mutations'
self.report[self.mutation_title] = pd.Series(dtype='float64')
self.large_indels = pd.Series(dtype='float64')
self.plasmid_title = 'Plasmid annotation'
self.report[self.plasmid_title] = pd.Series(dtype='float64')
self.amr_matrix_title = 'AMR matrix'
self.did_draw_amr_matrix = False
self.report[self.amr_matrix_title] = pd.Series(dtype='float64')
self.methods_title = 'Methods summary'
self.report[self.methods_title] = pd.Series(dtype='float64')
self.basecalling_methods = 'Basecalling & processing'
self.report[self.methods_title][self.basecalling_methods] = pd.Series(dtype='float64')
self.assembly_methods = 'Assembly & polishing'
self.report[self.methods_title][self.assembly_methods] = pd.Series(dtype='float64')
self.mutation_methods = 'Mutation screening '
self.report[self.methods_title][self.mutation_methods] = pd.Series(dtype='float64')
self.plasmid_methods = 'Plasmid annotation'
self.report[self.methods_title][self.plasmid_methods] = pd.Series(dtype='float64')
self.meta_title = 'PIMA meta-information'
# See if we got any unknown args. Not allowed.
if len(unknown_args) != 0 :
self.errors = self.errors + ['Unknown argument: ' + unknown for unknown in unknown_args]
def print_and_log(self, text, verbosity, color = Colors.ENDC) :
if verbosity <= self.verbosity :
time_string = '[' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + ']'
print(time_string + ' ' + color + text + Colors.ENDC)
if self.logging_handle :
self.logging_handle.write(time_string + ' ' + text)
def run_command(self, command) :
if not self.fake_run :
try :
return(re.split('\\n', subprocess.check_output(command, shell = True).decode('utf-8')))
except :
message = 'Command ' + command + ' failed; exiting'
self.error_out(message)
def print_and_run(self, command) :
self.print_and_log(command, self.command_verbosity)
return(self.run_command(command))
def print_warning(self, warning) :
self.print_and_log(warning, self.warning_verbosity, self.warning_color)
def add_warning(self, warning) :
self.print_warning(warning)
self.warnings += [warning]
def validate_file(self, the_file) :
return os.path.isfile(the_file)
def validate_file_size(self, the_file, min_size = 0) :
if not self.fake_run :
return os.stat(the_file).st_size >= min_size
else :
return True
def validate_file_and_size(self, the_file, min_size = 0) :
return(self.validate_file(the_file) and self.validate_file_size(the_file, min_size))
def validate_file_and_size_or_error(self, the_file, error_prefix = 'The file',
presence_suffix = 'doesn\'t exist',
size_suffix = 'is size 0', min_size = 0) :
if not self.validate_file(the_file) and not self.fake_run:
self.error_out(' '.join([error_prefix, the_file, presence_suffix]))
if not self.validate_file_size(the_file, min_size) and not self.fake_run :
self.error_out(' '.join([error_prefix, the_file, size_suffix]))
def validate_utility(self, utility, error) :
if not shutil.which(utility) :
self.errors += [error]
return False
else :
return True
def std_files(self, prefix) :
return([prefix + '.std' + i for i in ['out', 'err']])
def touch_file(self, a_file) :
command = ' '.join(['touch', a_file])
self.print_and_run(command)
def make_start_file(self, a_dir) :
start_file = os.path.join(a_dir, '.start')
self.touch_file(start_file)
def make_finish_file(self, a_dir) :
finish_file = os.path.join(a_dir, '.finish')
self.touch_file(finish_file)
def load_fasta(self, fasta) :
sequence = pd.Series(dtype = object)
for contig in Bio.SeqIO.parse(fasta, 'fasta') :
sequence[contig.id] = contig
return(sequence)
def load_genome(self) :
self.genome = self.load_fasta(self.genome_fasta)
self.genome_size = 0
for i in self.genome :
self.genome_size += len(i.seq)
def load_reference(self) :
self.reference = self.load_fasta(self.reference_fasta)
self.reference_size = 0
for i in self.reference :
self.reference_size += len(i.seq)
def download_databases(self) :
self.print_and_log('Downloading missing databases', self.main_process_verbosity, self.main_process_color)
DockerPathPlasmid = os.path.join('/home/DockerDir/Data/Temp_Data/plasmids_and_vectors.fasta')
DockerPathKraken = os.path.join('/home/DockerDir/Data/Temp_Data/kraken2')
database_fasta = plasmid_database_default_fasta
if not self.validate_file_and_size(database_fasta) and self.validate_file_and_size(DockerPathPlasmid):
self.plasmid_database = DockerPathPlasmid
elif not self.validate_file_and_size(database_fasta) and not self.validate_file_and_size(DockerPathPlasmid):
self.print_and_log('Downloading plasmid database', self.sub_process_verbosity, self.sub_process_color)
command = ' '.join(['wget',
'-O', database_fasta,
'http://pima.appliedbinf.com/data/plasmids_and_vectors.fasta'])
self.print_and_run(command)
if not os.path.isdir(kraken_database_default) and self.validate_file_and_size(DockerPathKraken):
self.kraken_database = DockerPathKraken
elif not os.path.isdir(kraken_database_default) and not self.validate_file_and_size(DockerPathKraken):
self.print_and_log('Downloading and building kraken2 database (may take some time)', self.sub_process_verbosity, self.sub_process_color)
kraken_stdout, kraken_stderr = self.std_files(kraken_database_default)
command = ' '.join(['kraken2-build',
'--standard',
'--use-ftp',
'--threads', str(self.threads),
'--db', kraken_database_default,
'1>' + kraken_stdout, '2>' + kraken_stderr])
self.print_and_run(command)
def bwa_index_fasta(self, fasta) :
self.print_and_log('Indexing FASTA with bwa index', self.sub_process_verbosity, self.sub_process_color)
# Check for an index already there
bwa_index = fasta + '.bwt'
if self.validate_file_and_size(bwa_index) :
return
# Make the bwa index
std_prefix = re.sub('\\.f(na|asta)$', '', fasta)
bwa_index_stdout, bwa_index_stderr = self.std_files(std_prefix + '_index')
command = ' '.join(['bwa',
'index',
fasta,
'1>' + bwa_index_stdout, '2>' + bwa_index_stderr])
self.print_and_run(command)
# Check that the index was built
self.validate_file_and_size_or_error(bwa_index, 'BWA index', 'doesn\'t exist', 'is empty')
def bwa_short_illumina_fastq(self, genome, fastq, bam) :
std_prefix = re.sub('\\.bam$', '', bam)
self.bwa_index_fasta(genome)
# Align the reads
sai = []
for i in range(len(fastq)) :
bwa_stdout, bwa_stderr = self.std_files(std_prefix + '_aln')
this_sai = std_prefix + '_aln_' + str(i) + '.sai'
command = ' '.join(['bwa aln',
'-t', str(self.threads),
genome,
fastq[i],
'1>', this_sai,
'2>', bwa_stderr])
sai += [this_sai]
self.print_and_run(command)
self.validate_file_and_size_or_error(this_sai)
# And turn the SAI into a proper SAM file
read_type = 'samse'
if len(fastq) > 1 :
read_type = 'sampe'
bwa_stdout, bwa_stderr = self.std_files(std_prefix + '_sam')
tmp_file = std_prefix + '.tmp'
command = ' '.join(['bwa',
read_type,
genome,
' '.join(sai),
' '.join(fastq),
'2>', bwa_stderr,
'| samtools',
'sort',
'-T', tmp_file,
'-o', bam,
'-',
'1>/dev/null 2>/dev/null'])
self.print_and_run(command)
self.validate_file_and_size_or_error(the_file = bam, min_size = 100)
self.index_bam(bam)
def minimap_ont_fastq(self, genome, fastq, bam) :
std_prefix = re.sub('\\.bam$', '', bam)
minimap_stdout, minimap_stderr = self.std_files(std_prefix)
command = ' '.join(['minimap2 -a',
'-t', str(self.threads),
'-x map-ont',
genome,
fastq,
'2>' + minimap_stderr,
'| samtools sort',
'-@', str(self.threads),
'-o', bam,
'-T reads.tmp -',
'1>/dev/null 2>/dev/null'])
self.print_and_run(command)
self.validate_file_and_size_or_error(the_file = bam, min_size = 1000)
self.index_bam(bam)
def minimap_illumina_fastq(self, genome, fastq, bam) :
std_prefix = re.sub('\\.bam$', '', bam)
minimap_stdout, minimap_stderr = self.std_files(std_prefix)
command = ' '.join(['minimap2 -a',
'-t', str(self.threads),
'-x sr',
genome,
' '.join(fastq),
'2>' + minimap_stderr,
'| samtools sort',
'-@', str(self.threads),
'-o', bam,
'-T reads.tmp -',
'1>/dev/null 2>/dev/null'])
self.print_and_run(command)
self.validate_file_and_size_or_error(the_file = bam, min_size = 1000)
self.index_bam(bam)
def index_bam(self, bam) :
command = ' '.join(['samtools index',
bam,
'1>/dev/null 2>/dev/null'])
self.print_and_run(command)
index_bai = bam + '.bai'
self.validate_file_and_size_or_error(the_file = index_bai, min_size = 1000)
def dnadiff_fasta(self, reference_fasta, query_fasta, output_prefix) :
dnadiff_stdout, dnadiff_stderr = self.std_files(output_prefix)
command = ' '.join(['dnadiff',
'-p', output_prefix,
reference_fasta,
query_fasta,
'1>' + dnadiff_stdout, '2>' + dnadiff_stderr])
output_1coords = output_prefix + '.1coords'
self.print_and_run(command)
self.validate_file_and_size_or_error(the_file = output_1coords, min_size = 5)
def error_out(self, message) :
print(Colors.FAIL + message + Colors.ENDC)
sys.exit(1)
def unless_only_basecall(function) :
def wrapper(self) :
if self.only_basecall :
return
function(self)
return wrapper
def unless_given_genome(function) :
def wrapper(self) :
if not(self.genome_fasta is None) :
return
function(self)
return wrapper
def unless_only_assemble(function) :
def wrapper(self) :
if self.only_assemble :
return
function(self)
return wrapper
def unless_no_assembly(function) :
def wrapper(self) :
if self.no_assembly :
return
function(self)
return wrapper
def validate_ont_watch(self) :
if not self.ont_watch :
return
if self.is_barcode :
return
self.print_and_log('Validating ONT watch dir and utilities', self.main_process_verbosity, self.main_process_color)
if self.ont_fast5 :
self.errors += ['--ont-watch and --ont-fast5 are mutually exclusive.']
if self.ont_fastq :
self.errors += ['--ont-watch and --ont-fastq are mutually exclusive.']
if self.genome_fasta :
self.errors += ['--ont-watch and --genome are mutually exclusive.']
if not os.path.isdir(self.ont_watch) :
self.errors += ['ONT watch directory does not exist.']
if self.ont_watch_reads_min < 0 :
self.errors += ['ONT watch min reads must be > 0.']
self.will_have_ont_fastq = True
self.analysis += ['watch_ont']
def validate_ont_fast5(self) :
if not self.ont_fast5 :
return
if self.is_barcode :
return
if self.ont_fastq :
self.errors += ['--ont-fast5 and --ont-fastq are mutually exclusive']
self.print_and_log('Validating ONT fast5 files and utilities', self.main_process_verbosity, self.main_process_color)
if not os.path.exists(self.ont_fast5) :
self.errors += ['Input FAST5 directory ' + self.ont_fast5 + ' cannot be found']
return
if not os.path.isdir(self.ont_fast5) :
self.errors += ['Input FAST5 directory ' + self.ont_fast5 + ' is not a directory']
return
#1 - Look for FAST5 files in the directory
#Start with the usual format for FAST5 data, one directory with a bunch of 0..n subdirectories
in_subdirs = False
search_string = self.ont_fast5 + "/**/*fast5"
fast5_files = glob.glob(search_string, recursive = True)
if not len(fast5_files) == 0:
in_subdirs = True
#If we can't find things in the subdirs, look in the main fast5 dir
in_maindir = False
search_string = self.ont_fast5 + "/*fast5"
fast5_files = glob.glob(search_string, recursive = True)
if not len(fast5_files) == 0:
in_maindir = True
if not in_subdirs and not in_maindir :
self.errors += ['Could not find FAST5 files in ' + self.ont_fast5 + ' or subdirectories']
def validate_ont_fastq(self):
if not self.ont_fastq :
return
self.print_and_log('Validating ONT FASTQ', self.main_process_verbosity, self.main_process_color)
if not self.validate_file_and_size(the_file = self.ont_fastq, min_size = 1000) :
self.errors += ['Input ONT FASTQ file ' + self.ont_fastq + ' cannot be found']
self.will_have_ont_fastq = True
def validate_genome_fasta(self) :
if not self.genome_fasta :
return
self.print_and_log('Validating genome FASTA', self.main_process_verbosity, self.main_process_color)
if not self.validate_file_and_size(self.genome_fasta, min_size = 1000) :
self.errors += ['Input genome FASTA ' + self.genome_fasta + ' cannot be found']
else :
self.load_genome()
self.will_have_genome_fasta = True
def validate_output_dir(self) :
self.print_and_log('Validating output dir', self.main_process_verbosity, self.main_process_color)
if not self.output_dir :
self.errors += ['No output directory given (--output)']
elif os.path.exists(self.output_dir) and not self.overwrite :
self.errors += ['Output directory ' + self.output_dir + ' already exists. Add --overwrite to ignore']
self.analysis = ['make_output_dir'] + self.analysis
def validate_guppy(self) :
if self.basecaller != 'guppy' :
return
if not (self.ont_fast5 or self.ont_watch) :
return
if self.ont_fastq :
return
self.print_and_log('Validating Guppy basecalling utilities', self.main_process_verbosity, self.main_process_color)
if self.validate_utility('guppy_basecaller', 'guppy_basecaller is not on the PATH.') :
command = 'guppy_basecaller --version'
self.versions['guppy'] = re.search('[0-9]+\\.[0-9.]+', self.print_and_run(command)[0]).group(0)
for utility in ['guppy_aligner', 'guppy_barcoder'] :
self.validate_utility(utility, utility + ' is not on the PATH.')
self.will_have_ont_fastq = True
if not self.ont_watch :
self.analysis += ['guppy_given_ont_fast5']
def validate_multiplexed(self) :
if not self.multiplexed :
return
if self.is_barcode :
return
if not self.will_have_ont_fastq :
self.errors += ['--multiplexed requires that an ONT FASTQ be given or generated']
# If we are watching an ONT run, we will demultiplex live
if self.ont_watch :
return
self.analysis += ['qcat_given_ont_fastq']
def validate_qcat(self) :
if not self.multiplexed :
return
if self.is_barcode :
return
self.print_and_log('Validating qcat demultiplexer', self.main_process_verbosity, self.main_process_color)
if self.validate_utility('qcat', 'qcat is not on the PATH.') :
command = 'qcat --version'
self.versions['qcat'] = re.search('[0-9]+\\.[0-9.]+', self.print_and_run(command)[0]).group(0)
def validate_info_given_ont_fastq(self) :
if not self.will_have_ont_fastq :
return
# If we are multiplexed, we will let the sub-analyses handle info
if self.multiplexed :
return
self.analysis += ['info_given_ont_fastq']
def validate_lorma(self) :
if not self.error_correct :
return
if not (self.ont_fast5 or self.ont_fastq) :
self.errors += ['--error-correct requires --ont-fast5 and/or --ont-fastq']
return
self.print_and_log('Validating lorma error corrector', self.main_process_verbosity, self.main_process_color)
self.validate_utility('lordec-correct', 'LoRMA is not on the PATH (required for ONT error-correction)')
self.analysis += ['lorma_ont_fastq']
def validate_contamination_check(self) :
if not self.contam_check :
return
self.print_and_log('Validating contamination check', self.main_process_verbosity, self.main_process_color)
if not self.will_have_ont_fastq and self.illumina_fastq is None :
self.errors += ['--contamination requires a set of FASTQ reads']
if self.validate_utility('kraken2', 'kraken2 is not on the PATH (required by --contamination-check).') :
command = 'kraken2 --version'
self.versions['kraken2'] = re.search('[0-9]+\\.[0-9.]+', self.print_and_run(command)[0]).group(0)
# Will instead do for each barcode
if self.multiplexed :
return
# Will instead do for each batch
if self.ont_watch :
return
self.analysis += ['fastq_contamination']
@unless_only_basecall
@unless_no_assembly
def validate_assembly_coverage(self) :
#TODO make these not magic numbers
if self.assembly_coverage > 300 or self.assembly_coverage < 50 :
self.errors += ['--assembly-coverage (' + str(self.assembly_coverage) + ') is outside of useful range (50 < x <300)']
@unless_only_basecall
@unless_no_assembly
def validate_genome_assembly_size(self) :
if self.genome_assembly_size is None :
return
self.print_and_log('Validating assembly size', self.main_process_verbosity, self.main_process_color)
if not re.match('^[0-9]+(\\.[0-9]+)?[mkgMKG]?$', self.genome_assembly_size) :
self.errors += ['--genome-size needs to be a floating point number, accepting k/m/g, got ' + \
str(self.genome_assembly_size)]
return
power = 0
if re.match('^[0-9]+(\\.[0-9]+)?[kK]$', self.genome_assembly_size) :
power = 3
elif re.match('^[0-9]+(\\.[0-9]+)?[mM]$', self.genome_assembly_size) :
power = 6
elif re.match('^[0-9]+(\\.[0-9]+)?[gG]$', self.genome_assembly_size) :
power = 9
self.genome_assembly_raw_size = float(re.sub('[mkgMKG]', '', self.genome_assembly_size)) * 10**power
@unless_only_basecall
@unless_given_genome
@unless_no_assembly
def validate_wtdbg2(self) :
if self.assembler != 'wtdbg2' :
return
if not self.will_have_ont_fastq :
return
self.print_and_log('Validating wtdbg2 utilities', self.main_process_verbosity, self.main_process_color)
if not self.genome_assembly_size :
self.errors += ['wtdbg2 requires --genome-size']
for utility in ['pgzf', 'kbm2', 'wtdbg2', 'wtpoa-cns', 'wtdbg-cns'] :
self.validate_utility(utility, utility + ' is not on the PATH (required by --assembler wtdbg2)')
self.will_have_ont_assembly = True
self.will_have_genome_fasta = True
self.analysis += ['wtdbg2_ont_fastq']
@unless_only_basecall
@unless_given_genome
@unless_no_assembly
def validate_flye(self) :
if self.assembler != 'flye' :
return
if not self.will_have_ont_fastq :
return