/
sbt.py
1267 lines (1003 loc) · 39.9 KB
/
sbt.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 python
"""
An implementation of sequence bloom trees, Solomon & Kingsford, 2015.
To try it out, do::
factory = GraphFactory(ksize, tablesizes, n_tables)
root = Node(factory)
graph1 = factory()
# ... add stuff to graph1 ...
leaf1 = Leaf("a", graph1)
root.insert(leaf1)
For example, ::
# filenames: list of fa/fq files
# ksize: k-mer size
# tablesizes: Bloom filter table sizes
# n_tables: Number of tables
factory = GraphFactory(ksize, tablesizes, n_tables)
root = Node(factory)
for filename in filenames:
graph = factory()
graph.consume_fasta(filename)
leaf = Leaf(filename, graph)
root.insert(leaf)
then define a search function, ::
def kmers(k, seq):
for start in range(len(seq) - k + 1):
yield seq[start:start + k]
def search_transcript(node, seq, threshold):
presence = [ node.data.get(kmer) for kmer in kmers(ksize, seq) ]
if sum(presence) >= int(threshold * len(seq)):
return 1
return 0
"""
from __future__ import print_function, unicode_literals, division
from collections import namedtuple
try:
from collections.abc import Mapping
except ImportError: # Python 2...
from collections import Mapping
from copy import copy
import json
import math
import os
from random import randint, random
import sys
from tempfile import NamedTemporaryFile
from .exceptions import IndexNotSupported
from .sbt_storage import FSStorage, TarStorage, IPFSStorage, RedisStorage, ZipStorage
from .logging import error, notify, debug
from .index import Index
from .nodegraph import Nodegraph, extract_nodegraph_info, calc_expected_collisions
STORAGES = {
'TarStorage': TarStorage,
'FSStorage': FSStorage,
'IPFSStorage': IPFSStorage,
'RedisStorage': RedisStorage,
'ZipStorage': ZipStorage,
}
NodePos = namedtuple("NodePos", ["pos", "node"])
class GraphFactory(object):
"""Build new nodegraphs (Bloom filters) of a specific (fixed) size.
Parameters
----------
ksize: int
k-mer size.
starting_size: int
size (in bytes) for each nodegraph table.
n_tables: int
number of nodegraph tables to be used.
"""
def __init__(self, ksize, starting_size, n_tables):
self.ksize = ksize
self.starting_size = starting_size
self.n_tables = n_tables
def __call__(self):
return Nodegraph(self.ksize, self.starting_size, self.n_tables)
def init_args(self):
return (self.ksize, self.starting_size, self.n_tables)
class SBT(Index):
"""A Sequence Bloom Tree implementation allowing generic internal nodes and leaves.
The default node and leaf format is a Bloom Filter (like the original implementation),
but we also provide a MinHash leaf class (in the sourmash.sbtmh.SigLeaf class)
Parameters
----------
factory: Factory
Callable for generating new datastores for internal nodes.
d: int
Number of children for each internal node. Defaults to 2 (a binary tree)
storage: Storage, default: None
A Storage is any place where we can save and load data for the nodes.
If set to None, will use a FSStorage.
Notes
-----
We use two dicts to store the tree structure: One for the internal nodes,
and another for the leaves (datasets).
"""
def __init__(self, factory, d=2, storage=None):
self.factory = factory
self._nodes = {}
self._missing_nodes = set()
self._leaves = {}
self.d = d
self.next_node = 0
self.storage = storage
def signatures(self):
for k in self.leaves():
yield k.data
def select(self, ksize=None, moltype=None):
first_sig = next(iter(self.signatures()))
ok = True
if ksize is not None and first_sig.minhash.ksize != ksize:
ok = False
if moltype is not None and first_sig.minhash.moltype != moltype:
ok = False
if ok:
return self
raise ValueError("cannot select SBT on ksize {} / moltype {}".format(ksize, moltype))
def new_node_pos(self, node):
if not self._nodes:
self.next_node = 1
return 0
if not self._leaves:
self.next_node = 2
return 1
min_leaf = min(self._leaves.keys())
next_internal_node = None
if self.next_node <= min_leaf:
for i in range(min_leaf):
if all((i not in self._nodes,
i not in self._leaves,
i not in self._missing_nodes)):
next_internal_node = i
break
if next_internal_node is None:
self.next_node = max(self._leaves.keys()) + 1
else:
self.next_node = next_internal_node
return self.next_node
def insert(self, signature):
"Add a new SourmashSignature in to the SBT."
from .sbtmh import SigLeaf
leaf = SigLeaf(signature.md5sum(), signature)
self.add_node(leaf)
def add_node(self, node):
pos = self.new_node_pos(node)
if pos == 0: # empty tree; initialize w/node.
n = Node(self.factory, name="internal." + str(pos))
self._nodes[0] = n
pos = self.new_node_pos(node)
# Cases:
# 1) parent is a Leaf (already covered)
# 2) parent is a Node (with empty position available)
# - add Leaf, update parent
# 3) parent is a Node (no position available)
# - this is covered by case 1
# 4) parent is None
# this can happen with d != 2, in this case create the parent node
p = self.parent(pos)
if isinstance(p.node, Leaf):
# Create a new internal node
# node and parent are children of new internal node
n = Node(self.factory, name="internal." + str(p.pos))
self._nodes[p.pos] = n
c1, c2 = self.children(p.pos)[:2]
self._leaves[c1.pos] = p.node
self._leaves[c2.pos] = node
del self._leaves[p.pos]
for child in (p.node, node):
child.update(n)
elif isinstance(p.node, Node):
self._leaves[pos] = node
node.update(p.node)
elif p.node is None:
n = Node(self.factory, name="internal." + str(p.pos))
self._nodes[p.pos] = n
c1 = self.children(p.pos)[0]
self._leaves[c1.pos] = node
node.update(n)
# update all parents!
p = self.parent(p.pos)
while p:
self._rebuild_node(p.pos)
node.update(self._nodes[p.pos])
p = self.parent(p.pos)
def find(self, search_fn, *args, **kwargs):
"Search the tree using `search_fn`."
unload_data = kwargs.get("unload_data", False)
# initialize search queue with top node of tree
matches = []
visited, queue = set(), [0]
# while the queue is not empty, load each node and apply search
# function.
while queue:
node_p = queue.pop(0)
# repair while searching.
node_g = self._leaves.get(node_p, None)
if node_g is None:
node_g = self._nodes.get(node_p, None)
if node_g is None:
if node_p in self._missing_nodes:
self._rebuild_node(node_p)
node_g = self._nodes[node_p]
else:
continue
# if we have not visited this node before,
if node_p not in visited:
visited.add(node_p)
# apply search fn. If return false, truncate search.
if search_fn(node_g, *args):
# leaf node? it's a match!
if isinstance(node_g, Leaf):
matches.append(node_g)
# internal node? descend.
elif isinstance(node_g, Node):
if kwargs.get('dfs', True): # defaults search to dfs
for c in self.children(node_p):
queue.insert(0, c.pos)
else: # bfs
queue.extend(c.pos for c in self.children(node_p))
if unload_data:
node_g.unload()
return matches
def search(self, query, *args, **kwargs):
"""Return set of matches with similarity above 'threshold'.
Results will be sorted by similarity, highest to lowest.
Optional arguments:
* do_containment: default False. If True, use Jaccard containment.
* best_only: default False. If True, allow optimizations that
may. May discard matches better than threshold, but first match
is guaranteed to be best.
* ignore_abundance: default False. If True, and query signature
and database support k-mer abundances, ignore those abundances.
"""
from .sbtmh import search_minhashes, search_minhashes_containment
from .sbtmh import SearchMinHashesFindBest
from .signature import SourmashSignature
threshold = kwargs['threshold']
ignore_abundance = kwargs.get('ignore_abundance', False)
do_containment = kwargs.get('do_containment', False)
best_only = kwargs.get('best_only', False)
unload_data = kwargs.get('unload_data', False)
# figure out scaled value of tree, downsample query if needed.
leaf = next(iter(self.leaves()))
tree_mh = leaf.data.minhash
tree_query = query
if tree_mh.scaled and query.minhash.scaled and \
tree_mh.scaled > query.minhash.scaled:
resampled_query_mh = tree_query.minhash
resampled_query_mh = resampled_query_mh.downsample_scaled(tree_mh.scaled)
tree_query = SourmashSignature(resampled_query_mh)
# define both search function and post-search calculation function
search_fn = search_minhashes
query_match = lambda x: tree_query.similarity(
x, downsample=False, ignore_abundance=ignore_abundance)
if do_containment:
search_fn = search_minhashes_containment
query_match = lambda x: tree_query.contained_by(x, downsample=True)
if best_only: # this needs to be reset for each SBT
search_fn = SearchMinHashesFindBest().search
# now, search!
results = []
for leaf in self.find(search_fn, tree_query, threshold, unload_data=unload_data):
similarity = query_match(leaf.data)
# tree search should always/only return matches above threshold
assert similarity >= threshold
results.append((similarity, leaf.data, None))
return results
def gather(self, query, *args, **kwargs):
"Return the match with the best Jaccard containment in the database."
from .sbtmh import GatherMinHashes
if not query.minhash: # empty query? quit.
return []
# use a tree search function that keeps track of its best match.
search_fn = GatherMinHashes().search
unload_data = kwargs.get('unload_data', False)
leaf = next(iter(self.leaves()))
tree_mh = leaf.data.minhash
scaled = tree_mh.scaled
threshold_bp = kwargs.get('threshold_bp', 0.0)
threshold = 0.0
# are we setting a threshold?
if threshold_bp:
# if we have a threshold_bp of N, then that amounts to N/scaled
# hashes:
n_threshold_hashes = threshold_bp / scaled
# that then requires the following containment:
threshold = n_threshold_hashes / len(query.minhash)
# is it too high to ever match? if so, exit.
if threshold > 1.0:
return []
# actually do search!
results = []
for leaf in self.find(search_fn, query, threshold,
unload_data=unload_data):
leaf_mh = leaf.data.minhash
containment = query.minhash.contained_by(leaf_mh, True)
assert containment >= threshold, "containment {} not below threshold {}".format(containment, threshold)
results.append((containment, leaf.data, None))
results.sort(key=lambda x: -x[0])
return results
def _rebuild_node(self, pos=0):
"""Recursively rebuilds an internal node (if it is not present).
Parameters
----------
pos: int
node to be rebuild. Any internal node under it will be rebuild too.
If you want to rebuild all missing internal nodes you can use pos=0
(the default).
"""
node = self._nodes.get(pos, None)
if node is not None:
# this node was already build, skip
return
node = Node(self.factory, name="internal.{}".format(pos))
self._nodes[pos] = node
for c in self.children(pos):
if c.pos in self._missing_nodes or isinstance(c.node, Leaf):
cnode = c.node
if cnode is None:
self._rebuild_node(c.pos)
cnode = self._nodes[c.pos]
cnode.update(node)
def parent(self, pos):
"""Return the parent of the node at position ``pos``.
If it is the root node (position 0), returns None.
Parameters
----------
pos: int
Position of the node in the tree.
Returns
-------
NodePos :
A NodePos namedtuple with the position and content of the parent node.
"""
if pos == 0:
return None
p = int(math.floor((pos - 1) / self.d))
if p in self._leaves:
return NodePos(p, self._leaves[p])
node = self._nodes.get(p, None)
return NodePos(p, node)
def children(self, pos):
"""Return all children nodes for node at position ``pos``.
Parameters
----------
pos: int
Position of the node in the tree.
Returns
-------
list of NodePos
A list of NodePos namedtuples with the position and content of all
children nodes.
"""
return [self.child(pos, c) for c in range(self.d)]
def child(self, parent, pos):
"""Return a child node at position ``pos`` under the ``parent`` node.
Parameters
----------
parent: int
Parent node position in the tree.
pos: int
Position of the child one under the parent. Ranges from
[0, arity - 1], where arity is the arity of the SBT
(usually it is 2, a binary tree).
Returns
-------
NodePos
A NodePos namedtuple with the position and content of the
child node.
"""
cd = self.d * parent + pos + 1
if cd in self._leaves:
return NodePos(cd, self._leaves[cd])
node = self._nodes.get(cd, None)
return NodePos(cd, node)
def save(self, path, storage=None, sparseness=0.0, structure_only=False):
"""Saves an SBT description locally and node data to a storage.
Parameters
----------
path : str
path to where the SBT description should be saved.
storage : Storage, optional
Storage to be used for saving node data.
Defaults to FSStorage (a hidden directory at the same level of path)
sparseness : float
How much of the internal nodes should be saved.
Defaults to 0.0 (save all internal nodes data),
can go up to 1.0 (don't save any internal nodes data)
structure_only: boolean
Write only the index schema and metadata, but not the data.
Defaults to False (save data too)
Returns
-------
str
full path to the new SBT description
"""
info = {}
info['d'] = self.d
info['version'] = 6
info["index_type"] = self.__class__.__name__ # TODO: check
# choose between ZipStorage and FS (file system/directory) storage.
if path.endswith(".sbt.zip"):
kind = "Zip"
storage = ZipStorage(path)
backend = "FSStorage"
name = os.path.basename(path[:-8])
subdir = '.sbt.{}'.format(name)
storage_args = FSStorage("", subdir).init_args()
storage.save(subdir + "/", b"")
index_filename = os.path.abspath(path)
else:
kind = "FS"
name = os.path.basename(path)
if path.endswith('.sbt.json'):
name = name[:-9]
index_filename = os.path.abspath(path)
else:
index_filename = os.path.abspath(path + '.sbt.json')
if storage is None:
# default storage
location = os.path.dirname(index_filename)
subdir = '.sbt.{}'.format(name)
storage = FSStorage(location, subdir)
index_filename = os.path.join(location, index_filename)
backend = [k for (k, v) in STORAGES.items() if v == type(storage)][0]
storage_args = storage.init_args()
info['storage'] = {
'backend': backend,
'args': storage_args
}
info['factory'] = {
'class': GraphFactory.__name__,
'args': self.factory.init_args()
}
nodes = {}
leaves = {}
total_nodes = len(self)
for n, (i, node) in enumerate(self):
if node is None:
continue
if isinstance(node, Node):
if random() - sparseness <= 0:
continue
data = {
# TODO: start using md5sum instead?
'filename': os.path.basename(node.name),
'name': node.name
}
try:
node.metadata.pop('max_n_below')
except (AttributeError, KeyError):
pass
data['metadata'] = node.metadata
if structure_only is False:
# trigger data loading before saving to the new place
node.data
node.storage = storage
if kind == "Zip":
node.save(os.path.join(subdir, data['filename']))
elif kind == "FS":
data['filename'] = node.save(data['filename'])
if isinstance(node, Node):
nodes[i] = data
else:
leaves[i] = data
if n % 100 == 0:
notify("{} of {} nodes saved".format(n+1, total_nodes), end='\r')
notify("Finished saving nodes, now saving SBT index file.")
info['nodes'] = nodes
info['signatures'] = leaves
if kind == "Zip":
tree_data = json.dumps(info).encode("utf-8")
save_path = "{}.sbt.json".format(name)
storage.save(save_path, tree_data)
storage.close()
elif kind == "FS":
with open(index_filename, 'w') as fp:
json.dump(info, fp)
notify("Finished saving SBT index, available at {0}\n".format(index_filename))
return path
@classmethod
def load(cls, location, leaf_loader=None, storage=None, print_version_warning=True):
"""Load an SBT description from a file.
Parameters
----------
location : str
path to the SBT description.
leaf_loader : function, optional
function to load leaf nodes. Defaults to ``Leaf.load``.
storage : Storage, optional
Storage to be used for saving node data.
Defaults to FSStorage (a hidden directory at the same level of path)
Returns
-------
SBT
the SBT tree built from the description.
"""
tempfile = None
sbt_name = None
tree_data = None
if storage is None and ZipStorage.can_open(location):
storage = ZipStorage(location)
sbts = storage.list_sbts()
if len(sbts) != 1:
print("no SBT, or too many SBTs!")
else:
tree_data = storage.load(sbts[0])
tempfile = NamedTemporaryFile()
tempfile.write(tree_data)
tempfile.flush()
dirname = os.path.dirname(tempfile.name)
sbt_name = os.path.basename(tempfile.name)
if sbt_name is None:
dirname = os.path.dirname(os.path.abspath(location))
sbt_name = os.path.basename(location)
if sbt_name.endswith('.sbt.json'):
sbt_name = sbt_name[:-9]
sbt_fn = os.path.join(dirname, sbt_name)
if not sbt_fn.endswith('.sbt.json') and tempfile is None:
sbt_fn += '.sbt.json'
with open(sbt_fn) as fp:
jnodes = json.load(fp)
if tempfile is not None:
tempfile.close()
version = 1
if isinstance(jnodes, Mapping):
version = jnodes['version']
if leaf_loader is None:
leaf_loader = Leaf.load
loaders = {
1: cls._load_v1,
2: cls._load_v2,
3: cls._load_v3,
4: cls._load_v4,
5: cls._load_v5,
6: cls._load_v6,
}
try:
loader = loaders[version]
except KeyError:
raise IndexNotSupported()
#if version >= 6:
# if jnodes.get("index_type", "SBT") == "LocalizedSBT":
# loaders[6] = LocalizedSBT._load_v6
if version < 3 and storage is None:
storage = FSStorage(dirname, '.sbt.{}'.format(sbt_name))
elif storage is None:
klass = STORAGES[jnodes['storage']['backend']]
if jnodes['storage']['backend'] == "FSStorage":
storage = FSStorage(dirname, jnodes['storage']['args']['path'])
elif storage is None:
storage = klass(**jnodes['storage']['args'])
return loader(jnodes, leaf_loader, dirname, storage, print_version_warning)
@staticmethod
def _load_v1(jnodes, leaf_loader, dirname, storage, print_version_warning=True):
if jnodes[0] is None:
raise ValueError("Empty tree!")
sbt_nodes = {}
sample_bf = os.path.join(dirname, jnodes[0]['filename'])
ksize, tablesize, ntables = extract_nodegraph_info(sample_bf)[:3]
factory = GraphFactory(ksize, tablesize, ntables)
for i, jnode in enumerate(jnodes):
if jnode is None:
continue
jnode['filename'] = os.path.join(dirname, jnode['filename'])
if 'internal' in jnode['name']:
jnode['factory'] = factory
sbt_node = Node.load(jnode, storage)
else:
sbt_node = leaf_loader(jnode, storage)
sbt_nodes[i] = sbt_node
tree = SBT(factory)
tree._nodes = sbt_nodes
return tree
@classmethod
def _load_v2(cls, info, leaf_loader, dirname, storage, print_version_warning=True):
nodes = {int(k): v for (k, v) in info['nodes'].items()}
if nodes[0] is None:
raise ValueError("Empty tree!")
sbt_nodes = {}
sbt_leaves = {}
sample_bf = os.path.join(dirname, nodes[0]['filename'])
k, size, ntables = extract_nodegraph_info(sample_bf)[:3]
factory = GraphFactory(k, size, ntables)
for k, node in nodes.items():
if node is None:
continue
node['filename'] = os.path.join(dirname, node['filename'])
if 'internal' in node['name']:
node['factory'] = factory
sbt_node = Node.load(node, storage)
sbt_nodes[k] = sbt_node
else:
sbt_node = leaf_loader(node, storage)
sbt_leaves[k] = sbt_node
tree = cls(factory, d=info['d'])
tree._nodes = sbt_nodes
tree._leaves = sbt_leaves
return tree
@classmethod
def _load_v3(cls, info, leaf_loader, dirname, storage, print_version_warning=True):
nodes = {int(k): v for (k, v) in info['nodes'].items()}
if not nodes:
raise ValueError("Empty tree!")
sbt_nodes = {}
sbt_leaves = {}
factory = GraphFactory(*info['factory']['args'])
max_node = 0
for k, node in nodes.items():
if node is None:
continue
if 'internal' in node['name']:
node['factory'] = factory
sbt_node = Node.load(node, storage)
sbt_nodes[k] = sbt_node
else:
sbt_node = leaf_loader(node, storage)
sbt_leaves[k] = sbt_node
max_node = max(max_node, k)
tree = cls(factory, d=info['d'], storage=storage)
tree._nodes = sbt_nodes
tree._leaves = sbt_leaves
tree._missing_nodes = {i for i in range(max_node)
if i not in sbt_nodes and i not in sbt_leaves}
if print_version_warning:
error("WARNING: this is an old index version, please run `sourmash migrate` to update it.")
error("WARNING: proceeding with execution, but it will take longer to finish!")
tree._fill_min_n_below()
return tree
@classmethod
def _load_v4(cls, info, leaf_loader, dirname, storage, print_version_warning=True):
nodes = {int(k): v for (k, v) in info['nodes'].items()}
if not nodes:
raise ValueError("Empty tree!")
sbt_nodes = {}
sbt_leaves = {}
factory = GraphFactory(*info['factory']['args'])
max_node = 0
for k, node in nodes.items():
if 'internal' in node['name']:
node['factory'] = factory
sbt_node = Node.load(node, storage)
sbt_nodes[k] = sbt_node
else:
sbt_node = leaf_loader(node, storage)
sbt_leaves[k] = sbt_node
max_node = max(max_node, k)
tree = cls(factory, d=info['d'], storage=storage)
tree._nodes = sbt_nodes
tree._leaves = sbt_leaves
tree._missing_nodes = {i for i in range(max_node)
if i not in sbt_nodes and i not in sbt_leaves}
tree.next_node = max_node
return tree
@classmethod
def _load_v5(cls, info, leaf_loader, dirname, storage, print_version_warning=True):
nodes = {int(k): v for (k, v) in info['nodes'].items()}
leaves = {int(k): v for (k, v) in info['leaves'].items()}
if not leaves:
raise ValueError("Empty tree!")
sbt_nodes = {}
sbt_leaves = {}
if storage is None:
klass = STORAGES[info['storage']['backend']]
if info['storage']['backend'] == "FSStorage":
storage = FSStorage(dirname, info['storage']['args']['path'])
elif storage is None:
storage = klass(**info['storage']['args'])
factory = GraphFactory(*info['factory']['args'])
max_node = 0
for k, node in nodes.items():
node['factory'] = factory
sbt_node = Node.load(node, storage)
sbt_nodes[k] = sbt_node
max_node = max(max_node, k)
for k, node in leaves.items():
sbt_leaf = leaf_loader(node, storage)
sbt_leaves[k] = sbt_leaf
max_node = max(max_node, k)
tree = cls(factory, d=info['d'], storage=storage)
tree._nodes = sbt_nodes
tree._leaves = sbt_leaves
tree._missing_nodes = {i for i in range(max_node)
if i not in sbt_nodes and i not in sbt_leaves}
return tree
@classmethod
def _load_v6(cls, info, leaf_loader, dirname, storage, print_version_warning=True):
nodes = {int(k): v for (k, v) in info['nodes'].items()}
leaves = {int(k): v for (k, v) in info['signatures'].items()}
if not leaves:
raise ValueError("Empty tree!")
sbt_nodes = {}
sbt_leaves = {}
if storage is None:
klass = STORAGES[info['storage']['backend']]
if info['storage']['backend'] == "FSStorage":
storage = FSStorage(dirname, info['storage']['args']['path'])
elif storage is None:
storage = klass(**info['storage']['args'])
factory = GraphFactory(*info['factory']['args'])
max_node = 0
for k, node in nodes.items():
node['factory'] = factory
sbt_node = Node.load(node, storage)
sbt_nodes[k] = sbt_node
max_node = max(max_node, k)
for k, node in leaves.items():
sbt_leaf = leaf_loader(node, storage)
sbt_leaves[k] = sbt_leaf
max_node = max(max_node, k)
tree = cls(factory, d=info['d'], storage=storage)
tree._nodes = sbt_nodes
tree._leaves = sbt_leaves
tree._missing_nodes = {i for i in range(max_node)
if i not in sbt_nodes and i not in sbt_leaves}
return tree
def _fill_min_n_below(self):
"""\
Propagate the smallest hash size below each node up the tree from
the leaves.
"""
def fill_min_n_below(node, *args, **kwargs):
original_min_n_below = node.metadata.get('min_n_below', sys.maxsize)
min_n_below = original_min_n_below
children = kwargs['children']
for child in children:
if child.node is not None:
if isinstance(child.node, Leaf):
min_n_below = min(len(child.node.data.minhash), min_n_below)
else:
child_n = child.node.metadata.get('min_n_below', sys.maxsize)
min_n_below = min(child_n, min_n_below)
if min_n_below == 0:
min_n_below = 1
node.metadata['min_n_below'] = min_n_below
return original_min_n_below != min_n_below
self._fill_up(fill_min_n_below)
def _fill_internal(self):
def fill_nodegraphs(node, *args, **kwargs):
children = kwargs['children']
for child in children:
if child.node is not None:
child.node.update(node)
return True
self._fill_up(fill_nodegraphs)
def _fill_up(self, search_fn, *args, **kwargs):
visited, queue = set(), list(reversed(sorted(self._leaves.keys())))
debug("started filling up")
processed = 0
while queue:
node_p = queue.pop(0)
parent = self.parent(node_p)
if parent is None:
# we are in the root, no more nodes available to search
assert len(queue) == 0
return
was_missing = False
if parent.node is None:
if parent.pos in self._missing_nodes:
self._rebuild_node(parent.pos)
parent = self.parent(node_p)
was_missing = True
else:
continue
siblings = self.children(parent.pos)
if node_p not in visited:
visited.add(node_p)
for sibling in siblings:
visited.add(sibling.pos)
try:
queue.remove(sibling.pos)
except ValueError:
pass
if search_fn(parent.node, children=siblings, *args) or was_missing:
queue.append(parent.pos)
processed += 1
if processed % 100 == 0:
debug("processed {}, in queue {}", processed, len(queue), sep='\r')
def __len__(self):
internal_nodes = set(self._nodes).union(self._missing_nodes)
return len(internal_nodes) + len(self._leaves)