-
Notifications
You must be signed in to change notification settings - Fork 0
/
PipelineProj010.py
5954 lines (5153 loc) · 239 KB
/
PipelineProj010.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: $
#
# 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.
#################################################################################
"""
==============================================
PipelineProj010.py - custom tasks for proj010
==============================================
:Author: Jethro Johnson
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
This module file contains generic functions for use in the script
pipeline_proj010_lncrna.py
"""
import gzip, os, re
import pysam
import random
import pickle
import shutil
import tempfile
import copy
import numpy as np
import collections
import itertools
import pandas as pd
import pandas.rpy.common as com
import rpy2.robjects as robjects
import rpy2.robjects.pandas2ri as pandas2ri
from rpy2.robjects import r as R
from rpy2.robjects import numpy2ri as rpyn
from rpy2.robjects.packages import importr
from scipy import stats
from bx.bbi.bigwig_file import BigWigFile
from pybedtools.contrib.bigwig import bam_to_bigwig
import CGAT.IOTools as IOTools
import CGAT.GTF as GTF
import CGAT.Bed as Bed
import CGATPipelines.Pipeline as P
import CGAT.Experiment as E
import CGAT.Expression as Expression
import CGAT.IndexedGenome as IndexedGenome
import CGATPipelines.PipelineUtilities as PU
from CGATPipelines.Pipeline import cluster_runnable
import PipelineProj010QC as QC
#################################################################################
#################################################################################
#################################################################################
## section: miscellaneous
#################################################################################
# Things that are too clunky to sit in the main pipeline
#################################################################################
def postProcessClosestBed( in_bed, outfile, cage = True ):
"""
Resolve intervals that are equidistant
"""
outf = IOTools.openFile( outfile, "w" )
if cage:
outf.write( "lnc_contig\t"
"lnc_start\t"
"lnc_end\t"
"lnc_id\t"
"lnc_score\t"
"lnc_strand\t"
"cage_contig\t"
"cage_start\t"
"cage_end\t"
"cage_id\t"
"cage_score\t"
"cage_strand\t"
"cage_thickStart\t"
"cage_thickEnd\t"
"cage_rgb\t"
"distance\n" )
else:
outf.write( "lnc_contig\t"
"lnc_start\t"
"lnc_end\t"
"lnc_id\t"
"lnc_score\t"
"lnc_strand\t"
"refcoding_contig\t"
"refcoding_start\t"
"refcoding_end\t"
"refcoding_id\t"
"refcoding_score\t"
"refcoding_strand\t"
"distance\n" )
def _get_distance( tss, start, end ):
tss, start, end = map( int, ( tss, start, end ) )
assert end > start, "Error in bedfile"
if tss > end:
distance = tss - end
elif start > tss:
distance = start - (tss + 1)
else:
distance = 0
return distance
# iterate through bedfile, add each entry to dictionary with gene_id as key
# for cage intervals resolve closest by selecting interval with closest thickSart
# for refcoding tss resolve closest by taking first interval
near_peaks = collections.defaultdict( list )
for line in IOTools.openFile( in_bed ):
near_peaks[ line.split()[3] ].append( line )
for key, values in near_peaks.iteritems():
if len( values ) == 1:
outf.write( near_peaks[ key ][0] )
pass
elif not cage:
outf.write( near_peaks[ key ][0] )
else:
dst = [ x.split()[-1] for x in values ]
assert len( set( dst ) ) == 1, "Duplicate entries with different distances"
tss = values[0].split()[1]
closest = None
closest_dist = None
dists = []
for value in enumerate( values ):
value_start = value[1].split()[12]
value_end = value[1].split()[13]
distance = _get_distance( tss, value_start, value_end )
dists.append( distance )
if closest_dist:
if distance < closest_dist:
closest = value[0]
closest_dist = distance
else:
closest = value[0]
closest_dist = distance
E.info( "Resolving equidistant peaks for %s: %s"
" Keeping %s, which corresponds to %s" %( key,
str( dists ),
str( closest_dist ),
near_peaks[key][closest].split()[9] ) )
outf.write( near_peaks[ key ][ closest ] )
outf.close()
def summarize_eRNAs( lncRNAs, infiles, outfile ):
"""
Takes sorted set of lncRNAs and makes empty dictionary.
Takes bedfiles containing gene/transcript, eRNAs/pRNAs for robust/permissive
/original datasets and outputs a single file that summarizes lncRNA status
for all datasets.
"""
# set up empty dictionary
summary_dict = {}
for gtf in GTF.flat_gene_iterator( GTF.iterator( IOTools.openFile( lncRNAs ) ) ):
gene_id = gtf[0].gene_id
assert gene_id not in summary_dict.keys(), "Duplicate Gene IDs"
summary_dict[ gene_id ] = { "gene": "ambiguous",
"gene_permissive": "ambiguous",
"gene_robust": "ambiguous",
"transcript": "ambiguous",
"transcript_permissive": "ambiguous",
"transcript_robust": "ambiguous" }
# set up counting dictionary
count_dict = { "gene": { "eRNA": 0, "pRNA": 0, "conflicted": 0 },
"gene_permissive": { "eRNA": 0, "pRNA": 0, "conflicted": 0 },
"gene_robust": { "eRNA": 0, "pRNA": 0, "conflicted": 0 },
"transcript": { "eRNA": 0, "pRNA": 0, "conflicted": 0 },
"transcript_permissive": { "eRNA": 0, "pRNA": 0, "conflicted": 0 },
"transcript_robust": { "eRNA": 0, "pRNA": 0, "conflicted": 0 } }
# iterate through infiles
for infile in infiles:
E.info( "Processing file: %s" % os.path.basename( infile ) )
# specify category based on filename
col_name = None
category = None
inf_name = os.path.basename( infile ).split("_")
if inf_name[1] in [ "eRNA", "pRNA" ]:
col_name = inf_name[0]
category = inf_name[1]
elif inf_name[1] in [ "permissive", "robust" ]:
assert inf_name[2] in [ "eRNA", "pRNA" ], "Unrecognized file name"
col_name = "_".join( inf_name[0:2] )
category = inf_name[2]
else:
raise Exception( "Unrecognised file name %s" % os.path.basename(infile) )
# HACK... transcripts have different TSS in bedfile, hence are not merged.
gene_id_list = [ bed.fields[0] for bed in Bed.iterator( IOTools.openFile( infile ) ) ]
if col_name.startswith( "gene" ):
assert len( gene_id_list ) == len( set( gene_id_list ) ), "Ambiguous TSS for genes"
gene_id_list = list( set( gene_id_list ) )
# iterate through gene_ids and add information
# for each interval to summary_dict
for gene_id in gene_id_list:
# E.info( "Processing gene_id %s" % gene_id )
# it is not possible for field to be conflicted until it has been
# parsed twice, no entry should be parsed more than twice.
assert summary_dict[ gene_id ][ col_name ] != "conflict", "Duplicate Gene IDs in eRNA files"
# reset ambiguous fields, based on current infile
if summary_dict[ gene_id ][ col_name ] == "ambiguous":
summary_dict[ gene_id ][ col_name ] = category
count_dict[ col_name ][ category ] += 1
# check no field is reassigned the same lncRNA status twice
elif summary_dict[ gene_id ][ col_name ] in [ "eRNA", "pRNA" ]:
if summary_dict[ gene_id ][ col_name ] == category:
raise ValueError( "lncRNA is categorised twice as %s. "
"Failed on %s, %s for file %s"
% ( category,
gene_id,
col_name,
os.path.basename( infile ) ) )
else:
# remove count from original classification
to_remove = summary_dict[ gene_id ][ col_name ]
count_dict[ col_name ][ to_remove ] -= 1
summary_dict[ gene_id ][ col_name ] = "conflicted"
count_dict[ col_name ][ "conflicted" ] += 1
else:
raise Exception( "Unrecognized field entry %s for gene_id"
" %s, file %s" % ( summary_dict[gene_id][col_name],
gene_id,
col_name ))
# write outfile
headers = [ "gene", "gene_permissive", "gene_robust",
"transcript", "transcript_permissive", "transcript_robust" ]
outf = IOTools.openFile( outfile, "w" )
outf.write( "gene_id\t" + "\t".join( headers ) + "\n" )
for gene_id, fields in summary_dict.iteritems():
out_fields = []
for field in headers:
out_fields.append( fields[ field ] )
outf.write( gene_id + "\t" + "\t".join( out_fields ) + "\n" )
outf.close()
# write summary outfile
headers = [ "eRNA", "pRNA", "conflicted" ]
outf_summary = P.snip( outfile, ".tsv.gz" ) + "_summary.tsv.gz"
outf_summary = IOTools.openFile( outf_summary, "w" )
outf_summary.write("data_set\t" + "\t".join( headers ) + "\n" )
for data_set, fields in count_dict.iteritems():
out_fields = []
for field in headers:
out_fields.append( str( fields[ field ] ) )
outf_summary.write( data_set + "\t" + "\t".join( out_fields ) + "\n" )
outf_summary.close()
def compareOverlaps(genes_gtf,
tf_bed,
genome_file,
genome_file_ungapped,
isochore_file,
outf_stub,
annotation="lncRNA" ):
"""
A wrapper for various commandline statements associated with comparing
the overlap between a geneset (genes_gtf) and a bed file of transcription
factor binding sites (tf_bed). The steps are as follows:
i) slop geneset (1kb upstream) and convert to bedfile
ii) run diff_bed.py to get overlap statistics
iii) run GAT to see if tf binding across gene intervals is enriched vs
background
iv) create boolean table detailing which gene_ids have tfbs in gene body
"""
# create outfiles
genes_bed_slop = outf_stub + "_" + annotation + "_1kb.bed.gz"
outf_diff = outf_stub + "_overlap.tsv"
outf_gat = outf_stub + "_bg_gat.tsv"
outf_tab = outf_stub + "_coverage.tsv.gz"
outf_bed = outf_stub + "_coverage.bed.tsv.gz"
# Create intervals from gtf gene models
statement = ( "zcat %(genes_gtf)s |"
" python %(scriptsdir)s/gtf2gtf.py"
" --method=merge-transcripts"
" --log=%(outf_stub)s.log |"
" bedtools slop "
" -i stdin"
" -l 1000"
" -r 0" # necessary to state -r if -l given
" -g %(genome_file)s |"
" python %(scriptsdir)s/gff2bed.py"
" --is-gtf"
" --log=%(outf_stub)s.log |"
" gzip > %(genes_bed_slop)s" )
P.run()
E.info( "Completed slop for sample %s" % genes_gtf )
# run diff_bed.py to compare overlap between tfbs and gene models
statement = ( "python %(scriptsdir)s/diff_bed.py"
" --pattern-identifier='.*/(.+).bed.gz'"
" --log=%(outf_stub)s.log"
" %(genes_bed_slop)s %(tf_bed)s"
" > %(outf_diff)s" )
P.run()
E.info( "Completed diff_bed comparison for sample %s" % genes_gtf )
# run gat to find significance of overlap between tfbs and
# geneset vs background
# gat annotations file requires 4th column to specify annotation
tmpf = P.getTempFilename("/ifs/scratch")
statement = ( "zcat %(genes_bed_slop)s |"
" awk 'BEGIN {OFS=\"\\t\"} {print $1,$2,$3,\"%(annotation)s\"}'"
" > %(tmpf)s" )
P.run()
job_options = "-l mem_free=5G"
statement = ( "gat-run.py"
" --segments=%(tf_bed)s"
" --annotations=%(tmpf)s" # replacement for gene_bed_slop
" --workspace-bed-file=%(genome_file_ungapped)s"
" --isochore-file=%(isochore_file)s"
" --ignore-segment-tracks"
" --truncate-segments-to-workspace"
" --num-samples=10000"
" -v5"
" --log=%(outf_stub)s.log"
" > %(outf_gat)s" )
P.run()
E.info( "Completed GAT run for sample %s" % genes_gtf )
os.unlink( tmpf )
# create table of booleans specifying whether a gene intersects a tfbs
# run bedtools intersect to retrieve gene ids intersecting tfbs
statement = ( "bedtools intersect"
" -a %(genes_bed_slop)s"
" -b %(tf_bed)s"
" -wa"
" -u |"
" gzip > %(outf_bed)s" )
P.run()
# create list of gene_ids with tf binding
bound_genes = []
for line in IOTools.openFile( outf_bed ):
gene_id = line.split()[3]
bound_genes.append( gene_id )
# write table
outf = IOTools.openFile( outf_tab, "w" )
outf.write( "gene_id\t%s\n" % os.path.basename(outf_stub) )
for gtfs in GTF.flat_gene_iterator(
GTF.iterator( IOTools.openFile( genes_gtf ) ) ):
gene_id = gtfs[0].gene_id
if gene_id in bound_genes:
outf.write( gene_id + "\tTRUE\n" )
else:
outf.write( gene_id + "\tFALSE\n" )
outf.close()
E.info( "Created overlap table for sample %s" % genes_gtf )
# extract chromatin de regions from DESeq output in csvdb
def getDEIntervals(database, table_name, direction, fold_change):
"""
Use PU fetch to return interavals at required thresholds from DESeq results
table.
"""
statement = ( "SELECT test_id, control_name, treatment_name, l2fold, pvalue"
" FROM %(table_name)s"
" WHERE l2fold %(direction)s %(fold_change)s" % locals() )
df = PU.fetch_DataFrame( statement, database = database )
return df
#################################################################################
#################################################################################
#################################################################################
## section: manipulate bam files
#################################################################################
@cluster_runnable
def normalizeBams(bamfile, normalization_file, outfile):
# create dictionary of normalization factors.
norm_factors = {}
for line in IOTools.openFile(normalization_file).readlines()[1:]:
line = line.split()
norm_factors[line[1]] = float(line[0])
# get the smallest normalization factor (this is the smallest bamfile).
norm_min = min(norm_factors.values())
# calculate this as a proportion of all normalization factors
for key, value in norm_factors.iteritems():
norm_factors[key] = norm_min/value
# pull out the relevant normalization factor
bam_id = P.snip(os.path.basename(bamfile), ".bam")
norm_factor = norm_factors[bam_id]
print bam_id, norm_factor
# # iterate through the bamfile
# pysam_in = pysam.Samfile(bamfile, "rb")
# pysam_out = pysam.Samfile(outfile, "wb", template=pysam_in)
# write out the specified proportion of reads
# for read in pysam_in.fetch():
# if random.random() <= norm_factor:
# pysam_out.write(read)
# pysam_in.close()
# pysam_out.close()
# pysam.index(outfile)
def normalize( infile, larger_nreads, outfile, smaller_nreads ):
threshold = float(smaller_nreads) / float(larger_nreads)
pysam_in = pysam.Samfile( infile, "rb" )
pysam_out = pysam.Samfile( outfile, "wb", template = pysam_in )
for read in pysam_in.fetch():
if random.random() <= threshold:
pysam_out.write( read )
pysam_in.close()
pysam_out.close()
pysam.index( outfile )
return outfile
@cluster_runnable
def normalizeBamfiles( sample_file, input_file, sample_outfile, input_outfile, submit=True ):
sample_sam = pysam.Samfile( sample_file, "rb" )
sample_nreads = 0
for read in sample_sam:
sample_nreads += 1
input_sam = pysam.Samfile( input_file, "rb" )
input_nreads = 0
for read in input_sam:
input_nreads += 1
if input_nreads > sample_nreads:
P.info( "%s bam has %s reads, %s bam has %s reads"
% ( input_file, input_nreads, sample_file, sample_nreads ) )
P.info( "%s being downsampled to match %s"
% ( input_file, sample_file ) )
input_outfile = normalize( input_file,
input_nreads,
input_outfile,
sample_nreads )
shutil.copyfile( sample_file, sample_outfile )
pysam.index( sample_outfile )
# return sample_outfile, input_outfile
elif sample_nreads > input_nreads:
P.info( "%s bam has %s reads, %s bam has %s reads"
% ( sample_file, sample_nreads, input_file, input_nreads ) )
P.info( "%s being downsampled to match %s"
% ( sample_file, input_file ) )
sample_outfile = normalize( sample_file,
sample_nreads,
sample_outfile,
input_nreads )
shutil.copyfile( input_file, input_outfile )
pysam.index( input_outfile )
# return sample_outfile, input_outfile
else:
E.info ( "WARNING: Both bamfiles are the same size!!" )
shutil.copyfile( sample_file, sample_outfile )
pysam.index( sample_outfile )
shutil.copyfile( input_file, input_outfile )
pysam.index( input_outfile )
# return sample_outfile, input_outfile
# merge bams using samtools merge
def mergeBam( infile_list, outfile ):
out_stub = P.snip( outfile, ".bam" )
to_cluster = True
job_options = "-l mem_free=5G"
statement = ( "samtools merge - %(infile_list)s"
" | samtools sort - %(out_stub)s"
" 2>%(outfile)s.log;"
" checkpoint;"
" samtools index %(outfile)s"
" 2>%(outfile)s.bai.log" )
P.run()
# randomly split reads from bamfile into two bamfiles of approx. equal size
def splitBam( infile, outfiles ):
# rewrite as a dictionary to take multiple splits
outfile_00, outfile_01 = outfiles
pysam_in = pysam.Samfile( infile, "rb" )
pysam_out_00 = pysam.Samfile( outfile_00, "wb", template = pysam_in )
pysam_out_01 = pysam.Samfile( outfile_01, "wb", template = pysam_in )
for read in pysam_in.fetch():
if random.random() <= 0.5:
pysam_out_00.write( read )
else:
pysam_out_01.write( read )
pysam_out_00.close()
pysam_out_01.close()
pysam.index( outfile_00 )
pysam.index( outfile_01 )
# randomly split reads from bamfile into a specified number of bamfiles
def multiSplitBam( infiles, outfiles, params ):
infile = infiles
outfile_stub = outfiles
n_outfiles = int(params[0])
pysam_in = pysam.Samfile( infile, "rb" )
outfile_handles = []
outfile_names = []
# create list of upper bounds for intervals
intervals = []
lower = 0
for i in range( n_outfiles ):
upper = lower + 1.0/n_outfiles
intervals.append( upper )
# add an outfile handle to list of outfile handles
outf = outfile_stub + "_" + str(i).zfill(2) + ".bam"
outfile_names.append( outf )
outfile_handles.append( pysam.Samfile( outf, "wb", template = pysam_in ) )
lower = upper
# iterate through reads in samfile and write them to an outfile at random
for read in pysam_in.fetch():
r_num = random.random()
for i in range( len( intervals ) ):
if r_num < intervals[i]:
outfile_handles[i].write( read )
break
else: continue
# close outfiles
for i in range( n_outfiles ):
outfile_handles[i].close()
# index outfiles
for split_sam in outfile_names:
pysam.index( split_sam )
# split bam file into separate files for + and - strands
def splitBamByStrand( infile, outfiles ):
out_pos, out_neg = outfiles
out_pos = P.snip( out_pos, ".bam" )
out_neg = P.snip( out_neg, ".bam" )
tmpf_pos = P.getTempFilename( "/scratch" )
tmpf_neg = P.getTempFilename( "/scratch" )
pysam_in = pysam.Samfile( infile, "rb" )
pysam_out_pos = pysam.Samfile( tmpf_pos, "wb", template = pysam_in )
pysam_out_neg = pysam.Samfile( tmpf_neg, "wb", template = pysam_in )
for read in pysam_in.fetch():
if read.is_read1 and not read.is_reverse:
pysam_out_pos.write( read )
elif read.is_read2 and read.is_reverse:
pysam_out_pos.write( read )
elif read.is_read1 and read.is_reverse:
pysam_out_neg.write( read )
elif read.is_read2 and not read.is_reverse:
pysam_out_neg.write( read )
pysam_out_pos.close()
pysam_out_neg.close()
pysam.sort( tmpf_pos, out_pos )
pysam.sort( tmpf_neg, out_neg )
# check this
pysam.index( out_pos + ".bam" )
pysam.index( out_neg + ".bam" )
os.unlink( tmpf_pos )
os.unlink( tmpf_neg )
# converts bamfile to bigwig, via bedgraph
# contigs - list of contig sizes (PARAMS_ANNOTATIONS["interface_contigs"])
# scale provides option for normalizing the bigwigs
def bam2bigwig( bamfile, bigwigfile, contigs, scale=1.0 ):
tmpf_1 = P.getTempFilename( "./bigwigs" )
tmpf_2 = P.getTempFilename( "./bigwigs" )
to_cluster = True
job_options = "-l mem_free=10G"
statement = ( "bedtools genomecov"
" -split"
" -scale %(scale)s"
" -bga"
" -ibam %(bamfile)s"
" -g %(contigs)s"
" > %(tmpf_2)s"
" bedGraphToBigWig"
" %(tmpf_2)s"
" %(contigs)s"
" %(bigwigfile)s"
" 2> %(bigwigfile)s.log" )
P.run()
os.unlink( tmpf_1 )
os.unlink( tmpf_2 )
# " 2> %(bigwigfile)s.log;"
# " sort -k1g,1g -k2n,2n"
# " %(tmpf_1)s"
# " > %(tmpf_2)s"
# " 2> %(bigwigfile)s.log;"
"""
# write sam header to a tempfile
tmpf = P.getTempFilename(".")
statement = ( "samtools view -H %(infile)s > %(tmpf)s.header" )
P.run()
# split bam into two files with original sam header
bamfile = pysam.Samfile( infile, "rb" )
nreads = 0
for entry in bamfile: nreads += 1
nreads_split = (nreads + 1)/num_split
to_cluster = True
statement = ( "samtools view %(infile)s"
" | shuf"
" split -d -l %(nreads_split)s - %(out_stub)s;"
" checkpoint;"
" cat %(tmpf)s.header > %(tmpf)s00;"
" cat %(out_stub)s00 >> %(tmpf)s00;"
" samtools view -bT %(genome_dir)s/%(genome)s.fa %(tmpf)s00 "
" > %(out_stub)s00.bam;"
" samtools index %(out_stub)s00.bam;"
" cat %(tmpf)s.header > %(tmpf)s01;"
" cat %(out_stub)s01 >> %(tmpf)s01;"
" samtools view -bT %(genome_dir)s/%(genome)s.fa %(tmpf)s01 "
" > %(out_stub)s01.bam;"
" samtools index %(out_stub)s01.bam;"
" rm %(tmpf)s.header %(tmpf)s00 %(tmpf)s01 %(out_stub)s00 %(out_stub)s01" )
P.run()
"""
#################################################################################
#################################################################################
#################################################################################
## section: manipulate gtf files
#################################################################################
# NB. GTF.iterator object attributes are zero based half open, which is pythonic
# as opposed to the original gtf which is 1-based inclusive (i.e. closed).
# Bed format is zero-based half open.
# Therefore accessing gtf attributes and writing them to bed format does not
# require any numeric conversion.
def defineTranscripts( exon_list ):
"""
Receives a list of gtf objects pertaining to multiple transcripts as
supplied by GTF.flat_gene_iterator.
Returns an ordered dictionary with transcript_id as key and (start, end,
number_of_intervals) as value. Dictionary is ordered by transcript start.
"""
transcript_dict = {}
for exon in exon_list:
t_id = exon.transcript_id
if t_id not in transcript_dict:
transcript_dict[ t_id ] = [ exon.start, exon.end, 1 ]
else:
transcript_dict[ t_id ][2] += 1
if transcript_dict[ t_id ][0] > exon.start:
transcript_dict[ t_id ][0] = exon.start
if transcript_dict[ t_id ][1] < exon.end:
transcript_dict[ t_id ][1] = exon.end
return collections.OrderedDict( sorted( transcript_dict.items(),
key = lambda t: t[1][0] ) )
def findTSSFromGTF( infile, outfile ):
inf = IOTools.openFile( infile, "r" )
outf = IOTools.openFile( outfile, "w" )
for exons in GTF.transcript_iterator( GTF.iterator( inf ) ):
chrom = exons[0].contig
start = str(exons[0].start)
end = str(exons[0].start + 1)
gene_id = exons[0].gene_id
strand = exons[0].strand
outf.write( chrom + "\t"
+ start + "\t"
+ end + "\t"
+ gene_id + "\t"
+ ".\t"
+ strand + "\n" )
outf.close()
# splits transcripts in gtf based on a chosen field, using dictionary
# output suffix as key and matching regex as value
# if retain == true, then all transcripts not matching regex will be output
# if dict contains value "other", failed matches are output using given key as
# suffix, otherwise failed matches are output using suffix 'unassigned'
def splitGTFByFieldValues( infile, out_stub, field, dictionary, retain = False ):
inf = IOTools.openFile( infile, "r" )
suffix = ".gtf" + infile.split( ".gtf" )[1]
other = "unassigned"
for key, value in dictionary.iteritems():
if key.lower() == "other":
other = dictionary.pop( key )
break # can't change dict size during iteration
other = IOTools.openFile( out_stub + "_" + other + suffix, "w" )
file_dict = {}
for key in dictionary.iterkeys():
file_dict[ key ] = IOTools.openFile( out_stub + "_" + key + suffix, "w" )
for transcript in GTF.transcript_iterator( GTF.iterator( inf ) ):
match = False
for key, value in dictionary.iteritems():
if re.search( value, transcript[0].__getattribute__( field ) ):
flat_transcript = IOTools.flatten( transcript )
for interval in flat_transcript:
file_dict[ key ].write( str( interval ) + "\n" )
match = True
else: continue
if retain and not match:
flat_transcript = IOTools.flatten( transcript )
for interval in flat_transcript:
other.write( str( interval ) + "\n" )
for value in file_dict.itervalues():
value.close()
other.close()
other = out_stub + "_unassigned" + suffix
if os.path.exists( other ):
if not retain:
os.unlink( other )
# intersect two gtf files
# remove any gene_id in gtf_a that intersects with gtf_b
def intersectGTFs( lncRNA_gtf,
reference_gtf,
filtered_gtf,
rejected_gtf,
control_gtf = None,
control_biotypes = None ):
"""
Intersects two gtf files using bedtools intersect. Removes any transcript for
which an interval in gtf_a intersects an interval in gtf_b.
Has the option of providing a third - control - gtf (plus list of biotypes).
If provided, any transcript to be removed is checked to see if it intersects
with the control. Those that intersect transcripts of specified biotype in
control file are rescued.
This is a hack designed to rescue transcripts that are labelled as protein
coding in refseq annotations but as lincRNAs in ensembl annotations.
"""
# intersect the lncRNA_gtf with the reference_gtf - any locus that intersects
# is output to tmpfile
tmpf = P.getTempFilename( "." )
statement = ( "bedtools intersect"
" -a %(lncRNA_gtf)s"
" -b %(reference_gtf)s"
" -u"
" -s"
" > %(tmpf)s" )
P.run()
# iterate through tmpfile and add intersecting gene_ids to gene_ids_to_reject
gene_ids_to_reject = []
for gtf in GTF.iterator( IOTools.openFile( tmpf ) ):
gene_ids_to_reject.append( gtf.gene_id )
gene_ids_to_reject = set( gene_ids_to_reject )
os.unlink( tmpf )
# iterate through the lncRNA_gtf, moving gene_ids_to_reject to temp_rejected
inf = IOTools.openFile( lncRNA_gtf )
temp_filtered = P.getTempFilename( "." )
temp_rejected = P.getTempFilename( "." )
temp_filtered_out = IOTools.openFile( temp_filtered, "w" )
temp_rejected_out = IOTools.openFile( temp_rejected, "w" )
for gtf in GTF.flat_gene_iterator( GTF.iterator( inf ) ):
if gtf[0].gene_id in gene_ids_to_reject:
for exon in IOTools.flatten( gtf ):
temp_rejected_out.write( str( exon ) + "\n" )
else:
for exon in IOTools.flatten( gtf ):
temp_filtered_out.write( str( exon ) + "\n" )
temp_rejected_out.close()
# if a control gtf is provided, then provide a chance to save temp_rejected
# i) intersect intervals in temp_rejected with intervals in control_gtf
# ii) if intersecting control intervals are of a specified biotype, then
# intervals in temp_rejected are saved (i.e. written to rescued and filtered )
if control_gtf:
assert isinstance( control_biotypes, (list,) ), "need to supply biotypes as list"
to_rej_gtf = IOTools.openFile( temp_rejected )
control_gtf = IOTools.openFile( control_gtf )
def_rejected = P.getTempFilename( "." )
rescued_gtf = re.sub( "filtered", "rescued", filtered_gtf )
to_rescue = []
# create index of intervals in control file
control_index = GTF.readAndIndex( GTF.iterator( control_gtf ) )
# iterate through the currently rejected transcripts
for gtf in GTF.transcript_iterator( GTF.iterator( to_rej_gtf ) ):
for exon in gtf:
if control_index.contains( exon.contig, exon.start, exon.end ):
# check if any intersecting control intervals are on the same strand
for interval in control_index.get( exon.contig, exon.start, exon.end ):
if exon.strand == interval[2].strand:
# for those that are, check biotype
if interval[2].source in control_biotypes:
to_rescue.append( exon.gene_id )
else:
continue
else:
continue
else:
continue
to_rej_gtf.close()
control_gtf.close()
# create a set gene_ids to save
to_rescue = set( to_rescue )
# iterate through the temp_rejected_gtfs,
# if they are in to_save write them to rescued_gtf and to filtered_gtf
# if not then write them to def_rejected
def_rejected_out = IOTools.openFile( def_rejected, "w" )
rescued_gtf_out = IOTools.openFile( rescued_gtf, "w" )
for gtf in GTF.flat_gene_iterator( GTF.iterator( IOTools.openFile( temp_rejected ) ) ):
if gtf[0].gene_id in to_rescue:
for exon in IOTools.flatten( gtf ):
temp_filtered_out.write( str( exon ) + "\n" )
rescued_gtf_out.write( str( exon ) + "\n" )
else:
for exon in IOTools.flatten( gtf ):
def_rejected_out.write( str( exon ) + "\n" )
os.unlink( temp_rejected )
def_rejected_out.close()
rescued_gtf_out.close()
else:
def_rejected = temp_rejected
temp_filtered_out.close()
# sort the outfiles by gene
statement = ( "cat %(temp_filtered)s |"
" python %(scriptsdir)s/gtf2gtf.py"
" --method=sort --sort-order=gene+transcript"
" --log %(filtered_gtf)s.log |"
" gzip"
" > %(filtered_gtf)s;"
" cat %(def_rejected)s |"
" python %(scriptsdir)s/gtf2gtf.py"
" --method=sort --sort-order=gene+transcript"
" --log %(filtered_gtf)s.log |"
" gzip"
" > %(rejected_gtf)s;" )
P.run()
os.unlink( temp_filtered )
os.unlink( def_rejected )
def collateChunks( gtf_chunks, distance ):
"""
Receives an iterator_sorted_chunks object and a specified distance. If the
adjacent chunks are less than specified distance apart, they are returned
as a list in the resulting generator.
"""
# take first interval in generator
last = gtf_chunks.next()
to_join = []
to_join.extend( last )
for gtf in gtf_chunks:
# check distance between adjacent intervals in generator
# NB. last will always be the last element in to_join, regardless of genomic position
dist = gtf[0].start - max([ x.end for x in to_join ])
# if adjacent intervals are on same contig & strand check order
if gtf[0].contig == last[0].contig and gtf[0].strand == last[0].strand:
assert gtf[0].start >= last[0].start, "gene features are not sorted!"
# if adjacent intervals are not suitable for merging, yield list
if gtf[0].contig != last[0].contig or gtf[0].strand != last[0].strand or dist > distance:
yield to_join
to_join = []
# set current interval to last and add to list
last = gtf
to_join.extend( last )
yield to_join
raise StopIteration
def calcIntergenicDist( gtf_chunks, ignore_overlap = False ):
"""
Receives an iterator_sorted_chunks object and calulates the distance between
adjacent chunks... returns as list. When adjacent gene models overlap the
one with the last end co-ordinate is retained if ignore_overlap,
then overlapping intervals are ignored.
"""
# take first interval in generator
last = gtf_chunks.next()
distances = {}
contains = collections.defaultdict( list )
for gtf in gtf_chunks:
# if adjacent intervals are not on the same contig then continue
if gtf[0].contig != last[0].contig or gtf[0].strand != last[0].strand:
last = gtf
continue
# sanity check
assert gtf[0].start >= last[0].start, "gene features are not sorted!"
# check distance between adjacent intervals in generator
dist = gtf[0].start - last[-1].end
# if distance is negative, then check which has largest end co-ordinate
# if gtf is contained within last, write to a dictionary
if dist < 0:
if gtf[-1].end < last[-1].end:
contains[ last[0].gene_id ].append( gtf[0].gene_id )
# print( last[0].gene_id, last[0].start, last[-1].end,
# gtf[0].gene_id, gtf[0].start, gtf[-1].end )
if ignore_overlap:
continue
else:
last = gtf
if ignore_overlap:
continue
distances[ gtf[0].gene_id ] = dist
last = gtf
return distances, contains
def splitGTFOnStrand( gtf_file ):
"""
Splits transcripts on strand, returning two tempfile names
"""
gtf_plus = P.getTempFile( "." )
gtf_minus = P.getTempFile( "." )
for gtf in GTF.transcript_iterator( GTF.iterator( IOTools.openFile( gtf_file ) ) ):
if gtf[0].strand == "+":
for exon in gtf:
gtf_plus.write( str( exon ) + "\n" )
elif gtf[0].strand == "-":
for exon in gtf:
gtf_minus.write( str( exon ) + "\n" )
else:
raise ValueError( "Unrecognised strand"