-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeature_finder.py
202 lines (179 loc) · 8.65 KB
/
feature_finder.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
#!/usr/bin/python3
from BCBio.GFF import GFFExaminer
from BCBio import GFF
from Bio import SeqIO, motifs
from Bio.SeqRecord import SeqRecord
from Bio.SeqFeature import SeqFeature , FeatureLocation
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from collections import Counter
import os, sys, gc
import numpy
class FeatPosition:
def __init__(self, id, name, chrom, start, end, strand):
self.id = id
self.name = name
self.chrom = chrom
self.start = start
self.end = end
self.strand = strand
class AligFeat:
def __init__(self, gene_id, gene_name, id, name, start, end, strand, score):
self.id = id
self.name = name
self.start = start
self.end = end
self.strand = strand
self.score = score
self.gene_id = gene_id
self.gene_name = gene_name
def get_features_from_gff(gff_file, limite_info) :
"""This function returns a dict object containing all the features
(as seqRecord objects) selected by featType and chromosomes contained
in the provided GFF file. The chromosome list must be a list of strings"""
handle = open(gff_file, 'r')
gene_dict = {}
for rec in GFF.parse(handle, limit_info=limite_info) :
for feat in rec.features :
feat.qualifiers["chrom"] = rec.id
gene_dict[feat.qualifiers["gene_id"][0]] = feat
handle.close()
return gene_dict
def positions(gene_list_file, gene_dict) :
"""Extract the position of the genes of interest from a gene dict"""
locations_list = []
gene_list = open(gene_list_file, 'r')
for line in gene_list :
try :
feat = gene_dict[line[0:len(line)-1]]
except KeyError :
print('Gene {} non trouvé'.format(line[0:len(line)-1]))
try :
location = FeatPosition(id = line[0:len(line)-1],
chrom = feat.qualifiers['chrom'],
name = feat.qualifiers['gene_name'][0],
start = feat.location.nofuzzy_start,
end = feat.location.nofuzzy_end,
strand = feat.strand )
locations_list.append(location)
except KeyError :
print('Pas de gene_name pour {}.'.format(line[0:len(line)-1]))
location = FeatPosition(id = line[0:len(line)-1],
chrom = feat.qualifiers['chrom'],
name = '',
start = feat.location.nofuzzy_start,
end = feat.location.nofuzzy_end,
strand = feat.strand )
locations_list.append(location)
gene_list.close()
return locations_list
def finding_sequences(fasta, features, distance, mode = "Cache", direc = "both") :
"""Extracts the up and downstream sequences from the gnenomic fasta file.
Possible to set the distance from start.
If you are short in RAM you can use mode = "Index"."""
print('Indexing genome')
if mode == "Cache" :
genome_dict = SeqIO.to_dict(SeqIO.parse(fasta, "fasta"))
elif mode == "Index" :
genome_dict = SeqIO.index(fasta, "fasta")
print('Done')
sequences_list = []
for feat in features :
if feat.strand == '+1' :
if direc == "both" :
sequence = genome_dict[feat.chrom].seq[(feat.start)-distance:(feat.start+distance)]
sequence.alphabet= IUPAC.unambiguous_dna
seqAnnot = SeqRecord(sequence)
seqAnnot.annotations["start"] = (feat.start)-distance
seqAnnot.annotations["end"] = feat.start
elif direc == "up" :
sequence = genome_dict[feat.chrom].seq[(feat.start)-distance:(feat.start)]
sequence.alphabet= IUPAC.unambiguous_dna
seqAnnot = SeqRecord(sequence)
seqAnnot.annotations["start"] = (feat.start)-distance
seqAnnot.annotations["end"] = feat.start
elif direc == "down" :
sequence = genome_dict[feat.chrom].seq[feat.start:(feat.start+distance)]
sequence.alphabet= IUPAC.unambiguous_dna
seqAnnot = SeqRecord(sequence)
seqAnnot.annotations["start"] = (feat.start)
seqAnnot.annotations["end"] = feat.start+distance
seqAnnot = SeqRecord(sequence)
seqAnnot.id = feat.id
seqAnnot.name = feat.name
seqAnnot.annotations["chr"] = feat.chrom
seqAnnot.annotations["strand"] = feat.strand
else :
if direc == "both" :
sequence = genome_dict[feat.chrom].seq[(feat.end)-distance:(feat.end)+distance].reverse_complement()
sequence.alphabet= IUPAC.unambiguous_dna
seqAnnot = SeqRecord(sequence)
seqAnnot.annotations["start"] = (feat.end)-distance
seqAnnot.annotations["end"] = feat.end+distance
elif direc == "down" :
sequence = genome_dict[feat.chrom].seq[(feat.end)-distance:(feat.end)].reverse_complement()
sequence.alphabet= IUPAC.unambiguous_dna
seqAnnot = SeqRecord(sequence)
seqAnnot.annotations["start"] = (feat.end)-distance
seqAnnot.annotations["end"] = feat.end
elif direc == "up" :
sequence = genome_dict[feat.chrom].seq[feat.end:(feat.end+distance)].reverse_complement()
sequence.alphabet= IUPAC.unambiguous_dna
seqAnnot = SeqRecord(sequence)
seqAnnot.annotations["start"] = (feat.end)
seqAnnot.annotations["end"] = feat.end+distance
seqAnnot.id = feat.id
seqAnnot.name = feat.name
seqAnnot.annotations["chr"] = feat.chrom
seqAnnot.annotations["strand"] = feat.strand
sequences_list.append(seqAnnot)
del(genome_dict)
return sequences_list
def writeFasta(records, output) :
with open(output, "w") as output_handle:
SeqIO.write(records, output_handle, "fasta")
def background(sequence) :
"""Calculates the background of a sequence : the rate of ACTG and returns it as a dictionnary"""
bckgrnd = {}
bckgrnd['A'] = sequence.count('A')/(len(sequence)-sequence.count('N'))
bckgrnd['C'] = sequence.count('C')/(len(sequence)-sequence.count('N'))
bckgrnd['G'] = sequence.count('G')/(len(sequence)-sequence.count('N'))
bckgrnd['T'] = sequence.count('T')/(len(sequence)-sequence.count('N'))
return(bckgrnd)
def motifs_list(jasp_motifs_file) :
jasp_motifs = open(jasp_motifs_file, 'r')
motifs_list = []
for m in motifs.parse(jasp_motifs, "jaspar") :
motifs_list.append(m)
jasp_motifs.close()
return motifs_list
def align_motif(mot, sequenceR, precision = 10**4, balance = 100000, pseudocounts = 0.1) :
mot.background = background(sequenceR.seq)
mot.pseudocounts = pseudocounts
distribution = mot.pssm.distribution(mot.background, precision=precision)
threshold = distribution.threshold_balanced(balance)
aligList = [(position+1, score) for position, score in enumerate(mot.pssm.calculate(sequenceR.seq)) if (position > 0)and(score > threshold)]
for alig in aligList :
sequenceR.features.append(AligFeat(id = mot.matrix_id, name = mot.name, start = alig[0], end = alig[0] + len(mot), strand = 1, score = alig[1], gene_id=sequenceR.id, gene_name=sequenceR.name))
seqRC = sequenceR.seq.reverse_complement()
mot.background = background(seqRC)
distribution = mot.pssm.distribution(background=mot.background, precision=precision)
threshold = distribution.threshold_balanced(balance)
aligListNeg = [(position+1, score) for position, score in enumerate(mot.pssm.calculate(seqRC)) if (position > 0)and(score > threshold)]
for alig in aligListNeg :
sequenceR.features.append(AligFeat(id = mot.matrix_id, name = mot.name, start = alig[0], end = alig[0] + len(mot), strand = -1, score = alig[1], gene_id=sequenceR.id, gene_name=sequenceR.name))
print('Found %i motifs' %len(sequenceR.features))
return sequenceR.features
def testingAllSeq(prod, return_list) :
for c in prod :
print('Testing gene %s with motif %s' % (c[1].id, c[0].matrix_id))
alig_seq = align_motif(mot=c[0], sequenceR=c[1])
if alig_seq != [] :
return_list.append(alig_seq)
def encoder(obj) :
if hasattr(obj, "__dict__") :
return obj.__dict__
elif isinstance(obj, numpy.floating) :
return float(obj)
else:
raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))