-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpipeline.py
2279 lines (1868 loc) · 73.4 KB
/
pipeline.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
import luigi
import os
import sys
#from subprocess import check_output, CalledProcessError
import subprocess
import logging
import pandas as pd
from textwrap import dedent
# Import custom modules
from scripts.qiime2_helper.summarize_sample_counts import (
load_qiime2_artifact,
generate_sample_count,
get_sample_count
)
from scripts.qiime2_helper.generate_combined_feature_table import combine_table
from scripts.qiime2_helper import artifact_helper
from scripts.qiime2_helper.generate_multiple_pcoa import (
generate_pdf,
generate_images,
save_as_json
)
from scripts.qiime2_helper.split_manifest_file_by_run_ID import (
split_manifest
)
# Define custom logger
logger = logging.getLogger("luigi logger")
## Path to configuration file to be used
#if("LUIGI_CONFIG_PATH" not in os.environ):
# raise FileNotFoundError("Add LUIGI_CONFIG_PATH to environment variable!")
#
#config_path = os.environ["LUIGI_CONFIG_PATH"]
#luigi.configuration.add_config_path(config_path)
# Path to configuration file to be used
config_path = os.environ.get('LUIGI_CONFIG_PATH', "/pipeline/AXIOME3/configuration/luigi.cfg")
luigi.configuration.add_config_path(config_path)
# Script directory
script_dir = "scripts"
# QIIME2 helper directory
qiime2_helper_dir = os.path.join(script_dir, "qiime2_helper")
# FAPROTAX directory with database file and script
FAPROTAX = "FAPROTAX"
def auto_sampling_depth(feature_table_artifact):
# Get the lowest sequence read in the samples
feature_table_df = load_qiime2_artifact(feature_table_artifact)
sample_count_df = generate_sample_count(feature_table_df)
# convert to int
sample_count_df['Count'] = sample_count_df['Count'].round(0).astype(int)
min_count = sample_count_df['Count'].min() if (sample_count_df['Count'].min() > 0) else 1
return str(min_count)
def run_cmd(cmd, step):
#try:
# output = check_output(cmd)
#except CalledProcessError as err:
# logger.error("In {step} following error occured\n{err}".format(
# step=step,
# err=err
# ))
# raise err
#except Exception as err:
# logger.error("In {step} unknown error occured\n{err}".format(
# step=step,
# err=err
# ))
# raise err
#finally:
# logger.error(output)
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = proc.communicate()
return_code = proc.returncode
if not(return_code == 0):
combined_msg = (stdout + stderr).decode('utf-8')
err_msg = "In {step}, the following command, : ".format(step=step) + \
"{cmd}\n\n".format(cmd=cmd) + \
"resulted in an error:\n{combined_msg}"\
.format(combined_msg=combined_msg)
web_err_msg = "<-->" + combined_msg + "<-->"
logger.error(err_msg)
raise ValueError(web_err_msg)
else:
return stdout
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
# Return false for all other strings
else:
return False
#elif v.lower() in ('no', 'false', 'f', 'n', '0'):
# return False
#else:
# raise argparse.ArgumentTypeError('Boolean value expected.')
class Out_Prefix(luigi.Config):
prefix = luigi.Parameter()
class Output_Dirs(luigi.Config):
# Define output paths
out_dir = Out_Prefix().prefix
input_upload_dir = os.path.join(out_dir, "input_upload")
manifest_dir = os.path.join(out_dir, "manifest")
denoise_dir = os.path.join(out_dir, "denoise")
rarefy_dir = os.path.join(out_dir, "rarefy")
taxonomy_dir = os.path.join(out_dir, "taxonomic_classification")
analysis_dir = os.path.join(out_dir, "analysis")
export_dir = os.path.join(out_dir, "exported")
rarefy_export_dir = os.path.join(out_dir, "rarefy_exported")
phylogeny_dir = os.path.join(analysis_dir, "phylogeny")
collapse_dir = os.path.join(out_dir, "taxa_collapse")
post_analysis_dir = os.path.join(out_dir, "post_analysis")
filtered_dir = os.path.join(post_analysis_dir, "filtered")
filtered_taxonomy_dir = os.path.join(filtered_dir, "taxonomy")
core_metric_dir = os.path.join(analysis_dir, "metrics")
alpha_sig_dir = os.path.join(post_analysis_dir, "alpha_group_significance")
pcoa_dir = os.path.join(analysis_dir, "pcoa_plots")
faprotax_dir = os.path.join(post_analysis_dir, "FAPROTAX")
picrust_dir = os.path.join(post_analysis_dir, "PICRUST2")
visualization_dir = os.path.join(out_dir, "visualization")
class Samples(luigi.Config):
"""
Global variables that multiple steps may need access to.
Includes...
1. Manifest file (.txt) (maybe only accept .txt extension?)
"""
manifest_file = luigi.Parameter()
metadata_file = luigi.Parameter(default='')
is_multiple = luigi.Parameter(default='n')
sampling_depth = luigi.Parameter(default='10000')
def get_samples(self):
# If manifest file not specified by user, return
if(self.manifest_file == "<MANIFEST_PATH>"):
return
manifest_df = pd.read_csv(self.manifest_file, index_col=0)
# Return set of sample IDs if multiple IDs found
if('run_ID' in manifest_df.columns):
return set(manifest_df['run_ID'])
# Return empty set if single run
else:
return set()
class Split_Samples(luigi.Task):
"""
Split samples based on metadata
"""
out_dir = Output_Dirs().manifest_dir
def output(self):
samples = Samples().get_samples()
is_multiple = str2bool(Samples().is_multiple)
# If multiple runs are specified in manifest file
if(is_multiple):
output = {}
for sample in samples:
manifest = "manifest_" + str(sample) + ".csv"
out_path = os.path.join(self.out_dir, manifest)
output[str(sample)] = luigi.LocalTarget(out_path)
return output
# Single run case
else:
output = os.path.join(self.out_dir, "manifest.csv")
return luigi.LocalTarget(output)
def run(self):
# Make output directory
run_cmd(['mkdir',
'-p',
self.out_dir],
self)
# Split manifest if multiple runs in manifest file
manifest_path = Samples().manifest_file
is_multiple = str2bool(Samples().is_multiple)
if(is_multiple):
split_manifest(manifest_path, self.out_dir)
else:
cmd = ['cp',
manifest_path,
self.output().path]
run_cmd(cmd, self)
class Import_Data(luigi.Task):
# Options for qiime tools import
sample_type = luigi.Parameter(
default='SampleData[PairedEndSequencesWithQuality]')
input_format = luigi.Parameter(default="PairedEndFastqManifestPhred33")
out_dir = Output_Dirs().input_upload_dir
samples = Samples().get_samples()
is_multiple = str2bool(Samples().is_multiple)
def requires(self):
return Split_Samples()
def output(self):
# Multiple run specified in the manifest file
if(self.is_multiple):
output = {}
for sample in self.samples:
prefix = str(sample) + "_paired_end_demux.qza"
paired_end_demux = os.path.join(self.out_dir, prefix)
output[str(sample)] = luigi.LocalTarget(paired_end_demux)
return output
# Single run case
else:
paired_end_demux = os.path.join(self.out_dir, "paired_end_demux.qza")
return luigi.LocalTarget(paired_end_demux)
def run(self):
step = str(self)
# Make output directory
run_cmd(['mkdir',
'-p',
self.out_dir],
step)
#inputPath = Samples().manifest_file
#
## Make sure input file actually exists
#try:
# with open(inputPath, 'r') as fh:
# fh.readlines()
#except FileNotFoundError:
# logger.error("Input file for qiime tools import does not exist...")
# raise
## in case of unexpected errors
#except Exception as err:
# logger.error(
# "In Import_Data() following error occured\n" + str(err))
# raise
# Multiple run
if(self.is_multiple):
for sample in self.samples:
cmd = ["qiime",
"tools",
"import",
"--type",
self.sample_type,
"--input-path",
self.input()[str(sample)].path,
"--output-path",
self.output()[str(sample)].path,
"--input-format",
self.input_format]
run_cmd(cmd, self)
# Single run
else:
inputPath = Samples().manifest_file
cmd = ["qiime",
"tools",
"import",
"--type",
self.sample_type,
"--input-path",
inputPath,
"--output-path",
self.output().path,
"--input-format",
self.input_format]
run_cmd(cmd, self)
class Summarize(luigi.Task):
samples = Samples().get_samples()
is_multiple = str2bool(Samples().is_multiple)
out_dir = Output_Dirs().input_upload_dir
def requires(self):
return Import_Data()
def output(self):
# Multiple run
if(self.is_multiple):
output = {}
for sample in self.samples:
prefix = str(sample) + "_paired_end_demux.qzv"
paired_end_demux = os.path.join(self.out_dir, prefix)
output[str(sample)] = luigi.LocalTarget(paired_end_demux)
return output
# Single run
else:
summary_file = os.path.join(self.out_dir, "paired_end_demux.qzv")
return luigi.LocalTarget(summary_file)
def run(self):
step = str(self)
# Make output directory
run_cmd(["mkdir",
"-p",
Output_Dirs().out_dir],
step)
# Multiple run
if(self.is_multiple):
for sample in self.samples:
# Generate summary file
cmd = ["qiime",
"demux",
"summarize",
"--i-data",
self.input()[str(sample)].path,
"--o-visualization",
self.output()[str(sample)].path]
run_cmd(cmd, self)
# Single run
else:
# Generate summary file
cmd = ["qiime",
"demux",
"summarize",
"--i-data",
self.input().path,
"--o-visualization",
self.output().path]
run_cmd(cmd, self)
class Denoise(luigi.Task):
trim_left_f = luigi.Parameter(default="19")
trunc_len_f = luigi.Parameter(default="250")
trim_left_r = luigi.Parameter(default="20")
trunc_len_r = luigi.Parameter(default="250")
n_cores = luigi.Parameter(default="1")
samples = Samples().get_samples()
is_multiple = str2bool(Samples().is_multiple)
denoise_dir = Output_Dirs().denoise_dir
def requires(self):
return Import_Data()
def output(self):
# Multiple runs
if(self.is_multiple):
output = {}
for sample in self.samples:
table_prefix = str(sample) + "_dada2_table.qza"
seq_prefix = str(sample) + "_dada2_rep_seqs.qza"
stats_prefix = str(sample) + "_stats_dada2.qza"
log_prefix = str(sample) + "_dada2_log.txt"
denoise_table = os.path.join(self.denoise_dir,
str(sample), table_prefix)
rep_seqs = os.path.join(self.denoise_dir,
str(sample), seq_prefix)
denoise_stats = os.path.join(self.denoise_dir,
str(sample), stats_prefix)
dada2_log = os.path.join(self.denoise_dir,
str(sample), log_prefix)
denoise_out = {
"table": luigi.LocalTarget(denoise_table),
"rep_seqs": luigi.LocalTarget(rep_seqs),
"stats": luigi.LocalTarget(denoise_stats),
"log": luigi.LocalTarget(dada2_log, format=luigi.format.Nop)
}
output[str(sample)] = denoise_out
return output
# Single run
else:
denoise_table = os.path.join(self.denoise_dir, "dada2_table.qza")
rep_seqs = os.path.join(self.denoise_dir, "dada2_rep_seqs.qza")
denoise_stats = os.path.join(self.denoise_dir, "stats_dada2.qza")
dada2_log = os.path.join(self.denoise_dir, "dada2_log.txt")
out = {
"table": luigi.LocalTarget(denoise_table),
"rep_seqs": luigi.LocalTarget(rep_seqs),
"stats": luigi.LocalTarget(denoise_stats),
"log": luigi.LocalTarget(dada2_log, format=luigi.format.Nop)
}
return out
def run(self):
# Make output directory
run_cmd(["mkdir",
"-p",
self.denoise_dir],
self)
if(self.is_multiple):
# Get cutoff for each sample
#trim_left_f_list = self.trim_left_f.split(',')
#trunc_len_f_list = self.trunc_len_f.split(',')
#trim_left_r_list = self.trim_left_r.split(',')
#trunc_len_r_list = self.trunc_len_r.split(',')
#trim_left_f_dict = {}
#trunc_len_f_dict = {}
#trim_left_r_dict = {}
#trunc_len_r_dict = {}
#for trim_f in trim_left_f_list:
# sample_id = trim_f.split(':')[0].strip()
# cutoff = trim_f.split(':')[1].strip()
# trim_left_f_dict[sample_id] = cutoff
#for trunc_f in trunc_len_f_list:
# sample_id = trunc_f.split(':')[0].strip()
# cutoff = trunc_f.split(':')[1].strip()
# trunc_len_f_dict[sample_id] = cutoff
#for trim_r in trim_left_r_list:
# sample_id = trim_r.split(':')[0].strip()
# cutoff = trim_r.split(':')[1].strip()
# trim_left_r_dict[sample_id] = cutoff
#for trunc_r in trunc_len_r_list:
# sample_id = trunc_r.split(':')[0].strip()
# cutoff = trunc_r.split(':')[1].strip()
# trunc_len_r_dict[sample_id] = cutoff
# Run dada2 for each sample
for sample in self.samples:
# Run dada2
#cmd = ["qiime",
# "dada2",
# "denoise-paired",
# "--i-demultiplexed-seqs",
# self.input()[str(sample)].path,
# "--p-trim-left-f",
# trim_left_f_dict[str(sample)],
# "--p-trunc-len-f",
# trunc_len_f_dict[str(sample)],
# "--p-trim-left-r",
# trim_left_r_dict[str(sample)],
# "--p-trunc-len-r",
# trunc_len_r_dict[str(sample)],
# "--p-n-threads",
# self.n_threads,
# "--o-table",
# self.output()[str(sample)]["table"].path,
# "--o-representative-sequences",
# self.output()[str(sample)]["rep_seqs"].path,
# "--o-denoising-stats",
# self.output()[str(sample)]["stats"].path,
# "--verbose"]
# Make output directory
run_cmd(['mkdir',
'-p',
os.path.join(self.denoise_dir, str(sample))],
self)
cmd = ["qiime",
"dada2",
"denoise-paired",
"--i-demultiplexed-seqs",
self.input()[str(sample)].path,
"--p-trim-left-f",
self.trim_left_f,
"--p-trunc-len-f",
self.trunc_len_f,
"--p-trim-left-r",
self.trim_left_r,
"--p-trunc-len-r",
self.trunc_len_r,
"--p-n-threads",
self.n_cores,
"--o-table",
self.output()[str(sample)]["table"].path,
"--o-representative-sequences",
self.output()[str(sample)]["rep_seqs"].path,
"--o-denoising-stats",
self.output()[str(sample)]["stats"].path,
"--verbose"]
output = run_cmd(cmd, self)
# Write a log file
with self.output()[str(sample)]["log"].open('wb') as fh:
fh.write(output)
else:
# Run dada2
cmd = ["qiime",
"dada2",
"denoise-paired",
"--i-demultiplexed-seqs",
self.input().path,
"--p-trim-left-f",
self.trim_left_f,
"--p-trunc-len-f",
self.trunc_len_f,
"--p-trim-left-r",
self.trim_left_r,
"--p-trunc-len-r",
self.trunc_len_r,
"--p-n-threads",
self.n_cores,
"--o-table",
self.output()["table"].path,
"--o-representative-sequences",
self.output()["rep_seqs"].path,
"--o-denoising-stats",
self.output()["stats"].path,
"--verbose"]
output = run_cmd(cmd, self)
# Write a log file
with self.output()["log"].open('wb') as fh:
fh.write(output)
class Merge_Denoise(luigi.Task):
samples = Samples().get_samples()
is_multiple = str2bool(Samples().is_multiple)
out_dir = Output_Dirs().denoise_dir
def requires(self):
return Denoise()
def output(self):
merged_table = os.path.join(self.out_dir, "merged_table.qza")
merged_seqs = os.path.join(self.out_dir, "merged_rep_seqs.qza")
output = {
'table': luigi.LocalTarget(merged_table),
'rep_seqs': luigi.LocalTarget(merged_seqs)
}
return output
def run(self):
# Make output directory
run_cmd(['mkdir',
'-p',
self.out_dir],
self)
# Multiple runs
if(self.is_multiple):
table_cmd = ['qiime',
'feature-table',
'merge',
'--o-merged-table',
self.output()['table'].path]
seqs_cmd = ['qiime',
'feature-table',
'merge-seqs',
'--o-merged-data',
self.output()['rep_seqs'].path]
for sample in self.samples:
table_cmd.append('--i-tables')
table_cmd.append(self.input()[str(sample)]['table'].path)
seqs_cmd.append('--i-data')
seqs_cmd.append(self.input()[str(sample)]['rep_seqs'].path)
run_cmd(table_cmd, self)
run_cmd(seqs_cmd, self)
# Single run
else:
run_cmd(['cp',
self.input()['table'].path,
self.output()['table'].path],
self)
run_cmd(['cp',
self.input()['rep_seqs'].path,
self.output()['rep_seqs'].path],
self)
class Merge_Denoise_Stats(luigi.Task):
dada2_dir = Output_Dirs().denoise_dir
out_dir = Output_Dirs().denoise_dir
def requires(self):
return Denoise()
def output(self):
merged_denoise_stats = os.path.join(self.out_dir, "merged_stats_dada2.qza")
merged_denoise_json = os.path.join(self.out_dir, "merged_stats_dada2.json")
output = {
"qza": luigi.LocalTarget(merged_denoise_stats),
"json": luigi.LocalTarget(merged_denoise_json)
}
return output
def run(self):
# Make output directory
run_cmd(["mkdir",
"-p",
self.out_dir],
self)
stats_df = artifact_helper.combine_dada2_stats_as_df(self.dada2_dir)
stats_artifact = artifact_helper.import_dada2_stats_df_to_q2(stats_df)
stats_df.to_json(self.output()["json"].path, orient='index')
stats_artifact.save(self.output()["qza"].path)
class Sample_Count_Summary(luigi.Task):
out_dir = Output_Dirs().denoise_dir
def requires(self):
return Merge_Denoise()
def output(self):
summary_file_tsv = os.path.join(self.out_dir, "sample_counts.tsv")
summary_file_json = os.path.join(self.out_dir, "sample_counts.json")
log_file = os.path.join(self.out_dir, "log.txt")
output = {
"tsv": luigi.LocalTarget(summary_file_tsv),
"json": luigi.LocalTarget(summary_file_json)
}
return output
def run(self):
# Make output directory
run_cmd(['mkdir',
'-p',
self.out_dir],
self)
get_sample_count(
self.input()['table'].path,
self.output()["tsv"].path,
self.output()["json"].path)
class Taxonomic_Classification(luigi.Task):
classifier = luigi.Parameter()
n_cores = luigi.Parameter(default="1")
out_dir = Output_Dirs().taxonomy_dir
def requires(self):
return Merge_Denoise()
def output(self):
classified_taxonomy = os.path.join(self.out_dir, "taxonomy.qza")
output = {
"taxonomy": luigi.LocalTarget(classified_taxonomy),
}
return output
def run(self):
# Make output directory
run_cmd(["mkdir",
"-p",
self.out_dir],
self)
# Run qiime classifier
cmd = ["qiime",
"feature-classifier",
"classify-sklearn",
"--i-classifier",
self.classifier,
"--i-reads",
self.input()["rep_seqs"].path,
"--o-classification",
self.output()["taxonomy"].path,
"--p-n-jobs",
self.n_cores,
"--verbose"]
output = run_cmd(cmd, self)
class Export_Feature_Table(luigi.Task):
export_dir = Output_Dirs().export_dir
def requires(self):
return Merge_Denoise()
def output(self):
biom = os.path.join(self.export_dir, "feature-table.biom")
return luigi.LocalTarget(biom)
def run(self):
# Make directory
run_cmd(["mkdir",
"-p",
self.export_dir],
self)
# Export file
cmd = ["qiime",
"tools",
"export",
"--input-path",
self.input()["table"].path,
"--output-path",
os.path.dirname(self.output().path)]
run_cmd(cmd, self)
class Export_Taxonomy(luigi.Task):
out_dir = Output_Dirs().taxonomy_dir
def requires(self):
return Taxonomic_Classification()
def output(self):
tsv = os.path.join(self.out_dir, "taxonomy.tsv")
return luigi.LocalTarget(tsv)
def run(self):
step = str(self)
# Make directory
run_cmd(["mkdir",
"-p",
self.out_dir],
step)
# Export file
cmd = ["qiime",
"tools",
"export",
"--input-path",
self.input()["taxonomy"].path,
"--output-path",
os.path.dirname(self.output().path)]
run_cmd(cmd, step)
class Export_Representative_Seqs(luigi.Task):
out_dir = Output_Dirs().analysis_dir
def requires(self):
return Merge_Denoise()
def output(self):
fasta = os.path.join(self.out_dir, "dna-sequences.fasta")
return luigi.LocalTarget(fasta)
def run(self):
# Make directory
run_cmd(["mkdir",
"-p",
self.out_dir],
self)
# Export file
cmd = ["qiime",
"tools",
"export",
"--input-path",
self.input()["rep_seqs"].path,
"--output-path",
os.path.dirname(self.output().path)]
run_cmd(cmd, self)
class Convert_Feature_Table_to_TSV(luigi.Task):
out_dir = Output_Dirs().denoise_dir
def requires(self):
return Merge_Denoise()
def output(self):
tsv = os.path.join(self.out_dir, "feature-table.tsv")
return luigi.LocalTarget(tsv)
def run(self):
step = str(self)
# Make output directory
run_cmd(["mkdir",
"-p",
self.out_dir],
step)
# Convert to TSV
output = artifact_helper.convert(self.input()["table"].path)
collapsed_df = output["feature_table"]
collapsed_df.T.to_csv(
self.output().path,
sep="\t",
index_label="SampleID"
)
class Generate_Combined_Feature_Table(luigi.Task):
out_dir = Output_Dirs().analysis_dir
def requires(self):
return {
"Taxonomic_Classification": Taxonomic_Classification(),
"Export_Representative_Seqs": Export_Representative_Seqs(),
"Merge_Denoise": Merge_Denoise(),
}
def output(self):
combined_table = os.path.join(self.out_dir, "ASV_table_combined.tsv")
log = os.path.join(self.out_dir, "ASV_table_combined.log")
output = {
"table": luigi.LocalTarget(combined_table),
#"log": luigi.LocalTarget(log, format=luigi.format.Nop),
}
return output
def run(self):
# Make output directory
run_cmd(["mkdir",
"-p",
self.out_dir],
self)
combine_table(self.input()["Merge_Denoise"]["table"].path,
self.input()["Export_Representative_Seqs"].path,
self.input()["Taxonomic_Classification"]["taxonomy"].path,
self.output()["table"].path)
# Write log files
#with self.output()["log"].open('w') as fh:
# fh.write(logged_pre_rarefied)
class Phylogeny_Tree(luigi.Task):
out_dir = Output_Dirs().phylogeny_dir
n_cores = luigi.Parameter(default="1")
def requires(self):
return Merge_Denoise()
def output(self):
alignment = os.path.join(self.out_dir,
"aligned_rep_seqs.qza")
masked_alignment = os.path.join(self.out_dir,
"masked_aligned_rep_seqs.qza")
tree = os.path.join(self.out_dir,
"unrooted_tree.qza")
rooted_tree = os.path.join(self.out_dir,
"rooted_tree.qza")
out = {
'alignment': luigi.LocalTarget(alignment),
'masked_alignment': luigi.LocalTarget(masked_alignment),
'tree': luigi.LocalTarget(tree),
'rooted_tree': luigi.LocalTarget(rooted_tree),
}
return out
def run(self):
# Create output directory
run_cmd(['mkdir',
'-p',
self.out_dir], self)
# Make phylogeny tree
cmd = ['qiime',
'phylogeny',
'align-to-tree-mafft-fasttree',
'--i-sequences',
self.input()['rep_seqs'].path,
'--p-n-threads',
self.n_cores,
'--o-alignment',
self.output()['alignment'].path,
'--o-masked-alignment',
self.output()['masked_alignment'].path,
'--o-tree',
self.output()['tree'].path,
'--o-rooted-tree',
self.output()['rooted_tree'].path
]
run_cmd(cmd, self)
class Taxa_Collapse(luigi.Task):
out_dir = Output_Dirs().taxonomy_dir
def requires(self):
return {"Merge_Denoise": Merge_Denoise(),
"Taxonomic_Classification": Taxonomic_Classification()
}
def output(self):
domain_collapsed_table = os.path.join(self.out_dir,
"domain_collapsed_table.qza")
phylum_collapsed_table = os.path.join(self.out_dir,
"phylum_collapsed_table.qza")
class_collapsed_table = os.path.join(self.out_dir,
"class_collapsed_table.qza")
order_collapsed_table = os.path.join(self.out_dir,
"order_collapsed_table.qza")
family_collapsed_table = os.path.join(self.out_dir,
"family_collapsed_table.qza")
genus_collapsed_table = os.path.join(self.out_dir,
"genus_collapsed_table.qza")
species_collapsed_table = os.path.join(self.out_dir,
"species_collapsed_table.qza")
output = {
"domain": luigi.LocalTarget(domain_collapsed_table),
"phylum": luigi.LocalTarget(phylum_collapsed_table),
"class": luigi.LocalTarget(class_collapsed_table),
"order": luigi.LocalTarget(order_collapsed_table),
"family": luigi.LocalTarget(family_collapsed_table),
"genus": luigi.LocalTarget(genus_collapsed_table),
"species": luigi.LocalTarget(species_collapsed_table)
}
return output
def run(self):
# Make output directory
run_cmd(["mkdir",
"-p",
self.out_dir],
self)
# Taxa collapse
taxa_keys = ["domain", "phylum", "class", "order", "family", "genus",
"species"]
# Taxa level; 1=domain, 7=species
level = 1
for taxa in taxa_keys:
cmd = ["qiime",
"taxa",
"collapse",
"--i-table",
self.input()["Merge_Denoise"]["table"].path,
"--i-taxonomy",
self.input()["Taxonomic_Classification"]["taxonomy"].path,
"--p-level",
str(level),
"--o-collapsed-table",
self.output()[taxa].path]
level = level + 1
run_cmd(cmd, self)
class Export_Taxa_Collapse(luigi.Task):
out_dir = Output_Dirs().taxonomy_dir
def requires(self):
return Taxa_Collapse()
def output(self):
exported_domain_collapsed_table = os.path.join(self.out_dir,
"domain_collapsed_table.tsv")
exported_phylum_collapsed_table = os.path.join(self.out_dir,
"phylum_collapsed_table.tsv")
exported_class_collapsed_table = os.path.join(self.out_dir,
"class_collapsed_table.tsv")