-
Notifications
You must be signed in to change notification settings - Fork 66
/
pipeline_timeseries.py
1593 lines (1309 loc) · 51.7 KB
/
pipeline_timeseries.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
#
# MRC FGU Computational Genomics Group
#
# $Id: pipeline_snps.py 2870 2010-03-03 10:20:29Z andreas $
#
# Copyright (C) 2009 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
###############################################################################
"""
==============================
pipeline_timeseries.py
================================
:Author: Mike Morgan
:Release: $Id$
:Date: |today|
:Tags: Python
A pipeline for analysing RNAseq timeseries gene expression data
Overview
========
A pipeline to perform time-dependent differential expression and
hierarchical clustering of timeseries RNA-seq data.
Input files are bam files and reference transcriptome
GTF(s). This pipeline generates, via a replicate resampling
iterative clustering approach or direct computation on sample replicates,
clusters of genes using a consensus clustering. Consensus clustering metrics
are also produced. Cluster eigengenes are derived as well
as loading plots for each gene/cluster.
Usage
=====
See :ref:`PipelineSettingUp` and :ref:`PipelineRunning` on general
information how to use CGAT pipelines.
targets are:
diffExpression - perform time-point and condition differential expression
analysis
clustering - perform hierarchical clustering on time series, per condition
full - perform both differential expression and clustering analysis
Configuration
-------------
The pipeline requires a configured :file:`pipeline.ini` file.
The sphinxreport report requires a :file:`conf.py` and
:file:`sphinxreport.ini` file (see :ref:`PipelineReporting`). To start
with, use the files supplied with the Example_ data.
Input
-----
Input are *.bam files in the format:
sample-time-replicate.bam
and a gtf/gff file of transcripts/genes/features over which to
count an analyse.
Optional inputs
+++++++++++++++
Requirements
------------
The pipeline requires the results from
:doc:`pipeline_annotations`. Set the configuration variable
:py:data:`annotations_database` and :py:data:`annotations_dir`.
On top of the default CGAT setup, the pipeline requires the following
software to be in the path:
+--------------+-----------+---------------------------+
|*Program* |*Version* |*Purpose* |
+--------------+-----------+---------------------------+
|featureCounts | |count mapped reads over |
| | |target gene models |
+--------------+-----------+---------------------------+
|R | 2.15/3.0 |PCA and data transformation|
+--------------+-----------+---------------------------+
|featureCounts | |read counting over genes |
+--------------+-----------+---------------------------+
Pipeline output
===============
The major output are a set of file with gene:cluster assignments and
clustering metrics
Requirements:
* featurecounts >= 1.4.6
* deseq
* deseq2
* masigpro
* wgcna
* rcolorbrewer
* ggplot2
* gplots
* reshape2
* venndiagram
* dtw
* flashclust
Glossary
========
.. glossary::
Code
====
"""
from ruffus import *
import sys
import glob
import gzip
import os
import itertools
import re
import math
import types
import collections
import time
import optparse
import shutil
import sqlite3
import random
import itertools
import tempfile
import numpy as np
import pandas as pd
import pandas.rpy.common as com
from pandas.io import sql
import rpy2.rinterface as rinterface
from rpy2.robjects import pandas2ri
from rpy2.robjects import r as R
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
import CGAT.Experiment as E
import CGAT.IOTools as IOTools
import CGAT.Database as Database
import CGAT.GTF as GTF
import CGATPipelines.PipelineTimeseries as PipelineTimeseries
import CGATPipelines.PipelineTracks as PipelineTracks
###################################################
###################################################
###################################################
# Pipeline configuration
###################################################
# load options from the config file
import CGAT.Pipeline as P
P.getParameters(
["%s/pipeline.ini" % os.path.splitext(__file__)[0],
"../pipeline.ini",
"pipeline.ini"])
PARAMS = P.PARAMS
###################################################################
###################################################################
# Helper functions mapping tracks to conditions, etc
###################################################################
# sample = PipelineTracks.AutoSample
# assign tracks
GENESETS = PipelineTracks.Tracks(PipelineTracks.Sample).loadFromDirectory(
glob.glob("*.gtf.gz"),
"(\S+).gtf.gz")
TRACKS3 = PipelineTracks.Tracks(PipelineTracks.Sample3)
TRACKS = TRACKS3.loadFromDirectory(glob.glob("*.bam"), "(\S+).bam")
REPLICATE = PipelineTracks.Aggregate(TRACKS, labels=("replicate", ))
TIME = PipelineTracks.Aggregate(TRACKS, labels=("condition", "tissue"))
###################################################################
###################################################################
###################################################################
def connect():
'''connect to database.
Use this method to connect to additional databases.
Returns a database connection.
'''
dbh = sqlite3.connect(PARAMS["database"])
statement = '''ATTACH DATABASE '%s' as annotations''' % (
PARAMS["annotations_database"])
cc = dbh.cursor()
cc.execute(statement)
cc.close()
return dbh
###################################################################
###################################################################
###################################################################
@follows(connect, mkdir("plots.dir"))
@transform("reference.gtf.gz",
suffix("reference.gtf.gz"),
"refcoding.gtf.gz")
def buildCodingGeneSet(infile, outfile):
'''build a gene set with only protein coding transcripts.
Genes are selected via their gene biotype in the GTF file.
Note that this set will contain all transcripts of protein
coding genes, including processed transcripts.
This set includes UTR and CDS.
'''
statement = '''
zcat %(infile)s | awk '$2 == "protein_coding"' | gzip > %(outfile)s
'''
P.run()
###################################################################
###################################################################
###################################################################
@follows(mkdir("feature_counts.dir"))
@files([(("%s.bam" % x.asFile(), "%s.gtf.gz" % y.asFile()),
("feature_counts.dir/%s_vs_%s.tsv.gz" % (x.asFile(), y.asFile())))
for x, y in itertools.product(TRACKS, GENESETS)])
def buildFeatureCounts(infiles, outfile):
'''counts reads falling into "features", which by default are genes.
A read overlaps if at least one bp overlaps.
Pairs and strandedness can be used to resolve reads falling into
more than one feature. Reads that cannot be resolved to a single
feature are ignored.
'''
infile, annotations = infiles
# featureCounts cannot handle gzipped in or out files
outfile = P.snip(outfile, ".gz")
annotations_tmp = P.getTempFilename()
# -p -B specifies count fragments rather than reads, and both
# reads must map to the feature
if PARAMS['featurecounts_paired'] == "1":
paired = "-p -B"
else:
paired = ""
job_options = "-pe dedicated %i" % PARAMS['featurecounts_threads']
statement = '''
zcat %(annotations)s > %(annotations_tmp)s;
checkpoint;
featureCounts %(featurecounts_options)s
-T %(featurecounts_threads)s
-s %(featurecounts_strand)s
-b
-a %(annotations_tmp)s
-o %(outfile)s
%(infile)s
> %(outfile)s.log;
checkpoint;
gzip %(outfile)s;
checkpoint;
rm %(annotations_tmp)s '''
P.run()
###################################################################
###################################################################
###################################################################
@collate(buildFeatureCounts,
regex("feature_counts.dir/(.+)-(.+)-(.+)_vs_(.+).tsv.gz"),
r"feature_counts.dir/\1-\4-feature_counts.tsv.gz")
def aggregateFeatureCounts(infiles, outfile):
''' build a matrix of counts with genes and tracks dimensions.
'''
# Use column 7 as counts. This is a possible source of bugs, the
# column position has changed before.
infiles = " ".join(infiles)
statement = '''
python %(scriptsdir)s/combine_tables.py
--columns=1
--take=7
--use-file-prefix
--regex-filename='(.+)_vs.+.tsv.gz'
--log=%(outfile)s.log
%(infiles)s
| sed 's/Geneid/gene_id/'
| sed 's/\-/\./g'
| tee %(outfile)s.table.tsv
| gzip > %(outfile)s '''
P.run()
###################################################################
###################################################################
###################################################################
@transform(aggregateFeatureCounts,
suffix(".tsv.gz"),
".load")
def loadFeatureCounts(infile, outfile):
P.load(infile, outfile, "--add-index=gene_id")
###################################################################
###################################################################
###################################################################
@follows(mkdir("combined_analysis.dir"), aggregateFeatureCounts)
@collate(aggregateFeatureCounts,
regex("feature_counts.dir/(.+)-(.+)-feature_counts.tsv.gz"),
r"combined_analysis.dir/\2-combined.tsv.gz")
def buildCombinedExpression(infiles, outfile):
'''
aggregate together all of the datasets for a combined
all-vs-all analysis
'''
infiles = " ".join(infiles)
statement = '''
python %(scriptsdir)s/combine_tables.py
--columns=1
--log=%(outfile)s.log
%(infiles)s
| sed 's/Geneid/gene_id/'
| sed 's/\-/\./g'
| tee %(outfile)s.table.tsv
| gzip > %(outfile)s
'''
P.run()
###################################################################
###################################################################
###################################################################
@transform(buildCombinedExpression,
suffix("combined.tsv.gz"),
"combined.load")
def loadCombinedExpression(infile, outfile):
P.load(infile, outfile)
###################################################################
###################################################################
###################################################################
@follows(mkdir("deseq.dir"), loadFeatureCounts)
@transform(aggregateFeatureCounts,
regex(r"feature_counts.dir/(.+)-(.+)-feature_counts.tsv.gz"),
r"deseq.dir/\1-\2-vst.tsv")
def DESeqNormalize(infile, outfile):
''' Use DESeq normalization and variance
stabilizing transformation on all data.
Use `blind` dispersion method and `fit-only`
sharingMode.
'''
time_agg = TIME.__dict__['track2groups'].keys()
time_points = [int(str(x).split("-")[1]) for x in time_agg]
time_points = set(time_points)
time_points = list(time_points)
time_points.sort()
time_points = [str(x) for x in time_points]
rep_agg = REPLICATE.__dict__['track2groups'].keys()
replicates = [str(x).split("-")[2] for x in rep_agg]
time_points = ",".join(time_points)
replicates = ",".join(replicates)
statement = '''
python %(scriptsdir)s/expression2expression.py
--task=deseq
--log=%(outfile)s.log
--replicates=%(replicates)s
--time=%(time_points)s
%(infile)s
> %(outfile)s '''
P.run()
###################################################################
###################################################################
###################################################################
@transform(DESeqNormalize,
suffix("-vst.tsv"),
"-vst.load")
def loadDESeqNormalize(infile, outfile):
P.load(infile, outfile, transpose=True)
##################################################################
###################################################################
###################################################################
if len([PARAMS['refs']]) > 1:
@follows(buildCombinedExpression)
@collate(buildCombinedExpression,
regex(r"combined_analysis.dir/(.+)-combined.tsv.gz"),
r"combined_analysis.dir/merged-combined.tsv.gz")
def mergeExpressionTables(infile, outfile):
'''
Merge refcoding and lncRNA count tables
'''
file1 = infile[0]
file2 = infile[1]
tmpfile = P.getTempFilename(shared=True)
df1 = pd.read_table(file1,
sep="\t",
index_col=0,
header=0,
compression="gzip")
df2 = pd.read_table(file2,
sep="\t",
index_col=0,
header=0,
compression="gzip")
out_frame = df1.append(df2)
out_frame.to_csv(tmpfile, sep="\t")
statement = '''cat %(tmpfile)s | gzip > %(outfile)s; rm -rf %(tmpfile)s'''
P.run()
@follows(aggregateFeatureCounts)
@collate(aggregateFeatureCounts,
regex(r"feature_counts.dir/(.+)-(.+)-feature_counts.tsv.gz"),
r"combined_analysis.dir/\1-merged.tsv.gz")
def mergeSingleExpressionTables(infile, outfile):
'''
Merge refcoding and lncRNA count tables from a single condition
if there are separate input reference gtfs.
'''
file1 = infile[0]
file2 = infile[1]
tmpfile = P.getTempFilename(shared=True)
df1 = pd.read_table(file1,
sep="\t",
index_col=0,
header=0,
compression="gzip")
df2 = pd.read_table(file2,
sep="\t",
index_col=0,
header=0,
compression="gzip")
out_frame = df1.append(df2)
out_frame.to_csv(tmpfile, sep="\t")
statement = '''cat %(tmpfile)s | gzip > %(outfile)s; rm -rf %(tmpfile)s'''
P.run()
else:
@follows(buildCombinedExpression)
@collate(buildCombinedExpression,
regex(r"combined_analysis.dir/(.+)-combined.tsv.gz"),
r"combined_analysis.dir/merged-combined.tsv.gz")
def mergeExpressionTables(infile, outfile):
'''
Only a single reference gtf, copy combined expression
table
'''
infile = infile[0]
statement = '''zcat %(infile)s | gzip > %(outfile)s'''
P.run()
@follows(aggregateFeatureCounts)
@transform(aggregateFeatureCounts,
regex("feature_counts.dir/(.+)-(.+)-feature_counts.tsv.gz"),
r"combined_analysis.dir/\1-merged.tsv.gz")
def mergeSingleExpressionTables(infile, outfile):
'''
Only a single reference gtf, copy expression table, no need to merge
'''
statement = ''' zcat %(infile)s | gzip > %(outfile)s'''
P.run()
##################################################################
###################################################################
###################################################################
@follows(loadCombinedExpression,
mergeExpressionTables,
mkdir("diff_condition.dir"))
@transform([buildCombinedExpression, mergeExpressionTables],
suffix("combined.tsv.gz"),
"condition-diff.tsv.gz")
def conditionDiffExpression(infile, outfile):
'''
Call DEGs showing statistically significantly
different expression based on interaction terms between condition
and time point. Uses DESeq2.
'''
statement = '''
zcat %(infile)s |
python %(scriptsdir)s/timeseries2diffgenes.py
--log=%(outfile)s.log
--method=condition
--alpha=%(deseq_alpha)s
--results-directory=diff_condition.dir
'''
P.run()
P.touch(outfile)
##################################################################
###################################################################
###################################################################
@follows(conditionDiffExpression)
@transform("diff_condition.dir/*.tsv",
regex(r"diff_condition.dir/(.+).tsv"),
r"diff_condition.dir/\1.load")
def loadConditionDiffExpression(infile, outfile):
P.load(infile, outfile)
##################################################################
###################################################################
###################################################################
@follows(mergeSingleExpressionTables,
mkdir("diff_timepoints.dir"))
@transform("combined_analysis.dir/*-merged.tsv.gz",
suffix("merged.tsv.gz"),
"diff-time.tsv.gz")
def timePointDiffExpression(infile, outfile):
'''
Within each condition test for differentially expressed
genes against the baseline time point. Uses DESeq2.
'''
statement = '''
python %(scriptsdir)s/timeseries2diffgenes.py
--log=%(outfile)s.log
--method=timepoint
--alpha=%(deseq_alpha)s
--results-directory=diff_timepoints.dir
%(infile)s
'''
P.run()
P.touch(outfile)
##################################################################
###################################################################
###################################################################
@follows(timePointDiffExpression)
@transform("diff_timepoints.dir/*.tsv",
regex(r"diff_timepoints.dir/(.+).tsv"),
r"diff_timepoints.dir/\1.load")
def loadTimePointDiffExpression(infile, outfile):
P.load(infile, outfile)
##################################################################
###################################################################
###################################################################
@follows(loadConditionDiffExpression)
@collate(r"diff_condition.dir/*.tsv",
regex(r"diff_condition.dir/(.+).(.+)_(.+).tsv"),
r"images.dir/\1-venn.png")
def drawConditionVennDiagram(infiles, outfile):
'''
Generates a Venn Diagram for the overlap of differentially
expressed genes and lncRNAs for up to the first 5 time points
for the time:condition interaction analysis.
'''
# select up to 5 time points to plot
select = []
time_points = PARAMS['venn_timepoints'].split(",")
if len(infiles) >= len(time_points):
for te in time_points:
fle = [x for x in infiles if re.search(r"0_%s" % te, x)]
if fle:
select.append(fle[0])
else:
pass
else:
select = infiles
select = ",".join(select)
statement = '''
python %(scriptsdir)s/diffgene2venn.py
--alpha=%(deseq_alpha)s
--log=condition-venn.log
--file-list=%(select)s
--output-directory=images.dir
'''
P.run()
##################################################################
###################################################################
###################################################################
@follows(loadConditionDiffExpression)
@collate(r"diff_timepoints.dir/*.tsv",
regex(r"diff_timepoints.dir/(.+)_(.+)_(.+)-time.tsv"),
r"images.dir/\1-time-venn.png")
def drawTimeVennDiagram(infiles, outfile):
'''
Generates a Venn Diagram for the overlap of differentially
expressed genes and lncRNAs for up to the first 5 time points
from the time point differential analysis.
'''
# select up to 5 time points to plot
select = []
time_points = PARAMS['venn_timepoints'].split(",")
if len(infiles) >= len(time_points):
for te in time_points:
fle = [x for x in infiles if re.search(r"%s-time" % te, x)]
if fle:
select.append(fle[0])
else:
pass
else:
select = infiles
select = ",".join(select)
statement = '''
python %(scriptsdir)s/diffgene2venn.py
--alpha=%(deseq_alpha)s
--log=condition-venn.log
--file-list=%(select)s
--output-directory=images.dir
'''
P.run()
##################################################################
###################################################################
###################################################################
@follows(loadDESeqNormalize)
@transform(DESeqNormalize,
regex("deseq.dir/(.+)-(.+)-vst.tsv"),
r"deseq.dir/\1-\2-filtered-vst.tsv")
def sumCovarFilter(infile, outfile):
'''
Filter gene list based on the distribution of the
sums of the covariance of each gene. This is highly
recommended to reduce the total number of genes used
in the dynamic time warping clustering to reduce the
computational time. The threshold is placed at the
intersection of the expected and observed value
for the given quantile.
'''
time_agg = TIME.__dict__['track2groups'].keys()
time_points = [int(str(x).split("-")[1]) for x in time_agg]
time_points = set(time_points)
time_points = list(time_points)
time_points.sort()
time_points = [str(x) for x in time_points]
rep_agg = REPLICATE.__dict__['track2groups'].keys()
replicates = [str(x).split("-")[2] for x in rep_agg]
time_points = ",".join(time_points)
replicates = ",".join(replicates)
statement = '''
python %(scriptsdir)s/expression2expression.py
--log=%(outfile)s.log
--task=sumcovar
--time=%(time_points)s
--replicates=%(replicates)s
--quantile=%(filtering_quantile)s
%(infile)s
> %(outfile)s'''
P.run()
###################################################################
###################################################################
###################################################################
@transform(sumCovarFilter,
suffix("-filtered-vst.tsv"),
"-filtered-vst.load")
def loadFilteredData(infile, outfile):
P.load(infile, outfile)
###################################################################
###################################################################
###################################################################
ANALYSIS = PARAMS['resampling_analysis_type']
if ANALYSIS == 'replicates':
@follows(sumCovarFilter,
mkdir("clustering.dir"))
@transform(sumCovarFilter,
regex("deseq.dir/(.+)-(.+)-filtered-vst.tsv"),
r"clustering.dir/\1-\2-replicates.tsv")
def genReplicateData(infile, outfile):
'''
Split each replicate into a separate file for clustering
within each replicate. Relies on each replicate being the
same across the whole time series.
'''
outdir = outfile.split("/")[0]
PipelineTimeseries.splitReplicates(infile=infile,
axis="column",
group_var="replicates",
outdir=outdir)
P.touch(outfile)
###################################################################
###################################################################
###################################################################
if PARAMS['resampling_parallel']:
@follows(genReplicateData,
mkdir("parallel_files.dir"))
@subdivide("clustering.dir/*-expression.tsv",
regex("clustering.dir/(.+)-(.+)-(.+)-expression.tsv"),
r"parallel_files.dir/\1-\2-\3-split.sentinel")
def splitFiles(infile, outfile):
'''
Arbitrarily split files into chunks for parallelisation
'''
PipelineTimeseries.splitFiles(infile=infile,
nchunks=PARAMS['resampling_chunks'],
out_dir="parallel_files.dir")
P.touch(outfile)
###################################################################
###################################################################
###################################################################
@follows(splitFiles)
@transform("parallel_files.dir/*-split.tsv",
regex("parallel_files.dir/(.+)-(.+)-(.+)-(.+)-split.tsv"),
add_inputs(r"clustering.dir/\1-\2-\3-expression.tsv"),
r"parallel_files.dir/\1-\2-\3-\4-distance.tsv")
def splitDistance(infiles, outfile):
'''
Calculate distances on split files
'''
if PARAMS['clustering_lag']:
clustering_options = " --lag=%s " % PARAMS['clustering_lag']
else:
clustering_options = " "
if PARAMS['clustering_k']:
clustering_options = " --k=%s " % PARAMS['clustering_k']
else:
clustering_options = " "
infile = infiles[0]
expression_file = infiles[1]
statement = '''
python %(scriptsdir)s/expression2distance.py
--log=%(outfile)s.log
--parallel
--distance-metric=%(clustering_metric)s
--expression-file=%(expression_file)s
%(clustering_options)s
--out=%(outfile)s
%(infile)s
'''
P.run()
###################################################################
###################################################################
###################################################################
@follows(splitDistance)
@collate(splitDistance,
regex("parallel_files.dir/(.+)-(.+)-(.+)-(.+)-distance.tsv"),
r"clustering.dir/\1-\2-\3-distance.tsv")
def distanceCalculation(infiles, outfile):
'''
Merge split files in the correct order, defined by their file
names.
'''
infiles = ",".join(infiles)
job_options = "-l mem_free=2G"
statement = '''
python /ifs/devel/projects/proj036/pipeline_timeseries/src/scripts/distance2merge.py
--log=%(outfile)s.log
--outfile=%(outfile)s
%(infiles)s
'''
P.run()
###################################################################
###################################################################
###################################################################
else:
@follows(genReplicateData)
@transform("clustering.dir/*-expression.tsv",
regex("clustering.dir/(.+)-(.+)-(.+)-expression.tsv"),
r"clustering.dir/\1-\2-\3-distance.tsv")
def distanceCalculation(infile, outfile):
'''
Calls the dtw script for each resampled file.
Calculates the dynamic time-warping distance for each
pairwise gene combination.
'''
if PARAMS['clustering_lag']:
clustering_options = " --lag=%s " % PARAMS['clustering_lag']
else:
clustering_options = " "
if PARAMS['clustering_k']:
clustering_options = " --k=%s " % PARAMS['clustering_k']
else:
clustering_options = " "
statement = '''
python %(scriptsdir)/expression2distance.py
--distance-metric=%(clustering_metric)s
--log=%(outfile)s.log
%(clustering_options)s
--out=%(outfile)s
%(infile)s
'''
P.run()
###################################################################
###################################################################
###################################################################
@follows(mkdir("tmp.dir/"),
distanceCalculation)
@transform(distanceCalculation,
suffix("-distance.tsv"),
"-clusters.tsv")
def clusterCut(infile, outfile):
'''
Use dynamic tree cutting to derive clusters for each
resampled distance matrix
'''
condition = (str(infile).split("-")[0]).lstrip("clustering.dir/")
gtf_source = str(infile).split("-")[1]
resample_prefix = str(infile).rstrip("-distance.tsv")
expression_file = "deseq.dir/%s-%s-expression.tsv" % (condition,
gtf_source)
wgcna_out = "clustering.dir/WGCNA.out"
cluster_file = "%s-clusterlabels.tsv" % (resample_prefix)
job_options = "-l mem_free=7.5G"
if PARAMS['clustering_deepsplit']:
options = " --split-clusters "
else:
options = " "
statement = '''
python %(scriptsdir)s/distance2clusters.py
--log=%(outfile)s.log
--task=cluster
--cluster-algorithm=%(clustering_algorithm)s
--cluster-file=%(cluster_file)s
--expression-file=%(expression_file)s
%(options)s
%(infile)s
> %(outfile)s'''
P.run()
###################################################################
###################################################################
##################################################################
@follows(clusterCut,
mkdir("consensus_cluster.dir"))
@collate(distanceCalculation,
regex("clustering.dir/(.+)-(.+)-(.+)-distance.tsv"),
r"consensus_cluster.dir/\1-\2-cocluster.tsv")
def clusterAgree(infiles, outfile):
'''
Calculate average distance matrix over replicates
'''
infiles = ",".join(infiles)
statement = '''
python %(scriptsdir)s/distance2clusters.py
--task=clustagree
--method=replicate
--log=%(outfile)s.log
%(infiles)s
> %(outfile)s
'''
P.run()
###################################################################
###################################################################
###################################################################
@follows(mkdir("plots.dir"))
@transform(clusterAgree,
suffix("-cocluster.tsv"),
"-consensus.tsv")
def consensusClustering(infile, outfile):
'''
hierachical clustering based on clustering correlation
across all resampled data sets
'''
if PARAMS['clustering_deepsplit']:
options = " --split-clusters "
else:
options = " "
statement = '''
python %(scriptsdir)s/distance2clusters.py
--log=%(outfile)s.log
--task=consensus-cluster
--cut-height=%(clustering_cut)s
--cluster-algorithm=%(clustering_consensus_algorithm)s
--cluster-size=%(clustering_min_size)s
%(options)s
%(infile)s
> %(outfile)s '''
P.run()
###################################################################
###################################################################
###################################################################
elif PARAMS["resampling_analysis_type"] == 'resample':
@follows(mkdir("clustering.dir"),
loadFilteredData)
@transform(sumCovarFilter,
regex("deseq.dir/(.+)-(.+)-filtered-vst.tsv"),
r"clustering.dir/\1-\2-resampled.tsv")
def genResampleData(infile, outfile):
'''
Resample the data n-times with replacement - generates
n flat files which are then propagated at later stages.
Files are generally small though.
'''