forked from Dfam-consortium/RepeatMasker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfamdb.py
executable file
·1738 lines (1397 loc) · 62.5 KB
/
famdb.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
famdb.py
Usage: famdb.py [-h] [-l LOG_LEVEL] command ...
This module provides classes and methods for working with FamDB files,
which contain Transposable Element (TE) families and associated taxonomy data.
# Classes
Family: Metadata and model of a TE family.
FamDB: HDF5-based format for storing Family objects.
SEE ALSO:
Dfam: http://www.dfam.org
AUTHOR(S):
Jeb Rosen <[email protected]>
LICENSE:
This code may be used in accordance with the Creative Commons
Zero ("CC0") public domain dedication:
https://creativecommons.org/publicdomain/zero/1.0/
DISCLAIMER:
This software is provided ``AS IS'' and any express or implied
warranties, including, but not limited to, the implied warranties of
merchantability and fitness for a particular purpose, are disclaimed.
In no event shall the authors or the Dfam consortium members be
liable for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.
"""
import argparse
import collections
import datetime
import json
import logging
import re
import sys
import textwrap
import time
import h5py
import numpy
LOGGER = logging.getLogger(__name__)
# Soundex codes
SOUNDEX_LOOKUP = {
'A': 0, 'E': 0, 'I': 0, 'O': 0, 'U': 0, 'Y': 0,
'B': 1, 'F': 1, 'P': 1, 'V': 1,
'C': 2, 'G': 2, 'J': 2, 'K': 2, 'Q': 2, 'S': 2, 'X': 2, 'Z': 2,
'D': 3, 'T': 3,
'L': 4,
'M': 5, 'N': 5,
'R': 6,
'H': None, 'W': None,
}
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
class Family: # pylint: disable=too-many-instance-attributes
"""A Transposable Element family, made up of metadata and a model."""
FamilyField = collections.namedtuple("FamilyField", ["name", "type"])
# Known metadata fields
META_FIELDS = [
# Core required family metadata
FamilyField("name", str),
FamilyField("accession", str),
FamilyField("version", int),
FamilyField("consensus", str),
FamilyField("length", int),
# Optional family metadata
FamilyField("title", str),
FamilyField("author", str),
FamilyField("description", str),
FamilyField("classification", str),
FamilyField("classification_note", str),
FamilyField("search_stages", str),
FamilyField("buffer_stages", str),
FamilyField("clades", list),
FamilyField("date_created", str),
FamilyField("date_modified", str),
FamilyField("repeat_type", str),
FamilyField("repeat_subtype", str),
FamilyField("features", str),
FamilyField("coding_sequences", str),
FamilyField("aliases", str),
FamilyField("citations", str),
FamilyField("refineable", bool),
FamilyField("target_site_cons", str),
# TODO: add source_assembly, source_method?
# Metadata available when a model is present
FamilyField("model", str),
FamilyField("max_length", int),
FamilyField("is_model_masked", bool),
FamilyField("seed_count", int),
FamilyField("build_method", str),
FamilyField("search_method", str),
FamilyField("taxa_thresholds", str),
FamilyField("general_cutoff", float),
]
# Metadata lookup by field name
META_LOOKUP = {field.name: field for field in META_FIELDS}
@staticmethod
def type_for(name):
"""Returns the expected data type for the attribute 'name'."""
return Family.META_LOOKUP[name].type
def __getattr__(self, name):
if name not in Family.META_LOOKUP:
raise AttributeError("Unknown Family metadata attribute '{}'".format(name))
# Data is converted on setting, so that consumers can rely on the correct types
def __setattr__(self, name, value):
if name not in Family.META_LOOKUP:
raise AttributeError("Unknown Family metadata attribute '{}'".format(name))
expected_type = self.type_for(name)
if value is not None and not isinstance(value, expected_type):
try:
value = expected_type(value)
except Exception as exc:
raise TypeError("Incompatible type for '{}'. Expected '{}', got '{}'".format(
name, expected_type, type(value))) from exc
super().__setattr__(name, value)
def accession_with_optional_version(self):
"""
Returns the accession of 'self', with '.version' appended if the version is known.
"""
acc = self.accession
if self.version is not None:
acc += "." + str(self.version)
return acc
# A useful string representation for debugging, but not much else
def __str__(self):
return "%s.%s '%s': %s len=%d" % (self.accession, self.version,
self.name, self.classification, self.length or -1)
def to_dfam_hmm(self, famdb, species=None, include_class_in_name=False): # pylint: disable=too-many-locals,too-many-branches
"""
Converts 'self' to Dfam-style HMM format.
'famdb' is used for lookups in the taxonomy database (id -> name).
If 'species' (a taxonomy id) is given, the assembly-specific GA/TC/NC
thresholds will be used instead of the threshold that was in the HMM
(usually a generic or strictest threshold).
"""
if self.model is None:
return None
out = ""
# Appends to 'out':
# "TAG Text"
#
# Or if wrap=True and 'text' has multiple lines:
# "TAG Line 1"
# "TAG Line 2"
def append(tag, text, wrap=False):
nonlocal out
if not text:
return
prefix = "%-6s" % tag
text = str(text)
if wrap:
text = textwrap.fill(text, width=72)
out += textwrap.indent(text, prefix)
out += "\n"
# TODO: Compare to e.g. finditer(). This does a lot of unnecessary
# allocation since most of model_lines are appended verbatim.
model_lines = self.model.split("\n")
i = 0
for i, line in enumerate(model_lines):
if line.startswith("HMMER3"):
out += line + "\n"
name = self.name or self.accession
if include_class_in_name:
rm_class = self.repeat_type
if self.repeat_subtype:
rm_class += "/" + self.repeat_subtype
name = name + "#" + rm_class
append("NAME", name)
append("ACC", self.accession_with_optional_version())
append("DESC", self.title)
elif any(map(line.startswith, ["NAME", "ACC", "DESC"])):
# Correct version of this line was output already
pass
elif line.startswith("CKSUM"):
out += line + "\n"
break
else:
out += line + "\n"
th_lines = []
species_hmm_ga = None
species_hmm_tc = None
species_hmm_nc = None
if self.taxa_thresholds:
for threshold in self.taxa_thresholds.split("\n"):
parts = threshold.split(",")
tax_id = int(parts[0])
(hmm_ga, hmm_tc, hmm_nc, hmm_fdr) = map(float, parts[1:])
tax_name = famdb.get_taxon_name(tax_id, 'scientific name')
if tax_id == species:
species_hmm_ga, species_hmm_tc, species_hmm_nc = hmm_ga, hmm_tc, hmm_nc
th_lines += ["TaxId:%d; TaxName:%s; GA:%.2f; TC:%.2f; NC:%.2f; fdr:%.3f;" % (
tax_id, tax_name, hmm_ga, hmm_tc, hmm_nc, hmm_fdr)]
if not species and self.general_cutoff:
species_hmm_ga = species_hmm_tc = species_hmm_nc = self.general_cutoff
if species_hmm_ga:
append("GA", "%.2f;" % species_hmm_ga)
append("TC", "%.2f;" % species_hmm_tc)
append("NC", "%.2f;" % species_hmm_nc)
for th_line in th_lines:
append("TH", th_line)
if self.build_method:
append("BM", self.build_method)
if self.search_method:
append("SM", self.search_method)
append("CT", (self.classification and self.classification.replace("root;", "")))
for clade_id in self.clades:
tax_name = famdb.get_sanitized_name(clade_id)
append("MS", "TaxId:%d TaxName:%s" % (clade_id, tax_name))
append("CC", self.description, True)
append("CC", "RepeatMasker Annotations:")
append("CC", " Type: %s" % (self.repeat_type or ""))
append("CC", " SubType: %s" % (self.repeat_subtype or ""))
species_names = [famdb.get_sanitized_name(c) for c in self.clades]
append("CC", " Species: %s" % ", ".join(species_names))
append("CC", " SearchStages: %s" % (self.search_stages or ""))
append("CC", " BufferStages: %s" % (self.buffer_stages or ""))
if self.refineable:
append("CC", " Refineable")
# Append all remaining lines unchanged
out += "\n".join(model_lines[i+1:])
return out
__COMPLEMENT_TABLE = str.maketrans(
"ACGTRYWSKMNXBDHV",
"TGCAYRSWMKNXVHDB"
)
def to_fasta(
self,
famdb,
use_accession=False,
include_class_in_name=False,
do_reverse_complement=False,
buffer=None
):
"""Converts 'self' to FASTA format."""
sequence = self.consensus
if sequence is None:
return None
sequence = sequence.upper()
if use_accession:
identifier = self.accession_with_optional_version()
else:
identifier = self.name or self.accession
if buffer:
if buffer is True:
# range-less specification: leave identifier unchanged, and use
# the whole sequence as the buffer
buffer = [1, len(sequence)]
else:
# range specification: append _START_END to the identifier
identifier += "_%d_%d" % (buffer[0], buffer[1])
sequence = sequence[buffer[0]-1:buffer[1]]
identifier = identifier + "#buffer"
if do_reverse_complement:
sequence = sequence.translate(self.__COMPLEMENT_TABLE)
sequence = sequence[::-1]
if include_class_in_name and not buffer:
rm_class = self.repeat_type
if self.repeat_subtype:
rm_class += "/" + self.repeat_subtype
identifier = identifier + "#" + rm_class
header = ">" + identifier
if do_reverse_complement:
header += " (anti)"
if use_accession and self.name:
header += " name=" + self.name
for clade_id in self.clades:
clade_name = famdb.get_sanitized_name(clade_id)
header += " @" + clade_name
if self.search_stages:
header += " [S:%s]" % self.search_stages
out = header + "\n"
i = 0
while i < len(sequence):
out += sequence[i:i+60] + "\n"
i += 60
return out
def to_embl(self, famdb, include_meta=True, include_seq=True): # pylint: disable=too-many-locals,too-many-branches,too-many-statements
"""Converts 'self' to EMBL format."""
sequence = self.consensus
if sequence is None:
return None
sequence = sequence.lower()
out = ""
# Appends to 'out':
# "TAG Text"
#
# Or if wrap=True and 'text' has multiple lines:
# "TAG Line 1"
# "TAG Line 2"
def append(tag, text, wrap=False):
nonlocal out
if not text:
return
prefix = "%-5s" % tag
if wrap:
text = textwrap.fill(str(text), width=72)
out += textwrap.indent(str(text), prefix)
out += "\n"
# Appends to 'out':
# "FT line 1"
# "FT line 2"
def append_featuredata(text):
nonlocal out
prefix = "FT "
if text:
out += textwrap.indent(textwrap.fill(str(text), width=72), prefix)
out += "\n"
id_line = self.accession
if self.version is not None:
id_line += "; SV " + str(self.version)
append("ID", "%s; linear; DNA; STD; UNC; %d BP." % (id_line, len(sequence)))
append("NM", self.name)
out += "XX\n"
append("AC", self.accession + ';')
out += "XX\n"
append("DE", self.title, True)
out += "XX\n"
if include_meta:
if self.aliases:
for alias_line in self.aliases.splitlines():
[db_id, db_link] = map(str.strip, alias_line.split(":"))
if db_id == "Repbase":
append("DR", "Repbase; %s." % db_link)
out += "XX\n"
if self.repeat_type == "LTR":
append("KW", "Long terminal repeat of retrovirus-like element; %s." % self.name)
else:
append("KW", "%s/%s." % (self.repeat_type or "", self.repeat_subtype or ""))
out += "XX\n"
for clade_id in self.clades:
lineage = famdb.get_lineage_path(clade_id)
if lineage[0] == "root":
lineage = lineage[1:]
if len(lineage) > 0:
append("OS", lineage[-1])
append("OC", "; ".join(lineage[:-1]) + ".", True)
out += "XX\n"
if self.citations:
citations = json.loads(self.citations)
citations.sort(key=lambda c: c["order_added"])
for cit in citations:
append("RN", "[%d] (bases 1 to %d)" % (cit["order_added"], self.length))
append("RA", cit["authors"], True)
append("RT", cit["title"], True)
append("RL", cit["journal"])
out += "XX\n"
append("CC", self.description, True)
out += "CC\n"
append("CC", "RepeatMasker Annotations:")
append("CC", " Type: %s" % (self.repeat_type or ""))
append("CC", " SubType: %s" % (self.repeat_subtype or ""))
species_names = [famdb.get_sanitized_name(c)
for c in self.clades]
append("CC", " Species: %s" % ", ".join(species_names))
append("CC", " SearchStages: %s" % (self.search_stages or ""))
append("CC", " BufferStages: %s" % (self.buffer_stages or ""))
if self.refineable:
append("CC", " Refineable")
if self.coding_sequences:
out += "XX\n"
append("FH", "Key Location/Qualifiers")
out += "FH\n"
for cds in json.loads(self.coding_sequences):
# TODO: sanitize values which might already contain a " in them?
append("FT", "CDS %d..%d" % (cds["cds_start"], cds["cds_end"]))
append_featuredata('/product="%s"' % cds["product"])
append_featuredata('/number=%s' % cds["exon_count"])
append_featuredata('/note="%s"' % cds["description"])
append_featuredata('/translation="%s"' % cds["translation"])
out += "XX\n"
if include_seq:
sequence = sequence.lower()
i = 0
counts = {"a": 0, "c": 0, "g": 0, "t": 0, "other": 0}
for char in sequence:
if char not in counts:
char = "other"
counts[char] += 1
append("SQ", "Sequence %d BP; %d A; %d C; %d G; %d T; %d other;" % (
len(sequence), counts["a"], counts["c"], counts["g"], counts["t"],
counts["other"]))
while i < len(sequence):
chunk = sequence[i:i+60]
i += 60
j = 0
line = ""
while j < len(chunk):
line += chunk[j:j + 10] + " "
j += 10
out += " %-66s %d\n" % (line, min(i, len(sequence)))
out += "//\n"
return out
@staticmethod
def read_embl_families(filename, lookup, header_cb=None):
"""
Iterates over Family objects from the .embl file 'filename'. The format
should match the output format of to_embl(), but this is not thoroughly
tested.
'lookup' should be a dictionary of Species names (in the EMBL file) to
taxonomy IDs.
If specified, 'header_cb' will be invoked with the contents of the
header text at the top of the file before the last iteration.
TODO: This mechanism is a bit awkward and should perhaps be reworked.
"""
def set_family_code(family, code, value):
"""
Sets an attribute on 'family' based on the hmm shortcode 'code'.
For codes corresponding to list attributes, values are appended.
"""
if code == "ID":
match = re.match(r'(\S*)', value)
acc = match.group(1)
acc = acc.rstrip(";")
family.accession = acc
elif code == "NM":
family.name = value
elif code == "DE":
family.description = value
elif code == "CC":
matches = re.match(r'\s*Type:\s*(\S+)', value)
if matches:
family.repeat_type = matches.group(1).strip()
matches = re.match(r'\s*SubType:\s*(\S+)', value)
if matches:
family.repeat_subtype = matches.group(1).strip()
matches = re.search(r'Species:\s*(.+)', value)
if matches:
for spec in matches.group(1).split(","):
name = spec.strip().lower()
if name:
tax_id = lookup.get(name)
if tax_id:
family.clades += [tax_id]
else:
LOGGER.warning("Could not find taxon for '%s'", name)
matches = re.search(r'SearchStages:\s*(\S+)', value)
if matches:
family.search_stages = matches.group(1).strip()
matches = re.search(r'BufferStages:\s*(\S+)', value)
if matches:
family.buffer_stages = matches.group(1).strip()
header = ""
family = None
in_header = True
in_metadata = False
with open(filename) as file:
for line in file:
if family is None:
# ID indicates start of metadata
if line.startswith("ID"):
family = Family()
family.clades = []
in_header = False
in_metadata = True
elif in_header:
matches = re.match(r"(CC)?\s*(.*)", line)
if line.startswith("XX"):
in_header = False
elif matches:
header_line = matches.group(2).rstrip('*').strip()
header += header_line + "\n"
else:
header += line
if family is not None:
if in_metadata:
# SQ line indicates start of sequence
if line.startswith("SQ"):
in_metadata = False
family.consensus = ""
# Continuing metadata
else:
split = line.rstrip("\n").split(None, maxsplit=1)
if len(split) > 1:
code = split[0].strip()
value = split[1].strip()
set_family_code(family, code, value)
# '//' line indicates end of the sequence area
elif line.startswith("//"):
family.length = len(family.consensus)
yield family
family = None
# Part of the sequence area
else:
family.consensus += re.sub(r'[^A-Za-z]', '', line)
if header_cb:
header_cb(header)
FILE_VERSION = "0.4"
class FamDB:
"""Transposable Element Family and taxonomy database."""
dtype_str = h5py.special_dtype(vlen=str)
GROUP_FAMILIES = "Families"
GROUP_FAMILIES_BYNAME = "Families/ByName"
GROUP_FAMILIES_BYACC = "Families/ByAccession"
GROUP_FAMILIES_BYSTAGE = "Families/ByStage"
GROUP_NODES = "Taxonomy/Nodes"
def __init__(self, filename, mode="r"):
if mode not in ["r", "w", "a"]:
raise ValueError("Invalid file mode. Expected 'r' or 'w' or 'a', got '{}'".format(mode))
reading = True
if mode == "w":
reading = False
self.file = h5py.File(filename, mode)
self.mode = mode
try:
if reading and self.file.attrs["version"] != FILE_VERSION:
raise Exception("File version is {}, but this is version {}".format(
self.file.attrs["version"], FILE_VERSION,
))
except:
# This 'except' catches both "version" missing from attrs, or the
# value not matching if it is present.
raise Exception("This file cannot be read by this version of famdb.py.")
self.__lineage_cache = {}
if self.mode == "w":
self.seen = {}
self.added = {'consensus': 0, 'hmm': 0}
self.__write_metadata()
elif self.mode == "a":
self.seen = {}
self.seen["name"] = set(self.file[FamDB.GROUP_FAMILIES_BYNAME].keys())
self.seen["accession"] = set(self.file[FamDB.GROUP_FAMILIES_BYACC].keys())
self.added = self.get_counts()
if reading:
self.names_dump = json.loads(self.file["TaxaNames"][0])
def __write_metadata(self):
self.file.attrs["generator"] = "famdb.py v0.1"
self.file.attrs["version"] = FILE_VERSION
self.file.attrs["created"] = str(datetime.datetime.now())
def __write_counts(self):
self.file.attrs["count_consensus"] = self.added['consensus']
self.file.attrs["count_hmm"] = self.added['hmm']
def set_db_info(self, name, version, date, desc, copyright_text):
"""Sets database metadata for the current file"""
self.file.attrs["db_name"] = name
self.file.attrs["db_version"] = version
self.file.attrs["db_date"] = date
self.file.attrs["db_description"] = desc
self.file.attrs["db_copyright"] = copyright_text
def get_db_info(self):
"""
Gets database metadata for the current file as a dict with keys
'name', 'version', 'date', 'description', 'copyright'
"""
if "db_name" not in self.file.attrs:
return None
return {
"name": self.file.attrs["db_name"],
"version": self.file.attrs["db_version"],
"date": self.file.attrs["db_date"],
"description": self.file.attrs["db_description"],
"copyright": self.file.attrs["db_copyright"],
}
def get_counts(self):
"""
Gets counts of entries in the current file as a dict
with 'consensus', 'hmm'
"""
return {
"consensus": self.file.attrs["count_consensus"],
"hmm": self.file.attrs["count_hmm"],
}
def close(self):
"""Closes this FamDB instance, making further use invalid."""
self.file.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __check_unique(self, family, key):
"""Verifies that 'family' is uniquely identified by its value of 'key'."""
seen = self.seen
value = getattr(family, key)
if key not in seen:
seen[key] = set()
if value in seen[key]:
raise Exception("Family is not unique! Already seen {}: {}".format(key, value))
seen[key].add(value)
def add_family(self, family):
"""Adds the family described by 'family' to the database."""
# Verify uniqueness of name and accession.
# This is important because of the links created to them later.
if family.name:
self.__check_unique(family, "name")
self.__check_unique(family, "accession")
# Increment counts
if family.consensus:
self.added['consensus'] += 1
if family.model:
self.added['hmm'] += 1
# Create the family data
dset = self.file.require_group(FamDB.GROUP_FAMILIES).create_dataset(family.accession, (0,))
# Set the family attributes
for k in Family.META_LOOKUP:
value = getattr(family, k)
if value:
dset.attrs[k] = value
# Create links
if family.name:
self.file.require_group(FamDB.GROUP_FAMILIES_BYNAME)[family.name] = h5py.SoftLink("/Families/" + family.accession)
self.file.require_group(FamDB.GROUP_FAMILIES_BYACC)[family.accession] = h5py.SoftLink("/Families/" + family.accession)
for clade_id in family.clades:
taxon_group = self.file.require_group(FamDB.GROUP_NODES).require_group(str(clade_id))
families_group = taxon_group.require_group("Families")
families_group[family.accession] = h5py.SoftLink("/Families/" + family.accession)
def add_stage_link(stage, accession):
stage_group = self.file.require_group(FamDB.GROUP_FAMILIES_BYSTAGE).require_group(stage.strip())
if accession not in stage_group:
stage_group[accession] = h5py.SoftLink("/Families/" + accession)
if family.search_stages:
for stage in family.search_stages.split(","):
add_stage_link(stage, family.accession)
if family.buffer_stages:
for stage in family.buffer_stages.split(","):
stage = stage.split("[")[0]
add_stage_link(stage, family.accession)
LOGGER.debug("Added family %s (%s)", family.name, family.accession)
def write_taxonomy(self, tax_db):
"""Writes taxonomy nodes in 'tax_db' to the database."""
LOGGER.info("Writing taxonomy nodes to database")
start = time.perf_counter()
self.names_dump = {}
count = 0
for taxon in tax_db.values():
if taxon.used:
count += 1
self.names_dump[taxon.tax_id] = taxon.names
def store_tree_links(taxon, parent_id):
group = self.file.require_group(FamDB.GROUP_NODES).require_group(str(taxon.tax_id))
if parent_id:
group.create_dataset("Parent", data=[parent_id])
child_ids = []
for child in taxon.children:
if child.used:
child_ids += [child.tax_id]
store_tree_links(child, taxon.tax_id)
group.create_dataset("Children", data=child_ids)
names_data = numpy.array([json.dumps(self.names_dump)])
names_dset = self.file.create_dataset("TaxaNames", shape=names_data.shape,
dtype=FamDB.dtype_str)
names_dset[:] = names_data
LOGGER.info("Writing taxonomy tree")
# 1 is the "root" taxon
store_tree_links(tax_db[1], None)
delta = time.perf_counter() - start
LOGGER.info("Wrote %d taxonomy nodes in %f", count, delta)
def finalize(self):
"""Writes some collected metadata, such as counts, to the database"""
self.__write_counts()
def has_taxon(self, tax_id):
"""Returns True if 'self' has a taxonomy entry for 'tax_id'"""
return str(tax_id) in self.file[FamDB.GROUP_NODES]
def search_taxon_names(self, text, kind=None, search_similar=False):
"""
Searches 'self' for taxons with a name containing 'text', returning an
iterator that yields a tuple of (id, is_exact) for each matching node.
Each id is returned at most once, and if any of its names are an exact
match the whole node is treated as an exact match.
If 'similar' is True, names that sound similar will also be considered
eligible.
A list of strings may be passed as 'kind' to restrict what kinds of
names will be searched.
"""
text = text.lower()
for tax_id, names in self.names_dump.items():
matches = False
exact = False
for name_cls, name_txt in names:
name_txt = name_txt.lower()
if kind is None or kind == name_cls:
if text == name_txt:
matches = True
exact = True
elif name_txt.startswith(text + " <"):
matches = True
exact = True
elif text == sanitize_name(name_txt):
matches = True
exact = True
elif text in name_txt:
matches = True
elif search_similar and sounds_like(text, name_txt):
matches = True
if matches:
yield [int(tax_id), exact]
def resolve_species(self, term, kind=None, search_similar=False):
"""
Resolves 'term' as a species or clade in 'self'. If 'term' is a number,
it is a taxon id. Otherwise, it will be searched for in 'self' in the
name fields of all taxa. A list of strings may be passed as 'kind' to
restrict what kinds of names will be searched.
If 'search_similar' is True, a "sounds like" search will be tried
first. If it is False, a "sounds like" search will still be performed
if no results were found.
This function returns a list of tuples (taxon_id, is_exact) that match
the query. The list will be empty if no matches were found.
"""
# Try as a number
try:
tax_id = int(term)
if self.has_taxon(tax_id):
return [[tax_id, True]]
return []
except ValueError:
pass
# Perform a search by name, splitting between exact and inexact matches for sorting
exact = []
inexact = []
for tax_id, is_exact in self.search_taxon_names(term, kind, search_similar):
if is_exact:
exact += [tax_id]
else:
inexact += [tax_id]
# Combine back into one list, with exact matches first
results = [[tax_id, True] for tax_id in exact]
for tax_id in inexact:
results += [[tax_id, False]]
if len(results) == 0 and not search_similar:
# Try a sounds-like search (currently soundex)
similar_results = self.resolve_species(term, kind, True)
if similar_results:
print("No results were found for that name, but some names sound similar:",
file=sys.stderr)
for tax_id, _ in similar_results:
names = self.get_taxon_names(tax_id)
print(tax_id, ", ".join(["{1}".format(*n) for n in names]), file=sys.stderr)
return results
def resolve_one_species(self, term, kind=None):
"""
Resolves 'term' in 'dbfile' as a taxon id or search term unambiguously.
Parameters are as in the 'resolve_species' method.
Returns None if not exactly one result is found,
and prints details to the screen.
"""
results = self.resolve_species(term, kind)
# Check for a single exact match first, to any field
exact_matches = []
for nid, is_exact in results:
if is_exact:
exact_matches += [nid]
if len(exact_matches) == 1:
return exact_matches[0]
if len(results) == 0:
print("No species found for search term '{}'".format(term), file=sys.stderr)
elif len(results) == 1:
return results[0][0]
else:
print("""Ambiguous search term '{}' (found {} results, {} exact).
Please use a more specific name or taxa ID, which can be looked
up with the 'names' command."""
.format(term, len(results), len(exact_matches)), file=sys.stderr)
return None
def get_taxon_names(self, tax_id):