-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSnakefile
1342 lines (1245 loc) · 50.1 KB
/
Snakefile
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
## Configuration file
import os
if len(config) == 0:
if os.path.isfile("./config.yaml"):
configfile: "./config.yaml"
else:
sys.exit("Make sure there is a config.yaml file in " + os.getcwd() + " or specify one with the --configfile commandline parameter.")
include: "rules/common.smk"
## Make sure that all expected variables from the config file are in the config dictionary
configvars = ['annotation', 'organism', 'build', 'release', 'txome', 'genome', 'gtf', 'salmonindex', 'salmonk', 'STARindex', 'HISAT2index', 'readlength', 'fldMean', 'fldSD', 'metatxt', 'design', 'contrast', 'genesets', 'ncores', 'FASTQ', 'fqext1', 'fqext2', 'fqsuffix', 'output', 'useCondaR', 'Rbin', 'run_trimming', 'run_STAR', 'run_HISAT2', 'run_DRIMSeq', 'run_camera']
for k in configvars:
if k not in config:
config[k] = None
## If any of the file paths is missing, replace it with ""
def sanitizefile(str):
if str is None:
str = ''
return str
config['txome'] = sanitizefile(config['txome'])
config['gtf'] = sanitizefile(config['gtf'])
config['genome'] = sanitizefile(config['genome'])
config['STARindex'] = sanitizefile(config['STARindex'])
config['HISAT2index'] = sanitizefile(config['HISAT2index'])
config['salmonindex'] = sanitizefile(config['salmonindex'])
config['metatxt'] = sanitizefile(config['metatxt'])
config['metacsv'] = os.path.splitext(os.path.basename(config['metatxt']))[0]+'.csv'
## Read metadata
if not os.path.isfile(config["metatxt"]):
sys.exit("Metadata file " + config["metatxt"] + " does not exist.")
import pandas as pd
samples = pd.read_csv(config["metatxt"], sep='\t')
if not set(['names','type']).issubset(samples.columns):
sys.exit("Make sure 'names' and 'type' are columns in " + config["metatxt"])
## Sanitize provided input and output directories
import re
def getpath(str):
if str in ['', '.', './']:
return ''
if str.startswith('./'):
regex = re.compile('^\./?')
str = regex.sub('', str)
if not str.endswith('/'):
str += '/'
return str
proj_dir = os.path.abspath(os.path.normpath(getpath(config["proj_dir"])))
outputdir = os.path.abspath(getpath(config["output"])) + "/"
FASTQdir = getpath(config["FASTQ"])
## Define the conda environment for all rules using R
if config["useCondaR"] == True:
Renv = "envs/environment_R.yaml"
else:
Renv = "envs/environment.yaml"
## Define the R binary
Rbin = config["Rbin"]
# The config.yaml files determines which steps should be performed
def stringtie_output(wildcards):
input = []
input.extend(expand(outputdir + "stringtie/{sample}/{sample}.gtf", sample = samples.names[samples.type == 'PE'].values.tolist()))
return input
def dbtss_output(wildcards):
input = []
input.extend(expand(outputdir + "dbtss_coverage/{sample}_dbtss_coverage_over_10.txt", sample = samples.names[samples.type == 'PE'].values.tolist()))
return input
def jbrowse_output(wildcards):
input = []
input.extend(expand("/var/www/html/jbrowse/" + os.path.basename(proj_dir) + "/samples/{sample}.bw", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.append("/var/www/html/jbrowse/" + os.path.basename(proj_dir) + "/trackList.json")
return input
def split_output(wildcards):
input = []
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam", sample = samples.names[samples.type == 'PE'].values.tolist()))
return input
def bigwig_output(wildcards):
input = []
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.all.bw", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.all.bw", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.all.bw", sample = samples.names[samples.type == 'PE'].values.tolist()))
return input
def read_dist_output(wildcards):
input = []
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}_all.read_distribution.json", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}_gdna.read_distribution.json", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}_cdna.read_distribution.json", sample = samples.names[samples.type == 'PE'].values.tolist()))
return input
## ------------------------------------------------------------------------------------ ##
## Target definitions
## ------------------------------------------------------------------------------------ ##
## Run all analyses
rule all:
input:
outputdir + "MultiQC/multiqc_report.html",
# outputdir + "seurat/unfiltered_seu.rds",
bigwig_output,
split_output,
read_dist_output,
# vcf = outputdir + "genotyped/all.vcf.gz",
# annotated_vcf = outputdir + "genotyped/variants.annotated.bcf",
# plugins = directory("resources/vep/plugins")
# dbtss_output,
# jbrowse_output,
copywriter_output = outputdir + "Rout/copywriter" + "/segment.Rdata",
# loom_file = outputdir + "velocyto/" + os.path.basename(proj_dir) + ".loom"
# velocyto_seu = outputdir + "velocyto/" + "unfiltered_seu.rds"
rule setup:
input:
outputdir + "Rout/pkginstall_state.txt",
outputdir + "Rout/softwareversions.done"
## Install R packages
rule pkginstall:
input:
script = "scripts/install_pkgs.R"
output:
outputdir + "Rout/pkginstall_state.txt"
params:
flag = config["annotation"],
ncores = config["ncores"],
organism = config["organism"]
priority:
50
conda:
Renv
log:
outputdir + "Rout/install_pkgs.Rout"
benchmark:
outputdir + "benchmarks/install_pkgs.txt"
shell:
'''{Rbin} CMD BATCH --no-restore --no-save "--args outtxt='{output}' ncores='{params.ncores}' annotation='{params.flag}' organism='{params.organism}'" {input.script} {log}'''
## FastQC on original (untrimmed) files
rule runfastqc:
input:
expand(outputdir + "FastQC/{sample}_" + str(config["fqext1"]) + "_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()),
expand(outputdir + "FastQC/{sample}_" + str(config["fqext2"]) + "_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()),
expand(outputdir + "FastQC/{sample}_fastqc.zip", sample = samples.names[samples.type == 'SE'].values.tolist())
## Trimming and FastQC on trimmed files
rule runtrimming:
input:
expand(outputdir + "FastQC/{sample}_" + str(config["fqext1"]) + "_val_1_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()),
expand(outputdir + "FastQC/{sample}_" + str(config["fqext2"]) + "_val_2_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()),
expand(outputdir + "FastQC/{sample}_trimmed_fastqc.zip", sample = samples.names[samples.type == 'SE'].values.tolist())
## Salmon quantification
rule runsalmonquant:
input:
expand(outputdir + "salmon/{sample}/quant.sf", sample = samples.names.values.tolist())
## STAR alignment
rule runstar:
input:
expand(outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam.bai", sample = samples.names.values.tolist()),
expand(outputdir + "STARbigwig/{sample}_Aligned.sortedByCoord.out.bw", sample = samples.names.values.tolist())
## HISAT2 alignment
rule runhisat2:
input:
expand(outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam.bai", sample = samples.names.values.tolist()),
expand(outputdir + "HISAT2bigwig/{sample}_Aligned.sortedByCoord.out.bw", sample = samples.names.values.tolist())
## DBTSS coverage
rule rundbtss:
input:
expand(outputdir + "dbtss_coverage/{sample}/{sample}_dbtss_coverage.txt", sample = samples.names.values.tolist())
## List all the packages that were used by the R analyses
rule listpackages:
log:
outputdir + "Rout/list_packages.Rout"
params:
Routdir = outputdir + "Rout",
outtxt = outputdir + "R_package_versions.txt",
script = "scripts/list_packages.R"
conda:
Renv
shell:
'''{Rbin} CMD BATCH --no-restore --no-save "--args Routdir='{params.Routdir}' outtxt='{params.outtxt}'" {params.script} {log}'''
## Print the versions of all software packages
rule softwareversions:
output:
touch(outputdir + "Rout/softwareversions.done")
conda:
"envs/environment.yaml"
shell:
"echo -n 'ARMOR version ' && cat version; "
"salmon --version; trim_galore --version; "
"echo -n 'cutadapt ' && cutadapt --version; "
"fastqc --version; STAR --version; hisat2 --version; samtools --version; multiqc --version; "
"bedtools --version"
## ------------------------------------------------------------------------------------ ##
## Reference preparation
## ------------------------------------------------------------------------------------ ##
## Generate Salmon index from merged cDNA and ncRNA files
rule salmonindex:
input:
txome = config["txome"]
output:
config["salmonindex"] + "/hash.bin"
log:
outputdir + "logs/salmon_index.log"
benchmark:
outputdir + "benchmarks/salmon_index.txt"
params:
salmonk = config["salmonk"],
salmonoutdir = config["salmonindex"],
anno = config["annotation"]
conda:
"envs/environment.yaml"
shell:
"""
if [ {params.anno} == "Gencode" ]; then
echo 'Salmon version:\n' > {log}; salmon --version >> {log};
salmon index -t {input.txome} -k {params.salmonk} -i {params.salmonoutdir} --gencode --type quasi
else
echo 'Salmon version:\n' > {log}; salmon --version >> {log};
salmon index -t {input.txome} -k {params.salmonk} -i {params.salmonoutdir} --type quasi
fi
"""
## Generate linkedtxome mapping
rule linkedtxome:
input:
txome = config["txome"],
gtf = config["gtf"],
salmonidx = config["salmonindex"] + "/hash.bin",
script = "scripts/generate_linkedtxome.R",
install = outputdir + "Rout/pkginstall_state.txt"
log:
outputdir + "Rout/generate_linkedtxome.Rout"
benchmark:
outputdir + "benchmarks/generate_linkedtxome.txt"
output:
config["salmonindex"] + ".json"
params:
flag = config["annotation"],
organism = config["organism"],
release = str(config["release"]),
build = config["build"]
conda:
Renv
shell:
'''{Rbin} CMD BATCH --no-restore --no-save "--args transcriptfasta='{input.txome}' salmonidx='{input.salmonidx}' gtf='{input.gtf}' annotation='{params.flag}' organism='{params.organism}' release='{params.release}' build='{params.build}' output='{output}'" {input.script} {log}'''
## Generate STAR index
rule starindex:
input:
genome = config["genome"],
gtf = config["gtf"]
output:
config["STARindex"] + "/SA",
config["STARindex"] + "/chrNameLength.txt"
log:
outputdir + "logs/STAR_index.log"
benchmark:
outputdir + "benchmarks/STAR_index.txt"
params:
STARindex = config["STARindex"],
readlength = config["readlength"]
conda:
"envs/environment.yaml"
threads:
config["ncores"]
shell:
"echo 'STAR version:\n' > {log}; STAR --version >> {log}; "
"STAR --runMode genomeGenerate --runThreadN {threads} --genomeDir {params.STARindex} "
"--genomeFastaFiles {input.genome} --sjdbGTFfile {input.gtf} --sjdbOverhang {params.readlength}"
## ------------------------------------------------------------------------------------ ##
## Quality control
## ------------------------------------------------------------------------------------ ##
## FastQC, original reads
rule fastqc:
input:
fastq = FASTQdir + "{sample}." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "FastQC/{sample}_fastqc.zip"
params:
FastQC = outputdir + "FastQC"
log:
outputdir + "logs/fastqc_{sample}.log"
benchmark:
outputdir + "benchmarks/fastqc_{sample}.txt"
conda:
"envs/environment.yaml"
threads:
config["ncores"]
shell:
"echo 'FastQC version:\n' > {log}; fastqc --version >> {log}; "
"fastqc -o {params.FastQC} -t {threads} {input.fastq}"
## FastQC, trimmed reads
rule fastqctrimmed:
input:
fastq = outputdir + "FASTQtrimmed/{sample}.fq.gz"
output:
outputdir + "FastQC/{sample}_fastqc.zip"
params:
FastQC = outputdir + "FastQC"
log:
outputdir + "logs/fastqc_trimmed_{sample}.log"
benchmark:
outputdir + "benchmarks/fastqc_trimmed_{sample}.txt"
conda:
"envs/environment.yaml"
threads:
config["ncores"]
shell:
"echo 'FastQC version:\n' > {log}; fastqc --version >> {log}; "
"fastqc -o {params.FastQC} -t {threads} {input.fastq}"
## Rseqc gene body coverage plot
rule genebodycoverage:
input:
bigwig = outputdir + "HISAT2bigwig/{sample}_Aligned.sortedByCoord.out.bw"
output:
coverage_txt = outputdir + "rseqc/{sample}.geneBodyCoverage.txt"
params:
sample = outputdir + "rseqc/{sample}",
bed = config["bed"]
log:
outputdir + "logs/genebodycoverage_{sample}.log"
benchmark:
outputdir + "benchmarks/genebodycoverage_{sample}.txt"
conda:
"envs/environment.yaml"
threads:
config["ncores"]
shell:
"echo 'geneBody_coverage.py version:\n' > {log}; geneBody_coverage.py --version >> {log}; "
"geneBody_coverage2.py -r {params.bed} -i {input.bigwig} -o {params.sample}"
# The config.yaml files determines which steps should be performed
def multiqc_input(wildcards):
input = []
input.extend(expand(outputdir + "FastQC/{sample}_fastqc.zip", sample = samples.names[samples.type == 'SE'].values.tolist()))
input.extend(expand(outputdir + "FastQC/{sample}_" + str(config["fqext1"]) + "_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "FastQC/{sample}_" + str(config["fqext2"]) + "_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()))
if config["run_genebodycoverage"]:
input.extend(expand(outputdir + "rseqc/{sample}." + "geneBodyCoverage.txt", sample = samples.names[samples.type == 'PE'].values.tolist()))
if config["run_SALMON"]:
input.extend(expand(outputdir + "salmon/{sample}/quant.sf", sample = samples.names.values.tolist()))
if config["run_trimming"]:
input.extend(expand(outputdir + "FASTQtrimmed/{sample}_trimmed.fq.gz", sample = samples.names[samples.type == 'SE'].values.tolist()))
input.extend(expand(outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext1"]) + "_val_1.fq.gz", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext2"]) + "_val_2.fq.gz", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "FastQC/{sample}_trimmed_fastqc.zip", sample = samples.names[samples.type == 'SE'].values.tolist()))
input.extend(expand(outputdir + "FastQC/{sample}_" + str(config["fqext1"]) + "_val_1_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()))
input.extend(expand(outputdir + "FastQC/{sample}_" + str(config["fqext2"]) + "_val_2_fastqc.zip", sample = samples.names[samples.type == 'PE'].values.tolist()))
if config["run_STAR"]:
input.extend(expand(outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam.bai", sample = samples.names.values.tolist()))
if config["run_HISAT2"]:
input.extend(expand(outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam.bai", sample = samples.names.values.tolist()))
# input.extend(expand(outputdir + "HISAT2/{sample}/{sample}-cdna.rnaseq_metrics.txt", sample = samples.names.values.tolist()))
return input
## Determine the input directories for MultiQC depending on the config file
def multiqc_params(wildcards):
param = [outputdir + "FastQC"]
if config["run_SALMON"]:
param.append(outputdir + "salmon")
if config["run_trimming"]:
param.append(outputdir + "FASTQtrimmed")
if config["run_STAR"]:
param.append(outputdir + "STAR")
if config["run_HISAT2"]:
param.append(outputdir + "HISAT2")
return param
## MultiQC
rule multiqc:
input:
multiqc_input
output:
outputdir + "MultiQC/multiqc_report.html"
params:
inputdirs = multiqc_params,
MultiQCdir = outputdir + "MultiQC"
log:
outputdir + "logs/multiqc.log"
benchmark:
outputdir + "benchmarks/multiqc.txt"
conda:
"envs/environment.yaml"
shell:
"echo 'MultiQC version:\n' > {log}; multiqc --version >> {log}; "
"multiqc {params.inputdirs} -f -o {params.MultiQCdir}"
## ------------------------------------------------------------------------------------ ##
## Adapter trimming
## ------------------------------------------------------------------------------------ ##
# TrimGalore!
rule trimgaloreSE:
input:
fastq = FASTQdir + "{sample}." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "FASTQtrimmed/{sample}_trimmed.fq.gz"
params:
FASTQtrimmeddir = outputdir + "FASTQtrimmed"
log:
outputdir + "logs/trimgalore_{sample}.log"
benchmark:
outputdir + "benchmarks/trimgalore_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"echo 'TrimGalore! version:\n' > {log}; trim_galore --version >> {log}; "
"trim_galore -q 20 --phred33 --length 20 -o {params.FASTQtrimmeddir} --path_to_cutadapt cutadapt {input.fastq}"
rule trimgalorePE:
input:
fastq1 = FASTQdir + "{sample}_" + str(config["fqext1"]) + "." + str(config["fqsuffix"]) + ".gz",
fastq2 = FASTQdir + "{sample}_" + str(config["fqext2"]) + "." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext1"]) + "_val_1.fq.gz",
outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext2"]) + "_val_2.fq.gz"
params:
FASTQtrimmeddir = outputdir + "FASTQtrimmed"
log:
outputdir + "logs/trimgalore_{sample}.log"
benchmark:
outputdir + "benchmarks/trimgalore_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"echo 'TrimGalore! version:\n' > {log}; trim_galore --version >> {log}; "
"trim_galore -q 20 --phred33 --length 20 -o {params.FASTQtrimmeddir} --path_to_cutadapt cutadapt "
"--paired {input.fastq1} {input.fastq2}"
## ------------------------------------------------------------------------------------ ##
## HISAT2 mapping
## ------------------------------------------------------------------------------------ ##
## Genome mapping with HISAT2
rule HISAT2PE:
input:
fastq1 = outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext1"]) + "_val_1.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}_" + str(config["fqext1"]) + "." + str(config["fqsuffix"]) + ".gz",
fastq2 = outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext2"]) + "_val_2.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}_" + str(config["fqext2"]) + "." + str(config["fqsuffix"]) + ".gz"
output:
bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.out.bam"
threads:
config["ncores"]
log:
version = outputdir + "logs/HISAT2_{sample}.log",
stats = outputdir + "HISAT2" + "/HISAT2_{sample}_stats.txt"
benchmark:
outputdir + "benchmarks/HISAT2_{sample}.txt"
params:
HISAT2index = config["HISAT2index"],
HISAT2dir = outputdir + "HISAT2"
conda:
"envs/environment.yaml"
shell:
"echo 'hisat2 --version:\n' > {log.version}; hisat2 --version >> {log.version}; "
"hisat2 --new-summary --pen-noncansplice 20 --threads {threads} --mp 1,0 --sp 3,1 -x {params.HISAT2index} -1 {input.fastq1} -2 {input.fastq2} 2> {log.stats} | samtools view -Sbo {output.bam}"
# convert and sort sam files
rule bamsort_hisat2:
input:
rg_bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.out.bam"
output:
sorted_bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam"
log:
outputdir + "logs/samtools_sort_{sample}.log"
benchmark:
outputdir + "benchmarks/samtools_sort_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"echo 'samtools version:\n' > {log}; samtools --version >> {log}; "
"samtools sort -O bam -o {output.sorted_bam} {input.rg_bam}"
# ## Convert BAM files to bigWig
# rule bigwighisat2:
# input:
# bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam"
# output:
# outputdir + "HISAT2bigwig/{sample}_Aligned.sortedByCoord.out.bw"
# params:
# HISAT2bigwigdir = outputdir + "HISAT2bigwig"
# log:
# outputdir + "logs/bigwig_{sample}.log"
# benchmark:
# outputdir + "benchmarks/bigwig_{sample}.txt"
# conda:
# "envs/environment.yaml"
# shell:
# "echo 'bedtools version:\n' > {log}; bedtools --version >> {log}; "
# "bedtools genomecov -split -ibam {input.bam} -bg | LC_COLLATE=C sort -k1,1 -k2,2n > "
# "{params.HISAT2bigwigdir}/{wildcards.sample}_Aligned.sortedByCoord.out.bedGraph; "
# "bedGraphToBigWig {params.HISAT2bigwigdir}/{wildcards.sample}_Aligned.sortedByCoord.out.bedGraph "
# "{input.chrl} {output}; rm -f {params.HISAT2bigwigdir}/{wildcards.sample}_Aligned.sortedByCoord.out.bedGraph"
## Convert gdna BAM files to bigWig
rule bigwighisat2:
input:
bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam"
output:
outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.all.bw"
params:
prefix = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out"
# HISAT2bigwigdir = outputdir + "HISAT2bigwig"
log:
outputdir + "logs/bigwig_{sample}.log"
benchmark:
outputdir + "benchmarks/bigwig_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"megadepth {input.bam} --threads {threads} --bigwig --prefix {params.prefix}"
## Convert gdna BAM files to bigWig
rule bigwiggdna:
input:
bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam"
output:
outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.all.bw"
params:
prefix = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna"
# HISAT2bigwigdir = outputdir + "HISAT2bigwig"
log:
outputdir + "logs/bigwig_{sample}.log"
benchmark:
outputdir + "benchmarks/bigwig_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"megadepth {input.bam} --threads {threads} --bigwig --prefix {params.prefix}"
## Convert cdna BAM files to bigWig
rule bigwigcdna:
input:
bam = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.bam"
output:
outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.all.bw"
params:
prefix = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna"
# HISAT2bigwigdir = outputdir + "HISAT2bigwig"
log:
outputdir + "logs/bigwig_{sample}.log"
benchmark:
outputdir + "benchmarks/bigwig_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"megadepth {input.bam} --threads {threads} --bigwig --prefix {params.prefix}"
## ------------------------------------------------------------------------------------ ##
## Split Intronic/Exonic
## ------------------------------------------------------------------------------------ ##
# Assign Reads to cDNA/gDNA based on exonic overlap
rule samdepth:
input:
bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam",
output:
depth_out = outputdir + "HISAT2/{sample}/{sample}_output.txt",
log:
outputdir + "logs/bedtools_{sample}.log"
benchmark:
outputdir + "benchmarks/bedtools_{sample}.txt"
threads:
config["ncores"]
params:
exonic_bed = config["exonic_bed"],
n_coverage = config["n_coverage"],
chrom_sizes = config["chrom_sizes"]
conda:
"envs/environment.yaml"
shell:
"echo 'bedtools version:\n' > {log}; bedtools --version >> {log}; "
"bedtools intersect -g {params.chrom_sizes} -sorted -wa -v -abam {input.bam} -b {params.exonic_bed} | "
"samtools depth /dev/stdin > {output.depth_out}"
rule bed_above_n:
input:
depth_out = outputdir + "HISAT2/{sample}/{sample}_output.txt",
script = "scripts/bed_from_areas_covered_above_N.py"
output:
bed_above_n = outputdir + "HISAT2/{sample}/{sample}_above_n.bed",
log:
outputdir + "logs/bedtools_{sample}.log"
benchmark:
outputdir + "benchmarks/bedtools_{sample}.txt"
threads:
config["ncores"]
params:
exonic_bed = config["exonic_bed"],
n_coverage = config["n_coverage"],
chrom_sizes = config["chrom_sizes"]
conda:
"envs/environment.yaml"
shell:
"python {input.script} {input.depth_out} {params.n_coverage} > {output.bed_above_n}"
rule split_exonic:
input:
bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam",
output:
gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna_w_peaks.bam",
cdna_bam = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.bam"
log:
outputdir + "logs/bedtools_{sample}.log"
benchmark:
outputdir + "benchmarks/bedtools_{sample}.txt"
threads:
config["ncores"]
params:
exonic_bed = config["exonic_bed"],
n_coverage = config["n_coverage"],
chrom_sizes = config["chrom_sizes"]
conda:
"envs/environment.yaml"
shell:
"echo 'bedtools version:\n' > {log}; bedtools --version >> {log}; "
"bedtools intersect -g {params.chrom_sizes} -wa -v -abam {input.bam} -b {params.exonic_bed} > {output.gdna_bam}; "
"bedtools intersect -g {params.chrom_sizes} -wa -abam {input.bam} -b {params.exonic_bed} 2> {log} > {output.cdna_bam}"
rule callpeaks_gdna:
input:
gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna_w_peaks.bam"
output:
gdna_broadpeaks = outputdir + "HISAT2/{sample}/NA_peaks.broadPeak"
log:
outputdir + "logs/macs2_{sample}.log"
benchmark:
outputdir + "benchmarks/macs2_{sample}.txt"
threads:
config["ncores"]
params:
outdir = outputdir + "HISAT2/{sample}",
conda:
"envs/environment.yaml"
shell:
"echo 'macs2 version:\n' > {log}; macs2 --version >> {log}; "
"macs2 callpeak --nomodel --extsize 147 -t {input.gdna_bam} -f BAM --broad --outdir {params.outdir}"
rule sortpeaks_gdna:
input:
gdna_broadpeaks = outputdir + "HISAT2/{sample}/NA_peaks.broadPeak"
output:
gdna_peak_bed = outputdir + "HISAT2/{sample}/{sample}-gdna.sorted.bed"
log:
outputdir + "logs/bedtools_{sample}.log"
benchmark:
outputdir + "benchmarks/bedtools_{sample}.txt"
threads:
config["ncores"]
params:
outdir = outputdir + "HISAT2/{sample}",
conda:
"envs/environment.yaml"
shell:
"echo 'bedtools version:\n' > {log}; bedtools --version >> {log}; "
"bedtools sort -i {input.gdna_broadpeaks} > {output.gdna_peak_bed}"
# rule exclude_gdna_peaks:
# input:
# gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna_w_peaks.bam",
# gdna_peak_bed = outputdir + "HISAT2/{sample}/{sample}-gdna.sorted.bed"
# output:
# gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam",
# log:
# outputdir + "logs/bedtools_{sample}.log"
# benchmark:
# outputdir + "benchmarks/bedtools_{sample}.txt"
# threads:
# config["ncores"]
# params:
# chrom_sizes = config["chrom_sizes"]
# conda:
# "envs/environment.yaml"
# shell:
# "echo 'bedtools version:\n' > {log}; bedtools --version >> {log}; "
# "bedtools intersect -wa -v -abam {input.gdna_bam} -b {input.gdna_peak_bed} > {output.gdna_bam}"
rule exclude_gdna_threshold:
input:
gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna_w_peaks.bam",
bed_above_n = outputdir + "HISAT2/{sample}/{sample}_above_n.bed"
output:
gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam",
log:
outputdir + "logs/bedtools_{sample}.log"
benchmark:
outputdir + "benchmarks/bedtools_{sample}.txt"
threads:
config["ncores"]
params:
chrom_sizes = config["chrom_sizes"]
conda:
"envs/environment.yaml"
shell:
"echo 'bedtools version:\n' > {log}; bedtools --version >> {log}; "
"bedtools intersect -wa -v -abam {input.gdna_bam} -b {input.bed_above_n} > {output.gdna_bam}"
rule split_bamindex:
input:
gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam",
cdna_bam = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.bam",
output:
gdna_bai = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bai",
cdna_bai = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.bai",
log:
outputdir + "logs/samtools_index_{sample}.log"
benchmark:
outputdir + "benchmarks/samtools_index_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"echo 'samtools version:\n' > {log}; samtools --version >> {log}; "
"samtools index {input.gdna_bam}; "
"samtools index {input.cdna_bam}"
rule compute_read_distribution:
input:
all_bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.out.bam",
output:
all_read_dist = outputdir + "HISAT2/{sample}/{sample}_all.read_distribution.json",
log:
outputdir + "logs/rseqc_{sample}.log"
benchmark:
outputdir + "benchmarks/rseqc_index_{sample}.txt"
threads:
config["ncores"]
params:
gtf = config["gtf"]
conda:
"envs/environment.yaml"
shell:
"bamstats -c 1 -a {params.gtf} -i {input.all_bam} -o {output.all_read_dist}"
rule compute_read_distribution_gdna:
input:
gdna_bam = outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam",
output:
gdna_read_dist = outputdir + "HISAT2/{sample}/{sample}_gdna.read_distribution.json",
log:
outputdir + "logs/rseqc_{sample}.log"
benchmark:
outputdir + "benchmarks/rseqc_index_{sample}.txt"
params:
gtf = config["gtf"]
conda:
"envs/environment.yaml"
shell:
"bamstats -c 1 -a {params.gtf} -i {input.gdna_bam} -o {output.gdna_read_dist}"
rule compute_read_distribution_cdna:
input:
cdna_bam = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.bam",
output:
cdna_read_dist = outputdir + "HISAT2/{sample}/{sample}_cdna.read_distribution.json",
log:
outputdir + "logs/rseqc_{sample}.log"
benchmark:
outputdir + "benchmarks/rseqc_index_{sample}.txt"
params:
gtf = config["gtf"]
conda:
"envs/environment.yaml"
shell:
"bamstats -c 1 -a {params.gtf} -i {input.cdna_bam} -o {output.cdna_read_dist}"
rule alignment_summary:
input:
# BAM aligned, splicing-aware, to reference genome
bam = outputdir + "HISAT2/{sample}/{sample}-cdna_Aligned.sortedByCoord.cdna.bam",
# Annotation file containing transcript, gene, and exon data
refflat="/dataVolume/storage/Homo_sapiens/grch38_tran/Homo_sapiens.GRCh38.87.refFlat"
output:
outputdir + "HISAT2/{sample}/{sample}-cdna.rnaseq_metrics.txt"
params:
# strand is optional (defaults to NONE) and pertains to the library preparation
# options are FIRST_READ_TRANSCRIPTION_STRAND, SECOND_READ_TRANSCRIPTION_STRAND, and NONE
strand="NONE",
# optional additional parameters, for example,
extra="VALIDATION_STRINGENCY=STRICT"
log:
"logs/picard/rnaseq-metrics/{sample}.log"
# optional specification of memory usage of the JVM that snakemake will respect with global
# resource restrictions (https://snakemake.readthedocs.io/en/latest/snakefiles/rules.html#resources)
# and which can be used to request RAM during cluster job submission as `{resources.mem_mb}`:
# https://snakemake.readthedocs.io/en/latest/executing/cluster.html#job-properties
resources:
mem_mb=1024
wrapper:
"0.76.0/bio/picard/collectrnaseqmetrics"
## ------------------------------------------------------------------------------------ ##
## CopywriteR
## ------------------------------------------------------------------------------------ ##
## CopywriteR
def human_readable(bin_size):
bin_size = bin_size/1000
bin_size = f'{bin_size}kb'
print(bin_size)
rule CopywriteR:
input:
outputdir + "Rout/pkginstall_state.txt",
sample_files = expand(outputdir + "HISAT2/{sample}/{sample}-gdna_Aligned.sortedByCoord.gdna.bam", sample = samples.names.values.tolist()),
script = "scripts/run_copywriter.R"
output:
outputdir + "Rout/copywriter" + "/segment.Rdata"
log:
outputdir + "Rout/copywriter.Rout"
benchmark:
outputdir + "benchmarks/copywriter.txt"
params:
bin_size = config["bin_size"],
copywriter_output_dir = proj_dir + "/output/copywriter",
threads = config["ncores"],
samples_pattern = "sortedByCoord.gdna.bam",
input_dir = outputdir + "HISAT2"
conda:
Renv
shell:
'''{Rbin} CMD BATCH --no-restore --no-save "--args threads='{threads}' copywriter_output_dir='{params.copywriter_output_dir}' bin_size='{params.bin_size}' input_dir='{params.input_dir}' samples_pattern='{params.samples_pattern}'" {input.script} {log}'''
## ------------------------------------------------------------------------------------ ##
## Stringtie
## ------------------------------------------------------------------------------------ ##
# Transcript assembly using StringTie
rule stringtie:
input:
cdna_bam = outputdir + "HISAT2/{sample}/{sample}_Aligned.sortedByCoord.cdna.bam"
output:
gtf = outputdir + "stringtie/{sample}/{sample}.gtf"
log:
outputdir + "logs/stringtie_{sample}.log"
benchmark:
outputdir + "benchmarks/stringtie_{sample}.txt"
threads:
config["ncores"]
params:
stringtiegtf = config["gtf"],
stringtiedir = outputdir + "stringtie"
conda:
"envs/environment.yaml"
shell:
"echo 'stringtie version:\n' > {log}; stringtie --version >> {log}; "
"stringtie {input.cdna_bam} -G {params.stringtiegtf} -x MT -eB -o {output.gtf}"
## ------------------------------------------------------------------------------------ ##
## Salmon abundance estimation
## ------------------------------------------------------------------------------------ ##
# Estimate abundances with Salmon
rule salmonSE:
input:
index = config["salmonindex"] + "/hash.bin",
fastq = outputdir + "FASTQtrimmed/{sample}_trimmed.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "salmon/{sample}/quant.sf"
log:
outputdir + "logs/salmon_{sample}.log"
benchmark:
outputdir + "benchmarks/salmon_{sample}.txt"
threads:
config["ncores"]
params:
salmonindex = config["salmonindex"],
fldMean = config["fldMean"],
fldSD = config["fldSD"],
salmondir = outputdir + "salmon"
conda:
"envs/environment.yaml"
shell:
"echo 'Salmon version:\n' > {log}; salmon --version >> {log}; "
"salmon quant -i {params.salmonindex} -l A -r {input.fastq} "
"-o {params.salmondir}/{wildcards.sample} --seqBias --gcBias "
"--fldMean {params.fldMean} --fldSD {params.fldSD} -p {threads}"
rule salmonPE:
input:
index = config["salmonindex"] + "/hash.bin",
fastq1 = outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext1"]) + "_val_1.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}_" + str(config["fqext1"]) + "." + str(config["fqsuffix"]) + ".gz",
fastq2 = outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext2"]) + "_val_2.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}_" + str(config["fqext2"]) + "." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "salmon/{sample}/quant.sf"
log:
outputdir + "logs/salmon_{sample}.log"
benchmark:
outputdir + "benchmarks/salmon_{sample}.txt"
threads:
config["ncores"]
params:
salmonindex = config["salmonindex"],
fldMean = config["fldMean"],
fldSD = config["fldSD"],
salmondir = outputdir + "salmon"
conda:
"envs/environment.yaml"
shell:
"echo 'Salmon version:\n' > {log}; salmon --version >> {log}; "
"salmon quant -i {params.salmonindex} -l A -1 {input.fastq1} -2 {input.fastq2} "
"-o {params.salmondir}/{wildcards.sample} --seqBias --gcBias "
"--fldMean {params.fldMean} --fldSD {params.fldSD} -p {threads}"
## ------------------------------------------------------------------------------------ ##
## STAR mapping
## ------------------------------------------------------------------------------------ ##
## Genome mapping with STAR
rule starSE:
input:
index = config["STARindex"] + "/SA",
fastq = outputdir + "FASTQtrimmed/{sample}_trimmed.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam"
threads:
config["ncores"]
log:
outputdir + "logs/STAR_{sample}.log"
benchmark:
outputdir + "benchmarks/STAR_{sample}.txt"
params:
STARindex = config["STARindex"],
STARdir = outputdir + "STAR"
conda:
"envs/environment.yaml"
shell:
"echo 'STAR version:\n' > {log}; STAR --version >> {log}; "
"STAR --genomeDir {params.STARindex} --readFilesIn {input.fastq} "
"--runThreadN {threads} --outFileNamePrefix {params.STARdir}/{wildcards.sample}/{wildcards.sample}_ "
"--outSAMtype BAM SortedByCoordinate --readFilesCommand gunzip -c"
rule starPE:
input:
index = config["STARindex"] + "/SA",
fastq1 = outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext1"]) + "_val_1.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}_" + str(config["fqext1"]) + "." + str(config["fqsuffix"]) + ".gz",
fastq2 = outputdir + "FASTQtrimmed/{sample}_" + str(config["fqext2"]) + "_val_2.fq.gz" if config["run_trimming"] else FASTQdir + "{sample}_" + str(config["fqext2"]) + "." + str(config["fqsuffix"]) + ".gz"
output:
outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam"
threads:
config["ncores"]
log:
outputdir + "logs/STAR_{sample}.log"
benchmark:
outputdir + "benchmarks/STAR_{sample}.txt"
params:
STARindex = config["STARindex"],
STARdir = outputdir + "STAR"
conda:
"envs/environment.yaml"
shell:
"echo 'STAR version:\n' > {log}; STAR --version >> {log}; "
"STAR --genomeDir {params.STARindex} --readFilesIn {input.fastq1} {input.fastq2} "
"--runThreadN {threads} --outFileNamePrefix {params.STARdir}/{wildcards.sample}/{wildcards.sample}_ "
"--outSAMtype BAM SortedByCoordinate --readFilesCommand gunzip -c"
## Index bam files
rule bamindex:
input:
bam = outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam"
output:
outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam.bai"
log:
outputdir + "logs/samtools_index_{sample}.log"
benchmark:
outputdir + "benchmarks/samtools_index_{sample}.txt"
conda:
"envs/environment.yaml"
shell:
"echo 'samtools version:\n' > {log}; samtools --version >> {log}; "
"samtools index {input.bam}"
## Convert BAM files to bigWig
rule bigwig:
input:
bam = outputdir + "STAR/{sample}/{sample}_Aligned.sortedByCoord.out.bam",
chrl = config["STARindex"] + "/chrNameLength.txt"
output:
outputdir + "STARbigwig/{sample}_Aligned.sortedByCoord.out.bw"
params: