forked from bihealth/seasnap-pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DE_pipeline.snake
1468 lines (1214 loc) · 58.3 KB
/
DE_pipeline.snake
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
## SeA-SnaP differential expression pipeline for RNA-seq analysis
## version: 1.0
## author: J.P.Pett (patrick.pett@bihealth.de)
#TODO: replace config value check by built-in? https://snakemake.readthedocs.io/en/stable/snakefiles/configuration.html#validation
import os, re, yaml, textwrap, pandas as pd
from collections import OrderedDict
from time import asctime, localtime, time
from pathlib import Path
from snakemake.utils import report, format as snakemake_format
from tools.pipeline_tools import DEPipelinePathHandler, ReportTool
yaml.add_representer(OrderedDict, lambda dumper, data: dumper.represent_dict(dict(data)))
SNAKEDIR = Path(workflow.current_basedir)
SNAKEFILE = workflow.snakefile
SCRIPTDIR = str(SNAKEDIR / "external_scripts")
# assemble config
config_file_name = config["file_name"] if "file_name" in config else "DE_config.yaml"
configfile: str(SNAKEDIR / "defaults" / "DE_config_defaults.yaml")
configfile: config_file_name
if config["organism_defaults"]:
configfile: str(SNAKEDIR / "defaults" / config["organism_defaults"])
configfile: config_file_name
# create path handler
conf_ranges = str(SNAKEDIR / "defaults" / "DE_config_ranges.yaml")
test_config = conf_ranges if config["pipeline_param"]["test_config"] else None
pph = DEPipelinePathHandler(workflow, test_config)
# exclude symbols '.' and '/' from wildcards
wildcard_constraints:
sample="[^./]+"
R_SESSION_INFO = r"""
cat("########################### session info ############################","\n")
print(sessionInfo())
cat("#####################################################################","\n\n")
"""
onstart:
# draw a dag
dag_file = pph.file_path(step="pipeline_report", extension="rule_execution.png", contrast="all")
os.makedirs(os.path.dirname(dag_file), exist_ok=True)
shell("snakemake --quiet --snakefile {} --rulegraph | dot -Tpng 1> {}".format(SNAKEFILE, dag_file))
# info about the pipeline run
info_file = pph.file_path(step="pipeline_report", extension="summary.csv", contrast="all")
os.makedirs(os.path.dirname(info_file), exist_ok=True)
shell("snakemake --quiet --snakefile {} --summary | sed 's/\t/, /g' 1> {}".format(SNAKEFILE, info_file))
# save merged config
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all")
with open(config_file, "w") as f: yaml.dump(config, f, default_flow_style=False)
##-------------------- starting point ----------------------------------------------------------------------
def get_inputs_all():
#contrasts
inputs = pph.expand_path(step="contrast", extension="rds")
#functional annotation
inputs.append(pph.expand_path(step = "goseq", extension = "go.rds", if_set = dict(goseq=True) ))
inputs.append(pph.expand_path(step = "goseq", extension = "kegg.rds", if_set = dict(goseq=True) ))
inputs.append(pph.file_path(step = "annotation", extension = "rds", contrast="all"))
inputs.append(pph.file_path(step = "export_raw_counts", extension = "xlsx", contrast = "all"))
inputs.append(pph.expand_path(step = "cluster_profiler", extension = "rds", if_set = dict(cluster_profiler=dict(run=True)) ))
inputs.append(pph.file_path(step = "tmod_dbs", extension = "rds", contrast="all"))
inputs.append(pph.file_path(step = "tmod_pca", extension = "rds", contrast="all", if_set=dict(tmod_pca=True)))
inputs.append(pph.expand_path(step = "tmod", extension = "rds", if_set = dict(tmod=True)))
#time series
for ts in config["time_series"]:
inputs.append(pph.file_path(step = "rain", extension = "tsv", contrast=ts))
#time series comparisons
for tsc in config["dodr"]["comparisons"]:
inputs.append(pph.file_path(step = "dodr", extension = "tsv", contrast=tsc))
return inputs
shell("rm -f {}".format(pph.file_path(step="pipeline_report", extension="report.html", contrast="all")))
rule all:
input:
get_inputs_all(),
# html generation does not work
#pph.file_path(step="report_html", extension="html", contrast="all"),
pph.file_path("report", "Rmd", contrast = "all")
output:
html = pph.file_path(step="pipeline_report", extension="report.html", contrast="all")
run:
loctime = asctime(localtime(time()))
rule_execution = pph.file_path("pipeline_report", "rule_execution.png", contrast="all")
summary = pph.file_path("pipeline_report", "summary.csv", contrast="all")
version_info = pph.file_path("pipeline_report", "version_info.txt", contrast="all")
conda_info = pph.file_path("pipeline_report", "conda_info.txt", contrast="all")
dag = rule_execution.split("/")[-1]
shell("conda list > {}".format(version_info))
shell("conda info > {}".format(conda_info))
report("""
=======================
RNAseq mapping pipeline
=======================
**Finished: {loctime}**
.. image:: {dag}
File status at pipeline start:
==============================
.. csv-table::
:file: {summary}
Version info:
=============
.. include:: {version_info}
:literal:
Conda info:
===========
.. include:: {conda_info}
:literal:
""", output.html, graph = rule_execution, table = summary)
rule export:
input:
get_inputs_all()
run:
pph.export()
##-------------------- make TxDb -----------------------------------------------------------------------------
rule TxDb_from_GTF:
""" make a TxDb object from GTF """
input:
gtf = config["organism"]["files"]["gtf"]
output:
pph.file_path(step = "TxDb_from_GTF", extension = "sqlite", contrast = "all")
log:
out = pph.file_path("TxDb_from_GTF", "output.log", contrast = "all", log=True)
run:
genus = config["organism"]["genus"]
taxon = config["organism"]["taxon"]
script = textwrap.dedent(r"""
#----- import packages
library(GenomicFeatures)
{R_SESSION_INFO}
#----- make transcript to gene table
TxDb <- makeTxDbFromGFF("{input.gtf}", format="gtf", organism="{genus}", taxonomyId={taxon})
#----- save Db
saveDb(TxDb, "{output}")
""")
script_file = pph.log(log.out, snakemake_format(script), step="TxDb_from_GTF", extension="R", contrast = "all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
##-------------------- import -------------------------------------------------------------------------------
DESIGN = config["experiment"]["design_formula"]
rule import_gene_counts:
""" collect count files (STAR) and build count matrix """
input:
samples = config["experiment"]["covariate_file"]["star"]
output:
rds=pph.file_path("import_gene_counts", "rds", contrast = "all"),
tsv=pph.file_path("import_gene_counts", "tsv", contrast = "all"),
xlsx=pph.file_path("import_gene_counts", "xlsx", contrast = "all")
log:
out = pph.file_path("import_gene_counts", "output.log", contrast = "all", log=True)
params:
tpm_xlsx=pph.file_path("import_gene_counts", "tpm.xlsx", contrast = "all"),
annot_pkg = config["organism"]["R"]["annotations"]
run:
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all")
column_filter = ""
if config["filters"]["experiment_whitelist"]:
column_filter += "&".join("is.element(sample_df${},{})".format( k, "c({})".format(",".join('"'+l+'"' for l in v)) )
for k,v in config["filters"]["experiment_whitelist"].items())
if config["filters"]["experiment_blacklist"]:
column_filter += "&".join("!is.element(sample_df${},{})".format( k, "c({})".format(",".join('"'+l+'"' for l in v)) )
for k,v in config["filters"]["experiment_blacklist"].items())
if column_filter == "":
column_filter = "TRUE"
r_gene_list = ("'"+config["filters"]["gene_list"]["file"]+"'") if config["filters"]["gene_list"]["file"] else "NULL"
r_gene_list_type = config["filters"]["gene_list"]["type"] or "NULL"
column_lvl = config["experiment"]["columns"] if "columns" in config["experiment"] else {}
level_list = "list({})".format(",".join("{}=c({})".format( n, ",".join('"'+s+'"' for s in l) ) for n,l in column_lvl.items()))
script = textwrap.dedent(r"""
#----- import packages
library(DESeq2)
library(writexl)
library(AnnotationDbi)
library({params.annot_pkg})
{R_SESSION_INFO}
#----- variables
sample_f <- "{input.samples}"
output_xlsx <- "{output.xlsx}"
output_tsv <- "{output.tsv}"
output_tpm_xlsx <- "{params.tpm_xlsx}"
output_rds <- "{output.rds}"
conf.f <- "{config_file}"
gene_list <- {r_gene_list}
subset_genes_type <- "{r_gene_list_type}"
#----- import data
sample_df <- read.table(sample_f, header=TRUE)
files <- as.character(sample_df$filename); print(files)
samples <- as.character(sample_df$label)
config <- yaml::yaml.load_file(conf.f)
#----- merge count files from star
df_list <- lapply(1:length(files), function(i) as.data.frame(read.csv(files[i], skip=4, sep="\t",
col.names=c("ID", samples[i]), check.names=FALSE, header=FALSE)))
count_dat <- Reduce(function(...) merge(..., all=TRUE, by="ID"), df_list)
rownames(count_dat) <- count_dat$ID
#----- subset genes
if (!is.null(gene_list)) {{
subset_genes <- as.character(read.csv(gene_list, header=F)[,1]); print(subset_genes)
if (subset_genes_type == "ENSEMBL"){{
subset_ensembl_genes <- subset_genes
}} else {{
subset_ensembl_genes <- mapIds({params.annot_pkg}, keys=subset_genes, column="ENSEMBL",
keytype=subset_genes_type, multiVals="first"); print(subset_ensembl_genes)
}}
count_dat <- count_dat[subset_ensembl_genes[!is.na(subset_ensembl_genes)],]
}}
#----- if present, merge tpm values (generated from star bam with TPMcalculator) for display along results
if ("tpm" %in% colnames(sample_df)) {{
tpm_files <- as.character(sample_df$tpm)
tpm_df_list <- lapply(1:length(tpm_files), function(i) as.data.frame(read.csv(tpm_files[i], sep="\t",
col.names=c("ID", samples[i]), check.names=FALSE, header=FALSE)))
tpm_dat <- Reduce(function(...) merge(..., all=TRUE, by="ID"), tpm_df_list); rownames(tpm_dat) <- tpm_dat$ID
}}
#----- change levels
level_cols <- {level_list}
for (col in names(level_cols)) {{
sample_df[,col] <- factor(sample_df[,col], levels = level_cols[[col]])
}}
#----- import counts in DESeq2
rownames(sample_df) <- sample_df$label; count_dat <- count_dat[, rownames(sample_df)]
dds <- DESeqDataSetFromMatrix(countData = as.matrix(count_dat), colData = sample_df, design = {DESIGN})
#----- save as rds
saveRDS(dds, file=output_rds)
#----- export counts as tables
colnames(count_dat) <- sample_df$label
write_xlsx(count_dat, path=output_xlsx)
write.table(count_dat, file=output_tsv, sep="\t", quote=F)
if ("tpm" %in% colnames(sample_df)) {{
symbol <- mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", tpm_dat$ID),
column="SYMBOL", keytype="ENSEMBL", multiVals="first")
tpm_dat <- cbind(symbol, tpm_dat)
colnames(tpm_dat) <- c("Symbol", "geneID", as.character(sample_df$label))
write_xlsx(tpm_dat, path=output_tpm_xlsx)
}}
""")
script_file = pph.log(log.out, snakemake_format(script), step="import_gene_counts", extension="R", contrast = "all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
rule import_featurecounts:
""" collect count files (featurecounts) and build count matrix """
input:
samples = config["experiment"]["covariate_file"]["star"]
output:
pph.file_path("import_featurecounts", "rds", contrast = "all")
log:
out = pph.file_path("import_featurecounts", "output.log", contrast = "all", log=True)
run:
column_filter = ""
if config["filters"]["experiment_whitelist"]:
column_filter += "&".join("is.element(sample_df${},{})".format( k, "c({})".format(",".join('"'+l+'"' for l in v)) )
for k,v in config["filters"]["experiment_whitelist"].items())
if config["filters"]["experiment_blacklist"]:
column_filter += "&".join("!is.element(sample_df${},{})".format( k, "c({})".format(",".join('"'+l+'"' for l in v)) )
for k,v in config["filters"]["experiment_blacklist"].items())
if column_filter == "":
column_filter = "TRUE"
column_lvl = config["experiment"]["columns"] if "columns" in config["experiment"] else {}
level_list = "list({})".format(",".join("{}=c({})".format( n, ",".join('"'+s+'"' for s in l) ) for n,l in column_lvl.items()))
script = textwrap.dedent(r"""
#----- import packages
library(DESeq2)
{R_SESSION_INFO}
#----- import data
sample_df <- read.table("{input.samples}", header=TRUE)
sample_df <- sample_df[{column_filter},]
files <- as.character(sample_df$filename); print(files)
samples <- as.character(sample_df$label)
#----- merge count files
read_fc <- function(fn, sn) read.csv(fn, comment="#", sep="\t", colClasses=c("character", rep("NULL", 5), "numeric"),
col.names=c("ID", rep("dummy", 5), sn), check.names=FALSE)
df_list <- lapply(1:length(files), function(i) as.data.frame(read_fc(files[i], samples[i])))
count_dat <- Reduce(function(...) merge(..., all=TRUE, by="ID"), df_list); rownames(count_dat) <- count_dat$ID
#----- change levels
level_cols <- {level_list}
for (col in names(level_cols)) {{
sample_df[,col] <- factor(sample_df[,col], levels = level_cols[[col]])
}}
#----- import counts in DESeq2
rownames(sample_df) <- sample_df$label; count_dat <- count_dat[, rownames(sample_df)]
dds <- DESeqDataSetFromMatrix(countData = as.matrix(count_dat), colData = sample_df, design = {DESIGN})
#----- save as rds
saveRDS(dds, file="{output}")
""")
script_file = pph.log(log.out, snakemake_format(script), step="import_featurecounts", extension="R", contrast = "all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
rule import_sf:
""" collect sf files (Salmon) and build count matrix """
input:
txdb = pph.file_path("TxDb_from_GTF", "sqlite", contrast = "all"),
samples = config["experiment"]["covariate_file"]["salmon"]
output:
pph.file_path("import_sf", "rds", contrast = "all")
log:
out = pph.file_path("import_sf", "output.log", contrast = "all", log=True)
run:
column_filter = ""
if config["filters"]["experiment_whitelist"]:
column_filter += "&".join("is.element(sample_df${},{})".format( k, "c({})".format(",".join('"'+l+'"' for l in v)) )
for k,v in config["filters"]["experiment_whitelist"].items())
if config["filters"]["experiment_blacklist"]:
column_filter += "&".join("!is.element(sample_df${},{})".format( k, "c({})".format(",".join('"'+l+'"' for l in v)) )
for k,v in config["filters"]["experiment_blacklist"].items())
if column_filter == "":
column_filter = "TRUE"
column_lvl = config["experiment"]["columns"] if "columns" in config["experiment"] else {}
level_list = "list({})".format(",".join("{}=c({})".format( k, ",".join('"'+l+'"' for l in v) ) for k,v in column_lvl.items()))
script = textwrap.dedent(r"""
#----- import packages
library(DESeq2)
library(tximport)
library(readr)
library(AnnotationDbi)
{R_SESSION_INFO}
#----- make transcript to gene table
TxDb <- loadDb(file = "{input.txdb}")
k <- keys(TxDb, keytype = "TXNAME")
tx2gene <- select(TxDb, k, "GENEID", "TXNAME")
#----- use tximport on input files
sample_df <- read.table("{input.samples}", header=TRUE)
sample_df <- sample_df[{column_filter},]
files <- as.character(sample_df$filename); print(files)
txi <- tximport(files, type = "salmon", tx2gene = tx2gene)
#----- change levels
level_cols <- {level_list}
for (col in names(level_cols)) {{
sample_df[,col] <- factor(sample_df[,col], levels = level_cols[[col]])
}}
#----- import txi in DESeq2
rownames(sample_df) <- sample_df$label
dds <- DESeqDataSetFromTximport(txi, colData = sample_df, design = {DESIGN})
#----- save as rds
saveRDS(dds, file="{output}")
""")
script_file = pph.log(log.out, snakemake_format(script), step="import_sf", extension="R", contrast = "all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
##-------------------- export_raw_counts -------------------------------------------------------------------------------
rule export_raw_counts:
""" export DESeq2 raw counts from the DESeq2 object as XLSX"""
input:
rds = pph.choose_input(choice_name = "mapping", options = [
dict(step = "import_gene_counts", extension = "rds", contrast = "all"),
dict(step = "import_featurecounts", extension = "rds", contrast = "all"),
dict(step = "import_sf", extension = "rds", contrast = "all")
])
output:
xlsx = pph.file_path("export_raw_counts", "xlsx", contrast = "all"),
csv = pph.file_path("export_raw_counts", "csv", contrast = "all")
log:
out = pph.file_path("export_raw_counts", "output.log", contrast = "all", log=True)
run:
script = textwrap.dedent(r"""
#----- import packages
library(DESeq2)
library(writexl)
library(tibble)
library(readr)
{R_SESSION_INFO}
#----- variables
output_xlsx <- "{output.xlsx}"
output_csv <- "{output.csv}"
input_rds <- "{input.rds}"
#----- read RDS object, extract count data, save as XLSX
dds <- readRDS(input_rds)
count_dat <- assay(dds)
count_dat <- as.data.frame(count_dat) %>% rownames_to_column("PrimaryID")
col_dat <- colData(dds)
colnames(count_dat)[-1] <- col_dat$label
write_csv(count_dat, path=output_csv)
write_xlsx(count_dat, path=output_xlsx)
""")
script_file = pph.log(log.out, snakemake_format(script), step="export_raw_counts", extension="R", contrast = "all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
##-------------------- DESeq2 -------------------------------------------------------------------------------
rule DESeq2:
""" run DESeq2 on a count matrix """
input:
pph.choose_input(choice_name = "mapping", options = [
dict(step = "import_gene_counts", extension = "rds", contrast = "all"),
dict(step = "import_featurecounts", extension = "rds", contrast = "all"),
dict(step = "import_sf", extension = "rds", contrast = "all")
])
output:
dds = pph.file_path("DESeq2", "deseq2.rds", contrast = "all"),
rld_blind = pph.file_path("DESeq2", "rld.blind.rds", contrast = "all"),
rld_model = pph.file_path("DESeq2", "rld.model.rds", contrast = "all"),
rld_blind_csv = pph.file_path("DESeq2", "rld.blind.csv", contrast = "all"),
rld_model_csv = pph.file_path("DESeq2", "rld.model.csv", contrast = "all")
log:
out = pph.file_path("DESeq2", "output.log", contrast = "all", log=True)
params:
coef_names = pph.file_path("DESeq2", "coef_names.txt", contrast = "all"),
rld_names = pph.file_path("DESeq2", "rld.model.csv", contrast = "all"),
annot_pkg = config["organism"]["R"]["annotations"]
run:
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all")
count_threshold = config["filters"]["low_counts"]
normalized_expression = config["normalization"]["normalized_expression"]
script = textwrap.dedent(r"""
#----- import packages
library(DESeq2)
library(AnnotationDbi)
library({params.annot_pkg})
{R_SESSION_INFO}
conf.f <- "{config_file}"
#----- load config
config <- yaml::yaml.load_file(conf.f)
#----- load DESeqDataSet
dds <- readRDS("{input}")
#----- pre-filtering
keep <- rowSums(counts(dds)) >= {count_threshold}
## at least min_counts in at least min_count_n number of samples
if(!is.null(config$filters$min_counts) && !is.null(config$filters$min_count_n)) {{
rs <- rowSums(counts(dds) > config$filters$min_counts)
keep <- keep & rs >= config$filters$min_count_n
}}
dds <- dds[keep,]; print(dds)
#----- DESeq2
dds <- DESeq(dds, betaPrior=FALSE, test="Wald")
# ----- Normalised expression values
rld_blind <- switch("{normalized_expression}",
"rld"=rlog(dds, blind=TRUE),
"vst"=vst(dds, blind=TRUE)
)
rld_model <- switch("{normalized_expression}",
"rld"=rlog(dds, blind=FALSE),
"vst"=vst(dds, blind=FALSE)
)
#----- save as rds
saveRDS(dds, file="{output.dds}")
saveRDS(rld_blind, file="{output.rld_blind}")
saveRDS(rld_model, file="{output.rld_model}")
#----- save other files
writeLines(resultsNames(dds), "{params.coef_names}")
write.table(data.frame(
gene_id=rownames(rld_model),
assay(rld_model),
symbol=mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(dds)),
column="SYMBOL", keytype="ENSEMBL", multiVals="first"),
entrez=mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(dds)),
column="ENTREZID", keytype="ENSEMBL", multiVals="first"),
check.names=FALSE
), file="{output.rld_model_csv}", sep="\t", col.names=TRUE, row.names=FALSE, quote=FALSE)
write.table(data.frame(
gene_id=rownames(rld_blind),
assay(rld_blind),
symbol=mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(dds)),
column="SYMBOL", keytype="ENSEMBL", multiVals="first"),
entrez=mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(dds)),
column="ENTREZID", keytype="ENSEMBL", multiVals="first"),
check.names=FALSE
), file="{output.rld_blind_csv}", sep="\t", col.names=TRUE, row.names=FALSE, quote=FALSE)
""")
script_file = pph.log(log.out, snakemake_format(script), step="DESeq2", extension="R", contrast = "all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
##-------------------- contrasts ----------------------------------------------------------------------------
rule contrast:
""" make a contrast """
input:
pph.file_path("DESeq2", "deseq2.rds", contrast = "all")
output:
rds = pph.file_path("contrast", "rds"),
csv = pph.file_path("contrast", "csv")
log:
out = pph.file_path("contrast", "output.log", log=True),
contrast_yaml = pph.file_path("contrast", "contrast.yaml", log=True)
params:
ma_plot = pph.file_path("contrast", "ma.pdf"),
count_plot = pph.file_path("contrast", "counts.pdf"),
annot_pkg = config["organism"]["R"]["annotations"]
run:
contrast = pph.get_contrast(wildcards.contrast)
with open(log.contrast_yaml, "w") as f: yaml.dump(contrast, f, default_flow_style=False)
# variants of contrast definition
contrast_column, contrast_ref = "group", ""
if "coef" in contrast:
contrast_type = "coef"
arg_val = '="{}"'.format(contrast["coef"])
contrast_def, lfc_def = "name" + arg_val, "coef" + arg_val
elif "ratio" in contrast:
contrast_type, ratio = "ratio", contrast["ratio"]
contrast_column, contrast_num, contrast_ref = ratio["column"], ratio["numerator"], ratio["denominator"]
contrast_def = lfc_def = 'contrast=c("{}", "{}", "{}")'.format(contrast_column, contrast_num, contrast_ref)
elif "vector" in contrast:
contrast_type = "vector"
contrast_def = lfc_def = 'contrast=c({})'.format(", ".join(map(str, contrast["vector"])))
else:
raise ValueError("Error in contrast: no valid contrast definition! must be one of {}".format(["coef:", "ratio:", "vector:"]))
# parameters
cutoff_FDR = contrast["max_p_adj"]
lfcThreshold = contrast["results_parameters"]["lfcThreshold"]
altHypothesis = contrast["results_parameters"]["altHypothesis"]
independentFiltering = "TRUE" if contrast["results_parameters"]["independentFiltering"] else "FALSE"
lfc_shrink_type = contrast["lfcShrink_parameters"]["type"]
rank_by = contrast["ranking_by"]
rank_order = contrast["ranking_order"].replace("x", "res$"+rank_by)
script = textwrap.dedent(r"""
#----- import packages
library(DESeq2)
library(AnnotationDbi)
library({params.annot_pkg})
{R_SESSION_INFO}
#----- load DESeqDataSet
dds <- readRDS("{input}")
#----- contrast
if ("{contrast_type}" == "ratio") {{
dds${contrast_column} = relevel(dds${contrast_column}, ref="{contrast_ref}")
dds <- nbinomWaldTest(dds)
}}
res <- results(dds, {contrast_def}, alpha={cutoff_FDR}, lfcThreshold={lfcThreshold},
altHypothesis="{altHypothesis}", independentFiltering={independentFiltering})
#----- log-fold-change shrinkage
#res$lfcShrunk <- res$log2FoldChange
#res$lfcShrunkSE <- res$lfcSE
if ("{lfc_shrink_type}"!="none"){{
lfc <- lfcShrink(dds, {lfc_def}, lfcThreshold={lfcThreshold}, type="{lfc_shrink_type}")
res$log2FoldChange_orig <- res$log2FoldChange
res$log2FoldChange <- lfc$log2FoldChange
res$lfcSE_orig <- res$lfcSE
res$lfcSE <- lfc$lfcSE
}}
#----- ranking
res <- res[order({rank_order}),]
#----- annotation [BEWARE- the in case on multiple mapping, the first entry will be selected]
res$symbol <- mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(res)),
column="SYMBOL", keytype="ENSEMBL", multiVals="first")
res$entrez <- mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(res)),
column="ENTREZID", keytype="ENSEMBL", multiVals="first")
#----- save as rds & csv
saveRDS(res, file="{output.rds}")
write.table(data.frame(gene_id=rownames(res), res), file="{output.csv}", sep="\t", col.names=TRUE, row.names=FALSE, quote=FALSE)
""")
script_file = pph.log(log.out, snakemake_format(script), step="contrast", extension="R", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
## ------------------------ annotation ---------------------------
## Annotation rule produces a table with mapping between the Primary IDs
## (ENSEMBL usually) and other potentially useful IDs as well as gene
## descriptions.
rule annotation:
""" Adding annotation information """
input:
# we use dds as this is the most reliable source of the primary IDs
dds = pph.file_path("DESeq2", "deseq2.rds", contrast = "all")
output:
res = pph.file_path(step = "annotation", extension = "rds", contrast="all"),
csv = pph.file_path(step = "annotation", extension = "csv", contrast="all")
log:
out = pph.file_path(step = "annotation", extension = "output.log", log=True, contrast="all")
run:
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all")
script = textwrap.dedent(r"""
library(AnnotationDbi)
{R_SESSION_INFO}
res.file <- "{output.res}"
res.csv <- "{output.csv}"
script.d <- "{SCRIPTDIR}"
conf.f <- "{config_file}"
dds <- "{input.dds}"
# ----------------------------------------
# No Snakemake wildcards beyond this point
# ----------------------------------------
library(orthomapper)
config <- yaml::yaml.load_file(conf.f)
gene_ids <- rownames(readRDS(dds))
res <- data.frame(PrimaryID=gene_ids, stringsAsFactors=FALSE)
res$ENSEMBL <- sub("\\..*$", "", res$PrimaryID)
annot <- orthomapper::entrez_annotate(res$ENSEMBL, taxon=as.numeric(config$organism$taxon),
keytype="ENSEMBL", column=c("SYMBOL", "ENTREZID", "REFSEQ", "GENENAME"))
if(!all(annot[,1] == res$ensembl))
stop("object returned by entrez_annotate() does not match query")
## no need to duplicate columns
res <- cbind(res, annot[, -1, drop=FALSE])
write.csv(res, row.names=FALSE, file=res.csv)
saveRDS(res, file=res.file)
""")
script_file = pph.log(log.out, snakemake_format(script), step="annotation", extension="R", contrast="all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
##-------------------- contrasts ----------------------------------------------------------------------------
## Same as contrasts, but saves all results from DESeq2
## everything named contrasts_full for consistency
rule contrasts_full:
""" make all contrasts (full version) """
input:
pph.file_path("DESeq2", "deseq2.rds", contrast = "all")
output:
rds = pph.file_path("contrasts_full", "rds"),
csv = pph.file_path("contrasts_full", "csv")
log:
out = pph.file_path("contrasts_full", "output.log", log=True),
params:
annot_pkg = config["organism"]["R"]["annotations"]
run:
contrast = pph.get_contrast(wildcards.contrast)
#with open(log.contrast_yaml, "w") as f: yaml.dump(contrast, f, default_flow_style=False)
# variants of contrast definition
contrast_column, contrast_ref = "group", ""
if "coef" in contrast:
contrast_type = "coef"
arg_val = '="{}"'.format(contrast["coef"])
contrast_def, lfc_def = "name" + arg_val, "coef" + arg_val
elif "ratio" in contrast:
contrast_type, ratio = "ratio", contrast["ratio"]
contrast_column, contrast_num, contrast_ref = ratio["column"], ratio["numerator"], ratio["denominator"]
contrast_def = lfc_def = 'contrast=c("{}", "{}", "{}")'.format(contrast_column, contrast_num, contrast_ref)
elif "vector" in contrast:
contrast_type = "vector"
contrast_def = lfc_def = 'contrast=c({})'.format(", ".join(map(str, contrast["vector"])))
else:
raise ValueError("Error in contrast: no valid contrast definition! must be one of {}".format(["coef:", "ratio:", "vector:"]))
# parameters
cutoff_FDR = contrast["max_p_adj"]
lfcThreshold = contrast["results_parameters"]["lfcThreshold"]
altHypothesis = contrast["results_parameters"]["altHypothesis"]
independentFiltering = "TRUE" if contrast["results_parameters"]["independentFiltering"] else "FALSE"
lfc_shrink_type = contrast["lfcShrink_parameters"]["type"]
rank_by = contrast["ranking_by"]
rank_order = contrast["ranking_order"].replace("x", "res$"+rank_by)
script = textwrap.dedent(r"""
#----- import packages
library(AnnotationDbi)
library(DESeq2)
library({params.annot_pkg})
{R_SESSION_INFO}
#----- load DESeqDataSet
dds <- readRDS("{input}")
#----- contrast
if ("{contrast_type}" == "ratio") {{
dds${contrast_column} = relevel(dds${contrast_column}, ref="{contrast_ref}")
dds <- nbinomWaldTest(dds)
}}
res <- results(dds, {contrast_def}, # alpha={cutoff_FDR}, lfcThreshold={lfcThreshold},
altHypothesis="{altHypothesis}") #, independentFiltering={independentFiltering})
#----- log-fold-change shrinkage
#res$lfcShrunk <- res$log2FoldChange
#res$lfcShrunkSE <- res$lfcSE
if ("{lfc_shrink_type}"!="none"){{
lfc <- lfcShrink(dds, {lfc_def}, # lfcThreshold={lfcThreshold},
type="{lfc_shrink_type}")
res$log2FoldChange_orig <- res$log2FoldChange
res$log2FoldChange <- lfc$log2FoldChange
res$lfcSE_orig <- res$lfcSE
res$lfcSE <- lfc$lfcSE
}}
#----- ranking
res <- res[order({rank_order}),]
#----- annotation [BEWARE- the in case on multiple mapping, the first entry will be selected]
res$symbol <- mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(res)),
column="SYMBOL", keytype="ENSEMBL", multiVals="first")
res$entrez <- mapIds({params.annot_pkg}, keys=sub("\\.[0-9]+$", "", row.names(res)),
column="ENTREZID", keytype="ENSEMBL", multiVals="first")
#----- save as rds & csv
saveRDS(res, file="{output.rds}")
write.table(data.frame(gene_id=rownames(res), res), file="{output.csv}", sep="\t", col.names=TRUE, row.names=FALSE, quote=FALSE)
""")
script_file = pph.log(log.out, snakemake_format(script), step="contrasts_full", extension="R", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
## ------------------------ preparation of the tmod databases ---------------------------
rule tmod_dbs:
""" Preparing tmod databases """
input:
#rds = pph.file_path("contrasts_full", "rds"),
annotation = pph.file_path(step="annotation", extension="rds", contrast="all")
output:
res = pph.file_path(step = "tmod_dbs", extension = "rds", contrast="all"),
map = pph.file_path(step = "tmod_dbs", extension = "mapping.rds", contrast="all")
log:
out = pph.file_path(step = "tmod_dbs", extension = "output.log", log=True, contrast="all")
run:
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all"),
script = textwrap.dedent(r"""
{R_SESSION_INFO}
res.file <- "{output.res}"
map.file <- "{output.map}"
script.d <- "{SCRIPTDIR}"
conf.f <- "{config_file}"
annot.f <- "{input.annotation}"
## ------------------------------
## no wildcards beyond this point
## ------------------------------
config <- yaml::yaml.load_file(conf.f)
source(file.path(script.d, "tmod_functions.R"))
## read the necessary files
## create the databases
dbs <- process_dbs(config)
saveRDS(dbs, file=res.file)
## provide mapping for the databases
map <- get_mapping(config, dbs, annot.f)
saveRDS(map, file=map.file)
""")
script_file = pph.log(log.out, snakemake_format(script), step="tmod_dbs", extension="R", contrast="all", **wildcards)
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
## ------------------------ gene set enrichments with tmod ---------------------------
rule tmod:
""" Gene set enrichment with tmod and MSigDB """
input:
rds = pph.file_path("contrasts_full", "rds"),
dbs = pph.file_path(step = "tmod_dbs", extension = "rds", contrast="all"),
map = pph.file_path(step = "tmod_dbs", extension = "mapping.rds", contrast="all")
output:
tmod_res = pph.file_path(step = "tmod", extension = "rds"),
tmod_gl = pph.file_path(step = "tmod", extension = "gl.rds"),
tmod_xlsx = pph.file_path(step = "tmod", extension = "xlsx")
log:
out = pph.file_path(step = "tmod", extension = "output.log", log=True)
run:
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all")
script = textwrap.dedent(r"""
{R_SESSION_INFO}
script.d <- "{SCRIPTDIR}"
conf.f <- "{config_file}"
de.input <- "{input.rds}"
map.f <- "{input.map}"
dbs.f <- "{input.dbs}"
res.file <- "{output.tmod_res}"
res.xlsx <- "{output.tmod_xlsx}"
res.gl.f <- "{output.tmod_gl}"
## ------------------------------
## no wildcards beyond this point
## ------------------------------
library(DESeq2)
library(tmod)
library(writexl)
library(purrr)
config <- yaml::yaml.load_file(conf.f)
source(file.path(script.d, "tmod_functions.R"))
dbs <- readRDS(dbs.f)
db.map <- readRDS(map.f)
de.res <- readRDS(de.input)
## create ordered gene lists for every database
message(paste0("Starting tmod for contrast ", de.input))
ordered_genelist <- get_ordered_genelist(de.res, config)
genelists <- lapply(dbs, map_genelists, ordered_genelist, db.map)
saveRDS(genelists, file=res.gl.f)
## run tmod using each of the predefined databases
res <- lapply(dbs, run_tmod, config, genelists, db.map)
## res is a list with an element for each db
## each element for a db is a list with an element for each
## of the sorting keys
## each of these elements contains objects `res` (df with results)
## and `gl` (genelist used to generate the results)
saveRDS(res, file=res.file)
message("tmod rds saved")
## shorten results for the human readable XLSX file
## filter the results
res.short <- lapply(res, function(x) lapply(x, reformat_res, pval.thr=Inf, auc.thr=0))
## hard: add lists of significant genes to the results tables
res.short <- imap(res, ~ {{
db.name <- .y
map(.x, ~ {{
add_sign_genes(., dbs[[db.name]], de.res, db.map)
}})
}})
## res.short still has two levels, one for the databases, another one
## for sorting keys, so we need to unlist – one level only
res.short <- unlist(res.short, recursive=FALSE)
## remove if there were no results
res.short <- res.short[!sapply(res.short, is.null)]
write_xlsx(res.short, path=res.xlsx)
""")
script_file = pph.log(log.out, snakemake_format(script), step="tmod", extension="R", **wildcards)
# run R
shell("Rscript --vanilla '{script_file}' &>> '{log.out}'")
##-------------------- multivariate tmod ----------------------------------------------------------------
rule tmod_pca:
""" Gene set enrichment of PCA with tmod and MSigDB """
input:
dds = pph.file_path("DESeq2", "deseq2.rds", contrast = "all"),
dbs = pph.file_path(step = "tmod_dbs", extension = "rds", contrast="all"),
map = pph.file_path(step = "tmod_dbs", extension = "mapping.rds", contrast="all")
output:
res = pph.file_path(step = "tmod_pca", extension = "rds", contrast="all"),
pca = pph.file_path(step = "tmod_pca", extension = "pca.rds", contrast="all"),
xlsx = pph.file_path(step = "tmod_pca", extension = "xlsx", contrast="all")
log:
out = pph.file_path(step = "tmod_pca", extension = "output.log", log=True, contrast="all")
run:
config_file = pph.file_path(step="pipeline_report", extension="yaml", contrast="all")
script = textwrap.dedent(r"""
{R_SESSION_INFO}
script.d <- "{SCRIPTDIR}"
conf.f <- "{config_file}"
dds.f <- "{input.dds}"
map.f <- "{input.map}"
dbs.f <- "{input.dbs}"
res.f <- "{output.res}"
res.xlsx <- "{output.xlsx}"
res.pca.f <- "{output.pca}"
## ------------------------------
## no wildcards beyond this point
## ------------------------------
require(DESeq2)
require(tmod)
require(tidyverse)
require(writexl)
config <- yaml::yaml.load_file(conf.f)
source(file.path(script.d, "tmod_functions.R"))
dbs <- readRDS(dbs.f)
db.map <- readRDS(map.f)
dds <- readRDS(dds.f)
rl <- assay(rlog(dds))
nullvar <- apply(rl, 1, var) < .Machine$double.eps
rl <- rl[ !nullvar, ]
genes <- rownames(rl)
if(is.null(genes)) stop("can't get primary IDs from DESeq2 object!")
pca <- prcomp(t(rl), scale.=TRUE)
saveRDS(pca, file=res.pca.f)
ncomp <- min(4, ncol(pca$x))
res <- lapply(dbs, function(db) {{
mapping.id <- db.map$dbs[[ db$name ]]
mapping <- db.map$maps[[ mapping.id ]]
g.id <- setNames(mapping[genes], genes)
ret <- lapply(1:ncomp, function(i) {{
glists <- list(
up=g.id[order(pca$rotation[,i])],
down=g.id[order(-pca$rotation[,i])],
abs=g.id[order(-abs(pca$rotation[,i]))])
lapply(glists, tmodCERNOtest, mset=db$dbobj)
}})
names(ret) <- paste0("PC.", 1:ncomp)
ret
}})
saveRDS(res, file=res.f)
## shorten results for the human readable XLSX file
## filter the results
res.short <- lapply(res, function(x) lapply(x, function(y) lapply(y, reformat_res, pval.thr=.05, auc.thr=.55)))
## res.short still has two levels, one for the databases, another one
## for sorting keys, so we need to unlist – one level only
res.short <- unlist(unlist(res.short, recursive=FALSE), recursive=FALSE)
write_xlsx(res.short, path=res.xlsx)