-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSnakefile
2916 lines (2623 loc) · 125 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
import csv
import os
import os.path
import rpy2.rinterface
import re
import shutil
import subprocess
import sys
import numpy as np
import pandas as pd
from atomicwrites import atomic_write, AtomicWriter
from math import log10, ceil
from itertools import product, count, chain
from subprocess import check_call, Popen, PIPE, CalledProcessError, list2cmdline
from rpy2 import robjects
from rpy2.robjects import r, pandas2ri
from rpy2.robjects import globalenv as r_env
from warnings import warn
from tempfile import TemporaryDirectory
from snakemake.io import expand
from snakemake.utils import min_version
min_version('3.7.1')
from snakemake.remote.FTP import RemoteProvider as FTPRemoteProvider
from snakemake.remote.HTTP import RemoteProvider as HTTPRemoteProvider
FTP = FTPRemoteProvider()
HTTP = HTTPRemoteProvider()
pandas2ri.activate()
rpy2.rinterface.set_writeconsole_warnerror(lambda x: sys.stderr.write(x))
# Commands to compress and decompress a variety of fastq compression
# methods
fastq_compression_cmds = {
'fq.gz': {
'compress': ['gzip', '-c'],
'decompress': ['gzip', '-d', '-c'],
},
'fq.bz2': {
'compress': ['bzip2', '-z', '-c'],
'decompress': ['bzip2', '-d', '-c'],
},
'fq.qp': {
'compress': ['quip', '-i', 'fastq', '-o', 'quip', '-c' ],
'decompress': ['quip', '-i', 'quip', '-o', 'fastq', '-c' ],
},
# i.e. no compression
'fq': {
'compress': ['cat'],
'decompress': ['cat'],
},
}
def Popen_pipeline(cmds, stdin=None, stdout=None, *args, **kwargs):
'''Popen a pipeline of several commands.
Returns a list with all the process objects returned by Popen.
Each command's stdout becomes the next command's stdin. The stdin
argument becomes the stdin of the first command, while the stdout
argument becomes the stdout of the last command. All other
arguments are passed to every invocation of Popen(), so ensure
that they make sense in that context.
'''
cmds = list(cmds)
if len(cmds) == 0:
raise ValueError('Cannot run a pipeline with zero commands')
if len(cmds) == 1:
return [Popen(cmds[0], stdin=stdin, stdout=stdout, *args, **kwargs)]
else:
first_cmd = cmds[0]
last_cmd = cmds[-1]
middle_cmds = cmds[1:-1]
proclist = [Popen(first_cmd, stdin=stdin, stdout=PIPE, *args, **kwargs)]
for cmd in middle_cmds:
prev_cmd_stdout = proclist[-1].stdout
proclist.append(Popen(cmd, stdin=prev_cmd_stdout, stdout=PIPE, *args, **kwargs))
prev_cmd_stdout = proclist[-1].stdout
proclist.append(Popen(last_cmd, stdin=prev_cmd_stdout, stdout=stdout, *args, **kwargs))
return proclist
def wait_for_subprocs(proclist, expected_exitcodes=0, wait_for_all=True):
'''Wait for a list of subprocesses to exit.
If any subprocess returns an exit code that is not in
expected_exitcodes (default: only 0), a CalledProcessError is
raised (as if subprocess.check_call was run). Even if an exception
is raised, this function will still wait for all remaining
processes to finish unless wait_for_all is False.
'''
# Allow supplying a single number or a list of numbers
try:
0 in expected_exitcodes
except TypeError:
expected_exitcodes = [ expected_exitcodes ]
if wait_for_all:
for proc in proclist:
proc.wait()
for proc in proclist:
exitcode = proc.wait()
if exitcode not in expected_exitcodes:
raise CalledProcessError(exitcode, proc.args)
def read_R_dataframe(rdsfile):
'''Read an R data frame stored in an RDS file.
Returns the result as a Pandas DataFrame.
'''
readRDS = robjects.r('readRDS')
df = readRDS((robjects.StrVector([rdsfile])))
return(pandas2ri.ri2py(df))
# TODO: Does a function like this already exist in pandas?
def dfselect(dframe, what=None, where=None, **where_kwargs):
'''Filter DataFrame and select columns.
First, the DataFrame is filtered according to the 'where'
arguments. Each key (or keyword argument) in 'where' should be a
column name, and its value should be the allowed value or values
for that column. Rows will be selected if they match all the
requirements in 'where'. Each filter can also be a callable, which
should take a single value and return True for including that
value and False for excluding it.
Second, if 'what' is not None, it will be used to select one or
more columns. As normal, using a single string returns a Series
object, while using a list of strings returns a DataFrame with a
subset of columns selected.
'''
if where is None:
where = dict()
where.update(where_kwargs)
if where:
selected = pd.Series(True, index=dframe.index)
for (colname, allowed_vals) in where.items():
if callable(allowed_vals):
allow_func = allowed_vals
allowed_rows = [allow_func(x) for x in dframe[colname]]
else:
try:
allowed_vals = pd.Series(allowed_vals)
except TypeError:
allowed_vals = pd.Series(list(allowed_vals))
allowed_rows = dframe[colname].isin(allowed_vals)
selected &= allowed_rows
dframe = dframe[selected]
if what is None:
return dframe
else:
return dframe[what]
def df_cartesian_product(*dfs):
'''Return the cartesian product of 2 or more DataFrames.
None of dfs should share a column name with any other, or else the
column names will have arbitrary suffixes.
'''
if len(dfs) == 0:
raise ValueError("Cannot generate empty Cartesian product")
elif len(dfs) == 1:
return dfs[0]
else:
all_colnames = list(chain.from_iterable(df.columns for df in dfs))
# Get an unused column name
merge_key = 'key_to_merge_on_'
while merge_key in all_colnames:
merge_key += 'xxxxx'
merged_df = dfs[0].copy()
merged_df[merge_key] = 1
for next_df in (df.copy() for df in dfs[1:]):
next_df[merge_key] = 1
merged_df = merged_df.merge(next_df, on=merge_key)
for i in merged_df:
if i.startswith(merge_key):
merged_df.drop(i, 1, inplace=True)
return merged_df
def recycled(it, length=None):
'''Recycle iterable to specified length.
Items are returned in round-robin order until the specified length
is reached. If length is None, the iterable is recycled
indefinitely.
Cannot handle infinite-length iterators as inputs, since it needs
to enumerate all the elements of an iterable in order to recycle
them.
'''
if length is None:
x = list(it)
while True:
yield from iter(x)
else:
need_recycling = True
try:
if len(it) >= length:
need_recycling = False
except TypeError:
pass
if need_recycling:
it = recycled(it)
i = 0
while i < length:
i += 1
yield next(it)
else:
yield from iter(it[:length])
raise StopIteration
def zip_recycled(*args, length=None):
'''Like zip(), but recycles all iterables to the specified length.
If length is None,
Cannot handle infinite-length iterators as inputs, since it needs
to enumerate all the elements of an iterable in order to recycle
them.
'''
return zip(*(recycled(arg, length) for arg in args))
def zip_longest_recycled(*args, warn_on_uneven=True):
'''Like itertools.zip_longest(), but recycles shorter iterables.
Unless kwarg warn_on_mismatch is set to False, a warning will be
raised if all the iterable lengths do not divide evenly into the
length of the longest iterable.
'''
args = [list(arg) for arg in args]
maxlen = max(map(len, args))
if warn_on_uneven:
if max(maxlen % len(arg) for arg in args) > 0:
warn("Longest iterable's length is not a multiple of shorter.")
return zip_recycled(*args, length=maxlen)
def list_salmon_output_files(outdirs, alignment=False):
file_list = [
'aux_info/bootstrap/bootstraps.gz',
'aux_info/bootstrap/names.tsv.gz',
'aux_info/eq_classes.txt',
'aux_info/exp3_seq.gz',
'aux_info/exp5_seq.gz',
'aux_info/expected_bias.gz',
'aux_info/fld.gz',
'aux_info/meta_info.json',
'aux_info/obs3_seq.gz',
'aux_info/obs5_seq.gz',
'aux_info/observed_bias.gz',
'aux_info/observed_bias_3p.gz',
'cmd_info.json',
'quant.genes.sf',
'quant.sf',
]
if alignment:
file_list += ['logs/salmon.log',]
else:
file_list += ['libParams/flenDist.txt', 'logs/salmon_quant.log',]
if isinstance(outdirs, str):
outdirs = [outdirs]
return [ os.path.join(od, f) for od in outdirs for f in file_list ]
def list_kallisto_output_files(outdir):
file_list = [
'abundance.h5', 'abundance.tsv', 'run_info.json',
]
return [ os.path.join(outdir, f) for f in file_list ]
def list_macs_callpeak_output_files(dirname):
file_list = [
'peaks.narrowPeak',
'peaks.xls',
'summits.bed',
# 'control_lambda.bdg',
# 'treat_pileup.bdg',
]
return [ os.path.join(dirname, fname) for fname in file_list ]
def read_narrowpeak(infile):
peaks = pd.DataFrame.from_csv(infile, header=None, sep='\t', index_col=None)
peaks.columns = ('chr', 'start', 'end', 'name', 'score', 'strand', 'signalValue', 'pValue', 'qValue', 'summit')
return peaks
def write_narrowpeak(peaks, outfile):
peaks.to_csv(outfile, sep='\t', header=False, index=False, quoting=csv.QUOTE_NONE)
def pick_top_peaks(infile, outfile, by='score', ascending=False, number=150000, *args, **kwargs):
'''Copy the top N peaks from infile to outfile.
Peaks are read from 'infile', sorted, and then the top 'number'
are written to 'outfile'. Peaks are read and written in narrowPeak
format. Arguments 'by', 'ascending', and any other arguments are
passed to pandas.DataFrame.sort_values to determine how to sort.
Reasonable values for 'by', include 'score', 'signalValue', and
'pValue'. Typically you want 'ascending=False' for all of these,
including 'pValue', which is typically on a negative log10 scale,
so higher values are more significant.
'''
peaks = read_narrowpeak(infile)
peaks.sort_values(by=by, axis=0, ascending=ascending, inplace=True, *args, **kwargs)
write_narrowpeak(peaks.head(number), outfile)
def call_R_external(f, *args, **kwargs):
arglist_string = r['paste'](r['deparse'](r['list'](*args, **kwargs), backtick=True, nlines=-1), collapse=" ")[0]
rcode = "do.call(%s, %s)" % (f, arglist_string)
check_call(['Rscript', '-e', rcode])
def dict_to_R_named_list(d):
return r['list'](**d)
rmd_default_formats = {
# The notebook format for html has additional bells & whistles
# that are useful even outside the context of interactive
# operation, so we use that format for html output.
'html': 'html_notebook',
'pdf': 'pdf_document',
}
def rmd_render(input, output_file, output_format=None, **kwargs):
if output_format is None:
if output_file is not None:
ext = os.path.splitext(output_file)[1][1:]
try:
output_format = rmd_default_formats[ext]
# If no specific output format is specified, just append
# "_document" and hope that works
except KeyError:
if ext == '':
raise ValueError("Cannot determine output format from file name.")
else:
output_format = ext + '_document'
# Output file will not be saved, so just pick something
# arbitrarily.
else:
output_format = 'html_document'
arg_converters = {
'params': dict_to_R_named_list,
'output_options': dict_to_R_named_list,
}
for (k, convfun) in arg_converters.items():
if k in kwargs:
kwargs[k] = convfun(kwargs[k])
with TemporaryDirectory() as tmpdir:
# The output name must not have a file extension because of
# https://github.com/rstudio/rmarkdown/issues/1180
tmp_output_file = os.path.join(tmpdir, "output_file")
call_R_external('rmarkdown::render', input=input, output_file=tmp_output_file, output_format=output_format, **kwargs)
if output_file is not None:
shutil.move(tmp_output_file, output_file)
def rmd_run_without_rendering(input, **kwargs):
'''Run the code in an Rmd file but don't produce a report.'''
rmd_render(input, output_file=None, output_format=None, **kwargs)
# Run a separate Snakemake workflow (if needed) to fetch the sample
# metadata, which must be avilable before evaluating the rules below.
# Without this two-step workflow, the below rules would involve quite
# complex use of multiple dynamic() inputs and outputs.
try:
rnaseq_samplemeta = read_R_dataframe('saved_data/samplemeta-RNASeq.RDS')
chipseq_samplemeta = read_R_dataframe('saved_data/samplemeta-ChIPSeq.RDS')
except Exception:
from processify import processify
from snakemake import snakemake
snakemake = processify(snakemake)
result = snakemake(
'pre.Snakefile',
targets=['saved_data/samplemeta-RNASeq.RDS', 'saved_data/samplemeta-ChIPSeq.RDS'],
lock=False,
quiet=True)
if not result:
raise Exception('Could not retrieve experiment metadata from GEO')
rnaseq_samplemeta = read_R_dataframe('saved_data/samplemeta-RNASeq.RDS')
chipseq_samplemeta = read_R_dataframe('saved_data/samplemeta-ChIPSeq.RDS')
rnaseq_samplemeta['time_point'] = rnaseq_samplemeta['days_after_activation'].apply(lambda x: 'Day{:.0f}'.format(x))
chipseq_samplemeta['time_point'] = chipseq_samplemeta['days_after_activation'].apply(lambda x: 'Day{:.0f}'.format(x))
promoter_radii = {
'H3K4me3': '1kbp',
'H3K4me2': '1kbp',
'H3K27me3': '2.5kbp',
'input': None,
}
chipseq_samplemeta['promoter_radius'] = chipseq_samplemeta['chip_antibody'].apply(lambda x: promoter_radii[x])
rnaseq_sample_libtypes = dict(zip(rnaseq_samplemeta['SRA_run'], rnaseq_samplemeta['libType']))
rnaseq_star_outdirs = [
'rnaseq_star_hg38.analysisSet_knownGene',
'rnaseq_star_hg38.analysisSet_ensembl.85',
]
rnaseq_hisat_outdir = 'rnaseq_hisat2_grch38_snp_tran'
aligned_rnaseq_star_bam_files = expand(
'aligned/{dirname}/{samp}/Aligned.sortedByCoord.out.bam',
dirname=rnaseq_star_outdirs, samp=rnaseq_samplemeta['SRA_run'])
aligned_rnaseq_hisat_bam_files = expand(
'aligned/{dirname}/{samp}/Aligned.bam',
dirname=rnaseq_hisat_outdir, samp=rnaseq_samplemeta['SRA_run'])
aligned_rnaseq_bam_files = aligned_rnaseq_star_bam_files + aligned_rnaseq_hisat_bam_files
aligned_rnaseq_bai_files = [ bam + '.bai' for bam in aligned_rnaseq_bam_files ]
chipseq_samplemeta_noinput = dfselect(chipseq_samplemeta, chip_antibody=lambda x: x != 'input')
promoter_radius_table = dfselect(chipseq_samplemeta_noinput, what=['chip_antibody', 'promoter_radius']).drop_duplicates()
def all_pairs(v, *, include_equal=False, include_reverse=False):
'''Return iterator over 2-tuples of input elements.
Tuples are yielded in arbitrary order. If 'include_equal' is True,
tuples with both elements the same will be allowed. If
'include_reverse' is True, tuples with the same elements in
opposite order (e.g. (1,2) and (2,1)) will both be yielded.
'''
try:
len(v)
except Exception:
v = list(v)
for i,j in product(range(len(v)), repeat=2):
if not include_equal and i == j:
continue
if not include_reverse and i > j:
continue
yield (v[i], v[j])
idr_sample_pairs = chipseq_samplemeta_noinput.\
groupby(['chip_antibody', 'cell_type', 'time_point']).\
apply(lambda x: pd.DataFrame.from_items(zip(count(), list(all_pairs(list(x['donor_id'])))),
orient='index', columns=['donorA', 'donorB'])).\
reset_index(level=3, drop=True).reset_index()
aligned_chipseq_input_bam_files = expand(
'aligned/chipseq_bowtie2_hg38.analysisSet/{SRA_run}/Aligned.bam',
SRA_run=list(chipseq_samplemeta['SRA_run'][chipseq_samplemeta['chip_antibody'] == 'input']))
aligned_chipseq_bam_files = expand(
'aligned/chipseq_bowtie2_hg38.analysisSet/{SRA_run}/Aligned.bam',
SRA_run=list(chipseq_samplemeta['SRA_run'][chipseq_samplemeta['chip_antibody'] != 'input']))
include: 'rulegraph.Snakefile'
include: 'tool_versions.py'
include: 'mem_requirements.py'
shell.executable('bash')
configfile: "snakemake_config.yaml"
subworkflow hg38_ref:
workdir: os.path.expanduser(config['hg38_path'])
targets = {
'rnaseq_counts': expand(
'saved_data/SummarizedExperiment_rnaseq_{aligner}_{genome}_{transcriptome}.RDS',
aligner = ['star', 'hisat2'],
genome = 'hg38.analysisSet',
transcriptome=['ensembl.85','knownGene']),
'rnaseq_quant': expand(
'saved_data/SummarizedExperiment_rnaseq_{quantifier}_{genome}_{transcriptome}.RDS',
quantifier=['kallisto','salmon','shoal'],
genome="hg38.analysisSet",
transcriptome=['ensembl.85','knownGene']),
'rnaseq_eda' : expand(
'reports/RNA-seq/{quant_method}_{genome}_{transcriptome}-exploration.html',
quant_method = ['star', 'hisat2', 'kallisto', 'salmon', 'shoal',],
genome = 'hg38.analysisSet',
transcriptome=['ensembl.85', 'knownGene']),
'rnaseq_compare' : 'reports/RNA-seq/rnaseq-compare.html',
'rnaseq_diffexp' : expand(
'reports/RNA-seq/{quant_method}_{genome}_{transcriptome}-diffexp.html',
quant_method = ['star', 'hisat2', 'kallisto', 'salmon', 'shoal',],
genome = 'hg38.analysisSet',
transcriptome=['ensembl.85', 'knownGene']),
'rnaseq_gst' : 'saved_data/CAMERA-results-RNA.RDS',
# TODO Properly parametrize for ChIP-seq as well
'rnaseq_cluster': expand(
'reports/RNA-seq/{quant_method}_{genome}_{transcriptome}-cluster.html',
quant_method = ['star', 'hisat2', 'kallisto', 'salmon', 'shoal',],
genome = 'hg38.analysisSet',
transcriptome=['ensembl.85', 'knownGene']),
'chipseq_eda' : expand(
'reports/ChIP-seq/{chip_antibody}-exploration.html',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
),
# TODO: Output tables
'chipseq_diffmod' : expand(
'reports/ChIP-seq/{chip_antibody}-diffmod.html',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
),
'chipseq_nvm_diminish': expand(
'reports/ChIP-seq/{chip_antibody}-NvM-diminish-analysis.html',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
),
'promoter_eda': expand(
'reports/ChIP-seq/{genome}_{transcriptome}_{chip_antibody}_{promoter_radius}-promoter-exploration.html',
zip_longest_recycled, genome=["hg38.analysisSet"],
**df_cartesian_product(pd.DataFrame({'transcriptome': ["knownGene", "ensembl.85"]}),
promoter_radius_table),
),
'promoter_diffmod': expand(
'reports/ChIP-seq/{genome}_{transcriptome}_{chip_antibody}_{promoter_radius}-promoter-diffmod.html',
zip_longest_recycled, genome=["hg38.analysisSet"],
**df_cartesian_product(pd.DataFrame({'transcriptome': ["knownGene", "ensembl.85"]}),
promoter_radius_table),
),
'promoter_gst': expand(
'saved_data/CAMERA-results-{chip_antibody}_{promoter_radius}-promoter.RDS',
zip_longest_recycled, **promoter_radius_table
),
'tsshood_eda': expand(
'reports/ChIP-seq/{genome}_{transcriptome}_{chip_antibody}_{neighborhood_radius}-tss-neighborhood_{window_size}-windows-exploration.html',
zip_longest_recycled, genome=["hg38.analysisSet"],
neighborhood_radius=["5kbp"], window_size=["500bp"],
**df_cartesian_product(pd.DataFrame({'transcriptome': ["knownGene", "ensembl.85"]}),
promoter_radius_table),
),
'macs_predictd' : 'results/macs_predictd/output.log',
'idr_peaks_epic' :expand(
'peak_calls/epic_{genome_build}/{chip_antibody}_condition.{condition}_donor.ALL/peaks_noBL_IDR.narrowPeak',
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
condition = list(chipseq_samplemeta_noinput\
.apply(lambda x: '%s.%s' % (x['cell_type'], x['time_point']), axis=1).unique()) + ['ALL']),
'idr_peaks_macs': expand(
'peak_calls/macs_{genome_build}/{chip_antibody}_condition.{condition}_donor.ALL/peaks_noBL_IDR.narrowPeak',
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
condition = list(chipseq_samplemeta_noinput\
.apply(lambda x: '%s.%s' % (x['cell_type'], x['time_point']), axis=1).unique()) + ['ALL']),
'idr_plots_one_cond': set(expand(
expand('plots/IDR/{{peak_caller}}_{{genome_build}}/{chip_antibody}/condition.{cell_type}.{time_point}/{donorA}vs{donorB}_idrplots.pdf',
zip_longest_recycled,
**dict(idr_sample_pairs.iteritems())),
peak_caller=['macs', 'epic'], genome_build='hg38.analysisSet')),
'idr_plots_all_cond': set(expand(
expand('plots/IDR/{{peak_caller}}_{{genome_build}}/{chip_antibody}/condition.ALL/{donorA}vs{donorB}_idrplots.pdf',
zip_longest_recycled,
**dict(idr_sample_pairs.iteritems())),
peak_caller=['macs', 'epic'], genome_build='hg38.analysisSet')),
'ccf_plots': expand('plots/csaw/CCF-plots{suffix}.pdf',
suffix=('', '-relative', '-noBL', '-relative-noBL')),
'site_profile_plot': 'plots/csaw/site-profile-plots.pdf',
'macs_peaks_allcond_alldonor': set(expand(
'peak_calls/macs_{genome_build}/{chip_antibody}_condition.ALL_donor.ALL/peaks.narrowPeak', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'])),
'macs_peaks_allcond_onedonor': set(expand(
'peak_calls/macs_{genome_build}/{chip_antibody}_condition.ALL_donor.{donor}/peaks.narrowPeak', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'],
donor=chipseq_samplemeta_noinput['donor_id'])),
'macs_peaks_onecond_alldonor': set(expand(
'peak_calls/macs_{genome_build}/{chip_antibody}_condition.{cell_type}.{time_point}_donor.ALL/peaks.narrowPeak', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'],
cell_type=chipseq_samplemeta_noinput['cell_type'],
time_point=chipseq_samplemeta_noinput['time_point'])),
'macs_peaks_onecond_onedonor': set(expand(
'peak_calls/macs_{genome_build}/{chip_antibody}_condition.{cell_type}.{time_point}_donor.{donor}/peaks.narrowPeak', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'],
cell_type=chipseq_samplemeta_noinput['cell_type'],
time_point=chipseq_samplemeta_noinput['time_point'],
donor=chipseq_samplemeta_noinput['donor_id'])),
'epic_peaks_allcond_alldonor': set(expand(
'peak_calls/epic_{genome_build}/{chip_antibody}_condition.ALL_donor.ALL/peaks.tsv', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'])),
'epic_peaks_allcond_onedonor': set(expand(
'peak_calls/epic_{genome_build}/{chip_antibody}_condition.ALL_donor.{donor}/peaks.tsv', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'],
donor=chipseq_samplemeta_noinput['donor_id'])),
'epic_peaks_onecond_alldonor': set(expand(
'peak_calls/epic_{genome_build}/{chip_antibody}_condition.{cell_type}.{time_point}_donor.ALL/peaks.tsv', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'],
cell_type=chipseq_samplemeta_noinput['cell_type'],
time_point=chipseq_samplemeta_noinput['time_point'])),
'epic_peaks_onecond_onedonor': set(expand(
'peak_calls/epic_{genome_build}/{chip_antibody}_condition.{cell_type}.{time_point}_donor.{donor}/peaks.tsv', zip_longest_recycled,
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'],
cell_type=chipseq_samplemeta_noinput['cell_type'],
time_point=chipseq_samplemeta_noinput['time_point'],
donor=chipseq_samplemeta_noinput['donor_id'])),
'all_idr_one_cond': set(expand(
expand('plots/IDR/{{peak_caller}}_{{genome_build}}/{chip_antibody}/condition.{cell_type}.{time_point}/{donorA}vs{donorB}_idrplots.pdf',
zip_longest_recycled,
**dict(idr_sample_pairs.iteritems())),
peak_caller=['macs', 'epic'], genome_build='hg38.analysisSet')),
'all_idr_all_cond': set(expand(
expand('plots/IDR/{{peak_caller}}_{{genome_build}}/{chip_antibody}/condition.ALL/{donorA}vs{donorB}_idrplots.pdf',
zip_longest_recycled,
**dict(idr_sample_pairs.iteritems())),
peak_caller=['macs', 'epic'], genome_build='hg38.analysisSet')),
'all_idr_filtered_peaks_epic': expand(
'peak_calls/epic_{genome_build}/{chip_antibody}_condition.{condition}_donor.ALL/peaks_noBL_IDR.narrowPeak',
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
condition = list(chipseq_samplemeta_noinput.apply(lambda x: '%s.%s' % (x['cell_type'], x['time_point']), axis=1).unique()) + ['ALL']),
'all_idr_filtered_peaks_macs': expand(
'peak_calls/macs_{genome_build}/{chip_antibody}_condition.{condition}_donor.ALL/peaks_noBL_IDR.narrowPeak',
genome_build='hg38.analysisSet',
chip_antibody=chipseq_samplemeta_noinput['chip_antibody'].unique(),
condition = list(chipseq_samplemeta_noinput.apply(lambda x: '%s.%s' % (x['cell_type'], x['time_point']), axis=1).unique()) + ['ALL']),
'mofa': [
'reports/promoter-mofa-analyze.html',
'reports/peak-mofa-analyze.html',
],
}
rule all:
'''This rule aggregates all the final outputs of the pipeline.'''
input:
targets['rnaseq_eda'],
targets['rnaseq_compare'],
targets['rnaseq_diffexp'],
targets['rnaseq_gst'],
targets['rnaseq_cluster'],
targets['macs_predictd'],
targets['chipseq_eda'],
targets['chipseq_diffmod'],
targets['chipseq_nvm_diminish'],
targets['promoter_eda'],
targets['promoter_diffmod'],
targets['promoter_gst'],
targets['tsshood_eda'],
targets['idr_peaks_epic'],
targets['idr_peaks_macs'],
targets['idr_plots_one_cond'],
targets['idr_plots_all_cond'],
targets['ccf_plots'],
targets['site_profile_plot'],
targets['mofa'],
'reports/lamere_2016_fig7.html',
rule all_rnaseq:
'''This rule aggregates all the final outputs of the pipeline.'''
input:
targets['rnaseq_eda'],
targets['rnaseq_compare'],
targets['rnaseq_diffexp'],
targets['rnaseq_gst'],
targets['rnaseq_cluster'],
rule all_chipseq:
'''This rule aggregates all the final outputs of the pipeline.'''
input:
targets['macs_predictd'],
targets['chipseq_eda'],
targets['chipseq_diffmod'],
targets['chipseq_nvm_diminish'],
targets['promoter_eda'],
targets['promoter_diffmod'],
targets['promoter_gst'],
targets['tsshood_eda'],
targets['idr_peaks_epic'],
targets['idr_peaks_macs'],
targets['idr_plots_one_cond'],
targets['idr_plots_all_cond'],
targets['ccf_plots'],
targets['site_profile_plot'],
'reports/lamere_2016_fig7.html',
rule all_rnaseq_counts:
input: targets['rnaseq_counts']
rule all_rnaseq_eda:
input:
targets['rnaseq_eda'],
targets['rnaseq_cluster'],
rule all_rnaseq_quant:
input: targets['rnaseq_quant']
rule all_rnaseq_diffexp:
input: targets['rnaseq_diffexp']
rule all_macs_callpeak:
input:
targets['macs_peaks_allcond_alldonor'],
targets['macs_peaks_allcond_onedonor'],
targets['macs_peaks_onecond_alldonor'],
targets['macs_peaks_onecond_onedonor'],
rule all_epic_callpeak:
input:
targets['epic_peaks_allcond_alldonor'],
targets['epic_peaks_allcond_onedonor'],
targets['epic_peaks_onecond_alldonor'],
targets['epic_peaks_onecond_onedonor'],
rule all_idr:
input:
targets['all_idr_one_cond'],
targets['all_idr_all_cond'],
rule all_idr_filtered_peaks:
input:
targets['all_idr_filtered_peaks_epic'],
targets['all_idr_filtered_peaks_macs'],
rule all_mofa:
input:
'reports/promoter-mofa-analyze.html',
'reports/peak-mofa-analyze.html',
rule fetch_sra_run:
'''Script to fetch the .sra file for an SRA run.
(An SRA run identifier starts with SRR.)
https://www.ncbi.nlm.nih.gov/sra
'''
output: 'sra_files/{sra_run,SRR.*}.sra'
version: SOFTWARE_VERSIONS['ASCP']
resources: concurrent_downloads=1
shell: 'scripts/get-sra-run-files.R {wildcards.sra_run:q}'
rule extract_fastq:
'''Extract FASTQ from SRA files.
Because the SRA files were originally generated from
coordinate-sorted BAM files, the reads in the SRA files are likely
also sorted. Hence, during extraction, the reads are also shuffled
deterministically (i.e. using a fixed seed). This ensures that
downstream tools expecting the reads in random order with respect
to their mapping position (e.g. Salmon) will be satisfied.
https://ncbi.github.io/sra-tools/
http://homes.cs.washington.edu/~dcjones/fastq-tools/
'''
input: 'sra_files/{sra_run}.sra'
output:
fqfile='fastq_files/{sra_run}.{fqext,fq(|\\.gz|\\.bz2|\\.qp)}',
temp_unshuffled=temp('fastq_files/{sra_run}_unshuffled.{fqext,fq(|\\.gz|\\.bz2|\\.qp)}_temp'),
temp_shuffled=temp('fastq_files/{sra_run}_shuffled.{fqext,fq(|\\.gz|\\.bz2|\\.qp)}_temp'),
version: (SOFTWARE_VERSIONS['SRATOOLKIT'], SOFTWARE_VERSIONS['FASTQ_TOOLS'])
resources: diskio=1
params:
compress_cmd = lambda wildcards: fastq_compression_cmds[wildcards.fqext]['compress']
shell:'''
echo "Dumping fastq for {wildcards.sra_run:q}..."
fastq-dump --stdout {input:q} | \
scripts/fill-in-empty-fastq-qual.py \
> {output.temp_unshuffled:q}
echo "Shuffling fastq for {wildcards.sra_run:q}..."
fastq-sort --random --seed=1986 {output.temp_unshuffled:q} > {output.temp_shuffled:q}
echo "Compressing fastq for {wildcards.sra_run:q}..."
{params.compress_cmd} < {output.temp_shuffled:q} > {output:q}
rm -f {output.temp_unshuffled:q} {output.temp_shuffled:q}
'''
rule align_rnaseq_with_star_single_end:
'''Align fastq file with STAR.
https://github.com/alexdobin/STAR
'''
input:
fastq='fastq_files/{samplename}.fq.gz',
index_sa=hg38_ref('STAR_index_{genome_build}_{transcriptome}/SA'),
transcriptome_gff=hg38_ref('{transcriptome}.gff3'),
output:
sam=temp('aligned/rnaseq_star_{genome_build}_{transcriptome}/{samplename}/Aligned.out.sam'),
sj='aligned/rnaseq_star_{genome_build}_{transcriptome}/{samplename}/SJ.out.tab',
logs=[ os.path.join('aligned/rnaseq_star_{genome_build}_{transcriptome}/{samplename}', fname)
for fname in ['Log.final.out', 'Log.out', 'Log.progress.out'] ],
params:
# Note: trailing slash is significant here
outdir='aligned/rnaseq_star_{genome_build}_{transcriptome}/{samplename}/',
index_genomedir=hg38_ref('STAR_index_{genome_build}_{transcriptome}'),
read_cmd=list2cmdline(fastq_compression_cmds['fq.gz']['decompress']),
version: SOFTWARE_VERSIONS['STAR']
threads: 8
resources: mem_gb=MEMORY_REQUIREMENTS_GB['star']
shell: '''
STAR \
--runThreadN {threads:q} \
--runMode alignReads \
--genomeDir {params.index_genomedir:q} \
--sjdbGTFfile {input.transcriptome_gff:q} \
--sjdbGTFfeatureExon CDS \
--sjdbGTFtagExonParentTranscript Parent \
--sjdbGTFtagExonParentGene gene_id \
--sjdbOverhang 100 \
--readFilesIn {input.fastq:q} \
--readFilesCommand {params.read_cmd:q} \
--outSAMattributes Standard \
--outSAMunmapped Within \
--outFileNamePrefix {params.outdir:q} \
--outSAMtype SAM
'''
rule convert_star_sam_to_bam:
input:
sam='aligned/rnaseq_star_{genome_build}_{transcriptome}/{samplename}/Aligned.out.sam',
output:
bam='aligned/rnaseq_star_{genome_build}_{transcriptome}/{samplename}/Aligned.sortedByCoord.out.bam',
shell: '''
picard-tools SortSam \
I={input.sam:q} O={output.bam:q} \
SORT_ORDER=coordinate VALIDATION_STRINGENCY=LENIENT
'''
rule align_rnaseq_with_hisat2_single_end:
'''Align fastq file with HISAT2.
https://ccb.jhu.edu/software/hisat2/index.shtml
'''
input: fastq='fastq_files/{samplename}.fq.gz',
index_f1=hg38_ref('HISAT2_index_grch38_snp_tran/index.1.ht2'),
transcriptome_gff=hg38_ref('knownGene.gff3'),
chrom_mapping=hg38_ref('chrom_mapping_GRCh38_ensembl2UCSC.txt'),
output: bam='aligned/rnaseq_hisat2_grch38_snp_tran/{samplename}/Aligned.bam',
log: 'aligned/rnaseq_hisat2_grch38_snp_tran/{samplename}/hisat2.log'
version: SOFTWARE_VERSIONS['HISAT2']
threads: 8
resources: mem_gb=MEMORY_REQUIREMENTS_GB['hisat2']
run:
index_basename = re.sub('\\.1\\.ht2', '', input.index_f1)
outdir = os.path.dirname(output.bam)
cmds = [
[
'hisat2',
'--threads', str(threads),
'-q', '--phred33',
'--very-sensitive',
'--dta-cufflinks',
'-x', index_basename,
'-U', input.fastq,
'-k', '20',
'--time',
],
[
# Convert to UCSC chromosome names
'scripts/bam-rename-chroms.py', input.chrom_mapping,
],
[
'picard-tools', 'SortSam', 'I=/dev/stdin', 'O=/dev/stdout',
'SORT_ORDER=coordinate', 'VALIDATION_STRINGENCY=LENIENT',
]
]
with atomic_write(output.bam, mode='wb', overwrite=True) as outfile, \
open(log[0], mode='wb') as logfile:
pipeline = Popen_pipeline(cmds, stdout=outfile, stderr=logfile)
wait_for_subprocs(pipeline)
# There are multiple index_bam rules each restricted to a subset of
# bam files in order to improve the rulegraph appearance.
rule index_bam_rnaseq:
'''Create .bai file for a bam file.
This rule is identical to index_bam_chipseq. They are only
separated in order to yield a less-confusing rule graph
visualization.
https://broadinstitute.github.io/picard/
'''
input: '{basename}.bam'
output: '{basename,aligned/rnaseq_.*}.bam.bai'
shell: '''
picard-tools BuildBamIndex I={input:q} O={output:q} \
VALIDATION_STRINGENCY=LENIENT
'''
rule index_bam_chipseq:
'''Create .bai file for a bam file.
This rule is identical to index_bam_rnaseq. They are only
separated in order to yield a less-confusing rule graph
visualization.
https://broadinstitute.github.io/picard/
'''
input: '{basename}.bam'
output: '{basename,aligned/chipseq_.*}.bam.bai'
shell: '''
picard-tools BuildBamIndex I={input:q} O={output:q} \
VALIDATION_STRINGENCY=LENIENT
'''
rule bam2bed:
'''Convert a bam file to bed using bedtools.
http://bedtools.readthedocs.io/en/latest/
'''
input: '{basename}.bam'
output: '{basename}_reads.bed'
version: SOFTWARE_VERSIONS['BEDTOOLS']
shell: '''
bedtools bamtobed -i {input:q} > {output:q}
'''
rule bam2bed_macs_filterdup:
'''Convert a bam file to bed, filtering duplicates.
This rule uses the 'macs2 filterdup' command to remove excess
duplicate reads while converting to bed format. Note that this
command does not necessarily remove all duplicates, only those in
excess of what would be expected by chance. The log file reports
the maximum number of duplicates allowed at each locus for a given
sample.
https://github.com/taoliu/MACS
'''
input: '{basename}.bam'
output: bed='{basename}_reads_macs_filterdup.bed',
log: '{basename}_macs_filterdup.log'
version: SOFTWARE_VERSIONS['MACS']
shell: '''
macs2 filterdup --ifile {input:q} --format BAM \
--gsize hs --keep-dup auto \
--ofile {output.bed:q} \
2>&1 | tee {log:q} 1>&2
'''
# The hisat2 documentation doesn't specify which version of Ensembl
# they used to build the prebuilt index. Hopefully it doesn't matter
# too much.
rule count_rnaseq_hisat2_ensembl:
'''Assign & count reads reads aligned to Ensembl genes by HISAT2.
https://bioconductor.org/packages/release/bioc/html/Rsubread.html
'''
input:
samplemeta='saved_data/samplemeta-RNASeq.RDS',
bam_files=expand(
'aligned/rnaseq_hisat2_grch38_snp_tran/{SRA_run}/Aligned.bam',
SRA_run=rnaseq_samplemeta['SRA_run']),
bai_files=expand(
'aligned/rnaseq_hisat2_grch38_snp_tran/{SRA_run}/Aligned.bam.bai',
SRA_run=rnaseq_samplemeta['SRA_run']),
txdb=hg38_ref('TxDb.Hsapiens.ensembl.hg38.v85.sqlite3'),
genemeta=hg38_ref('genemeta.ensembl.85.RDS')
output: sexp='saved_data/SummarizedExperiment_rnaseq_hisat2_hg38.analysisSet_ensembl.{release}.RDS'
params:
expected_bam_files=','.join(expand(
'aligned/rnaseq_hisat2_grch38_snp_tran/{SRA_run}/Aligned.bam',
SRA_run=rnaseq_samplemeta['SRA_run'])),
bam_file_pattern='aligned/rnaseq_hisat2_grch38_snp_tran/{{SAMPLE}}/Aligned.bam',
version: R_package_version('RSubread')
threads: len(rnaseq_samplemeta)
resources: mem_gb=MEMORY_REQUIREMENTS_GB['rnaseq_count']
shell: '''
scripts/rnaseq-count.R \
--samplemeta-file {input.samplemeta:q} \
--sample-id-column SRA_run \
--bam-file-pattern {params.bam_file_pattern:q} \
--output-file {output.sexp:q} \
--expected-bam-files {params.expected_bam_files:q} \
--threads {threads:q} \
--annotation-txdb {input.txdb:q} \
--additional-gene-info {input.genemeta:q}
'''
rule count_rnaseq_hisat2_knownGene:
'''Assign & count reads reads aligned to UCSC known genes by HISAT2.
https://bioconductor.org/packages/release/bioc/html/Rsubread.html
'''
input:
samplemeta='saved_data/samplemeta-RNASeq.RDS',
bam_files=expand(
'aligned/rnaseq_hisat2_grch38_snp_tran/{SRA_run}/Aligned.bam',
SRA_run=rnaseq_samplemeta['SRA_run']),
bai_files=expand(
'aligned/rnaseq_hisat2_grch38_snp_tran/{SRA_run}/Aligned.bam.bai',
SRA_run=rnaseq_samplemeta['SRA_run']),
genemeta=hg38_ref('genemeta.org.Hs.eg.db.RDS')
output: sexp='saved_data/SummarizedExperiment_rnaseq_hisat2_hg38.analysisSet_knownGene.RDS'
params: