-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathconservation_intersect.py
executable file
·183 lines (152 loc) · 6.72 KB
/
conservation_intersect.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
#!/usr/bin/env python
from optparse import OptionParser
from bx.intervals.intersection import Interval, IntervalTree
import gzip, glob, os, sys, subprocess
################################################################################
# conservation_intersect.py
#
# Intersect a list of segments (e.g. lincRNAs) in gff format with the multiZ
# blocks and print out the phastCons/PhyloP scores.
#
# Assumes that the gff entries are disjoint which can be accomplished using
# mergeBed.
#
# mergeBed has a little quirk where a 1 bp gff entry will be changed into
# a 2 bp entry, which causes very slight differences between using the '-l'
# option and not.
################################################################################
################################################################################
# main
################################################################################
def main():
usage = 'usage: %prog [options] <gff file>'
parser = OptionParser(usage)
parser.add_option('-b', dest='background_gff', help='GFF file describing valid background sequences [Default: %default] NOT IMPLEMENTED')
parser.add_option('-l', dest='lncrna', action='store_true', default=False, help='Use the lncRNA specific phastcons file to speed things up [Default: %default]')
parser.add_option('-c', dest='conservation_type', default='phylop', help='Conservation type to use [phastcons|phylop] [Default: %default]')
(options,args) = parser.parse_args()
if len(args) != 1:
parser.error('Must provide gff file to intersect')
gff_file = args[0]
cons_dir = '%s/research/common/data/%s' % (os.environ['HOME'],options.conservation_type)
if not os.path.isdir(cons_dir):
parser.error('Must specify conservation type as "phylop" or "phastcons"')
# build interval trees
print >> sys.stderr, 'Building interval trees ...',
chr_features = {}
p = subprocess.Popen('sortBed -i %s | mergeBed -i -' % gff_file, shell=True, stdout=subprocess.PIPE)
for line in p.stdout:
a = line.split('\t')
chr_features.setdefault(a[0], IntervalTree()).insert_interval( Interval(int(a[1])+1,int(a[2])) )
p.communicate()
print >> sys.stderr, 'Done'
# build background interval trees
if options.background_gff:
chr_features_bg = sample_background_intervals(gff_file, options.background_gff)
# process overlapping chromosome blocks
if options.lncrna:
lnc_files = glob.glob('%s/lnc_catalog.*wigFix.gz' % cons_dir)
if len(lnc_files) != 1:
print >> sys.stderr, 'Ambiguous lnc catalog file'
exit(1)
else:
process_file(chr_features, lnc_files[0])
else:
for pc_file in glob.glob('%s/chr*' % cons_dir):
process_file(chr_features, pc_file)
################################################################################
# intersect_scores
#
# Print out block scores overlapping features.
################################################################################
def intersect_scores(features, block_start, block_scores):
block_end = block_start+len(block_scores)-1
for overlap_interval in features.find(block_start, block_start+len(block_scores)):
# block internal to invterval
if overlap_interval.start <= block_start <= block_end <= overlap_interval.end:
start = 0
end = len(block_scores)
# interval internal to block
elif block_start <= overlap_interval.start <= overlap_interval.end <= block_end:
start = overlap_interval.start - block_start
end = start + overlap_interval.end - overlap_interval.start + 1
# left block overlap interval
elif block_start < overlap_interval.start:
start = overlap_interval.start - block_start
end = start + block_end - overlap_interval.start + 1
# right block overlap interval
else:
start = 0
end = overlap_interval.end - block_start + 1
#start = overlap_interval.start - block_start
#end = start + overlap_interval.end - overlap_interval.start
print '\n'.join([str(s) for s in block_scores[start:end]])
################################################################################
# process_file
#
# Process overlapping chromosome blocks in the given file.
################################################################################
def process_file(chr_features, pc_file):
if pc_file[-2:] == 'gz':
pc_f = gzip.open(pc_file)
elif os.path.isfile(pc_file):
pc_f = open(pc_file)
elif os.path.isfile(pc_file+'.gz'):
pc_f = gzip.open(pc_file+'.gz')
chrom = os.path.split(pc_file)[1].split('.')[0]
print >> sys.stderr, 'Processing %s ...' % chrom,
block_start = 0
block_scores = []
line = pc_f.readline()
while line:
if line.startswith('fixedStep'):
if block_scores:
intersect_scores(chr_features.get(chrom, IntervalTree()), block_start, block_scores)
a = line.split()
chrom = a[1][6:]
block_start = int(a[2][6:])
block_scores = []
else:
block_scores.append(float(line.rstrip()))
line = pc_f.readline()
intersect_scores(chr_features.get(chrom, IntervalTree()), block_start, block_scores)
pc_f.close()
print >> sys.stderr, 'Done'
################################################################################
# sample_background_intervals
#
# Simulate many datasets of the same size and length distribution from the
# background sequence specificed.
#
# Input
# feature_gff: GFF file of features.
# background_gff: GFF file of background sequences from which to simulate
# features.
#
# Output
# ???
################################################################################
def sample_background_intervals(feature_gff, background_gff):
# determine length distributions
feature_lengths = {}
for line in open(feature_gff):
a = line.split('\t')
flen = int(a[4]) - int(a[3]) + 1
feature_lengths[flen] = feature_lengths.get(flen,0) + 1
# merge background gff
background_intervals = []
p = subprocess.Popen('sortBed -i %s | mergeBed -i -' % background_gff, shell=True, stdout=subprocess.PIPE)
for line in p.stdout:
a = line.split('\t')
chrom = a[0]
start = int(a[1])
end = int(a[2])
# convert to gff
background_intervals.append((chrom,start+1,end))
# sample
chr_features_bg = {}
################################################################################
# __main__
################################################################################
if __name__ == '__main__':
main()