1. Vinay Sajip
  2. whoosh

Source

whoosh / src / whoosh / support / dawg.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
# Copyright 2009 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``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 MATT CHAPUT OR CONTRIBUTORS 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.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of Matt Chaput.

from array import array

from whoosh.system import _INT_SIZE
from whoosh.util import utf8encode, utf8decode


class BaseNode(object):
    """This is the base class for objects representing nodes in a directed
    acyclic word graph (DAWG).
    
    * ``final`` is a property which is True if this node represents the end of
      a word.
      
    * ``__contains__(label)`` returns True if the node has an edge with the
      given label.
      
    * ``__iter__()`` returns an iterator of the labels for the node's outgoing
      edges.
      
    * ``__len__()`` returns the number of outgoing edges.
    
    * ``edge(label)`` returns the Node connected to the edge with the given
      label.
      
    * ``all_edges()`` returns a dictionary of the node's outgoing edges, where
      the keys are the edge labels and the values are the connected nodes.
    """
    
    def __contains__(self, key):
        raise NotImplementedError
    
    def __iter__(self):
        raise NotImplementedError
    
    def __len__(self):
        raise NotImplementedError
    
    def edge(self, key):
        raise NotImplementedError
    
    def all_edges(self):
        e = self.edge
        return dict((key, e(key)) for key in self)
    
    def edge_count(self):
        return len(self) + sum(self.edge(key).edge_count() for key in self)


class BuildNode(object):
    def __init__(self):
        self.final = False
        self._edges = {}
        self._hash = None

    def __repr__(self):
        return "<%s:%s %s>" % (self.id, "".join(self._edges.keys()), self.final)

    def __hash__(self):
        if self._hash is not None:
            return self._hash
        h = int(self.final)
        for key, node in self._edges.iteritems():
            h ^= hash(key) ^ hash(node)
        self._hash = h
        return h

    def __eq__(self, other):
        if self.final != other.final:
            return False
        mine, theirs = self._edges, other._edges
        if len(mine) != len(theirs):
            return False
        for key in mine.iterkeys():
            if key not in theirs or not mine[key] == theirs[key]:
                return False
        return True
    
    def __ne__(self, other):
        return not(self.__eq__(other))
    
    def __contains__(self, key):
        return key in self._edges
    
    def __iter__(self):
        return iter(self._edges)
    
    def __len__(self):
        return len(self._edges)
    
    def put(self, key, node):
        self._hash = None  # Invalidate the cached hash value
        self._edges[key] = node
    
    def edge(self, key):
        return self._edges[key]
    
    def all_edges(self):
        return self._dict
    

class DawgWriter(object):
    def __init__(self, dbfile=None, reduced=True):
        self.dbfile = dbfile
        self.reduced = reduced
        
        self.lastword = ""
        # List of nodes that have not been checked for duplication.
        self.unchecked = []
        # List of unique nodes that have been checked for duplication.
        self.minimized = {}
        
        self.root = BuildNode()
        self.offsets = {}
    
    def insert(self, word):
        if word < self.lastword:
            raise Exception("Out of order %r..%r." % (self.lastword, word))

        # find common prefix between word and previous word
        prefixlen = 0
        for i in xrange(min(len(word), len(self.lastword))):
            if word[i] != self.lastword[i]: break
            prefixlen += 1

        # Check the unchecked for redundant nodes, proceeding from last
        # one down to the common prefix size. Then truncate the list at that
        # point.
        self._minimize(prefixlen)

        # Add the suffix, starting from the correct node mid-way through the
        # graph
        if not self.unchecked:
            node = self.root
        else:
            node = self.unchecked[-1][2]

        for letter in word[prefixlen:]:
            nextnode = BuildNode()
            node.put(letter, nextnode)
            self.unchecked.append((node, letter, nextnode))
            node = nextnode

        node.final = True
        self.lastword = word

    def _minimize(self, downto):
        # Proceed from the leaf up to a certain point
        for i in xrange(len(self.unchecked) - 1, downto - 1, -1):
            (parent, letter, child) = self.unchecked[i];
            if child in self.minimized:
                # Replace the child with the previously encountered one
                parent.put(letter, self.minimized[child])
            else:
                # Add the state to the minimized nodes.
                self.minimized[child] = child;
            self.unchecked.pop()

    def write(self, dbfile=None):
        dbfile = self.dbfile or dbfile
        dbfile.write_int(0)  # File flags
        dbfile.write_uint(0)  # Pointer to root node
        
        self._minimize(0)
        root = self.root
        if self.reduced:
            reduce(root)
        offset = self._write_node(root)
        self._reset()
        
        dbfile.flush()
        dbfile.seek(_INT_SIZE)
        dbfile.write_uint(offset)
        dbfile.close()
    
    def _write_node(self, node):
        dbfile = self.dbfile
        keys = node._edges.keys()
        ptrs = array("I")
        for key in keys:
            sn = node._edges[key]
            if id(sn) in self.offsets:
                ptrs.append(self.offsets[id(sn)])
            else:
                ptr = self._write_node(sn)
                self.offsets[id(sn)] = ptr
                ptrs.append(ptr)
        
        start = dbfile.tell()
        
        # The low bit indicates whether this node represents the end of a word
        flags = int(node.final)
        # The second lowest bit = whether this node has children
        flags |= bool(keys) << 1
        # The third lowest bit = whether all keys are single chars
        singles = all(len(k) == 1 for k in keys)
        flags |= singles << 2
        # The fourth lowest bit = whether all keys are one byte
        if singles:
            bytes = all(ord(key) <= 255 for key in keys)
            flags |= bytes << 3
        dbfile.write_byte(flags)
        
        if keys:
            dbfile.write_varint(len(keys))
            dbfile.write_array(ptrs)
            if singles:
                for key in keys:
                    o = ord(key)
                    if bytes:
                        dbfile.write_byte(o)
                    else:
                        dbfile.write_ushort(o)
            else:
                for key in keys:
                    dbfile.write_string(utf8encode(key)[0])
        
        return start


class DiskNode(BaseNode):
    def __init__(self, dr, offset):
        self.dr = dr
        self.id = offset
        
        dbfile = dr.dbfile
        dbfile.seek(offset)
        flags = dbfile.read_byte()
        self.final = bool(flags & 1)
        self._edges = {}
        if flags & 2:
            singles = flags & 4
            bytes = flags & 8
            
            nkeys = dbfile.read_varint()
            
            ptrs = dbfile.read_array("I", nkeys)
            for i in xrange(nkeys):
                ptr = ptrs[i]
                if singles:
                    if bytes:
                        charnum = dbfile.read_byte()
                    else:
                        charnum = dbfile.read_ushort()
                    self._edges[unichr(charnum)] = ptr
                else:
                    key = utf8decode(dbfile.read_string())[0]
                    if len(key) > 1:
                        self._edges[key[0]] = PatNode(dr, key[1:], ptr)
                    else:
                        self._edges[key] = ptr
            
    def __repr__(self):
        return "<%s:%s %s>" % (self.id, "".join(self._edges.keys()), self.final)
    
    def __contains__(self, key):
        return key in self._edges
    
    def __iter__(self):
        return iter(self._edges)
    
    def __len__(self):
        return len(self._edges)
    
    def edge(self, key):
        v = self._edges[key]
        if not isinstance(v, BaseNode):
            # Convert pointer to disk node
            v = DiskNode(self.dr, v)
            #if self.caching:
            self._edges[key] = v
        return v
    

class PatNode(BaseNode):
    final = False
    
    def __init__(self, dr, label, nextptr, i=0):
        self.dr = dr
        self.label = label
        self.nextptr = nextptr
        self.i = i
    
    def __repr__(self):
        return "<%r(%d) %s>" % (self.label, self.i, self.final)
    
    def __contains__(self, key):
        if self.i < len(self.label) and key == self.label[self.i]:
            return True
        else:
            return False
    
    def __iter__(self):
        if self.i < len(self.label):
            return iter(self.label[self.i])
        else:
            return []
    
    def __len__(self):
        if self.i < len(self.label):
            return 1
        else:
            return 0
    
    def edge(self, key):
        label = self.label
        i = self.i
        if i < len(label) and key == label[i]:
            i += 1
            if i < len(self.label):
                return PatNode(self.dr, label, self.nextptr, i)
            else:
                return DiskNode(self.dr, self.nextptr)
        else:
            raise KeyError(key)
        
    def edge_count(self):
        return DiskNode(self.dr, self.nextptr).edge_count()


class ComboNode(BaseNode):
    """Base class for DAWG nodes that blend the nodes of two different graphs.
    
    Concrete subclasses need to implement the ``edge()`` method and possibly
    the ``final`` property.
    """
    
    def __init__(self, a, b):
        self.a = a
        self.b = b
    
    def __repr__(self):
        return "<%s %r %r>" % (self.__class__.__name__, self.a, self.b)
    
    def __contains__(self, key):
        return key in self.a or key in self.b
    
    def __iter__(self):
        return iter(set(self.a) | set(self.b))
    
    def __len__(self):
        return len(set(self.a) | set(self.b))
    
    @property
    def final(self):
        return self.a.final or self.b.final
    

class UnionNode(ComboNode):
    """Makes two graphs appear to be the union of the two graphs.
    """
    
    def edge(self, key):
        a = self.a
        b = self.b
        if key in a and key in b:
            return UnionNode(a.edge(key), b.edge(key))
        elif key in a:
            return a.edge(key)
        else:
            return b.edge(key)
        

class IntersectionNode(ComboNode):
    """Makes two graphs appear to be the intersection of the two graphs.
    """
    
    def edge(self, key):
        a = self.a
        b = self.b
        if key in a and key in b:
            return IntersectionNode(a.edge(key), b.edge(key))


# Reader for disk-based graph files

class DawgReader(object):
    def __init__(self, dbfile):
        self.dbfile = dbfile
        
        dbfile.seek(0)
        self.fileflags = dbfile.read_int()
        self.root = DiskNode(self, dbfile.read_uint())
    

# Functions

def reduce(node):
    edges = node._edges
    if edges:
        for key, sn in edges.items():
            reduce(sn)
            if len(sn) == 1:
                skey, ssn = sn._edges.items()[0]
                if sn.final == ssn.final or (ssn.final and len(ssn) == 0):
                    del edges[key]
                    edges[key + skey] = ssn
                

def edge_count(node):
    c = len(node)
    return c + sum(edge_count(node.edge(key)) for key in node)


def dump_dawg(node, tab=0):
    print "  " * tab, id(node), node.final
    for key in node:
        print "  " * tab, key, ":"
        dump_dawg(node.edge(key), tab + 1)


def within(node, text, k=1, prefix=0, seen=None):
    if seen is None:
        seen = set()
    
    sofar = ""
    if prefix:
        node = skip_prefix(node, text, prefix)
        if node is None:
            return
        sofar, text = text[:prefix], text[prefix:]
    
    for sug in _within(node, text, k, sofar=sofar):
        if sug in seen:
            continue
        yield sug
        seen.add(sug)
            

def _within(node, word, k=1, i=0, sofar=""):
    assert k >= 0
    
    if i == len(word) and node.final:
        yield sofar
    
    # Match
    if i < len(word) and word[i] in node:
        for w in _within(node.edge(word[i]), word, k, i + 1, sofar + word[i]):
            yield w
    
    if k > 0:
        dk = k - 1
        ii = i + 1
        # Insertions
        for key in node:
            for w in _within(node.edge(key), word, dk, i, sofar + key):
                yield w
        
        if i < len(word):
            char = word[i]
            
            # Transposition
            if i < len(word) - 1 and char != word[ii] and word[ii] in node:
                second = node.edge(word[i+1])
                if char in second:
                    for w in _within(second.edge(char), word, dk, i + 2,
                                     sofar + word[ii] + char):
                        yield w
            
            # Deletion
            for w in _within(node, word, dk, ii, sofar):
                yield w
            
            # Replacements
            for key in node:
                if key != char:
                    for w in _within(node.edge(key), word, dk, ii, sofar + key):
                        yield w


def skip_prefix(node, text, prefix):
    for key in text[:prefix]:
        if key in node:
            node = node.edge(key)
        else:
            return None
    return node


def find_nearest(node, prefix):
    sofar = []
    for i in xrange(len(prefix)):
        char = prefix[i]
        if char in node:
            sofar.apped(char)
            node = node.edge(char)
        else:
            break
    sofar.extend(run_out(node, sofar))
    return "".join(sofar)
    

def run_out(node, sofar):
    sofar = []
    while not node.final:
        first = min(node.keys())
        sofar.append(first)
        node = node.edge(first)
    return sofar