Debian Codegraph @

SeqLib/aho_corasick.hpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2015 Christopher Gilbert.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22
23 #ifndef AHO_CORASICK_HPP
24 #define AHO_CORASICK_HPP
25
26 #include <algorithm>
27 #include <cctype>
28 #include <map>
29 #include <memory>
30 #include <set>
31 #include <string>
32 #include <queue>
33 #include <vector>
34
35 namespace aho_corasick {
36
37 // class interval
38 class interval {
39 size_t d_start;
40 size_t d_end;
41
42 public:
43 interval(size_t start, size_t end)
44 : d_start(start)
45 , d_end(end) {}
46
47 size_t get_start() const { return d_start; }
48 size_t get_end() const { return d_end; }
49 size_t size() const { return d_end - d_start + 1; }
50
51 bool overlaps_with(const interval& other) const {
52 return d_start <= other.d_end && d_end >= other.d_start;
53 }
54
55 bool overlaps_with(size_t point) const {
56 return d_start <= point && point <= d_end;
57 }
58
59 bool operator <(const interval& other) const {
60 return get_start() < other.get_start();
61 }
62
63 bool operator !=(const interval& other) const {
64 return get_start() != other.get_start() || get_end() != other.get_end();
65 }
66
67 bool operator ==(const interval& other) const {
68 return get_start() == other.get_start() && get_end() == other.get_end();
69 }
70 };
71
72 // class interval_tree
73 template<typename T>
74 class interval_tree {
75 public:
76 using interval_collection = std::vector<T>;
77
78 private:
79 // class node
80 class node {
81 enum direction {
82 LEFT, RIGHT
83 };
84 using node_ptr = std::unique_ptr<node>;
85
86 size_t d_point;
87 node_ptr d_left;
88 node_ptr d_right;
89 interval_collection d_intervals;
90
91 public:
92 node(const interval_collection& intervals)
93 : d_point(0)
94 , d_left(nullptr)
95 , d_right(nullptr)
96 , d_intervals()
97 {
98 d_point = determine_median(intervals);
99 interval_collection to_left, to_right;
100 for (const auto& i : intervals) {
101 if (i.get_end() < d_point) {
102 to_left.push_back(i);
103 } else if (i.get_start() > d_point) {
104 to_right.push_back(i);
105 } else {
106 d_intervals.push_back(i);
107 }
108 }
109 if (to_left.size() > 0) {
110 d_left.reset(new node(to_left));
111 }
112 if (to_right.size() > 0) {
113 d_right.reset(new node(to_right));
114 }
115 }
116
117 size_t determine_median(const interval_collection& intervals) const {
118 int start = -1;
119 int end = -1;
120 for (const auto& i : intervals) {
121 int cur_start = i.get_start();
122 int cur_end = i.get_end();
123 if (start == -1 || cur_start < start) {
124 start = cur_start;
125 }
126 if (end == -1 || cur_end > end) {
127 end = cur_end;
128 }
129 }
130 return (start + end) / 2;
131 }
132
133 interval_collection find_overlaps(const T& i) {
134 interval_collection overlaps;
135 if (d_point < i.get_start()) {
136 add_to_overlaps(i, overlaps, find_overlapping_ranges(d_right, i));
137 add_to_overlaps(i, overlaps, check_right_overlaps(i));
138 } else if (d_point > i.get_end()) {
139 add_to_overlaps(i, overlaps, find_overlapping_ranges(d_left, i));
140 add_to_overlaps(i, overlaps, check_left_overlaps(i));
141 } else {
142 add_to_overlaps(i, overlaps, d_intervals);
143 add_to_overlaps(i, overlaps, find_overlapping_ranges(d_left, i));
144 add_to_overlaps(i, overlaps, find_overlapping_ranges(d_right, i));
145 }
146 return interval_collection(overlaps);
147 }
148
149 protected:
150 void add_to_overlaps(const T& i, interval_collection& overlaps, interval_collection new_overlaps) const {
151 for (const auto& cur : new_overlaps) {
152 if (cur != i) {
153 overlaps.push_back(cur);
154 }
155 }
156 }
157
158 interval_collection check_left_overlaps(const T& i) const {
159 return interval_collection(check_overlaps(i, LEFT));
160 }
161
162 interval_collection check_right_overlaps(const T& i) const {
163 return interval_collection(check_overlaps(i, RIGHT));
164 }
165
166 interval_collection check_overlaps(const T& i, direction d) const {
167 interval_collection overlaps;
168 for (const auto& cur : d_intervals) {
169 switch (d) {
170 case LEFT:
171 if (cur.get_start() <= i.get_end()) {
172 overlaps.push_back(cur);
173 }
174 break;
175 case RIGHT:
176 if (cur.get_end() >= i.get_start()) {
177 overlaps.push_back(cur);
178 }
179 break;
180 }
181 }
182 return interval_collection(overlaps);
183 }
184
185 interval_collection find_overlapping_ranges(node_ptr& node, const T& i) const {
186 if (node) {
187 return interval_collection(node->find_overlaps(i));
188 }
189 return interval_collection();
190 }
191 };
192 node d_root;
193
194 public:
195 interval_tree(const interval_collection& intervals)
196 : d_root(intervals) {}
197
198 interval_collection remove_overlaps(const interval_collection& intervals) {
199 interval_collection result(intervals.begin(), intervals.end());
200 std::sort(result.begin(), result.end(), [](const T& a, const T& b) -> bool {
201 if (b.size() - a.size() == 0) {
202 return a.get_start() > b.get_start();
203 }
204 return a.size() > b.size();
205 });
206 std::set<T> remove_tmp;
207 for (const auto& i : result) {
208 if (remove_tmp.find(i) != remove_tmp.end()) {
209 continue;
210 }
211 auto overlaps = find_overlaps(i);
212 for (const auto& overlap : overlaps) {
213 remove_tmp.insert(overlap);
214 }
215 }
216 for (const auto& i : remove_tmp) {
217 result.erase(
218 std::find(result.begin(), result.end(), i)
219 );
220 }
221 std::sort(result.begin(), result.end(), [](const T& a, const T& b) -> bool {
222 return a.get_start() < b.get_start();
223 });
224 return interval_collection(result);
225 }
226
227 interval_collection find_overlaps(const T& i) {
228 return interval_collection(d_root.find_overlaps(i));
229 }
230 };
231
232 // class ahoemit
233 template<typename CharType>
234 class ahoemit: public interval {
235 public:
236 typedef std::basic_string<CharType> string_type;
237 typedef std::basic_string<CharType>& string_ref_type;
238
239 private:
240 string_type d_keyword;
241
242 public:
243 ahoemit()
244 : interval(-1, -1)
245 , d_keyword() {}
246
247 ahoemit(size_t start, size_t end, string_type keyword)
248 : interval(start, end)
249 , d_keyword(keyword) {}
250
251 string_type get_keyword() const { return string_type(d_keyword); }
252 bool is_empty() const { return (get_start() == -1 && get_end() == -1); }
253 };
254
255 // class token
256 template<typename CharType>
257 class token {
258 public:
259 enum token_type{
260 TYPE_FRAGMENT,
261 TYPE_MATCH,
262 };
263
264 using string_type = std::basic_string<CharType>;
265 using string_ref_type = std::basic_string<CharType>&;
266 using ahoemit_type = ahoemit<CharType>;
267
268 private:
269 token_type d_type;
270 string_type d_fragment;
271 ahoemit_type d_ahoemit;
272
273 public:
274 token(string_ref_type fragment)
275 : d_type(TYPE_FRAGMENT)
276 , d_fragment(fragment)
277 , d_ahoemit() {}
278
279 token(string_ref_type fragment, const ahoemit_type& e)
280 : d_type(TYPE_MATCH)
281 , d_fragment(fragment)
282 , d_ahoemit(e) {}
283
284 bool is_match() const { return (d_type == TYPE_MATCH); }
285 string_type get_fragment() const { return string_type(d_fragment); }
286 ahoemit_type get_ahoemit() const { return d_ahoemit; }
287 };
288
289 // class state
290 template<typename CharType>
291 class state {
292 public:
293 typedef state<CharType>* ptr;
294 typedef std::unique_ptr<state<CharType>> unique_ptr;
295 typedef std::basic_string<CharType> string_type;
296 typedef std::basic_string<CharType>& string_ref_type;
297 typedef std::set<string_type> string_collection;
298 typedef std::vector<ptr> state_collection;
299 typedef std::vector<CharType> transition_collection;
300
301 private:
302 size_t d_depth;
303 ptr d_root;
304 std::map<CharType, unique_ptr> d_success;
305 ptr d_failure;
306 string_collection d_ahoemits;
307
308 public:
309 state(): state(0) {}
310
311 state(size_t depth)
312 : d_depth(depth)
313 , d_root(depth == 0 ? this : nullptr)
314 , d_success()
315 , d_failure(nullptr)
316 , d_ahoemits() {}
317
318 ptr next_state(CharType character) const {
319 return next_state(character, false);
320 }
321
322 ptr next_state_ignore_root_state(CharType character) const {
323 return next_state(character, true);
324 }
325
326 ptr add_state(CharType character) {
327 auto next = next_state_ignore_root_state(character);
328 if (next == nullptr) {
329 next = new state<CharType>(d_depth + 1);
330 d_success[character].reset(next);
331 }
332 return next;
333 }
334
335 size_t get_depth() const { return d_depth; }
336
337 void add_ahoemit(string_ref_type keyword) {
338 d_ahoemits.insert(keyword);
339 }
340
341 void add_ahoemit(const string_collection& ahoemits) {
342 for (const auto& e : ahoemits) {
343 string_type str(e);
344 add_ahoemit(str);
345 }
346 }
347
348 string_collection get_ahoemits() const { return d_ahoemits; }
349
350 ptr failure() const { return d_failure; }
351
352 void set_failure(ptr fail_state) { d_failure = fail_state; }
353
354 state_collection get_states() const {
355 state_collection result;
356 for (auto it = d_success.cbegin(); it != d_success.cend(); ++it) {
357 result.push_back(it->second.get());
358 }
359 return state_collection(result);
360 }
361
362 transition_collection get_transitions() const {
363 transition_collection result;
364 for (auto it = d_success.cbegin(); it != d_success.cend(); ++it) {
365 result.push_back(it->first);
366 }
367 return transition_collection(result);
368 }
369
370 private:
371 ptr next_state(CharType character, bool ignore_root_state) const {
372 ptr result = nullptr;
373 auto found = d_success.find(character);
374 if (found != d_success.end()) {
375 result = found->second.get();
376 } else if (!ignore_root_state && d_root != nullptr) {
377 result = d_root;
378 }
379 return result;
380 }
381 };
382
383 template<typename CharType>
384 class basic_trie {
385 public:
386 using string_type = std::basic_string < CharType > ;
387 using string_ref_type = std::basic_string<CharType>&;
388
389 typedef state<CharType> state_type;
390 typedef state<CharType>* state_ptr_type;
391 typedef token<CharType> token_type;
392 typedef ahoemit<CharType> ahoemit_type;
393 typedef std::vector<token_type> token_collection;
394 typedef std::vector<ahoemit_type> ahoemit_collection;
395
396 class config {
397 bool d_allow_overlaps;
398 bool d_only_whole_words;
399 bool d_case_insensitive;
400
401 public:
402 config()
403 : d_allow_overlaps(true)
404 , d_only_whole_words(false)
405 , d_case_insensitive(false) {}
406
407 bool is_allow_overlaps() const { return d_allow_overlaps; }
408 void set_allow_overlaps(bool val) { d_allow_overlaps = val; }
409
410 bool is_only_whole_words() const { return d_only_whole_words; }
411 void set_only_whole_words(bool val) { d_only_whole_words = val; }
412
413 bool is_case_insensitive() const { return d_case_insensitive; }
414 void set_case_insensitive(bool val) { d_case_insensitive = val; }
415 };
416
417 private:
418 std::unique_ptr<state_type> d_root;
419 config d_config;
420 bool d_constructed_failure_states;
421
422 public:
423 basic_trie(): basic_trie(config()) {}
424
425 basic_trie(const config& c)
426 : d_root(new state_type())
427 , d_config(c)
428 , d_constructed_failure_states(false) {}
429
430 basic_trie& case_insensitive() {
431 d_config.set_case_insensitive(true);
432 return (*this);
433 }
434
435 basic_trie& remove_overlaps() {
436 d_config.set_allow_overlaps(false);
437 return (*this);
438 }
439
440 basic_trie& only_whole_words() {
441 d_config.set_only_whole_words(true);
442 return (*this);
443 }
444
445 void insert(string_type keyword) {
446 if (keyword.empty())
447 return;
448 state_ptr_type cur_state = d_root.get();
449 for (const auto& ch : keyword) {
450 cur_state = cur_state->add_state(ch);
451 }
452 cur_state->add_ahoemit(keyword);
453 }
454
455 template<class InputIterator>
456 void insert(InputIterator first, InputIterator last) {
457 for (InputIterator it = first; first != last; ++it) {
458 insert(*it);
459 }
460 }
461
462 token_collection tokenise(string_type text) {
463 token_collection tokens;
464 auto collected_ahoemits = parse_text(text);
465 size_t last_pos = -1;
466 for (const auto& e : collected_ahoemits) {
467 if (e.get_start() - last_pos > 1) {
468 tokens.push_back(create_fragment(e, text, last_pos));
469 }
470 tokens.push_back(create_match(e, text));
471 last_pos = e.get_end();
472 }
473 if (text.size() - last_pos > 1) {
474 tokens.push_back(create_fragment(typename token_type::ahoemit_type(), text, last_pos));
475 }
476 return token_collection(tokens);
477 }
478
479 ahoemit_collection parse_text(string_type text) {
480 check_construct_failure_states();
481 size_t pos = 0;
482 state_ptr_type cur_state = d_root.get();
483 ahoemit_collection collected_ahoemits;
484 for (auto c : text) {
485 if (d_config.is_case_insensitive()) {
486 c = std::tolower(c);
487 }
488 cur_state = get_state(cur_state, c);
489 store_ahoemits(pos, cur_state, collected_ahoemits);
490 pos++;
491 }
492 if (d_config.is_only_whole_words()) {
493 remove_partial_matches(text, collected_ahoemits);
494 }
495 if (!d_config.is_allow_overlaps()) {
496 interval_tree<ahoemit_type> tree(typename interval_tree<ahoemit_type>::interval_collection(collected_ahoemits.begin(), collected_ahoemits.end()));
497 auto tmp = tree.remove_overlaps(collected_ahoemits);
498 collected_ahoemits.swap(tmp);
499 }
500 return ahoemit_collection(collected_ahoemits);
501 }
502
503 private:
504 token_type create_fragment(const typename token_type::ahoemit_type& e, string_ref_type text, size_t last_pos) const {
505 auto start = last_pos + 1;
506 auto end = (e.is_empty()) ? text.size() : e.get_start();
507 auto len = end - start;
508 typename token_type::string_type str(text.substr(start, len));
509 return token_type(str);
510 }
511
512 token_type create_match(const typename token_type::ahoemit_type& e, string_ref_type text) const {
513 auto start = e.get_start();
514 auto end = e.get_end() + 1;
515 auto len = end - start;
516 typename token_type::string_type str(text.substr(start, len));
517 return token_type(str, e);
518 }
519
520 void remove_partial_matches(string_ref_type search_text, ahoemit_collection& collected_ahoemits) const {
521 size_t size = search_text.size();
522 ahoemit_collection remove_ahoemits;
523 for (const auto& e : collected_ahoemits) {
524 if ((e.get_start() == 0 || !std::isalpha(search_text.at(e.get_start() - 1))) &&
525 (e.get_end() + 1 == size || !std::isalpha(search_text.at(e.get_end() + 1)))
526 ) {
527 continue;
528 }
529 remove_ahoemits.push_back(e);
530 }
531 for (auto& e : remove_ahoemits) {
532 collected_ahoemits.erase(
533 std::find(collected_ahoemits.begin(), collected_ahoemits.end(), e)
534 );
535 }
536 }
537
538 state_ptr_type get_state(state_ptr_type cur_state, CharType c) const {
539 state_ptr_type result = cur_state->next_state(c);
540 while (result == nullptr) {
541 cur_state = cur_state->failure();
542 result = cur_state->next_state(c);
543 }
544 return result;
545 }
546
547 void check_construct_failure_states() {
548 if (!d_constructed_failure_states) {
549 construct_failure_states();
550 }
551 }
552
553 void construct_failure_states() {
554 std::queue<state_ptr_type> q;
555 for (auto& depth_one_state : d_root->get_states()) {
556 depth_one_state->set_failure(d_root.get());
557 q.push(depth_one_state);
558 }
559 d_constructed_failure_states = true;
560
561 while (!q.empty()) {
562 auto cur_state = q.front();
563 for (const auto& transition : cur_state->get_transitions()) {
564 state_ptr_type target_state = cur_state->next_state(transition);
565 q.push(target_state);
566
567 state_ptr_type trace_failure_state = cur_state->failure();
568 while (trace_failure_state->next_state(transition) == nullptr) {
569 trace_failure_state = trace_failure_state->failure();
570 }
571 state_ptr_type new_failure_state = trace_failure_state->next_state(transition);
572 target_state->set_failure(new_failure_state);
573 target_state->add_ahoemit(new_failure_state->get_ahoemits());
574 }
575 q.pop();
576 }
577 }
578
579 void store_ahoemits(size_t pos, state_ptr_type cur_state, ahoemit_collection& collected_ahoemits) const {
580 auto ahoemits = cur_state->get_ahoemits();
581 if (!ahoemits.empty()) {
582 for (const auto& str : ahoemits) {
583 auto ahoemit_str = typename ahoemit_type::string_type(str);
584 collected_ahoemits.push_back(ahoemit_type(pos - ahoemit_str.size() + 1, pos, ahoemit_str));
585 }
586 }
587 }
588 };
589
590 typedef basic_trie<char> trie;
591 typedef basic_trie<wchar_t> wtrie;
592
593
594 } // namespace aho_corasick
595
596 #endif // AHO_CORASICK_HPP