Debian Codegraph @

eutils/search.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: search.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "os"
35 "strings"
36 "unicode"
37 )
38
39 // Searching for a single substring uses the Boyer-Moore-Horspool algorithm,
40 // as described in Niklaus Wirth, Algorithms and Data Structures, Prentice-Hall,
41 // 1986, p. 69.
42 // The original published code had a typographical error, where:
43 // UNTIL (j < 0) OR (p[j] # s[i])
44 // should have been:
45 // UNTIL (j < 0) OR (p[j] # s[k])
46 // This was corrected in later editions.
47
48 // Simultaneous searching for multiple substrings uses a Finite State Machine,
49 // as described in Andrew Binstock and John Rex, Practical Algorithms for
50 // Programmers, Addison-Wesley, 1995, p. 111.
51
52 // BMHSearcher for Boyer-Moore-Horspool search
53 type BMHSearcher struct {
54 skipTable [256]int
55 pattern string
56 patlen int
57 sensitive bool
58 whole bool
59 relaxed bool
60 compress bool
61 circular bool
62 }
63
64 // StringSearcher primes Boyer-Moore-Horspool displacement table
65 func StringSearcher(pattern string, caseSensitive, wholeWord, relaxed, compress, circular bool) *BMHSearcher {
66
67 if pattern == "" {
68 return nil
69 }
70
71 if wholeWord {
72 relaxed = true
73 }
74
75 if relaxed {
76 pattern = RelaxString(pattern)
77 } else if compress {
78 pattern = CompressRunsOfSpaces(pattern)
79 pattern = strings.TrimSpace(pattern)
80 }
81
82 if wholeWord {
83 pattern = " " + pattern + " "
84 }
85
86 patlen := len(pattern)
87
88 // position of last character in pattern
89 last := patlen - 1
90
91 // build precomputed Boyer-Moore-Horspool pattern matching table, which, by experiment,
92 // was slightly (but reproducibly) faster than the Boyer-Moore-Sunday variant.
93
94 // displacement table
95 var skip [256]int
96
97 // initialize bad character displacement table
98 for i := range skip {
99 skip[i] = patlen
100 }
101 for i := range last {
102 ch := pattern[i]
103 if caseSensitive {
104 skip[ch] = last - i
105 } else {
106 // same displacement for upper and lower case character
107 lwr := unicode.ToLower(rune(ch))
108 upr := unicode.ToUpper(rune(ch))
109 skip[lwr] = last - i
110 skip[upr] = last - i
111 }
112 }
113
114 return &BMHSearcher{
115 sensitive: caseSensitive,
116 whole: wholeWord,
117 relaxed: relaxed,
118 compress: compress,
119 circular: circular,
120 skipTable: skip,
121 pattern: pattern,
122 patlen: patlen,
123 }
124 }
125
126 // Search method uses precomputed Searcher tables to search a string or sequence
127 func (srch *BMHSearcher) Search(text string, offset int, proc func(string, string, int) bool) {
128
129 if srch == nil || text == "" || proc == nil {
130 return
131 }
132
133 if srch.relaxed {
134 text = RelaxString(text)
135 } else if srch.compress {
136 text = CompressRunsOfSpaces(text)
137 text = strings.TrimSpace(text)
138 }
139
140 if srch.whole {
141 text = " " + text + " "
142 }
143
144 // single pattern, use Boyer-Moore-Horspool algorithm
145
146 // original length of text before any duplication to simulate circularity
147 cutoff := len(text)
148
149 if cutoff < srch.patlen {
150 // DisplayError("Search text is shorter than pattern")
151 return
152 }
153
154 if srch.circular {
155 // for circular DNA molecule, copy initial characters and add them to the end of the text
156 overhang := text[:srch.patlen]
157 text += overhang
158 }
159
160 // copy values into local variables for speed
161 txtlen := len(text)
162 pattern := srch.pattern[:]
163 patlen := srch.patlen
164 max := txtlen - patlen
165 last := patlen - 1
166 skip := srch.skipTable[:]
167
168 // two slightly-different search variants avoids repeatedly testing srch.sensitive in inner loop
169 if srch.sensitive {
170
171 i := offset
172 for i <= max {
173
174 j := last
175 k := i + last
176 // case-sensitive test
177 for j >= 0 && text[k] == pattern[j] {
178 j--
179 k--
180 }
181 if j < 0 {
182 // if not past end of original text
183 if i < cutoff {
184 // send result to callback
185 if !proc(text[:], pattern[:], i) {
186 return
187 }
188 }
189 }
190 // find character in text above last character in pattern
191 ch := text[i+last]
192 // displacement table can shift pattern by one or more positions
193 i += skip[ch]
194 }
195
196 } else {
197
198 i := offset
199 for i <= max {
200
201 j := last
202 k := i + last
203 // case insensitive test
204 for j >= 0 && unicode.ToLower(rune(text[k])) == unicode.ToLower(rune(pattern[j])) {
205 j--
206 k--
207 }
208 if j < 0 {
209 // if not past end of original text
210 if i < cutoff {
211 // send result to callback
212 if !proc(text[:], pattern[:], i) {
213 return
214 }
215 }
216 }
217 // find character in text above last character in pattern
218 ch := text[i+last]
219 // displacement table can shift pattern by one or more positions
220 i += skip[ch]
221 }
222 }
223 }
224
225 // Matches method sends matching positions down an integer channel
226 func (srch *BMHSearcher) Matches(text string) <-chan int {
227
228 if srch == nil || text == "" {
229 return nil
230 }
231
232 out := make(chan int, chanDepth)
233 if out == nil {
234 DisplayError("Unable to create string search matcher")
235 os.Exit(1)
236 }
237
238 stringMatch := func(text string, out chan<- int) {
239
240 // close channel when all positions have been sent
241 defer close(out)
242
243 srch.Search(text[:], 0,
244 func(txt, ptn string, pos int) bool {
245 out <- pos
246 return true
247 })
248 }
249
250 // launch single matcher goroutine
251 go stringMatch(text[:], out)
252
253 return out
254 }
255
256 // Finite State Machine structures
257 type transitEntry struct {
258 char rune
259 next int
260 }
261
262 type matchesEntry struct {
263 match string
264 alias string
265 }
266
267 type stateEntry struct {
268 transit []transitEntry
269 matches []matchesEntry
270 failure int
271 }
272
273 // FSMSearcher for Finite State Machine search
274 type FSMSearcher struct {
275 stateArray []stateEntry
276 maxpatlen int
277 sensitive bool
278 whole bool
279 relaxed bool
280 compress bool
281 circular bool
282 }
283
284 const failState = -1
285
286 // fsmSearcher primes Finite State Machine transition tables
287 func fsmSearcher(patterns []string, caseSensitive, wholeWord, relaxed, compress, circular, isSequence, bothStrands bool) *FSMSearcher {
288
289 if patterns == nil {
290 return nil
291 }
292
293 if isSequence {
294 caseSensitive = false
295 wholeWord = false
296 relaxed = false
297 } else {
298 circular = false
299 }
300
301 if wholeWord {
302 relaxed = true
303 }
304
305 highState := 0
306
307 stateTable := make(map[int]map[rune]int)
308 stateFails := make(map[int]int)
309 stateMatch := make(map[int][]string)
310 stateAlias := make(map[string]string)
311
312 maxpatlen := 0
313
314 gotoState := func(state int, ch rune, failZero bool) int {
315
316 st, ok := stateTable[state]
317 if ok {
318 for lt, nx := range st {
319 if ch == lt {
320 return nx
321 }
322 }
323 }
324 if state == 0 && failZero {
325 return 0
326 }
327 return failState
328 }
329
330 addTransition := func(state int, ch rune, next int) {
331
332 st := stateTable[state]
333 if st == nil {
334 st = make(map[rune]int)
335 stateTable[state] = st
336 }
337 if caseSensitive {
338 st[ch] = next
339 } else {
340 // map to lower case character
341 lwr := unicode.ToLower(rune(ch))
342 st[lwr] = next
343 }
344 }
345
346 addOutput := func(state int, word string) {
347
348 mt, ok := stateMatch[state]
349 if !ok {
350 mt = make([]string, 0, 1)
351 }
352 mt = append(mt, word)
353 stateMatch[state] = mt
354 }
355
356 enterWord := func(word string) {
357
358 state := 0
359
360 // try to overlay beginning of word onto existing table
361 i := 0
362 for _, ch := range word {
363 nx := gotoState(state, ch, false)
364 if nx == failState {
365 break
366 }
367 i++
368 state = nx
369 }
370
371 // create new states for remaining characters in word
372 rem := word[i:]
373 for _, ch := range rem {
374 highState++
375 addTransition(state, ch, highState)
376 state = highState
377 }
378
379 // at end of word record match information
380 addOutput(state, word)
381 }
382
383 findFail := func(state, newState int, ch rune) {
384
385 nx := 0
386
387 // traverse existing failure path
388 for {
389 nx = gotoState(state, ch, true)
390 if nx != failState {
391 break
392 }
393 state = stateFails[state]
394 }
395
396 // add new failure state
397 stateFails[newState] = nx
398
399 // add matches of substring at new state
400 mt, ok := stateMatch[nx]
401 if ok {
402 for _, wrd := range mt {
403 addOutput(newState, wrd)
404 }
405 }
406 }
407
408 computeFail := func() {
409
410 // first-in first-out queue for computing failure states
411 var queue []int
412
413 // queue up states reached directly from state 0 (depth 1)
414 stateFails[0] = 0
415
416 st, ok := stateTable[0]
417 if ok {
418 for _, s := range st {
419 stateFails[s] = 0
420 queue = append(queue, s)
421 }
422 }
423
424 for len(queue) > 0 {
425
426 // remove top of queue
427 r := queue[0]
428 queue = queue[1:]
429
430 // depth 1 states beget depth 2 states, etc.
431 st, ok := stateTable[r]
432 if ok {
433 for ch, s := range st {
434 queue = append(queue, s)
435 state := stateFails[r]
436 findFail(state, s, ch)
437 }
438 }
439 }
440 }
441
442 alreadySeen := make(map[string]bool)
443
444 // initialize state table with search patterns
445 for _, txt := range patterns {
446
447 alias := ""
448
449 if isSequence {
450 txt, alias = SplitInTwoLeft(txt, ":")
451 }
452
453 if !caseSensitive {
454 txt = strings.ToLower(txt)
455 }
456
457 if relaxed {
458 txt = RelaxString(txt)
459 } else if compress {
460 txt = CompressRunsOfSpaces(txt)
461 txt = strings.TrimSpace(txt)
462 }
463
464 if wholeWord {
465 txt = " " + txt + " "
466 }
467
468 // skip if duplicate pattern
469 if alreadySeen[txt] {
470 if isSequence {
471 saw := stateAlias[txt]
472 // but if sequence alias previously generated for reverse complement of a pattern
473 if saw != "" && strings.HasPrefix(saw, "(") && strings.HasSuffix(saw, ")") {
474 if alias == "" {
475 alias = strings.ToUpper(txt)
476 }
477 // print top strand match under current entry
478 stateAlias[txt] = alias
479 }
480 }
481 continue
482 }
483 alreadySeen[txt] = true
484
485 if alias == "" {
486 alias = txt
487 if isSequence {
488 alias = strings.ToUpper(alias)
489 }
490 }
491 stateAlias[txt] = alias
492
493 enterWord(txt)
494
495 if bothStrands {
496 // also enter non-palindromic reverse complemenet
497 rev := ReverseComplement(txt)
498 if strings.ToUpper(rev) != strings.ToUpper(txt) {
499 alreadySeen[rev] = true
500 // search for lacZ ATGACCATGATTACGGATT on E. coli minus strand
501 // shows top strand match (AATCCGTAATCATGGTCAT) in parentheses
502 stateAlias[rev] = "(" + alias + ")"
503 enterWord(rev)
504 }
505 }
506
507 // track longest pattern, duplicate that much past end if circular molecule
508 mx := len(txt)
509 if maxpatlen < mx {
510 maxpatlen = mx
511 }
512 }
513
514 // compute states to go to on failure to match a character
515 computeFail()
516
517 // replace maps with arrays of structures for faster performance
518
519 // create master array
520 stateArray := make([]stateEntry, highState+1)
521
522 // populate master array from data in maps
523 for state := 0; state <= highState; state++ {
524
525 tsit := make([]transitEntry, 0, 1)
526 st, ok := stateTable[state]
527 if ok {
528 for lt, nx := range st {
529 te := transitEntry{char: lt, next: nx}
530 tsit = append(tsit, te)
531 }
532 }
533 stateArray[state].transit = tsit
534
535 stateArray[state].failure = stateFails[state]
536
537 mtch := make([]matchesEntry, 0, 1)
538 for _, mt := range stateMatch[state] {
539 al := stateAlias[mt]
540 if al == "" {
541 al = mt
542 }
543 me := matchesEntry{match: mt, alias: al}
544 mtch = append(mtch, me)
545 }
546 stateArray[state].matches = mtch
547 }
548
549 return &FSMSearcher{
550 sensitive: caseSensitive,
551 whole: wholeWord,
552 relaxed: relaxed,
553 compress: compress,
554 circular: circular,
555 stateArray: stateArray,
556 maxpatlen: maxpatlen,
557 }
558 }
559
560 // PatternSearcher primes Finite State Machine transition tables
561 func PatternSearcher(patterns []string, caseSensitive, wholeWord, relaxed, compress, circular bool) *FSMSearcher {
562
563 return fsmSearcher(patterns, caseSensitive, wholeWord, relaxed, compress, circular, false, false)
564 }
565
566 // SequenceSearcher primes tables for searching on one or more nucleotide or protein sequences
567 func SequenceSearcher(patterns []string, isProtein, isCircular, topStrandOnly bool) *FSMSearcher {
568
569 if patterns == nil {
570 return nil
571 }
572
573 if isProtein {
574 topStrandOnly = true
575 }
576
577 // expands nucleotide ambiguity characters into individual instantiated patterns
578 expandPattern := func(pat string) ([]string, bool) {
579
580 if pat == "" {
581 return nil, false
582 }
583
584 var expanded []string
585
586 overflowed := false
587
588 // recursive function definition
589 var expandNext func(prev, next string, level int)
590
591 expandNext = func(prev, next string, level int) {
592
593 // limits on recursion depth and number of expanded patterns
594 if overflowed {
595 return
596 } else if level > 256 {
597 overflowed = true
598 } else if len(expanded) > 256 {
599 overflowed = true
600 } else if next != "" {
601 // take next character
602 curr := next[:1]
603 next = next[1:]
604 // get set of bases if ambiguous
605 exp, ok := expandNuc[curr]
606 if !ok {
607 exp = curr
608 }
609 // recursively expand for each base at this position
610 for _, ch := range exp {
611 expandNext(prev+string(ch), next, level+1)
612 }
613 } else {
614 // at end of string, record one unambiguous pattern
615 expanded = append(expanded, prev)
616 }
617 }
618
619 expandNext("", pat, 1)
620
621 return expanded, overflowed
622 }
623
624 var arry []string
625
626 for _, pat := range patterns {
627
628 // each pattern can optionally be followed by a colon and an alias
629 txt, alias := SplitInTwoLeft(pat, ":")
630
631 if isProtein {
632 // bypass nucleotide character expansion
633
634 if alias != "" {
635 txt += ":" + alias
636 } else {
637 txt += ":" + txt
638 }
639 arry = append(arry, txt)
640
641 // go to next pattern
642 continue
643 }
644
645 // expand nucleotide ambiguity characters in pattern to instantiate all matching sequences
646 expanded, overflowed := expandPattern(txt)
647
648 if overflowed {
649 DisplayError("Ignoring pattern expansion of '%s' due to overflow", pat)
650 continue
651 }
652
653 for _, str := range expanded {
654 if alias == "+" {
655 // RCCGGY:+ prints RCCGGY
656 str += ":" + txt
657 } else if alias == "-" {
658 // RCCGGY:- prints RCCGGY-ACCGGC, etc.
659 str += ":" + txt + "-" + str
660 } else if alias != "" {
661 // RCCGGY:BsrFI-v2 prints BsrFI-v2
662 str += ":" + alias
663 } else {
664 // RCCGGY prints ACCGGC, ACCGGT, GCCGGC, or GCCGGT
665 str += ":" + str
666 }
667 arry = append(arry, str)
668 }
669 }
670
671 return fsmSearcher(arry, false, false, false, true, isCircular, true, !topStrandOnly)
672 }
673
674 // Search uses precomputed Searcher tables to search a string or sequence
675 func (srch *FSMSearcher) Search(text string, proc func(string, string, int) bool) {
676
677 if srch == nil || text == "" || proc == nil {
678 return
679 }
680
681 if srch.relaxed {
682 text = RelaxString(text)
683 } else if srch.compress {
684 text = CompressRunsOfSpaces(text)
685 text = strings.TrimSpace(text)
686 }
687
688 if srch.whole {
689 text = " " + text + " "
690 }
691
692 // multiple patterns, use Finite State Machine
693 // (can coerce use of FSM on single pattern by entering the same pattern twice)
694
695 // original length of text before any duplication to simulate circularity
696 cutoff := len(text)
697
698 if cutoff < srch.maxpatlen {
699 // DisplayError("Search text is shorter than pattern")
700 return
701 }
702
703 if srch.circular {
704 // for circular DNA molecule, copy initial characters and add them to the end of the text
705 overhang := text[:srch.maxpatlen]
706 text += overhang
707 }
708
709 // not the same as version used in creation - no failZero argument, and works on final arrays
710 gotoState := func(state int, ch rune) int {
711
712 tbl := srch.stateArray[state]
713 if tbl.transit != nil {
714 for _, te := range tbl.transit {
715 if ch == te.char {
716 return te.next
717 }
718 }
719 }
720 if state == 0 {
721 return 0
722 }
723 return failState
724 }
725
726 state := 0
727 for pos, ch := range text {
728
729 nx := 0
730
731 if !srch.sensitive {
732 ch = unicode.ToLower(rune(ch))
733 }
734
735 for {
736 nx = gotoState(state, ch)
737 if nx != failState {
738 break
739 }
740 tbl := srch.stateArray[state]
741 state = tbl.failure
742 }
743
744 state = nx
745
746 tbl := srch.stateArray[state]
747 if tbl.matches != nil {
748 for _, me := range tbl.matches {
749 point := pos - len(me.match) + 1
750 // if not past end of original text
751 if point < cutoff {
752 // send result to callback
753 if !proc(text[:], me.alias, point) {
754 return
755 }
756 }
757 }
758 }
759 }
760 }