-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsuffixtreeLibrary.py
More file actions
306 lines (264 loc) · 9.93 KB
/
Copy pathsuffixtreeLibrary.py
File metadata and controls
306 lines (264 loc) · 9.93 KB
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
import sys
class STree():
"""Class representing the suffix tree."""
def __init__(self, input=''):
self.root = _SNode()
self.root.depth = 0
self.root.idx = 0
self.root.parent = self.root
self.root._add_suffix_link(self.root)
if not input == '':
self.build(input)
def _check_input(self, input):
"""Checks the validity of the input.
In case of an invalid input throws ValueError.
"""
if isinstance(input, str):
return 'st'
elif isinstance(input, list):
if all(isinstance(item, str) for item in input):
return 'gst'
raise ValueError("String argument should be of type String or"
" a list of strings")
def build(self, x):
"""Builds the Suffix tree on the given input.
If the input is of type List of Strings:
Generalized Suffix Tree is built.
:param x: String or List of Strings
"""
type = self._check_input(x)
if type == 'st':
x += next(self._terminalSymbolsGenerator())
self._build(x)
if type == 'gst':
self._build_generalized(x)
def _build(self, x):
"""Builds a Suffix tree."""
self.word = x
self._build_McCreight(x)
def _build_naive(self, x):
"""Builds a Suffix tree using the naive O(n^2) algorithm."""
u = self.root
d = 0
for i in range(len(x)):
while d == u.depth and u._has_transition(x[i+d]):
u = u._get_transition_link(x[i+d])
d += 1
while d < u.depth and x[u.idx + d] == x[i+d]:
d += 1
if d < u.depth:
u = self._create_node(x,u, d)
self._create_leaf(x, i,u, d)
u = self.root
d = 0
def _build_McCreight(self, x):
"""Builds a Suffix tree using McCreight O(n) algorithm.
Algorithm based on:
McCreight, Edward M. "A space-economical suffix tree construction algorithm." - ACM, 1976.
Implementation based on:
UH CS - 58093 String Processing Algorithms Lecture Notes
"""
u = self.root
d = 0
for i in range(len(x)):
while u.depth == d and u._has_transition(x[d+i]):
u = u._get_transition_link(x[d+i])
d = d + 1
while d < u.depth and x[u.idx + d] == x[i + d]:
d = d + 1
if d < u.depth:
u = self._create_node(x, u, d)
self._create_leaf(x, i, u, d)
if not u._get_suffix_link():
self._compute_slink(x, u)
u = u._get_suffix_link()
d = d - 1
if d < 0:
d = 0
def _create_node(self, x, u, d):
i = u.idx
p = u.parent
v = _SNode(idx=i, depth=d)
v._add_transition_link(u,x[i+d])
u.parent = v
p._add_transition_link(v, x[i+p.depth])
v.parent = p
return v
def _create_leaf(self, x, i, u, d):
w = _SNode()
w.idx = i
w.depth = len(x) - i
u._add_transition_link(w, x[i + d])
w.parent = u
return w
def _compute_slink(self, x, u):
d = u.depth
v = u.parent._get_suffix_link()
while v.depth < d - 1:
v = v._get_transition_link(x[u.idx + v.depth + 1])
if v.depth > d - 1:
v = self._create_node(x, v, d-1)
u._add_suffix_link(v)
def _build_Ukkonen(self, x):
"""Builds a Suffix tree using Ukkonen's online O(n) algorithm.
Algorithm based on:
Ukkonen, Esko. "On-line construction of suffix trees." - Algorithmica, 1995.
"""
# TODO.
raise NotImplementedError()
def _build_generalized(self, xs):
"""Builds a Generalized Suffix Tree (GST) from the array of strings provided.
"""
terminal_gen = self._terminalSymbolsGenerator()
_xs = ''.join([x + next(terminal_gen) for x in xs]).lower() ### case-insensitive
self.word = _xs
self._generalized_word_starts(xs)
self._build(_xs)
self.root._traverse(self._label_generalized)
def _label_generalized(self, node):
"""Helper method that labels the nodes of GST with indexes of strings
found in their descendants.
"""
if node.is_leaf():
x = {self._get_word_start_index(node.idx)}
else:
x = {n for ns in node.transition_links for n in ns[0].generalized_idxs}
node.generalized_idxs = x
def _get_word_start_index(self, idx):
"""Helper method that returns the index of the string based on node's
starting index"""
i = 0
for _idx in self.word_starts[1:]:
if idx < _idx:
return i
else:
i+=1
return i
def lcs(self, stringIdxs=-1):
"""Returns the Largest Common Substring of Strings provided in stringIdxs.
If stringIdxs is not provided, the LCS of all strings is returned.
::param stringIdxs: Optional: List of indexes of strings.
"""
if stringIdxs == -1 or not isinstance(stringIdxs, list):
stringIdxs = set(range(len(self.word_starts)))
else:
stringIdxs = set(stringIdxs)
deepestNode = self._find_lcs(self.root, stringIdxs)
start = deepestNode.idx
end = deepestNode.idx + deepestNode.depth
return self.word[start:end], self.word ##@sam## also returns all descriptions of a cluster
def _find_lcs(self, node, stringIdxs):
"""Helper method that finds LCS by traversing the labeled GSD."""
nodes = [self._find_lcs(n, stringIdxs)
for (n,_) in node.transition_links
if n.generalized_idxs.issuperset(stringIdxs)]
if nodes == []:
return node
deepestNode = max(nodes, key=lambda n: n.depth)
return deepestNode
def _generalized_word_starts(self, xs):
"""Helper method returns the starting indexes of strings in GST"""
self.word_starts = []
i = 0
for n in range(len(xs)):
self.word_starts.append(i)
i += len(xs[n]) + 1
def find(self, y):
"""Returns starting position of the substring y in the string used for
building the Suffix tree.
:param y: String
:return: Index of the starting position of string y in the string used for building the Suffix tree
-1 if y is not a substring.
"""
node = self.root
while True:
edge = self._edgeLabel(node, node.parent)
if edge.startswith(y):
return node.idx
i = 0
while(i < len(edge) and edge[i] == y[0]):
y = y[1:]
i += 1
node = node._get_transition_link(y[0])
if not node:
return -1
def find_all(self, y):
y_input = y
node = self.root
while True:
edge = self._edgeLabel(node, node.parent)
if edge.startswith(y):
break
else:
i = 0
while(i < len(edge) and edge[i] == y[0]):
y = y[1:]
i += 1
node = node._get_transition_link(y[0])
if not node:
return []
leaves = node._get_leaves()
return [n.idx for n in leaves]
def _edgeLabel(self, node, parent):
"""Helper method, returns the edge label between a node and it's parent"""
return self.word[node.idx + parent.depth : node.idx + node.depth]
def _terminalSymbolsGenerator(self):
"""Generator of unique terminal symbols used for building the Generalized Suffix Tree.
Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols
are not part of the input string.
"""
py2 = sys.version[0] < '3'
UPPAs = list(list(range(0xE000,0xF8FF+1)) + list(range(0xF0000,0xFFFFD+1)) + list(range(0x100000, 0x10FFFD+1)))
for i in UPPAs:
if py2:
yield(unichr(i))
else:
yield(chr(i))
raise ValueError("To many input strings.")
class _SNode():
"""Class representing a Node in the Suffix tree."""
def __init__(self, idx=-1, parentNode=None, depth=-1):
# Links
self._suffix_link = None
self.transition_links = []
# Properties
self.idx = idx
self.depth = depth
self.parent = parentNode
self.generalized_idxs = {}
def __str__(self):
return("SNode: idx:"+ str(self.idx) + " depth:"+str(self.depth) +
" transitons:" + str(self.transition_links))
def _add_suffix_link(self, snode):
self._suffix_link = snode
def _get_suffix_link(self):
if self._suffix_link != None:
return self._suffix_link
else:
return False
def _get_transition_link(self, suffix):
for node,_suffix in self.transition_links:
if _suffix == '__@__' or suffix == _suffix:
return node
return False
def _add_transition_link(self, snode, suffix=''):
tl = self._get_transition_link(suffix)
if tl: # TODO: imporve this.
self.transition_links.remove((tl,suffix))
self.transition_links.append((snode,suffix))
def _has_transition(self, suffix):
for node,_suffix in self.transition_links:
if _suffix == '__@__' or suffix == _suffix:
return True
return False
def is_leaf(self):
return self.transition_links == []
def _traverse(self, f):
for (node,_) in self.transition_links:
node._traverse(f)
f(self)
def _get_leaves(self):
if self.is_leaf():
return [self]
else:
return [x for (n,_) in self.transition_links for x in n._get_leaves()]