/
ip_gene.py
executable file
·356 lines (294 loc) · 12.7 KB
/
ip_gene.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
#!/usr/bin/env python
__author__ = 'Luis Cunha'
import sys
import os
sys.path.append(os.path.abspath("bin"))
from bx.intervals.intersection import IntervalTree
import time
import cPickle as pickle
import random
import collections
from multiprocessing import Pool
import readIntervals as ri
import json
import argparse
import pprint
pp = pprint.PrettyPrinter(indent=4)
"""
Perform Monte Carlo simulation to permutate a list of genomic segments and calculate the proportion of intervals
overlapping the same gene.
Input:
number of steps;
segments file in bed format must be present in the data folder
Output:
file with the result of each simulation per line
result as json describing occurrence or not (1 / 0) of each number of overlaps
e.g: observed 5, 6, 7, 9, 11 overlaps {0:0, 1:0, 2:0, 3:0, 4:0, 5:1, 6:1, 7:1, 8:0, 9:1, 10:0, 11:1, 12:0}
Usage:
intervalpermutation -n <number of steps> -o <output file>
"""
#Globals
EXOME_ARRAY_LENGTH = 74494878 - 1 # length of the gene position array. Value used to generate random number in this range
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
REFSEQ_POSITIONS_ARRAY = BASE_DIR + "/data/positionArrayRefSeq_chrsizeX.bed"
REFSEQ_GENES_BEDFILE = BASE_DIR + "/data/refseq_genes.bed"
REFSEQ_POSITION_ARRAY = "positionArrayRefSeqX.p"
CHRM_SIZE_REFSEQ_POSITION_ARRAY = "positionArrayRefSeq_chrsizeX.p"
COUNT_SHUFFLE = {} #keeps track of the distribution of random permutations per chromosome
COUNT = {}
class IntervalTreeDict(object):
"""Build an Interval Tree data structure of gene position ranges
"""
def __init__(self, bed_file):
"""
:param bed_file:
:return interval tree data structure of gene ranges:
"""
self.interval_tree_dict = dict()
error_message = "Skipping line {0} too short with only {1} column(s).Check that it conforms to bed format:\n{2}"
with open(bed_file, 'r') as bed_file_Handler:
for count, line in enumerate(bed_file_Handler):
segmentProperties = line.split("\t")
numberOfColumns = len(segmentProperties)
try:
chromosome, segment_start, segment_end, name = segmentProperties[:4]
except ValueError:
print error_message.format(count + 1, numberOfColumns, line.strip())
continue
segment_start, segment_end = int(segment_start), int(segment_end)
if chromosome in self.interval_tree_dict:
tree = self.interval_tree_dict[chromosome]
else:
tree = IntervalTree()
self.interval_tree_dict[chromosome] = tree
tree.add(segment_start, segment_end, tuple(segmentProperties[:4]))
def find(self, chromosome, start, end):
return self.interval_tree_dict[chromosome].find(start, end)
class InitializeIntervals:
"""Read:
- the RefSeq gene position and gene size arrays from disk to be used on each simulation step
- the dictionary of intervals of all individuals, from the pickle file on disk. If the file does not exits,
- all intervals file. Pickle dump it to disk to be used in subsequent runs. If file not exist (first time usage)
call the readIntervals module (in the bin subdirectory) and process individual interval files into a single file.
"""
def __init__(self):
try:
self.positionArray = pickle.load(open(BASE_DIR + '/data/'+ REFSEQ_POSITION_ARRAY, 'rb'))
self.chrArray = pickle.load(open(BASE_DIR + '/data/' + CHRM_SIZE_REFSEQ_POSITION_ARRAY, 'rb'))
self.individuals = self.load_intervals_all_individuals()
except:
print "failed loading required files RefSeq Array, Chr Array, or individual intervals"
sys.exit(0)
def load_intervals_all_individuals(self):
"""
:return all interval dictionary:
"""
if not os.path.isfile(BASE_DIR + "/data/allintervals.p"):
if not os.path.exists("data"):
os.makedirs("data")
readIntervals = ri.readIntervals()
individual = readIntervals.readIntervals()
intervals = {}
for id in individual:
intervals[id] = []
with open(BASE_DIR + "/data/" + id + ".id.bed", "r") as bef_file_handler:
lines = bef_file_handler.readlines()
for line in lines:
l = line.split()
intervals[id].append({l[0]: int(l[2]) - int(l[1])})
pickle.dump(intervals, open(BASE_DIR + "/data/allintervals.p", "wb"))
return intervals
else:
return pickle.load(open("data/allintervals.p", "rb"))
@property
def position_array(self):
return self.positionArray
@property
def chr_array(self):
return self.chrArray
@property
def _individuals(self):
return self.individuals
def find_chr_from_array_position(position):
"""
:param position:
:return chromosome:
>>> find_chr_from_array_position(46968736)
12
"""
result = refSeq_chromosome_tree.find("1", position, position)
try:
chromosome = int(result[0][3].strip())
print "1", position, chromosome
return chromosome
except KeyError:
print "Position out of range: ", position
return 0
def test_shuffled_interval_overlap(intervals):
"""Test that the shuffled intervals do not overlap each other
If there is a single overlap, discard this while shuffle step and redo
(discarding only this interval would introduce a bias in the probability of the position and it would not be a
purely random shuffle)
:param intervals:
:return: True if no overlap, False if overlap
>>> test_shuffled_interval_overlap({50968446: 67782986})
True
"""
print "testing"
print intervals
results = {}
for interval in intervals.values()[0]:
try:
chromosome = interval[0]
if chromosome not in results:
results[chromosome] = {}
results[chromosome][interval[1]] = interval[2]
except:
pass #Do not interrupt due to any exception. Continue to the next interval
for chromosome in results:
intervals = results[chromosome]
ordered_intervals = collections.OrderedDict(sorted(intervals.items()))
starts=[]
ends=[]
#print "od", ordered_intervals
[(starts.append(start_), ends.append(end_)) for start_, end_ in ordered_intervals.items()]
for x in range(0, len(starts)-1):
if int(starts[x+1])<int(ends[x]):
print "reject", starts, ends
return False
print "accept", starts, ends
print intervals
return True
def shuffle(individual_intervals):
"""Shuffle the position of every interval:
- picks a random position along the length of the Positions Array
- gets the exome coordinate from this position. Note that intervals are only allowed to be shuffled into coding
regions of the exome. Specifically, those regions covered by the capture probes
- intervals of each individual are shuffled together, with each individual shuffled in parallel in a separate
thread
individual_intervals format: {indID:[{chr:length}, {chr:length}]}
:param individual_intervals:
:return shuffled intervals:
"""
print "running parallel process"
random.seed() #set seed on each thread to avoid same random number generation on the threads
time.sleep(random.randint(0, 9))
intervals = {individual_intervals[0]: []}
for interval in individual_intervals[1]:
randomPosition = random.randint(0, EXOME_ARRAY_LENGTH)
start = positionArray[randomPosition]
end = start + int(interval.values()[0]) #length
chromosome = find_chr_from_array_position(randomPosition)
intervals[individual_intervals[0]].append((chromosome, start, end))
if chromosome not in COUNT_SHUFFLE: COUNT_SHUFFLE[chromosome] = 0
COUNT_SHUFFLE[chromosome] += 1
if test_shuffled_interval_overlap(intervals) == True: #if segments do not overlap
"""log the distribution of random intervals"""
with open(BASE_DIR + "/tmp/shuffled_intervals.json", "a") as outfile:
json.dump(intervals, outfile)
outfile.write("\n")
return intervals
else:
shuffle(individual_intervals)
def start_shuffle(output_file,np):
"""Initiate parallel threads for interval shuffling phase
:param output_file:
:return 0:
"""
index=0
starttime = time.time()
individualIntervals = allIndividuals.items()
try:
print "starting parallel shuffle..."
pool = Pool(np)
results = pool.map(shuffle, individualIntervals)
print "pool finished\n"
print str(results)
pool.close()
pool.join()
except:
os.nice(100)
pass
else:
print "bbb"
print "finished shuffling phase. Starting overlap analysis"
elapsedtime = time.time() - starttime
reads = {}
persons_reads = {}
for result in results:
for y in result.values()[0]:
id = str(index)
reads[id] = [str(y[0]), str(y[1]), str(y[2]), str(result.keys()[0])]
if str(result.keys()[0]) not in persons_reads: persons_reads[str(result.keys()[0])] = []
persons_reads[str(result.keys()[0])].append(id)
index += 1
"""Dictionary to keep track of occurrence of each number of overlaps: 0/1 (no/yes)"""
local_overall_overlaps = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0,
13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0}
"""for each interval, of each individual, get the genes in this region from the tree representation of refseq
genes(refseq_gene_tree) and build a dictionary of gene:[list of intervals covering this gene]
finally COUNT the number of intervals covering the gene. This is in number of intervals overlaping a gene
"""
genes = {}
for read in reads:
l = reads[read]
print l
a = refseq_gene_tree.interval_tree(l[0], int(l[1]), int(l[2]))
for result in a:
b = result[3][:-1]
if b not in genes:
genes[b] = []
genes[b].append(l[3])
for result in genes:
if len(genes[result]) > 1:
if (len(genes[result])) not in local_overall_overlaps:
local_overall_overlaps[len(genes[result])] = 0
if local_overall_overlaps[len(genes[result])] == 0:
local_overall_overlaps[len(genes[result])] = 1
with open(output_file, 'a') as outfile:
json.dump(local_overall_overlaps, outfile)
outfile.write("\n")
print "Finished in {0:.1f}".format(elapsedtime) + " s"
return 0
"""load global arrays and intervals"""
refSeq_chromosome_tree = IntervalTreeDict(REFSEQ_POSITIONS_ARRAY)
refseq_gene_tree = IntervalTreeDict(REFSEQ_GENES_BEDFILE)
#load required files(arrays, intervals)
try:
print "Loading Individuals, positionsArray, and chromosomeArray"
initialize = InitializeIntervals()
allIndividuals = initialize._individuals
positionArray = initialize.positionArray
chrArray = initialize.chrArray
except:
print "failed initialization"
sys.exit(0)
def usage():
print "shuffle python shuffle5.py -n <number of steps> -o <output file>"
sys.exit(0)
def main():
parser = argparse.ArgumentParser(
description='Monte Carlo simulation to permutate genomic intervals and calculate the proportion of segments overlapping the same gene')
parser.add_argument('-o', '--output', help='output file')
parser.add_argument('-v', dest='verbose', action='store_true')
parser.add_argument('-nRuns', '--numberRuns', help='number of simulation steps')
parser.add_argument('-np', '--n_processors', help="number of threads")
args = parser.parse_args()
nRuns = int(args.numberRuns)
np = int(args.n_processors)
output = BASE_DIR + "/result/" + args.output
print "Starting...\n"
while nRuns > 0:
try:
print "Iteration " + str(nRuns)
start_shuffle(output, np)
print "finished iteration " + str(nRuns) + "\n"
nRuns -= 1
except: #If any exception occurs, continue with next step of simulation
time.sleep(1)
print "exception raised"
start_shuffle(output)
if __name__ == "__main__":
import doctest
print doctest.testmod()
main()