-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathalefuncs.py
executable file
·2515 lines (2179 loc) · 78.5 KB
/
alefuncs.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
### This is a collection of functions and classes I wrote during my postdoc at the UMCU
### The following code is meant to be compatible with Python 2.7 and 3.x (minor modifications may be needed in case of Python 3)
### If you use Python 2.7 please include "from __future__ import division, pint_function" to your script
### The imports are included in the functions' body for clarity.
### If you need to call a function over and over then consider to move the imports at the beginning of your script.
### This collection is meant to be used by "copy/paste" not as a module (mostly due to the imports),
### altough you can use "from alefuncs import something", "from alefuncs import *", and "import alefuncs as ale", without problems.
### author: [email protected]
### version: 2017_02
def print_sbar(n,m,s='|#.|',size=30,message=''):
'''(int,int,string,int) => None
Print a progress bar using the simbols in 's'.
Example:
range_limit = 1000
for n in range(range_limit):
print_sbar(n,m=range_limit)
time.sleep(0.1)
'''
import sys
#adjust to bar size
if m != size:
n =(n*size)/m
m = size
#calculate ticks
_a = int(n)*s[1]+(int(m)-int(n))*s[2]
_b = round(n/(int(m))*100,1)
#adjust overflow
if _b >= 100:
_b = 100.0
#to stdout
sys.stdout.write('\r{}{}{}{} {}% '.format(message,s[0],_a,s[3],_b))
sys.stdout.flush()
def hash(a_string,algorithm='md5'):
'''str => str
Return the hash of a string calculated using various algorithms.
Example:
>>> hash('prova','md5')
'189bbbb00c5f1fb7fba9ad9285f193d1'
>>> hash('prova','sha256')
'6258a5e0eb772911d4f92be5b5db0e14511edbe01d1d0ddd1d5a2cb9db9a56ba'
'''
import hashlib
if algorithm == 'md5':
return hashlib.md5(a_string.encode()).hexdigest()
elif algorithm == 'sha256':
return hashlib.sha256(a_string.encode()).hexdigest()
else:
raise ValueError('algorithm {} not found'.format(algorithm))
def get_first_transcript_by_gene_name(gene_name):
'''str => str
Return the id of the main trascript for a given gene.
The data is from http://grch37.ensembl.org/
'''
from urllib import urlopen
from pyensembl import EnsemblRelease
data = EnsemblRelease(75)
gene = data.genes_by_name(gene_name)
gene_id = str(gene[0]).split(',')[0].split('=')[-1]
gene_location = str(gene[0]).split('=')[-1].strip(')')
url = 'http://grch37.ensembl.org/Homo_sapiens/Gene/Summary?db=core;g={};r={}'.format(gene_id,gene_location)
for line in urlopen(url):
if '<tbody><tr><td class="bold">' in line:
return line.split('">')[2].split('</a>')[0]
def get_exons_coord_by_gene_name(gene_name):
'''str => OrderedDict({'exon_id':[coordinates]})
Return an OrderedDict having as k the exon_id
and as value a tuple containing the genomic coordinates ('chr',start,stop).
Example:
'''
from pyensembl import EnsemblRelease
gene = data.genes_by_name(gene_name)
gene_id = str(gene[0]).split(',')[0].split('=')[-1]
gene_location = str(gene[0]).split('=')[-1].strip(')')
gene_transcript = get_first_transcript_by_gene_name(gene_name).split('.')[0]
table = OrderedDict()
for exon_id in data.exon_ids_of_gene_id(gene_id):
exon = data.exon_by_id(exon_id)
coordinates = (exon.contig, exon.start, exon.end)
table.update({exon_id:coordinates})
return table
class Render(QWebPage):
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
def get_html(str_url):
'''url => html
Return a PyQt4-rendered html page.
It requires the Render class'''
r_html = Render(str_url)
html = r_html.frame.toHtml()
return html
def get_exons_coord_by_gene_name(gene_name):
'''
Example:
table = get_exons_coord_by_gene_name('TP53')
for k,v in table.iteritems():
print k,v
>>> ENSE00002419584 ['7,579,721', '7,579,700']
ENSE00003625790 ['7,579,590', '7,579,312']
ENSE00003518480 ['7,578,554', '7,578,371']
ENSE00003462942 ['7,578,289', '7,578,177']
ENSE00003504863 ['7,577,608', '7,577,499']
ENSE00003586720 ['7,577,155', '7,577,019']
ENSE00003636029 ['7,576,926', '7,576,853']
ENSE00003634848 ['7,574,033', '7,573,927']
ENSE00002667911 ['7,579,940', '7,579,839']
ENSE00002051192 ['7,590,799', '7,590,695']
ENSE00002034209 ['7,573,008', '7,571,722']
ENSE00003552110 ['7,576,657', '7,576,525']
'''
from collections import OrderedDict
from pyensembl import EnsemblRelease
data = EnsemblRelease(75)
gene = data.genes_by_name(gene_name)
gene_id = str(gene[0]).split(',')[0].split('=')[-1]
gene_location = str(gene[0]).split('=')[-1].strip(')')
gene_transcript = get_first_transcript_by_gene_name(gene_name).split('.')[0]
url = 'http://grch37.ensembl.org/Homo_sapiens/Transcript/Exons?db=core;g={};r={};t={}'.format(gene_id,gene_location,gene_transcript)
str_html = get_html(url)
html = ''
for line in str_html.split('\n'):
try:
#print line
html += str(line)+'\n'
except UnicodeEncodeError:
pass
blocks = html.split('\n')
table = OrderedDict()
for exon_id in data.exon_ids_of_gene_id(gene_id):
for i,txt in enumerate(blocks):
if exon_id in txt:
if exon_id not in table:
table.update({exon_id:[]})
for item in txt.split('<td style="width:10%;text-align:left">')[1:-1]:
table[exon_id].append(item.split('</td>')[0])
return table
def split_overlap(array,size,overlap):
'''(list,int,int) => [[...],[...],...]
Split a list into chunks of a specific size and overlap.
Examples:
array = list(range(10))
split_overlap(array,4,2)
>>> [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [6, 7, 8, 9]]
array = list(range(11))
split_overlap(array,4,2)
>>> [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [6, 7, 8, 9], [8, 9, 10]]
'''
result = []
while True:
if len(array) <= size:
result.append(array)
return result
else:
result.append(array[:size])
array = array[size-overlap:]
def reorder_dict(d,keys):
'''(dict,list) => OrderedDict
Change the order of a dictionary's keys
without copying the dictionary (save RAM!).
Return an OrderedDict.
'''
tmp = OrderedDict()
for k in keys:
tmp[k] = d[k]
del d[k] #this saves RAM
return tmp
#test = OrderedDict({'1':1,'2':2,'4':4,'3':3})
#print(test)
#test2 = reorder_dict(test,['1','2','3','4'])
#print(test)
#print(test2)
#>>> OrderedDict([('2', 2), ('3', 3), ('4', 4), ('1', 1)])
#>>> OrderedDict()
#>>> OrderedDict([('1', 1), ('2', 2), ('3', 3), ('4', 4)])
def in_between(one_number,two_numbers):
'''(int,list) => bool
Return true if a number is in between two other numbers.
Return False otherwise.
'''
if two_numbers[0] < two_numbers[1]:
pass
else:
two_numbers = sorted(two_numbers)
return two_numbers[0] <= one_number <= two_numbers[1]
def is_overlapping(svA,svB,limit=0.9):
'''(list,list,float) => bool
Check if two SV ovelaps for at least 90% (limit=0.9).
svX = [chr1,brk1,chr2,brk2]
'''
# Step 1.
# Select the breaks in order to have lower coordinates first
if int(svA[1]) <= int(svA[3]):
chr1_A = svA[0]
brk1_A = int(svA[1])
chr2_A = svA[2]
brk2_A = int(svA[3])
else:
chr2_A = svA[0]
brk2_A = svA[1]
chr1_A = svA[2]
brk1_A = svA[3]
if int(svB[1]) <= int(svB[3]):
chr1_B = svB[0]
brk1_B = int(svB[1])
chr2_B = svB[2]
brk2_B = int(svB[3])
else:
chr2_B = svB[0]
brk2_B = int(svB[1])
chr1_B = svB[2]
brk1_B = int(svB[3])
# Step 2.
# Determine who is the longest
# Return False immediately if the chromosomes are not the same.
# This computation is reasonable only for sv on the same chormosome.
if chr1_A == chr2_A and chr1_B == chr2_B and chr1_A == chr1_B:
len_A = brk2_A - brk1_A
len_B = brk2_B - brk1_B
if len_A >= len_B:
len_reference = len_A
len_sample = len_B
else:
len_reference = len_B
len_sample = len_A
limit = round(len_reference * limit) # this is the minimum overlap the two sv need to share
# to be considered overlapping
# if the sample is smaller then the limit then there is no need to go further.
# the sample segment will never share enough similarity with the reference.
if len_sample < limit:
return False
else:
return False
# Step 3.
# Determine if there is an overlap
# >> There is an overlap if a least one of the break of an sv is in beetween the two breals of the other sv.
overlapping = False
for b in [brk1_A,brk2_A]:
if in_between(b,[brk1_B,brk2_B]):
overlapping = True
for b in [brk1_B,brk2_B]:
if in_between(b,[brk1_A,brk2_A]):
overlapping = True
if not overlapping:
return False
# Step 4.
# Determine the lenght of the ovelapping part
# easy case: if the points are all different then, if I sort the points,
# the overlap is the region between points[1] and points[2]
# |-----------------| |---------------------|
# |--------------| |-------------|
points = sorted([brk1_A,brk2_A,brk1_B,brk2_B])
if len(set(points)) == 4: # the points are all different
overlap = points[2]-points[1]
elif len(set(points)) == 3: #one point is in common
# |-----------------|
# |--------------|
if points[0] == points[1]:
overlap = points[3]-points[2]
# |---------------------|
# |-------------|
if points[2] == points[3]:
overlap = points[2]-points[1]
# |-----------------|
# |-------------|
if points[1] == points[2]:
return False # there is no overlap
else:
# |-----------------|
# |-----------------|
return True # if two points are in common, then it is the very same sv
if overlap >= limit:
return True
else:
return False
def load_obj(file):
'''
Load a pickled object.
Be aware that pickle is version dependent,
i.e. objects dumped in Py3 cannot be loaded with Py2.
'''
import pickle
try:
with open(file,'rb') as f:
obj = pickle.load(f)
return obj
except:
return False
def save_obj(obj, file):
'''
Dump an object with pickle.
Be aware that pickle is version dependent,
i.e. objects dumped in Py3 cannot be loaded with Py2.
'''
import pickle
try:
with open(file,'wb') as f:
pickle.dump(obj, f)
print('Object saved to {}'.format(file))
return True
except:
print('Error: Object not saved...')
return False
#save_obj(hotspots_review,'hotspots_review_CIS.txt')
def query_encode(chromosome, start, end):
'''
Queries ENCODE via http://promoter.bx.psu.edu/ENCODE/search_human.php
Parses the output and returns a dictionary of CIS elements found and the relative location.
'''
## Regex setup
re1='(chr{})'.format(chromosome) # The specific chromosome
re2='(:)' # Any Single Character ':'
re3='(\\d+)' # Integer
re4='(-)' # Any Single Character '-'
re5='(\\d+)' # Integer
rg = re.compile(re1+re2+re3+re4+re5,re.IGNORECASE|re.DOTALL)
## Query ENCODE
std_link = 'http://promoter.bx.psu.edu/ENCODE/get_human_cis_region.php?assembly=hg19&'
query = std_link + 'chr=chr{}&start={}&end={}'.format(chromosome,start,end)
print(query)
html_doc = urlopen(query)
html_txt = BeautifulSoup(html_doc, 'html.parser').get_text()
data = html_txt.split('\n')
## Parse the output
parsed = {}
coordinates = [i for i, item_ in enumerate(data) if item_.strip() == 'Coordinate']
elements = [data[i-2].split(' ')[-1].replace(': ','') for i in coordinates]
blocks = [item for item in data if item[:3] == 'chr']
print(elements)
try:
i = 0
for item in elements:
#print(i)
try:
txt = blocks[i]
#print(txt)
m = rg.findall(txt)
bins = [''.join(item) for item in m]
parsed.update({item:bins})
i += 1
print('found {}'.format(item))
except:
print('the field {} was empty'.format(item))
return parsed
except Exception as e:
print('ENCODE query falied on chr{}:{}-{}'.format(chromosome, start, end))
print(e)
return False
def compare(dict_A,dict_B):
'''(dict,dict) => dict, dict, dict
Compares two dicts of bins.
Returns the shared elements, the unique elements of A and the unique elements of B.
The dicts shape is supposed to be like this:
OrderedDict([('1',
['23280000-23290000',
'24390000-24400000',
...]),
('2',
['15970000-15980000',
'16020000-16030000',
...]),
('3',
['610000-620000',
'3250000-3260000',
'6850000-6860000',
...])}
'''
chrms = [str(x) for x in range(1,23)] + ['X','Y']
shared = OrderedDict()
unique_A = OrderedDict()
unique_B = OrderedDict()
for k in chrms:
shared.update({k:[]})
unique_A.update({k:[]})
unique_B.update({k:[]})
if k in dict_A and k in dict_B:
for bin_ in dict_A[k]:
if bin_ in dict_B[k]:
shared[k].append(bin_)
else:
unique_A[k].append(bin_)
for bin_ in dict_B[k]:
if bin_ not in shared[k]:
unique_B[k].append(bin_)
elif k not in dict_A:
unique_B[k] = [bin_ for bin_ in dict_B[k]]
elif k not in dict_B:
unique_A[k] = [bin_ for bin_ in dict_A[k]]
return shared, unique_A, unique_B
#To manage heavy files
def yield_file(infile):
with open(infile, 'r') as f:
for line in f:
if line[0] not in ['#','\n',' ','']:
yield line.strip()
#Downaload sequence from ensembl
def sequence_from_coordinates(chromosome,strand,start,end,account="[email protected]"):
'''
Download the nucleotide sequence from the gene_name.
This function works only with with GRCh37.
Inputs can be str or int e.g. 1 or '1'
'''
from Bio import Entrez, SeqIO
Entrez.email = account # Always tell NCBI who you are
#GRCh37 from http://www.ncbi.nlm.nih.gov/assembly/GCF_000001405.25/#/def_asm_Primary_Assembly
NCBI_IDS = {'1':'NC_000001.10','2':'NC_000002.11','3':'NC_000003.11','4':'NC_000004.11',
'5':'NC_000005.9','6':'NC_000006.11','7':'NC_000007.13','8':'NC_000008.10',
'9':'NC_000009.11','10':'NC_000010.10','11':'NC_000011.9','12':'NC_000012.11',
'13':'NC_000013.10','14':'NC_000014.8','15':'NC_000015.9','16':'NC_000016.9',
'17':'NC_000017.10','18':'NC_000018.9','19':'NC_000019.9','20':'NC_000020.10',
'21':'NC_000021.8','22':'NC_000022.10','X':'NC_000023.10','Y':'NC_000024.9'}
try:
handle = Entrez.efetch(db="nucleotide",
id=NCBI_IDS[str(chromosome)],
rettype="fasta",
strand=strand, #"1" for the plus strand and "2" for the minus strand.
seq_start=start,
seq_stop=end)
record = SeqIO.read(handle, "fasta")
handle.close()
sequence = str(record.seq)
return sequence
except ValueError:
print('ValueError: no sequence found in NCBI')
return False
#GC content calculator
def gc_content(sequence,percent=True):
'''
Return the GC content of a sequence.
'''
sequence = sequence.upper()
g = sequence.count("G")
c = sequence.count("C")
t = sequence.count("T")
a = sequence.count("A")
gc_count = g+c
total_bases_count = g+c+t+a
if total_bases_count == 0:
print('Error in gc_content(sequence): sequence may contain only Ns')
return None
try:
gc_fraction = float(gc_count) / total_bases_count
except Exception as e:
print(e)
print(sequence)
if percent:
return gc_fraction * 100
else:
return gc_fraction
##Flexibility calculator##
#requires stabflex3.py
#result handler
class myResultHandler(SFResult):
def report(self,verbose=True):
self.result = []
if verbose:
print("# data description : {}".format(self.description))
print("# window size : {}".format(self.size))
print("# window step : {}".format(self.step))
for i in range(len(self.x)):
self.result.append(('{}-{}'.format(round(self.x[i]-self.size/2),
round(self.x[i]+self.size/2)),
round(self.y[i],2)))
if verbose:
print("# bins examined : {}".format(len(self.result)))
print("# max flexibility : {}".format(max([v for i,v in self.result])))
return self.result
#main algorithm
class myFlex(SFAlgorithm): #in line version of the pyflex3.py main class
def __init__(self, sequence, window_size, step_zize):
self.size = window_size
self.step = step_zize
self.seq = sequence
def analyse(self, data, verbose=False):
seq = self.seq
length = len(seq)
if verbose:
print("Using {} data from {}".format(data.description, data.source))
print("Running ...")
# start timer
start = time.clock()
offset = self.size/2
i = 0
x = array.array('f')
y = array.array('f')
finished = False
while not finished:
try:
sum = 0
for j in range(self.size):
a = seq[i + j]
b = seq[i + j + 1]
sum += data.get(a,b)
x.append(offset + i)
y.append(sum / self.size)
i += self.step
except IndexError:
finished = True
# stop timer
end = time.clock()
elapsed = end - start
if verbose:
print("Finished, elapsed time {} seconds ({} bases/sec)".format(round(elapsed,2),length/elapsed))
return myResultHandler(self.seq, data, x, y, self.step, self.size,
description = data.description,
label = data.label,
source = data.source)
#Endpoint function to calculate the flexibility of a given sequence
def dna_flex(sequence,window_size=500,step_zize=100,verbose=False):
'''(str,int,int,bool) => list_of_tuples
Calculate the flexibility index of a sequence.
Return a list of tuples.
Each tuple contains the bin's coordinates
and the calculated flexibility of that bin.
Example:
dna_flex(seq_a,500,100)
>>> [('0-500', 9.7),('100-600', 9.77),...]
'''
if verbose:
print("Algorithm window size : %d" % window_size)
print("Algorithm window step : %d" % step_zize)
print("Sequence has {} bases".format(len(self.seq)))
algorithm = myFlex(sequence,window_size,step_zize)
flexibility_result = algorithm.analyse(flexibility_data)
return flexibility_result.report(verbose)
##Repeats scanner##
#G-quadruplex
def g4_scanner(sequence):
'''
G-quadruplex motif scanner.
Scan a sequence for the presence of the regex motif:
[G]{3,5}[ACGT]{1,7}[G]{3,5}[ACGT]{1,7}[G]{3,5}[ACGT]{1,7}[G]{3,5}
Reference: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1636468/
Return two callable iterators.
The first one contains G4 found on the + strand.
The second contains the complementary G4 found on the + strand, i.e. a G4 in the - strand.
'''
#forward G4
pattern_f = '[G]{3,5}[ACGT]{1,7}[G]{3,5}[ACGT]{1,7}[G]{3,5}[ACGT]{1,7}[G]{3,5}'
result_f = re.finditer(pattern_f, sequence)
#reverse G4
pattern_r = '[C]{3,5}[ACGT]{1,7}[C]{3,5}[ACGT]{1,7}[C]{3,5}[ACGT]{1,7}[C]{3,5}'
result_r = re.finditer(pattern_r, sequence)
return result_f, result_r
#Repeat-masker
def parse_RepeatMasker(infile="RepeatMasker.txt",rep_type='class'):
'''
Parse RepeatMasker.txt and return a dict of bins for each chromosome
and a set of repeats found on that bin.
dict = {'chromosome':{'bin':set(repeats)}}
'''
chromosomes = [str(c) for c in range(1,23)]+['X','Y']
result = {}
if rep_type == 'name':
idx = 10 #repName
elif rep_type == 'class':
idx = 11 #repClass
elif rep_type == 'family':
idx = 12 #repFamily
else:
raise NameError('Invalid rep_type "{}". Expected "class","family" or "name"'.format(rep_type))
#RepeatMasker.txt is around 500MB!
for line in yield_file(infile):
data = line.split('\t')
chromosome = data[5].replace('chr','')
start = data[6]
end = data[7]
bin_ = '{}-{}'.format(start,end)
repeat = data[idx].replace('?','')
if chromosome in chromosomes:
if chromosome not in result:
result.update({chromosome:{bin_:set([repeat])}})
else:
if bin_ not in result[chromosome]:
result[chromosome].update({bin_:set([repeat])})
else:
result[chromosome][bin_].add(repeat)
return result
with open(hotspots_by_threshold,'rb') as f:
hotspots_A = pickle.load(f)
if type(hotspots_A) == list:
tmp = OrderedDict()
for c,h,t in hotspots_A:
if c not in tmp:
tmp.update({c:[h]})
else:
tmp[c] += [h]
hotspots_A = tmp
print(len(hotspots_A)) # 24
with open(hotspots_top5percent,'rb') as f:
hotspots_B = pickle.load(f)
print(len(hotspots_B)) # 23 since 1000G does not have chrY
def next_day(d='2012-12-04'):
'''Return the next day in the calendar.'''
Y,M,D = d.split('-')
t = datetime.date(int(Y),int(M),int(D))
_next = t + datetime.timedelta(1)
return str(_next)
# next_day('2012-12-31')
# >>> '2013-01-01'
def previous_day(d='2012-12-04'):
'''Return the previous day in the calendar.'''
Y,M,D = d.split('-')
t = datetime.date(int(Y),int(M),int(D))
_prev = t + datetime.timedelta(-1)
return str(_prev)
# previous_day('2013-01-01')
# >>> '2012-12-31'
def intersect(list1,list2):
'''(list,list) => list
Return the intersection of two lists, i.e. the item in common.
'''
return [item for item in list2 if item in list1]
def annotate_fusion_genes(dataset_file):
'''
Uses FusionGenes_Annotation.pl to find fusion genes in the dataset.
Generates a new file containing all the annotations.
'''
import time
start = time.time()
print('annotating', dataset_file, '...')
raw_output = run_perl('FusionGenes_Annotation.pl', dataset_file)
raw_list = str(raw_output)[2:].split('\\n')
outfile = dataset_file[:-4] + '_annotated.txt'
with open(outfile, 'w') as outfile:
line_counter = 0
header = ['##ID', 'ChrA', 'StartA', 'EndA', 'ChrB', 'StartB', 'EndB', 'CnvType', 'Orientation',
'GeneA', 'StrandA', 'LastExonA', 'TotalExonsA', 'PhaseA',
'GeneB', 'StrandB', 'LastExonB', 'TotalExonsB', 'PhaseB',
'InFrame', 'InPhase']
outfile.write(list_to_line(header, '\t') + '\n')
for item in raw_list:
cleaned_item = item.split('\\t')
if len(cleaned_item) > 10: # FusionGenes_Annotation.pl return the data twice. We kepp the annotated one.
outfile.write(list_to_line(cleaned_item, '\t') + '\n')
line_counter += 1
print('succesfully annotated',line_counter, 'breakpoints from', dataset_file, 'in', time.time()-start, 'seconds')
# track threads
try:
global running_threads
running_threads -= 1
except:
pass
# dataset_file = '/home/amarcozz/Documents/Projects/Fusion Genes/Scripts/test_datasets/public/breaks/Decipher-DeletionsOnly.txt'
# annotate_fusion_genes(dataset_file)
def blastn(input_fasta_file,db_path='/Users/amarcozzi/Desktop/BLAST_DB/',db_name='human_genomic',out_file='blastn_out.xml'):
'''
Run blastn on the local machine using a local database.
Requires NCBI BLAST+ to be installed. http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=Download
Takes a fasta file as input and writes the output in an XML file.
'''
from Bio.Blast.Applications import NcbiblastnCommandline
db = db_path + db_name
blastn_cline = NcbiblastnCommandline(query=input_fasta_file, db=db, evalue=0.001, outfmt=5, out=out_file)
print(blastn_cline)
stdout, stderr = blastn_cline()
# to be tested
def check_line(line,unexpected_char=['\n','',' ','#']):
'''
Check if the line starts with an unexpected character.
If so, return False, else True
'''
for item in unexpected_char:
if line.startswith(item):
return False
return True
def dice_coefficient(sequence_a,sequence_b):
'''(str, str) => float
Return the dice cofficient of two sequences.
'''
a = sequence_a
b = sequence_b
if not len(a) or not len(b): return 0.0
# quick case for true duplicates
if a == b: return 1.0
# if a != b, and a or b are single chars, then they can't possibly match
if len(a) == 1 or len(b) == 1: return 0.0
# list comprehension, preferred over list.append() '''
a_bigram_list = [a[i:i+2] for i in range(len(a)-1)]
b_bigram_list = [b[i:i+2] for i in range(len(b)-1)]
a_bigram_list.sort()
b_bigram_list.sort()
# assignments to save function calls
lena = len(a_bigram_list)
lenb = len(b_bigram_list)
# initialize match counters
matches = i = j = 0
while (i < lena and j < lenb):
if a_bigram_list[i] == b_bigram_list[j]:
matches += 2
i += 1
j += 1
elif a_bigram_list[i] < b_bigram_list[j]:
i += 1
else:
j += 1
score = float(matches)/float(lena + lenb)
return score
def find_path(graph, start, end, path=[]):
'''
Find a path between two nodes in a graph.
Works on graphs like this:
graph ={'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
'''
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
def find_all_paths(graph, start, end, path=[]):
'''
Find all paths between two nodes of a graph.
Works on graphs like this:
graph ={'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
'''
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def find_shortest_path(graph, start, end, path=[]):
'''
Find the shortest path between two nodes of a graph.
Works on graphs like this:
graph ={'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
'''
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_shortest_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
# ##
# graph = {'A': ['B', 'C'],
# 'B': ['C', 'D'],
# 'C': ['D'],
# 'D': ['C'],
# 'E': ['F'],
# 'F': ['C']}
# >>> find_path(graph, 'A', 'D')
# ['A', 'B', 'C', 'D']
# >>> find_all_paths(graph, 'A', 'D')
# [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]
# >>> find_shortest_path(graph, 'A', 'D')
# ['A', 'C', 'D']
def gen_rnd_string(length):
'''
Return a string of uppercase and lowercase ascii letters.
'''
import random, string
s = [l for l in string.ascii_letters]
random.shuffle(s)
s = ''.join(s[:length])
return s
def gene_synonyms(gene_name):
'''str => list()
Queries http://rest.genenames.org and returns a list of synonyms of gene_name.
Returns None if no synonym was found.
'''
import httplib2 as http
import json
from urllib.parse import urlparse
result = []
headers = {'Accept': 'application/json'}
uri = 'http://rest.genenames.org'
path = '/search/{}'.format(gene_name)
target = urlparse(uri+path)
method = 'GET'
body = ''
h = http.Http()
response, content = h.request(
target.geturl(),
method,
body,
headers )
if response['status'] == '200':
# assume that content is a json reply
# parse content with the json module
data = json.loads(content.decode('utf8'))
for item in data['response']['docs']:
result.append(item['symbol'])
return result
else:
print('Error detected: ' + response['status'])
return None
#print(gene_synonyms('MLL3'))
def string_to_number(s):
'''
Convert a bytes string into a single number.
'''
return int.from_bytes(s.encode(), 'little')
#string_to_number('foo bar baz')
#>>> 147948829660780569073512294
def number_to_string(n):
'''
Convert a number into a bytes string.
'''
import math
return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()
#x = 147948829660780569073512294
#number_to_string(x)
#>>> 'foo bar baz'
def determine_average_breaks_distance(dataset): # tested only for deletion/duplication
'''