-
Notifications
You must be signed in to change notification settings - Fork 1
/
famdb_helper_methods.py
226 lines (173 loc) · 5.96 KB
/
famdb_helper_methods.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
import re
import h5py
from famdb_globals import (
SOUNDEX_LOOKUP,
GROUP_FAMILIES,
dfam_acc_pat,
)
from famdb_helper_classes import Family
def accession_bin(acc):
"""Maps an accession (Dfam or otherwise) into apropriate bins (groups) in HDF5"""
dfam_match = dfam_acc_pat.match(acc)
if dfam_match:
path = (
GROUP_FAMILIES
+ "/"
+ dfam_match.group(1)
+ "/"
+ dfam_match.group(2)
+ "/"
+ dfam_match.group(3)
+ "/"
+ dfam_match.group(4)
)
else:
path = GROUP_FAMILIES + "/Aux/" + acc[0:2].lower()
return path
def get_family(entry):
if not entry:
return None
family = Family()
# Read the family attributes and data
for k in entry.attrs:
value = entry.attrs[k]
setattr(family, k, value)
return family
def families_iterator(g, prefix=""):
for key, item in g.items():
path = "{}/{}".format(prefix, key)
if isinstance(item, h5py.Dataset): # test for dataset
yield (key)
elif isinstance(item, h5py.Group): # test for group (go down)
yield from families_iterator(item, path)
# Filter methods --------------------------------------------------------------------------
def filter_name(family, name):
"""Returns True if the family's name begins with 'name'."""
if family.attrs.get("name"):
if family.attrs["name"].lower().startswith(name):
return True
return False
def filter_search_stages(family, stages):
"""Returns True if the family belongs to a search stage in 'stages'."""
if family.attrs.get("search_stages"):
sstages = (ss.strip() for ss in family.attrs["search_stages"].split(","))
for family_ss in sstages:
if family_ss in stages:
return True
return False
def filter_repeat_type(family, rtype):
"""
Returns True if the family's RepeatMasker Type plus SubType
(e.g. "DNA/CMC-EnSpm") starts with 'rtype'.
"""
if family.attrs.get("repeat_type"):
full_type = family.attrs["repeat_type"]
if family.attrs.get("repeat_subtype"):
full_type = full_type + "/" + family.attrs["repeat_subtype"]
if full_type.lower().startswith(rtype):
return True
return False
def filter_curated(accession, curated):
"""
Returns True if the family's curatedness is the same as 'curated'. In
other words, 'curated=True' includes only curated familes and
'curated=False' includes only uncurated families.
Families are currently assumed to be curated unless their name is of the
form DR<9 digits>.
TODO: perhaps this should be a dedicated 'curated' boolean field on Family
"""
is_curated = not (
accession.startswith("DR")
and len(accession) == 11
and all((c >= "0" and c <= "9" for c in accession[2:]))
)
return is_curated == curated
def soundex(word):
"""
Converts 'word' according to American Soundex[1].
This is used for "sounds like" types of searches.
[1]: https://en.wikipedia.org/wiki/Soundex#American_Soundex
"""
codes = [SOUNDEX_LOOKUP[ch] for ch in word.upper() if ch in SOUNDEX_LOOKUP]
# Start at the second code
i = 1
# Drop identical sounds and H and W
while i < len(codes):
code = codes[i]
prev = codes[i - 1]
if code is None:
# Drop H and W
del codes[i]
elif code == prev:
# Drop adjacent identical sounds
del codes[i]
else:
i += 1
# Keep the first letter
coding = word[0]
# Keep codes, except for the first or vowels
codes_rest = filter(lambda c: c > 0, codes[1:])
# Append stringified remaining numbers
for code in codes_rest:
coding += str(code)
# Pad to 3 digits
while len(coding) < 4:
coding += "0"
# Truncate to 3 digits
return coding[:4]
def sounds_like(first, second):
"""
Returns true if the string 'first' "sounds like" 'second'.
The comparison is currently implemented by running both strings through the
soundex algorithm and checking if the soundex values are equal.
"""
soundex_first = soundex(first)
soundex_second = soundex(second)
return soundex_first == soundex_second
def sanitize_name(name):
"""
Returns the "sanitized" version of the given 'name'.
This must be kept in sync with Dfam's algorithm.
"""
name = re.sub(r"[\s\,\_]+", "_", name)
name = re.sub(r"[\(\)\<\>\']+", "", name)
return name
def is_fasta(infile):
fasta_el = {"header": None, "body": None}
with open(infile, "r") as file:
for line in file.readlines():
if line.startswith(">") and fasta_el["header"] is not None:
fasta_el["header"] = line
elif not line.startswith(">") and fasta_el["body"] is not None:
fasta_el["body"] = line
if fasta_el["header"] is not None and fasta_el["body"] is not None:
fasta_el["header"] = None
fasta_el["body"] = None
return fasta_el["header"] is None and fasta_el["body"] is None
# def gen_min_map():
# return {
# "file_map": {
# "0": {
# "T_root": 1,
# "bytes": 0,
# "nodes": [1],
# "F_roots": [1],
# "T_root_name": "root",
# "F_roots_names": ["root"],
# "filename": "min_init",
# }
# }
# }
# def gen_min_data():
# dum_node = TaxNode(1, 1)
# dum_node.names.append("root")
# tax_db = {1: dum_node}
# partition_nodes = {0: [1]}
# min_map = gen_min_map()
# dum_fam = Family()
# dum_fam.name = "dummy"
# dum_fam.accession = "DUMMYAccession"
# dum_fam.clades = [0]
# dum_fam.consensus = "BLAHBLAHBLAH"
# dum_fam.model = "BLAHBLAHBLAH"
# return tax_db, partition_nodes, min_map, [dum_fam]