-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipeline_iCLIP.py
1720 lines (1318 loc) · 58.4 KB
/
pipeline_iCLIP.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 iCLIP
===========================
:Author: Ian Sudbery
:Release: $Id$
:Date: |today|
:Tags: Python
A pipeline template.
Overview
========
Usage
=====
See :ref:`PipelineSettingUp` and :ref:`PipelineRunning` on general information how to use
CGAT pipelines.
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:`PipelineDocumenation`). To start with, use the files supplied
with the :ref:`Example` data.
Input
-----
The inputs should be a fastq file. The pipeline expects these to be raw fastq
files. That is that they contain the UMIs and the barcodes still on the 5' end
of the reads. It is expected that these will not be demultiplexed, although
demultiplex fastqs will also work.
In addition to the fastq files, a table of barcodes and samples is required as
sample_table.tsv.
It has four columns:
The first contains the barcode including UMI bases, marked as Xs.
The second contains the barcode sequence without the UMI bases.
The third contains the sample name you'd like to use
The fourth contains the fastq files that contain reads from this sample
e.g.
NNNGGTTNN GGTT FlipIn-FLAG-R1 hiseq7,hiseq8,miseq
Means that the sample FlipIn-FLAG-R1 should have reads in the fastq files
hiseq7, hiseq8 and miseq, is marked by the barcode GGTT and is embeded in the
UMI as NNNGGTTNN.
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* |
+--------------------+-------------------+------------------------------------------------+
|CGAPipelines | |Pipelining infrastructure, mapping pipeline |
+--------------------+-------------------+------------------------------------------------+
|CGAT | >=0.2.4 |Various |
+--------------------+-------------------+------------------------------------------------+
|Bowtie | >=1.1.2 |Filtering out PhiX reads |
+--------------------+-------------------+------------------------------------------------+
|FastQC | >=0.11.2 |Quality Control of demuxed reads |
+--------------------+-------------------+------------------------------------------------+
|STAR or HiSat | |Spliced mapping of reads |
+--------------------+-------------------+------------------------------------------------+
|bedtools | |Interval manipulation |
+--------------------+-------------------+------------------------------------------------+
|samtools | |Read manipulation |
+--------------------+-------------------+------------------------------------------------+
|subread | |FeatureCounts read quantifiacation |
+--------------------+-------------------+------------------------------------------------+
|MEME |>=4.9.1 |Motif finding |
+--------------------+-------------------+------------------------------------------------+
|DREME |>=4.9.1 |Motif finding |
+--------------------+-------------------+------------------------------------------------+
|bedGraphToBigWig | |Converstion of results to BigWig |
+--------------------+-------------------+------------------------------------------------+
|reaper | 13-100 |Used for demuxing and clipping reads |
+--------------------+-------------------+------------------------------------------------+
Pipeline output
===============
As well as the report, clusters, as BED files are in the clusters.dir directory,
and traces as bigWig files are in the bigwig directory. Both of these are exported
as a UCSU genome browser track hub in the export directory.
Example
=======
Example data and configuration is avaiable in example_data.tar.gz
Glossary
========
.. glossary::
Code
====
"""
from ruffus import *
from ruffus.combinatorics import *
import sys, glob, gzip, os, itertools, re, math, types, collections, time
import optparse, shutil
import sqlite3
import CGAT.Experiment as E
import CGAT.IOTools as IOTools
import CGAT.Database as Database
import CGATPipelines.PipelineMapping as PipelineMapping
import CGATPipelines.PipelineMotifs as PipelineMotifs
import CGATPipelines.PipelineRnaseq as PipelineRnaseq
import PipelineiCLIP
###################################################
###################################################
###################################################
## Pipeline configuration
###################################################
# load options from the config file
import CGATPipelines.Pipeline as P
P.getParameters(
["%s.ini" % __file__[:-len(".py")],
"../pipeline.ini",
"pipeline.ini" ] )
PARAMS = P.PARAMS
PARAMS_ANNOTATIONS = P.peekParameters( PARAMS["annotations_dir"],
"pipeline_annotations.py" )
PipelineMotifs.PARAMS = PARAMS
PipelineiCLIP.PARAMS = PARAMS
###################################################################
###################################################################
## Helper functions mapping tracks to conditions, etc
###################################################################
import CGATPipelines.PipelineTracks as PipelineTracks
# define some tracks if needed
TRACKS = PipelineTracks.Tracks(PipelineTracks.Sample3)
for line in IOTools.openFile("sample_table.tsv"):
track = line.split("\t")[2]
TRACKS.tracks.append(PipelineTracks.Sample3(filename=track))
###################################################################
###################################################################
###################################################################
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
###################################################################
###################################################################
###################################################################
## worker tasks
###################################################################
@transform("*.fastq.gz", regex("(.+).fastq.gz"),
add_inputs(os.path.join(PARAMS["bowtie_index_dir"],
PARAMS["phix_genome"]+".fa")),
r"\1.fastq.clean.gz")
def filterPhiX(infiles, outfile):
''' Use mapping to bowtie to remove any phiX mapping reads '''
infile, reffile = infiles
outfile = P.snip(outfile, ".gz")
bam_out = P.snip(infile, ".fastq.gz") + ".phix.bam"
job_threads = PARAMS["phix_bowtie_threads"]
job_memory = PARAMS["phix_bowtie_memory"]
options = PARAMS["phix_bowtie_options"] + " --un %s" % outfile
genome = PARAMS["phix_genome"]
bowtie_threads = PARAMS["phix_bowtie_threads"]
m = PipelineMapping.Bowtie(executable=PARAMS["phix_bowtie_exe"],
strip_sequence=False,
remove_non_unique=False,
tool_options=options)
statement = m.build((infile,), bam_out)
statement += "checkpoint; gzip %(outfile)s"
P.run()
@transform("sample_table.tsv", suffix(".tsv"), ".load")
def loadSampleInfo(infile, outfile):
P.load(infile, outfile,
options="--header-names=format,barcode,track,lanes -i barcode -i track")
###################################################################
@follows(mkdir("demux_fq"))
@transform(filterPhiX, regex("(.+).fastq.clean.gz"),
r"demux_fq/\1.fastq.umi_trimmed.gz")
def extractUMI(infile, outfile):
''' Remove UMI from the start of each read and add to the read
name to allow later deconvolving of PCR duplicates '''
statement=''' zcat %(infile)s
| python %(project_src)s/UMI-tools/extract_umi.py
--bc-pattern=%(reads_bc_pattern)s
-L %(outfile)s.log
| gzip > %(outfile)s '''
P.run()
###################################################################
@transform(extractUMI, suffix(".fastq.umi_trimmed.gz"),
"umi_stats.load")
def loadUMIStats(infile, outfile):
''' load stats on UMI usage from the extract_umi log into the
database '''
infile = infile + ".log"
P.load(infile, outfile, "-i sample -i barcode -i UMI")
###################################################################
@transform(filterPhiX,
regex("(.+).fastq.clean.gz"),
add_inputs("sample_table.tsv"),
r"\1_reaper_metadata.tsv")
def generateReaperMetaData(infile, outfile):
'''Take the sample_table and use it to generate a metadata table
for reaper in the correct format '''
adaptor_5prime = PARAMS["reads_5prime_adapt"]
adaptor_3prime = PARAMS["reads_3prime_adapt"]
outlines = []
lane = P.snip(infile[0], ".fastq.clean.gz")
for line in IOTools.openFile(infile[1]):
fields = line.split("\t")
barcode = fields[1]
lanes = fields[-1].strip().split(",")
if lane in lanes:
outlines.append([barcode, adaptor_3prime, adaptor_5prime, "-"])
header = ["barcode", "3p-ad", "tabu", "5p-si"]
IOTools.writeLines(outfile, outlines, header)
###################################################################
@follows(loadUMIStats, generateReaperMetaData)
@subdivide(extractUMI, regex(".+/(.+).fastq.umi_trimmed.gz"),
add_inputs(r"\1_reaper_metadata.tsv", "sample_table.tsv"),
r"demux_fq/*_\1.fastq*gz")
def demux_fastq(infiles, outfiles):
'''Demultiplex each fastq file into a seperate file for each
barcode/UMI combination'''
infile, meta, samples = infiles
track = re.match(".+/(.+).fastq.umi_trimmed.gz", infile).groups()[0]
statement = '''reaper -geom 5p-bc
-meta %(meta)s
-i <( zcat %(infile)s | sed 's/ /_/g')
--noqc
-basename demux_fq/%(track)s_
-clean-length 15 > %(track)s_reapear.log;
checkpoint;
rename _. _ demux_fq/*clean.gz;
'''
for line in IOTools.openFile(samples):
line = line.split("\t")
bc, name, lanes = line[1:]
name = name.strip()
if PARAMS["reads_paired"]:
ext = "fastq.1.gz"
else:
ext = "fastq.gz"
if track in lanes.strip().split(","):
statement += '''checkpoint;
mv demux_fq/%(track)s_%(bc)s.clean.gz
demux_fq/%(name)s_%(track)s.%(ext)s; ''' % locals()
P.run()
###################################################################
@active_if(PARAMS["reads_paired"]==1)
@transform("*.fastq.2.gz", suffix(".fastq.2.gz"),
".fastq.reaped.2.gz")
def reapRead2(infile,outfile):
track = P.snip(outfile,".fastq.reaped.2.gz")
statement = ''' reaper -geom no-bc
-3pa %(reads_3prime_adapt)s
-i %(infile)s
-basename %(track)s
--noqc
-clean-length 15 > %(track)s_pair_reaper.log;
checkpoint;
mv %(track)s.lane.clean.gz %(outfile)s '''
P.run()
###################################################################
@active_if(PARAMS["reads_paired"]==1)
@follows(mkdir("reconciled.dir"), reapRead2)
@transform(demux_fastq,
regex(".+/(.+)_(.+).fastq.1.gz"),
add_inputs(r"\2.fastq.2.gz"),
[r"reconciled.dir/\1_\2.fastq.2.gz",
r"reconciled.dir/\1_\2.fastq.1.gz"])
def reconsilePairs(infiles, outfiles):
''' Pull reads read 2 file that are present in each read 1 file '''
track = P.snip(os.path.basename(infiles[0]), ".fastq.1.gz")
infiles = " ".join(infiles)
job_options = "-l mem_free=1G"
statement = '''python %(scripts_dir)s/fastqs2fastqs.py
--method=reconcile
--id-pattern-1='(.+)_.+_[ATGC]+'
--output-filename-pattern=reconciled.dir/%(track)s.fastq.%%s.gz
%(infiles)s > reconciled.dir/%(track)s.log '''
P.run()
###################################################################
@follows(mkdir("fastqc"))
@transform(demux_fastq, regex(".+/(.+).fastq(.*)\.gz"),
r"fastqc/\1\2.fastqc")
def qcDemuxedReads(infile, outfile):
''' Run fastqc on the post demuxing and trimmed reads'''
m = PipelineMapping.FastQc(nogroup=False, outdir="fastqc")
statement = m.build((infile,),outfile)
exportdir = "fastqc"
P.run()
###################################################################
@transform(qcDemuxedReads, regex("(.+)/(.+)\.fastqc"),
inputs(r"\1/\2_fastqc/fastqc_data.txt"),
r"\1/\2_length_distribution.tsv")
def getLengthDistribution(infile, outfile):
''' Parse length distribution out of the fastqc results '''
statement = '''
sed -e '/>>Sequence Length Distribution/,/>>END_MODULE/!d' %(infile)s
| grep -P '^[0-9]+'
| sed '1istart\\tend\\tcount'
| sed 's/-/\\t/' > %(outfile)s '''
P.run()
###################################################################
@merge(getLengthDistribution, "read_length_distribution.load")
def loadLengthDistribution(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename=".+/(.+)_length_distribution.tsv",
options="-i start -i end")
###################################################################
@follows(demux_fastq,qcDemuxedReads, loadUMIStats, loadSampleInfo,
loadLengthDistribution)
def PrepareReads():
pass
###################################################################
# Mapping
###################################################################
def mapping_files():
infiles = glob.glob("%s/*.fastq*gz" % PARAMS["input"])
infiles = [infile for infile in infiles if ".fastq.umi_trimmed.gz" not in infile]
outfiles = set(
["mapping.dir/%(mapper)s.dir/%(track)s.%(mapper)s.bam"
% {"mapper": PARAMS["mappers"],
"track": re.match("%s/(.+).fastq.*gz"
% PARAMS["input"], infile).groups()[0]}
for infile in infiles
if "umi_trimmed" not in infile])
yield (infiles, outfiles)
###################################################################
@follows(mkdir("mapping.dir"), demux_fastq)
@files(mapping_files)
def run_mapping(infiles, outfiles):
''' run the mapping target of the mapping pipeline '''
to_cluster = False
statement = ''' ln -f pipeline.ini mapping.dir/pipeline.ini;
checkpoint;
cd mapping.dir;
nice python %(pipelinedir)s/pipeline_mapping.py
make mapping
-v5 -p%(pipeline_mapping_jobs)s '''
P.run()
###################################################################
@follows(run_mapping)
@collate("mapping.dir/*.dir/*-*-*_*.bam",
regex("(.+)/([^_]+\-.+\-[^_]+)_(.+)\.([^.]+)\.bam"),
r"\1/merged_\2.\4.bam")
def mergeBAMFiles(infiles, outfile):
'''Merge reads from the same library, run on different lanes '''
if len(infiles) == 1:
P.clone(infiles[0], outfile)
return
infiles = " ".join(infiles)
statement = ''' samtools merge %(outfile)s %(infiles)s >& %(outfile)s.log'''
P.run()
###################################################################
@transform(mergeBAMFiles, suffix(".bam"), ".bam.bai")
def indexMergedBAMs(infile, outfile):
''' Index the newly merged BAM files '''
statement = ''' samtools index %(infile)s '''
P.run()
###################################################################
@merge(indexMergedBAMs, "mapping.sentinal")
def mapping_qc(infiles, outfile):
''' run mapping pipeline qc targets '''
to_cluster = False
statement = '''cd mapping.dir;
nice python %(pipelinedir)s/pipeline_mapping.py
make qc -v5 -p%(pipeline_mapping_jobs)s '''
P.run()
P.touch("mapping.sentinal")
###################################################################
@follows(mapping_qc)
@originate("mapping.dir/geneset.dir/reference.gtf.gz")
def buildReferenceGeneSet(outfile):
to_cluster = False
statement = '''cd mapping.dir;
nice python %(pipelinedir)s/pipeline_mapping.py
make buildReferenceGeneSet
-v5 -p%(pipeline_mapping_jobs)s '''
P.run()
###################################################################
@transform(buildReferenceGeneSet,
regex(".+/(.+).gtf.gz"),
r"\1.context.bed.gz")
def generateContextBed(infile, outfile):
''' Generate full length primary transcript annotations to count
mapping contexts '''
genome = os.path.join(PARAMS["annotations_dir"], "contigs.tsv")
statement = ''' zcat %(infile)s
| python %(scripts_dir)s/gtf2gtf.py
--method=exons2introns
-L %(outfile)s.log
| awk 'BEGIN{FS="\\t";OFS="\\t"} {$2="intron"; print}'
| gzip > %(outfile)s.tmp.gtf.gz;
checkpoint;
zcat %(infile)s %(outfile)s.tmp.gtf.gz
| python %(scripts_dir)s/gff2bed.py
--set-name=source
-L %(outfile)s.log
| sort -k1,1 -k2,2n
> %(outfile)s.tmp.bed;
checkpoint;
bedtools complement -i %(outfile)s.tmp.bed -g %(genome)s
| awk 'BEGIN{OFS="\\t"} {print ($0 "\\tnone\\t0\\t.")}'
> %(outfile)s.tmp2.bed;
checkpoint;
cat %(outfile)s.tmp.bed %(outfile)s.tmp2.bed
| sort -k1,1 -k2,2n
| gzip > %(outfile)s;
checkpoint;
rm %(outfile)s.tmp.bed %(outfile)s.tmp2.bed %(outfile)s.tmp.gtf.gz '''
P.run()
###################################################################
@transform(generateContextBed, suffix(".context.bed.gz"),
".context_interval_stats.tsv.gz")
def getContextIntervalStats(infile, outfile):
''' Generate length stastics on context file '''
statement = ''' python %(scripts_dir)s/bed2stats.py
--aggregate-by=name
-I %(infile)s
| gzip > %(outfile)s '''
P.run()
###################################################################
@transform(getContextIntervalStats, suffix(".tsv.gz"),
".load")
def loadContextIntervalStats(infile, outfile):
P.load(infile, outfile)
###################################################################
@transform(mapping_qc, regex("(.+)"),
"mapping.dir/view_mapping.load")
def createViewMapping(infile, outfile):
''' Create tables neccessary for mapping report '''
to_cluster = False
statement = '''cd mapping.dir;
nice python %(scripts_dir)s/../../CGATPipelines/CGATPipelines/pipeline_mapping.py
make createViewMapping -v5 -p1 '''
P.run()
###################################################################
@follows(mapping_qc,loadContextIntervalStats )
def mapping():
pass
###################################################################
# Deduping, Counting, etc
###################################################################
@follows(mkdir("deduped.dir"), run_mapping)
@transform(indexMergedBAMs, regex("(.+)/merged_(.+)\.([^\.]+)\.bam.bai"),
inputs(r"\1/merged_\2.\3.bam"),
r"deduped.dir/\2.bam")
def dedup_alignments(infile, outfile):
''' Deduplicate reads, taking UMIs into account'''
outfile = P.snip(outfile, ".bam")
job_memory="7G"
statement = ''' python %(project_src)s/UMI-tools/dedup_umi.py
%(dedup_options)s
--output-stats=%(outfile)s
-I %(infile)s
-S %(outfile)s.tmp.bam
-L %(outfile)s.log;
checkpoint;
samtools sort %(outfile)s.tmp.bam %(outfile)s;
checkpoint;
samtools index %(outfile)s.bam ;
checkpoint;
rm %(outfile)s.tmp.bam'''
P.run()
###################################################################
@transform([dedup_alignments,indexMergedBAMs],
regex("(?:merged_)?(.+).bam(?:.bai)?"),
r"\1.frag_length.tsv")
def getFragLengths(infile, outfile):
''' estimate fragment length distribution from read lengths'''
intrack = re.match("(.+).bam(?:.bai)?", infile).groups()[0]
statement = ''' python %(project_src)s/length_stats.py
-I %(intrack)s.bam
-S %(outfile)s
-L %(outfile)s.log
'''
if PARAMS["reads_paired"] == 1:
statement += "--paired=%s" % (
int(PARAMS["reads_length"]) - len(PARAMS["reads_bc_pattern"]))
P.run()
###################################################################
@collate(getFragLengths,
regex("(mapping|deduped).dir/.+\.frag_length.tsv"),
r"\1.frag_lengths.load")
def loadFragLengths(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename=".+/(.+\-.+\-.+).frag_length.tsv",
options=" -i Length")
###################################################################
@transform(dedup_alignments,
suffix(".bam"), ".bam_stats.tsv")
def dedupedBamStats(infile, outfile):
''' Calculate statistics on the dedeupped bams '''
statement = '''python %(scripts_dir)s/bam2stats.py
--force-output
< %(infile)s > %(outfile)s '''
P.run()
###################################################################
@merge(dedupedBamStats, "deduped_bam_stats.load")
def loadDedupedBamStats(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename=".+/(.+).bam_stats.tsv")
###################################################################
@transform(dedup_alignments,
suffix(".bam"),
".nspliced.txt")
def getNspliced(infile, outfile):
''' Calculate the number of reads spliced by grepping the
cigar string for Ns'''
statement = ''' samtools view %(infile)s
| awk '$6 ~ /N/'
| wc -l > %(outfile)s '''
P.run()
###################################################################
@merge(getNspliced, "deduped_nspliced.load")
def loadNspliced(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename=".+/(.+).nspliced.txt",
cat="track",
has_titles=False,
header="track,nspliced",)
###################################################################
@transform(dedup_alignments, suffix(".bam"), ".umi_stats.tsv.gz")
def deduped_umi_stats(infile, outfile):
''' calculate histograms of umi frequencies '''
statement = '''python %(project_src)s/umi_hist.py
-I %(infile)s
-L %(outfile)s.log
| gzip > %(outfile)s '''
P.run()
###################################################################
@merge(deduped_umi_stats, "dedup_umi_stats.load")
def loadDedupedUMIStats(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename=".+/(.+).umi_stats.tsv.gz",
cat="track",
options="-i track -i UMI")
###################################################################
@follows(mkdir("saturation.dir"), run_mapping)
@subdivide(indexMergedBAMs, regex(".+/merged_(.+)\.[^\.]+\.bam.bai"),
[r"saturation.dir/\1.%.3f.bam" % (1.0/(2 ** x))
for x in range(1, 6)] +
[r"saturation.dir/\1.%.3f.bam" % (x/10.0)
for x in range(6, 11, 1)])
def subsetForSaturationAnalysis(infile, outfiles):
'''Perform subsetting of the original BAM files, dedup and
return the context stats. Test for resturn on investment for
further sequencing of the same libraries '''
track = re.match(".+/merged_(.+)\.[^\.]+\.bam", infile).groups()[0]
infile = P.snip(infile, ".bai")
statements = []
statement_template = '''
python %%(project_src)s/UMI-tools/dedup_umi.py
%%(dedup_options)s
-I %(infile)s
-L %(outfile)s.log
-S %(outfile)s.tmp.bam
--subset=%(subset).3f;
checkpoint;
samtools sort %(outfile)s.tmp.bam %(outfile)s;
checkpoint;
samtools index %(outfile)s.bam '''
for x in range(1, 6):
subset = 1.0/(2 ** x)
outfile = "saturation.dir/%%(track)s.%.3f" % subset
statements.append(statement_template % locals())
for x in range(6, 11):
subset = x/10.0
outfile = "saturation.dir/%%(track)s.%.3f" % subset
statements.append(statement_template % locals())
P.run()
###################################################################
@transform(subsetForSaturationAnalysis, suffix(".bam"), ".bamstats.tsv")
def subsetBamStats(infile, outfile):
''' Stats on the subset BAMs '''
job_options = "-l mem_free=500M"
statement = ''' python %(scripts_dir)s/bam2stats.py
--force-output < %(infile)s > %(outfile)s '''
P.run()
###################################################################
@merge(subsetBamStats, "subset_bam_stats.load")
def loadSubsetBamStats(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename= ".+/(.+-.+-.+)\.([0-9]+\.[0-9]+).bamstats.tsv",
cat="track,subset")
###################################################################
@transform([indexMergedBAMs, dedup_alignments, subsetForSaturationAnalysis],
regex("(?:merged_)?(.+).bam(?:.bai)?"),
add_inputs(generateContextBed),
r"\1.reference_context.tsv")
def buildContextStats(infiles, outfile):
''' Find context from reads '''
infile, reffile = infiles
infile = re.match("(.+.bam)(?:.bai)?", infile).groups()[0]
statement = ''' python %(scripts_dir)s/bam_vs_bed.py
--min-overlap=0.5
--log=%(outfile)s.log
%(infile)s %(reffile)s
> %(outfile)s '''
job_options = "-l mem_free=4G"
P.run()
###################################################################
@collate(buildContextStats,
regex("(mapping|deduped|saturation).dir/(?:[^/]+.dir/)?(.+).tsv"),
r"\1_context_stats.load")
def loadContextStats(infiles, outfile):
if "saturation" in infiles[0]:
regex_filename = ".+/(.+-.+-.+)\.([0-9]+\.[0-9]+).reference_context.tsv"
cat = "track,subset"
else:
regex_filename = ".+/(.+).reference_context.tsv"
cat = "track"
P.concatenateAndLoad(infiles, outfile,
regex_filename=regex_filename,
cat=cat)
###################################################################
@transform(buildReferenceGeneSet,
suffix(".gtf.gz"),
".flat.gtf.gz")
def flattenGeneSet(infile, outfile):
''' Get gtf with geneset flattened so that introns are definately
intron sequence '''
statement = '''python %(scriptsdir)s/gtf2gtf.py
--method=sort
--sort-order=gene+transcript
-I %(infile)s
| python %(scriptsdir)s/gtf2gtf.py
--method=merge-exons
-L %(outfile)s.log
-S %(outfile)s '''
P.run()
###################################################################
@transform(dedup_alignments, suffix(".bam"),
add_inputs(flattenGeneSet),
".splicing_index")
def calculateSplicingIndex(infiles, outfile):
'''Calculate the splicing index: number of reads
reads spliced at each junction divided by number of
reads not spliced'''
bamfile, gtffile = infiles
PipelineiCLIP.calculateSplicingIndex(bamfile,
gtffile,
outfile,
submit=True)
@merge(calculateSplicingIndex, "splicing_index.load")
def loadSplicingIndex(infiles, outfile):
P.concatenateAndLoad(infiles, outfile,
regex_filename="deduped.dir/(.+).splicing_index")
###################################################################
@follows(loadContextStats,
loadSubsetBamStats,
loadDedupedBamStats,
loadFragLengths,
loadNspliced,
loadDedupedUMIStats,
loadSplicingIndex)
def MappingStats():
pass
###################################################################
# Quality control and reproducibility
###################################################################
@follows(mkdir("reproducibility.dir"))
@collate(dedup_alignments, regex(".+/(.+\-.+)\-.+.bam"),
r"reproducibility.dir/\1-agg.reproducibility.tsv.gz")
def calculateReproducibility(infiles, outfile):
''' Calculate cross-link reproducibility as defined by
Sugimoto et al, Genome Biology 2012 '''
job_options = "-l mem_free=1G"
infiles = " ".join(infiles)
statement = '''python %(project_src)s/calculateiCLIPReproducibility.py
%(infiles)s
-L %(outfile)s.log
| gzip > %(outfile)s '''
P.run()
###################################################################
@follows(mkdir("reproducibility.dir"))
@merge(dedup_alignments,
r"reproducibility.dir/agg-agg-agg.reproducibility.tsv.gz")
def reproducibilityAll(infiles, outfile):
''' Test weather sites from one file reproduce in other of different factors '''
job_options = "-l mem_free=10G"
infiles = " ".join(infiles)
statement = '''python %(project_src)s/calculateiCLIPReproducibility.py
%(infiles)s
-L %(outfile)s.log
| gzip > %(outfile)s '''
P.run()
###################################################################
@follows(mkdir("reproducibility.dir"))
@transform(dedup_alignments,
regex(".+/(.+).bam"),
add_inputs("deduped.dir/%s*.bam" % PARAMS["experiment_input"]),
r"reproducibility.dir/\1_vs_control.reproducibility.tsv.gz")
def reproducibilityVsControl(infiles, outfile):
'''Test what fraction of the locations in each bam also appear
in the control files'''
track = infiles[0]
if track in infiles[1:]:
P.touch(outfile)
else:
job_options = "-l mem_free=1G"
infiles = " ".join(infiles)
statement = '''python %(project_src)s/calculateiCLIPReproducibility.py
%(infiles)s
-L %(outfile)s.log
-t %(track)s
| gzip > %(outfile)s '''
P.run()
###################################################################
@merge(calculateReproducibility,
r"reproducibility.dir/experiment_reproducibility.load")
def loadReproducibility(infiles, outfile):
P.concatenateAndLoad(infiles, outfile, cat="Experiment",
regex_filename=".+/(.+)-agg.reproducibility.tsv.gz",
options="-i Track -i fold -i level")
###################################################################
@transform(reproducibilityAll, regex("(.+)"),
"reproducibility.dir/all_reproducibility.load")
def loadReproducibilityAll(infile, outfile):
P.load(infile, outfile, "-i Track -i fold -i level")
###################################################################
@merge(reproducibilityVsControl,
"reproducibility.dir/reproducibility_vs_control.load")
def loadReproducibilityVsControl(infiles, outfile):
infiles = [infile for infile in infiles
if not PARAMS["experiment_input"] in infile]
P.concatenateAndLoad(infiles, outfile, cat="Experiment",
regex_filename=".+/(.+\-.+)\-.+_vs_control.reproducibility.tsv.gz",
options = "-i File -i fold -i level")
###################################################################
@permutations(dedup_alignments, formatter(".+/(?P<TRACK>.+).bam"),
2,
"reproducibility.dir/{TRACK[0][0]}_vs_{TRACK[1][0]}.tsv.gz")
def computeDistances(infiles, outfile):
''' Compute the reproduciblity between each indevidual pair of samples
this can then be readily converted to a distance measure'''
track = infiles[0]
infiles = " ".join(infiles)
job_options="-l mem_free=2G"
statement = '''python %(project_src)s/calculateiCLIPReproducibility.py
%(infiles)s
-L %(outfile)s.log
-t %(track)s
-m 1
| gzip > %(outfile)s '''