forked from enormandeau/Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ortology.py
executable file
·223 lines (186 loc) · 7.57 KB
/
ortology.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Quick and dirty script to find ortologous genes among many species
# WARNING! Works only under Linux
__authors__ = "Eric Normandeau"
__program_name__ = "ortology"
__version_info__ = ('0', '0', '2')
__version__ = '.'.join(__version_info__)
__revision_date__ = "2010-04-21"
# Importing modules
import re
import math
from collections import defaultdict
# Class definitions
class AutoDict(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
# Function definitions
def readfasta(sp_name, re_pattern):
"""Read FASTA file, build dictionary of names pointing to sequences"""
out = {}
with open(sp_name + ".fa") as f:
for line in f:
if line.startswith(">"):
contig_name = re.findall(re_pattern, line)
if len(contig_name) > 0:
contig_name = sp_name + "_" + contig_name[0]
else:
contig_name = "NoNameFound"
contig_seq = ""
out[contig_name] = contig_seq
else:
out[contig_name] += line.rstrip()
return out
def build_orto_dict(central_sp, other_sp, central_n, other_n):
"""That would be hard to summarize in one line :P"""
d = AutoDict()
for sp in other_sp:
filename1 = central_sp + "_" + sp + ".txt"
filename2 = sp + "_" + central_sp + ".txt"
with open(filename1) as f1:
with open(filename2) as f2:
line_count = 0
max_line_count = 10000000
for line in f1:
ids = []
if line_count > max_line_count:
break
first_id = re.findall(central_n, line)
if len(first_id) > 0:
ids.append(central_sp + "_" + first_id[0])
second_id = re.findall(other_n, line)
if len(second_id) > 0:
ids.append(sp + "_" + second_id[0])
if len(ids) == 2:
d[central_sp][sp][ids[0]] = ids[1]
line_count +=1 # Remove after testing phase
line_count = 0
for line in f2:
ids = []
if line_count > max_line_count:
break
first_id = re.findall(other_n, line)
if len(first_id) > 0:
ids.append(sp + "_" + first_id[0])
second_id = re.findall(central_n, line)
if len(second_id) > 0:
ids.append(central_sp + "_" + second_id[0])
if len(ids) == 2:
d[sp][central_sp][ids[0]] = ids[1]
line_count +=1 # Remove after testing phase
return d
def check_ortology(a_dict, central_sp, other_sp):
"""Use build_ortolog_dict dictionary to determine ortology."""
d = defaultdict(list)
ortologous_count = 0
for sp in other_sp:
for id1 in a_dict[central_sp][sp].keys():
id2 = a_dict[central_sp][sp][id1]
if a_dict[sp][central_sp][id2] == id1:
ortologous_count += 1
d[id1].append(id2)
print "There are", ortologous_count, "ortologous relationships"
return d
def reduce_ortologue_dict(a_dict, min_orto):
"""Keep only genes for which there is a minimum number of ortologues."""
d = defaultdict(list)
for i in a_dict:
if len(a_dict[i]) >= min_orto:
d[i] = a_dict[i]
print "With a mimimum of", min_orto, "ortologues, we keep", \
len(d.keys()), "genes."
return d
def export_table(d, central_sp, other_sp):
"""Write presence/absence table of ortology for each species to a file."""
with open("ortology_table.txt", "w") as f:
f.write(central_sp)
for sp in other_sp:
f.write("\t" + sp)
f.write("\n")
for gene in sorted(d):
gene_re = re.compile("[A-Z]{2,}[0-9]+\.*[0-9]*")
gene_id = re.findall(gene_re, gene)[0]
f.write(gene_id)
for sp in other_sp:
presence = 0
for ortolog in d[gene]:
if ortolog.find(sp + "_") > -1:
presence = 1
f.write("\t" + str(presence))
f.write("\n")
def complement(seq):
"""Return the complement of a sequenc *NOT* it's reverse complement"""
if not seq.isalpha():
print "The sequence contained non-alphabetic characters"
print seq
if not seq.isupper():
print "The sequence contained non capital-letter characters"
seq = seq.upper()
return seq.replace("A","t").replace("T","a").replace("C","g").replace("G","c").upper()
def reverse_complement(seq):
return complement(seq)[::-1]
def correct_sense(s1, s2):
"""Insure s2 is in the same sense as s1 for alignment"""
len_word = 11
min_ratio = 2
s2_rev = reverse_complement(s2)
score_sense = 1
score_anti = 1
for i in range(len(s1) - len_word + 1):
word = s1[i:i + len_word]
if s2.find(word) > -1:
score_sense +=1
if s2_rev.find(word) > -1:
score_anti +=1
ratio = math.log(float(score_sense) / score_anti, 10)
correct_seq = s2
#if ratio > math.log(min_ratio, 10):
# correct_seq = s2
if ratio < - math.log(min_ratio, 10):
correct_seq = s2_rev
return correct_seq
def export_sequences(d, central_sp, other_sp, central_n, other_n):
central_sp_seqs = readfasta(central_sp, central_n)
#print "Loaded", len(central_sp_seqs.keys()), "sequences from", central_sp
for sp in other_sp:
sp_seqs = readfasta(sp, other_n)
#print "Loaded", len(sp_seqs.keys()), "sequences from", sp
with open("./ortology_results/" + sp + "_ortologs.txt", "w") as out_file:
for k in sorted(d.keys()):
for contig in d[k]:
if contig.find(sp) > -1:
ncar = 60
out_file.write(">" + k + "_" + k + "\n")
seq1 = central_sp_seqs[k]
seq1c = seq1[:]
while len(seq1) > 0:
out_file.write(seq1[:ncar] + "\n")
seq1 = seq1[ncar:]
out_file.write(">" + k + "_" + contig + "\n")
seq2 = sp_seqs[contig]
seq2 = correct_sense(seq1c, seq2)
while len(seq2) > 0:
out_file.write(seq2[:ncar] + "\n")
seq2 = seq2[ncar:]
print sp, "finished"
# Pseudo main
central_species = "salmo"
other_species = "coreg danio esoxl mykis namay salve".split()
#other_species = "coreg mykis namay salve".split()
central_name = re.compile("[A-Z]{2,}[0-9]+\.*[0-9]*")
other_names = re.compile("_(Contig_[0-9]+)")
min_sp = 6
my_dict = build_orto_dict(central_species, other_species, central_name, other_names)
orto_genes = check_ortology(my_dict, central_species, other_species)
reduced_orto = reduce_ortologue_dict(orto_genes, min_sp)
print "Writing result files:"
export_table(reduced_orto, central_species, other_species)
export_sequences(reduced_orto, central_species, other_species, central_name, other_names)
#for i in range(6, 0, -1):
# reduce_ortologue_dict(orto_genes, i)