Docsity

Efficient Pattern Matching with Error Tolerance: Analysis and Simulation, Papers of Computer Science

Toggle sidebar
bg1
Algorithmica (1999) 23: 127–158 Algorithmica
©1999 Springer-VerlagNew York Inc.
Faster Approximate String Matching1
R. Baeza-Yates2and G. Navarro2
Abstract. We present a new algorithm for on-line approximate string matching. The algorithm is based
on the simulation of a nondeterministic finite automaton built from the pattern and using the text as input.
This simulation uses bit operations on a RAM machine with word length w=Ä(logn)bits, where nis the
text size. This is essentially similar to the model used in Wu and Manber’s work, although we improve the
search time by packing the automaton states differently. The running time achieved is O(n)for small patterns
(i.e., whenever mk =O(logn)), where mis the pattern length and k<mis the number of allowed errors.
This is in contrast with the result of Wu and Manber, which is O(kn)for m=O(logn). Longer patterns can
be processed by partitioning the automaton into many machine words, at O(mk/w n)search cost. We allow
generalizations in the pattern, such as classes of characters, gaps, and others, at essentially the same search
cost.
We then explore other novel techniques to cope with longer patterns. We show how to partition the
pattern into short subpatterns which can be searched with less errors using the simple automaton, to obtain an
average cost close to O(pmk/w n). Moreover, we allow the superimposition of many subpatterns in a single
automaton, obtaining near O(pmk/(σ w) n)average complexity (σis the alphabet size).
We perform a complete analysis of all the techniques and show how to combine them in an optimal form,
also obtaining new tighter bounds for the probability of an approximate occurrence in random text. Finally,
we show experimental results comparing our algorithms against previous work. These experiments show that
our algorithms are among the fastest for typical text searching, being the fastest in some cases. Although we
aim mainly at text searching, we believe that our ideas can be successfully applied to other areas such as
computational biology.
Key Words. Text searching allowing errors, Bit-parallelism.
1. Introduction. Approximatestring matchingis oneof themain problemsin classical
string algorithms, with applications to text searching, computational biology, pattern
recognition, etc. Given a text of length n, a pattern of length m, and a maximal number
of errors allowed, k, we want to find all text positions where the pattern matches the
text up to kerrors. Errors can be substituting, deleting, or inserting a character. We call
α=k/mthe error ratio, and σthe alphabet size.
The solutions to this problem differ if the algorithm has to be on-line (that is, the
text is not known in advance) or off-line (the text can be preprocessed). In this paper we
are interested in the first case, where the classical dynamic programming solution has
O(mn)running time [21], [22].
Recently several algorithms have been presented that achieve O(kn)comparisons in
the worst-case [28], [13], [16], [17] or in the average case [29], [13], by taking advantage
1This work has been supported in part by FONDECYT Grants 1950622 and 1960881.
2Department of Computer Science, University of Chile, Blanco Encalada 2120, Santiago, Chile.
{rbaeza,gnavarro}@dcc.uchile.cl.
Received November 22, 1996; revised October 13 and December 5, 1997. Communicated by M. Y. Kao.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download Efficient Pattern Matching with Error Tolerance: Analysis and Simulation and more Papers Computer Science in PDF only on Docsity!

Algorithmica (1999) 23: 127–

Algorithmica

© 1999 Springer-Verlag New York Inc.

Faster Approximate String Matching^1

R. Baeza-Yates^2 and G. Navarro^2

Abstract. We present a new algorithm for on-line approximate string matching. The algorithm is based on the simulation of a nondeterministic finite automaton built from the pattern and using the text as input. This simulation uses bit operations on a RAM machine with word length w = ƒ(log n ) bits, where n is the text size. This is essentially similar to the model used in Wu and Manber’s work, although we improve the search time by packing the automaton states differently. The running time achieved is O ( n ) for small patterns (i.e., whenever mk = O (log n )), where m is the pattern length and k < m is the number of allowed errors. This is in contrast with the result of Wu and Manber, which is O ( kn ) for m = O (log n ). Longer patterns can be processed by partitioning the automaton into many machine words, at O ( mk /w n ) search cost. We allow generalizations in the pattern, such as classes of characters, gaps, and others, at essentially the same search cost. We then explore other novel techniques to cope with longer patterns. We show how to partition the pattern into short subpatterns which can be searched with less errors using the simple automaton, to obtain an average cost close to O (

mk /w n ). Moreover, we allow the superimposition of many subpatterns in a single

automaton, obtaining near O (

mk /(σ w) n ) average complexity (σ is the alphabet size). We perform a complete analysis of all the techniques and show how to combine them in an optimal form, also obtaining new tighter bounds for the probability of an approximate occurrence in random text. Finally, we show experimental results comparing our algorithms against previous work. These experiments show that our algorithms are among the fastest for typical text searching, being the fastest in some cases. Although we aim mainly at text searching, we believe that our ideas can be successfully applied to other areas such as computational biology.

Key Words. Text searching allowing errors, Bit-parallelism.

1. Introduction. Approximate string matching is one of the main problems in classical string algorithms, with applications to text searching, computational biology, pattern recognition, etc. Given a text of length n , a pattern of length m , and a maximal number of errors allowed, k , we want to find all text positions where the pattern matches the text up to k errors. Errors can be substituting, deleting, or inserting a character. We call α = k / m the error ratio , and σ the alphabet size. The solutions to this problem differ if the algorithm has to be on-line (that is, the text is not known in advance) or off-line (the text can be preprocessed). In this paper we are interested in the first case, where the classical dynamic programming solution has O ( mn ) running time [21], [22]. Recently several algorithms have been presented that achieve O ( kn ) comparisons in the worst-case [28], [13], [16], [17] or in the average case [29], [13], by taking advantage

(^1) This work has been supported in part by FONDECYT Grants 1950622 and 1960881. (^2) Department of Computer Science, University of Chile, Blanco Encalada 2120, Santiago, Chile. {rbaeza,gnavarro}@dcc.uchile.cl.

Received November 22, 1996; revised October 13 and December 5, 1997. Communicated by M. Y. Kao.

128 R. Baeza-Yates and G. Navarro

of the properties of the dynamic programming matrix (e.g., values in neighbor cells differ at most by one). Following the same trend is [9], with average time complexity O ( kn /

σ ). All average-case figures assume random text and uniformly distributed alphabets. Other approaches first filter the text, reducing the area where dynamic programming needs to be used [27], [30], [26], [25], [10], [11], [19], [8], [23]. These algorithms achieve “sublinear” expected time in many cases for low error ratios (i.e., not all text characters are inspected, O ( kn logσ m / m ) is a typical figure), although filtration is not effective for more errors. Filtration is based on the fact that some portions of the pattern must appear with no errors even in an approximate occurrence. In [29] the use of a deterministic finite automaton (DFA) which recognizes the ap- proximate occurrences of the pattern in the text is proposed. Although the search phase is O ( n ), the DFA can be huge. In [20] and [15] the automaton is computed in lazy form (i.e., only the states actually reached in the text are generated). Yet other approaches use bit-parallelism [2], [4], [34], i.e., they simulate parallelism with bit operations in a RAM machine of word length w = ƒ(log n ) bits, to reduce the number of operations. In [32] the cells of the dynamic programming matrix are packed in diagonals to achieve O ( mn log(σ )/w) time complexity. In [35] a Four Russians approach is used to pack the matrix in machine words, achieving O ( kn /w) time on average (ending up in fact with a DFA where they can trade the number of states for their internal complexity). Of special interest to this work is [34], which considers a nondeterministic finite au- tomaton (NFA) functionally similar to the DFA but having only a few states. O ( kmn /w) time is achieved in [34] by parallelizing in bits the work of such an automaton. The main contributions of the present work follow.

  • We present a new algorithm for approximate string matching. It is based on bit- parallelism, where bit operations are used to simulate the behavior of an NFA built from the pattern and using the text as input. This automaton is similar to that of Wu and Manber [34]. However, we pack diagonals instead of rows into machine words. This leads to a worst-case running time of O ( n ) (independently of k ) for small patterns (i.e., mk = O (w)). This is the case in most single-word text patterns. This simple algorithm is experimentally shown to be the fastest one we are aware of for short patterns, except for very small k values where other filtration algorithms are even faster.
  • We show how to partition a large automaton that does not fit in a computer word, to obtain an algorithm which performs near d mk /we n operations, against d m /we kn performed by Wu and Manber (their operations are simpler, though). The difference is especially noticeably in small patterns. This algorithm performs well for all error ratios if the pattern is not very long, being the fastest for high error ratios, an area largely unexplored in previous work.
  • We show that some generalizations in the pattern (which we call extended patterns ) can be handled at almost no additional search cost. We allow one to have classes of characters at each pattern position (instead of just one character per position), gaps inside the pattern, etc.
  • We present a technique to partition a long pattern into subpatterns, such that the

130 R. Baeza-Yates and G. Navarro

Fig. 1. An NFA for approximate string matching. Unlabeled transitions match any character. Active states are ( 2 , 3 ), ( 2 , 4 ), and ( 1 , 3 ), besides those always active of the lower-left triangle. We enclose in dotted lines the states actually represented in our algorithm.

“occurrences” or “matches”) of Text whose edit distance to pat is at most k , the number of allowed errors. It is common to report only the endpoints of occurrences, as well as to discard occurrences containing or contained in others. In this work we focus on returning endpoints of occurrences not containing others. The edit distance between two strings a and b is the minimum number of edit oper- ations needed to transform a into b. The allowed edit operations are deleting, inserting, and replacing a character. Therefore, the problem is nontrivial for 0 < k < m. The error ratio is defined as α = k / m. We use a C-like notation for the operations (e.g., &, |, ==,! =, ∧, ¿). We use text to denote the current character of Text and, unlike C, str [ j ] to denote the j th character of str (i.e., the strings begin at position one, not zero). Consider the NFA for searching "patt" with at most k = 2 errors shown in Figure 1. Every row denotes the number of errors seen. The first one 0, the second one 1, and so on. Every column represents matching the pattern up to a given position. At each iteration, a new text character is considered and the automaton changes its states. Horizontal arrows represent matching a character (since we advance in the pattern and in the text, and they can only be followed if the corresponding match occurs), vertical arrows represent inserting a character in the pattern (since we advance in the text but not in the pattern, increasing the number of errors), solid diagonal arrows represent replacing a character (since we advance in the text and pattern, increasing the number of errors), and dashed diagonal arrows represent deleting a character of the pattern (they are empty transitions, since we delete the character from the pattern without advancing in the text, and increase the number of errors). Finally, the self-loop at the initial state allows us to consider any character as a potential starting point of a match, and the automaton accepts a character (as the end of a match) whenever a rightmost state is active. If we do not care about

Faster Approximate String Matching 131

the number of errors of the occurrences, we can consider as final states those of the last full diagonal. Because of the empty transitions, this makes acceptance equivalent to the lower-right state being active. This NFA has ( m + 1 ) × ( k + 1 ) states. We assign number ( i , j ) to the state at row i and column j , where i ∈ 0 · · · k , j ∈ 0 · · · m. Initially, the active states at row i are at the columns from 0 to i , to represent the deletion of the first i characters of the pattern. Consider the boolean matrix A corresponding to this automaton. Ai , j is 1 if state ( i , j ) is active and 0 otherwise. The matrix changes as each character of the text is read. The new values A ′ i , j can be computed from the current ones by the following rule:

(1) A ′ i , j = ( Ai , j − 1 & ( text == pat [ j ])) | Ai − 1 , j | Ai − 1 , j − 1 | A ′ i − 1 , j − 1 ,

which is used for i ∈ 0 · · · k , j ∈ 1 · · · m. If i = 0 only the first term is used. Note that the empty transitions are represented by immediately propagating a 1 at any position to all the elements following it in its diagonal, all in a single iteration (thus computing the ε-closure). The self-loop at the initial state is represented by the fact that column j = 0 is never updated. The main comparison-based algorithms for approximate string matching consist fun- damentally in working on a dynamic programming matrix. Each column of the ma- trix holds the state of the search at a given text character. It is not hard to show that what the column stores at position j is the minimum row of this NFA which is active in column j of the automaton. In this sense, the dynamic programming matrix cor- responds to simulating this automaton by columns (i.e., packing columns in machine words) [3]. On the other hand, the work of Wu and Manber consists fundamentally in simulating this automaton by rows (packing each row in a machine word). In both cases the depen- dencies introduced by the diagonal empty transitions prevent the parallel computation of the new values. In the next section we present an approach that avoids this depen- dence, by simulating the automaton using diagonals, such that each diagonal captures the ε-closure [3]. This idea leads to a new and fast algorithm.

3. A New Algorithm. Suppose we use just the full diagonals of the automaton (i.e., those of length k +1). This presents no problem, since those (shorter) diagonals below the full ones always have value 1, while those past the full ones do not influence state ( m , k ). The last statement may not be obvious, since the vertical transitions allow us to carry 1’s from the last diagonals to state ( m , k ). However, each 1 present at the last diagonals must have crossed the last full diagonal, where the empty transitions (deletions) would have immediately copied it to the state ( m , k ). That is, any 1 that goes again to state ( m , k ) corresponds to a segment containing one that has already been reported. Notice also that, whenever state ( i , j ) is active, states ( i + d , j + d ) are also active for all d > 0 (due to the empty deletion transition). Thus, if we number diagonals regarding the column at which they begin, the state of each diagonal i can be represented by a number Di , the smallest row value active in that diagonal (i.e., the smallest error). Then the state of this simulation consists of m − k + 1 values in the range 0 · · · k + 1. Note that D 0 is always 0, hence, there is no need to store it. The new values for Di ( i ∈ 1 · · · m − k ) after we read a new text character c are

Faster Approximate String Matching 133

Fig. 2. Encoding of the example NFA. In this example, t [’t’] = 0011.

The computation of the g function is carried out by defining, for each character c , an m bits long mask t [ c ], representing match (0) or mismatch (1) against the pattern, and then computing a mask T [ c ] having at each block the ( k + 1 ) bits long segment of t [ c ] that is relevant to that block (see Figure 2). That is,

(3) t [ c ] = ( c! = pat [ m ]) ( c! = pat [ m − 1]) · · · ( c! = pat [1]),

where each condition stands for a bit and they are aligned to the right. So we precompute

T [ c ] = 0 sk + 1 ( t [ c ], 0 ) 0 sk + 1 ( t [ c ], 1 ) · · · 0 sk + 1 ( t [ c ], m − k − 1 )

for each c , where sj ( x , i ) shifts x to the right in i bits and takes the last j bits of the result (the bits that “fall” are discarded). Note that T [ c ] fits in a computer word if the problem does. We now have all the elements to implement the algorithm. We represent the current state by a computer word D. The value of all Di ’s is initially k + 1, so the initial value of D is D in = (0 1 k +^1 ) m − k^. The formula to update D upon reading a text character c is derived from (2):

(4) D ′^ = ( D ø 1 ) | ( 0 k +^11 ) m − k

& ( D ø ( k + 3 )) | ( 0 k +^11 ) m − k −^1 0 1 k +^1 & ((( x + ( 0 k +^11 ) m − k^ ) ∧ x ) ¿ 1 ) & D in,

where

x = ( D ¿ ( k + 2 )) | T [ c ]. The update formula is a sequence of and ’s, corresponding to the min of (2). The first line corresponds to Di + 1, the second line to Di + 1 + 1, the third line is the g function applied to the previous diagonal, and the fourth line ensures the invariant of having 0’s in the separators (needed to limit the propagation of “+”). Note that we are assuming that the shifts get 0’s from both borders of the word (i.e., unsigned semantics). If this is not the case in a particular architecture, additional masking is necessary.

134 R. Baeza-Yates and G. Navarro

We detect that state ( m , k ) is active by checking whether D & ( 1 ø k ) is 0. When we find a match, we clear the last diagonal. This ensures that our occurrences always end with a match.

3.2. A Simple Filter. We can improve the previous algorithm (and in fact most other algorithms as well) by noticing that any approximate occurrence of the pattern with k errors must begin with one of its k + 1 first characters. This allows us to discard large parts of the text quickly with very few operations per character. We do not run the automaton through all text characters, but scan the text looking for any of the k + 1 initial characters of the pattern. Only then do we start the automaton. When the automaton returns to its initial configuration, we resume the scanning. The scanning is much cheaper than the operation of our automaton, and in fact it is cheaper than the work done per text character in most algorithms. We precompute a boolean table S [ c ], that stores for each character c whether it is one of the first k + 1 letters of the pattern. Observe that this table alone solves the problem for the case k = m − 1 (since each positive answer of S is an occurrence). Figure 3 presents the complete algorithm (i.e., using the automaton plus the filter).

Fig. 3. Algorithm to search for a short pattern. Strings are assumed to start at position 1.

136 R. Baeza-Yates and G. Navarro

We find a match whenever DI − 1 , J − 1 has a 0 in its last position, i.e., at ( k − _r_ ( _I_ − 1 )) + ( r + 1 )(` c J − ( m − k )), counting from the right. In that case we must clear the last diagonal, i.e., that of Di , J − 1 for all i. The fact that we select the minimal I and that we solve the case k = m − 1 with a simpler algorithm (the S table) causes this general scheme to fall into three simpler cases: (a) the automaton is horizontal, (b) the automaton is horizontal and only one diagonal fits in each word, and (c) the automaton spreads horizontally and vertically but only one diagonal fits in each word. Those cases can be solved with a simpler (two or three times faster) update formula. In practice, there are some cases where a purely vertical automaton is better [5]. In particular, Wu and Manber’s automaton can be thought of as a vertical partitioning of the NFA of Figure 1 (although the details are different).

3.4. Handling Extended Patterns. We now show that some of the generalizations of the approximate string search problem considered in [4], [34] and [35] can be introduced into our algorithm at no additional search cost. We call those patterns involving some of these generalizations extended patterns. As in the shift-or algorithm for exact matching [4], we can specify a set of characters at each position of the pattern instead of a single one (this is called “limited expressions” in [35]). For example, to find “patt” in case-insensitive, we search for {p, P}{a, A}{t, T}{t, T}; to find “patt” followed by a digit, we search for {p}{a}{t}{t}{ 0 .. 9 }. This is achieved by modifying the t [] table (3), making any element of the set to match that position, with no running time overhead. In addition to classes of characters, we can support the # operator as defined in [34]. That is, x # y allows zero or more arbitrary characters among the strings x and y in the occurrences. Those characters are not counted as errors. As shown in [33], in order to handle this operator we must enforce that whenever an automaton state in column | x | is active, it keeps active from then on. Hence, to search for x 1 # x 2 # · · · # xt we create a D # word having all 1’s except at all states of columns | x 1 |, | x 1 | + | x 2 |,... , | x 1 | + | x 2 | + · · · + | xt − 1 |. We now modify the computation of x in (2), which becomes

x = (( D ¿ ( k + 2 )) | T [ text ]) & ( D | D #)

(clearly this technique is orthogonal to the use of classes of characters). This technique is easily extended to partitioned automata. We can modify the automaton to compute edit distance (more precisely, determine whether the edit distance is ≤ k or not). This is obtained by eliminating the initial self- loop and initializing the automaton at D = D in. However, we need to represent the k + 1 initial diagonals that we discarded. If we need the exact edit distance, we must also represent the last k diagonals that we discarded. If there is no a priori bound on the distance, we need to set k = m. We can search for whole words, running the edit-distance algorithm only from word beginnings (where we re-initialize D = D in), and checking matches only at the end of words. Searching with different integral costs for insertion and substitution (including not allowing such operations) can be accommodated in our scheme, by changing the arrows.

Faster Approximate String Matching 137

Deletion is built into the model in such a way that in order to accommodate it we must change the meaning of our “diagonals,” so that they are straight ε-transition chains. Other generalizations are studied in [34]. We can handle them too, although not as easily and efficiently as the previous ones. One such generalization is the combination in the pattern of parts that must match exactly with others that can match with errors. The adaptation to avoid propagation of ε-closures in our scheme is ad hoc and not as elegant as in [34]. However, we believe that the most effective way to handle these patterns is to search quickly for the parts that match exactly and then try to extend those matches to the complete pattern, using our automaton to compute edit distance. Another such generalization is approximate search of regular expressions. In [34] the regularities among rows allow one to solve any regular expression of m letters using d m / 8 e or even d m / 16 e operations per text character, using d m / 8 e 28 d m /we or d m / 16 e 216 d m /we machine words of memory, respectively. Our partitioned automata are not so regular, and we would need roughly O ( k^2 ) times Wu and Manber’s space requirements and operations per text character. To be more precise, in our scheme their formulas are still valid provided we replace m by ( m − k )( k + 2 ). For instance, at the cost they pay for m ≤ 32, we can only solve for m ≤ 9. However, our scheme is still reasonably applicable for short expressions.

4. New Partitioning Techniques. The following lemma, which is a generalization of the partitioning scheme presented in [34] and [18], suggests a way to partition a large problem into smaller ones.

LEMMA 1. If segm = Text [ a .. b ] matches pat with k errors , and pat = p 1 · · · pj ( a concatenation of subpatterns ), then segm includes a segment that matches at least one of the pi’s , with b k / j c errors.

PROOF. Suppose the opposite. Then, in order to transform pat into segm , we need to transform each pi into an si , such that segm = s 1 · · · sj. However, since no pi is present in segm with less than b k / j c errors, each pi needs at least 1 + b k / j c edit operations to be transformed into any segment of segm ( si in particular). Thus the whole transformation needs at least j ( 1 + b k / j c) > j ( k / j ) = k operations. A contradiction.

The lemma is a generalization of that of [34] because Wu and Manber consider only the case j = k + 1 (we return to this case later), and it is a (slight) generalization of that of [18] because Myers considers only cases of the form j = 2 t^ (the pattern is partioned in a binary fashion until short enough subpatterns are obtained). Moreover, the previous authors always consider partitioning into pieces of almost the same size, while the lemma allows any split. We now explore different ways to use the lemma.

4.1. Pattern Partitioning. The lemma allows us to reduce the number of errors if we divide the pattern, provided we search all the subpatterns. Each match of a subpattern must be checked to determine if it is in fact a complete match (notice that the subpatterns

Faster Approximate String Matching 139

checking its area, and advancing that subsearch to its next candidate position. This allows us to avoid reverifying the same text because of different overlapping candidate areas. This is done by remembering the last checked position and keeping the state of the checking algorithm. The effectiveness of this method is limited by the error level. If the subpatterns appear very often, we spend a lot of time verifying candidate text positions. In Section 5 we find out which is the error level that allows us to use this scheme.

4.2. Superimposing the Subproblems. When the search is divided into a number of subsearches for smaller patterns P 1 ,... , Pr , it is possible not to search each one sepa- rately. We describe a technique, called superimposition , to collapse a number of searches into a single one. In our scheme, all patterns have almost the same length. If they differ (at most by one), we truncate them to the shortest length. Hence, all the automata have the same structure, differing only in the labels of the horizontal arrows. The superimposition is defined as follows: we build the t [] table for each pattern (see (3)), and then take the bitwise- and of all the tables. The resulting t [] table matches in position i with the i th character of any pattern. We then build the automaton as before using this table. The resulting automaton accepts a text position if it ends an occurrence of a much more relaxed pattern (in fact it is an extended pattern ), namely,

{ P 1 [1],... , Pr [1]} · · · { P 1 [ m ],... , Pr [ m ]},

for example, if the search is for patt and wait, the string watt is accepted with zero errors (see Figure 5). Each occurrence reported by the automaton has to be verified for all the patterns involved.

Fig. 5. An NFA to filter the parallel search of patt and wait.

140 R. Baeza-Yates and G. Navarro

For a moderate number of patterns, this still constitutes a good filtering mechanism, at the same cost of a single search. Clearly, the relaxed pattern triggers many more verifica- tions than the simple ones. This severely limits the amount of possible superimposition. However, as we show later, in practice this can cut the search times by two or three. This idea has been applied to the problem of multiple approximate string matching, where similar speedup figures were obtained [7]. We analyze later how many subpatterns can be collapsed while keeping the number of verifications small. We must then form sets of patterns that can be searched together, and search each set separately. Notice that extended patterns containing #’s may not be superimposed because their D # words are different. Observe that having the same character at the same position for two patterns improves filtering efficiency. This fact can be used to select the best partition of the pattern.

4.3. Mixed Partitioning. Finally, it is possible to combine automaton and pattern parti- tioning. If we partition the pattern in subpatterns that are still too large to fit in a computer word, the automaton for each subpattern has to be further partitioned into subautomata. This is a generalization that includes both techniques as particular cases, and uses a smaller j value. As we show in the analysis, however, this technique is no better in practice than pure pattern partitioning. However, we find that the larger j is, the less tolerant to the error level our scheme is. Therefore, using a smaller j can be necessary if α is high. For high error levels we use the largest j allowed. For α large enough, though, the only allowed value for j is one, which is equivalent to pure automaton partitioning. Therefore, mixed partitioning provides a smooth transition between pure pattern and pure automaton partitioning. Superimposition could also be applied on the resulting (large) automata.

5. Analysis. In this section we analyze the different aspects of our algorithms. We also study some statistics of the problem which are useful for the analysis. We make heavy use of the shorthand α = k / m. It is important to notice that our average-case analysis assumes that the pattern is not extended and that text and patterns are random strings over an independently generated and uniformly distributed alphabet of size σ. If the alphabet is not uniformly distributed we must replace the σ in the formulas by 1/ p , where p is the probability that two random letters match. For generalized patterns, the α i values are different, but we are unable to compute them. We summarize here the results of this section, which involve the optimal heuristic to combine our algorithms. Table 1 presents a summary of the important limiting α values found in the analysis. We now sketch how the algorithm behaves among the areas delimited by m and α 0 < α 1 < α 2. In all cases we can use the heuristic of the S table to reduce the average cost.

  • If the problem fits in a single word (i.e., ( m − k )( k + 2 ) ≤ w), the simple algorithm should be used, which is O ( n ) time in the average and worst case. If the problem does not fit in a single word, we may use pattern, automaton, or mixed partitioning.

142 R. Baeza-Yates and G. Navarro

Fig. 7. Theoretical and practical bounds for α.

5.1. The Statistics of the Problem. Even natural questions about the distribution and statistical behavior of this problem are very hard to answer. Some of them are: what is the probability of an occurrence? How many occurrences are there on average? How many columns of the dynamic programming matrix are active? Some of these questions also arise in the analysis of our algorithms. We give our new results here. A first concern is the probability of matching. Let f ( m , k ) be the probability of a random pattern of length m matching a given text position with k errors or less. This probability is crucial to assure that the number of verifications of candidate matches in pattern partitioning is not too large. We show in the Appendix that for α ≤ 1 − e /(

σ γ 1 /(^2 (^1 −α))), f ( m , k ) is O (γ m^ ), with γ < 1. In particular, for α < 1 − e /

σ , f ( m , k ) is exponentially decreasing with m. Figure 7 shows the experimental verification of this analysis for m = 300 (we obtained similar results with other m values). The curve α = 1 − 1 /

σ is included to show its closeness to the experimental data. Least squares gives the approximation α = 1 −

  1. 09 /

σ , with a squared error smaller than 10−^4. The experiment consists of generating a large random text and running the search of a random pattern on that text, with k = m errors. At each text character, we record the minimum k for which that position would match the pattern. Finally, we analyze the histogram, and consider that k is safe up to where the histogram values become significant. The threshold is set to n / m^2 , since m^2 is the cost of verifying a match. However, the selection of this threshold is not very important, since the histogram is extremely concentrated. For example, it has five or six significant values for m in the hundreds. A second question we answer is: what is the number of columns we work on, on average, in the cut-off heuristic of Ukkonen [29]? That is, if we call Cr the smallest-row active state of column r in our NFA, what is the largest r satisfying Cr ≤ k? The columns satisfying Cr ≤ k are called active , and columns past the last active one need not be computed. Ukkonen conjectured that the number of active columns was O ( k ), but this

Faster Approximate String Matching 143

was proved later by Chang and Lampe [9]. We follow the proof of [9] to find a tighter bound. If we call L the last active column, we have

E ( L ) ≤ K +

r > K

r P [ Cr ≤ k ]

for any K. Since we know that if k / r < 1 − e /

σ , then P [ Cr ≤ k ] = O (γ r^ ) with γ < 1, we take K = k /( 1 − e /

σ ) to obtain

E ( L ) ≤

k 1 − e /

σ

r > k /( 1 − e /√σ )

r O (γ r^ ) =

k 1 − e /

σ

(6) + O ( 1 ),

which shows that, on average, the last active column is O ( k ). This refines the proof of [9] that the heuristic of [29] is O ( kn ). By using least squares on experimental data we find that a very accurate formula is 0. 9 k /( 1 − 1. 09 /

σ ).

5.2. The Simple Algorithm. The preprocessing phase of this algorithm can be opti- mized to take O (σ + m min( m , σ )) time, and it requires O (σ ) space. The search phase needs O ( n ) time. However, this algorithm is limited to the case in which ( m − k )( k + 2 ) ≤ w. In the RAM model it is assumed log 2 n ≤ w, so a machine-independent bound is ( m − k )( k + 2 ) ≤ log 2 n. Since ( m − k )( k + 2 ) takes its maximum value when k = m / 2 −1, we can assure that this algorithm can be applied whenever m ≤ 2 (

w − 1 ), indepen- dently of k. That is, we have a linear algorithm for m = O (

log n ), for example, m ≤ 9 for w = 32 bits, or m ≤ 14 for w = 64 bits.

5.3. Partitioning the Automaton. If we divide the automaton in IJ subautomata ( I d- rows and J d-columns), we must update I cells at each d-column. However, we use a heuristic similar to [29] (i.e., not processing the m columns but only up to the last active one), so we work only on active automaton diagonals. To compute the expected last active diagonal, we use the result of (6). Since this measures active columns and we work on active diagonals, we subtract k to obtain that on average we work on ke /(

σ − e ) diagonals. Since we pack ( m − k )/ J diagonals in a single cell, we work on average on ( ke /(

σ − e ) + 1 ) J /( m − k ) machine words. However, since there are only J d-columns, our total complexity is

IJ min

ke ( m − k )(

σ − e )

n ,

which shows that any choice for I and J is the same for a fixed IJ. Since IJ ≈ ( m − k )( k + 1 )/(w − 1 ), the final cost expression is independent (up to round-offs) of I and J :

min

m − k ,

ke √ σ − e

k + 1 w − 1

(7) n ,

which is O ( k^2 n /(

σ log n )) time. It improves if α ≥ 1 − e /

σ , being O (( m − k ) kn /log n ) time. This last complexity is also the worst case of this algorithm. To see where automaton partitioning is better than plain dynamic programming, consider that, for large α, the first one works O ( I J ) = O (( m − k )( k + 1 )/(w− 1 )) per text

Faster Approximate String Matching 145

5.5. Superimposing the Subpatterns. Suppose we decide to superimpose r patterns in a single search. We are limited in the amount of this superimposition because of the increase in the error level to tolerate. We now analyze how many patterns we can superimpose. We prove in the Appendix that the probability of a given text position matching a random pattern is exponentially decreasing with m for α < 1 − e /

σ , while if this condition does not hold the probability is very high. In this formula, 1/σ stands for the probability of a character crossing a horizontal edge of the automaton (i.e., the probability of two characters being equal). To extend this result, we note that we have r characters on each edge now, so the above-mentioned probability is 1 − ( 1 − 1 /σ ) r^. Hence, the new limit for α is

α < 1 − e

σ

) r ≈ 1 − e

r σ

where the (pessimistic) approximation is tight for r ø σ. If we use pattern partitioning, we must search j subpatterns ( j is determined by m and k , it is not dependent on r ). Using (9) again, we have that the number of verifications is negligible for

α < 1 − e

r σ

(11) m j /( m − k )

where solving for r we get that the maximum allowed amount of superimposition r ′^ is

r ′^ =

( 1 − α)^2 σ e^2 m^2 d (w,α)

and therefore we must partition the set into j ′^ = j / r ′^ subsets of size r ′^ each. That implies that the cost of our algorithm is in general O ( j ′ n ). Replacing j = ( m − k ) d (w, α) yields that the cost is

e^2 d (w, α) m^1 +^2 d (w,α) σ ( 1 − α)

n

and since the technique is limited to the case α < 1 − e /

σ , we have a complexity of

O

d (w, α) m^1 +^2 d (w,α) √ σ

n

≈ O

km σ w

m^2 /

√w n

where the approximation is valid for moderate m values. A natural question is for which error level can we superimpose all the j patterns to obtain a linear algorithm, i.e., where r ′^ ≥ j holds. That is (using (11)),

α < 1 − e

j σ

m j /( m − k ),

where the limit point is defined as

α 0 = 1 − e

m ( 1 − α 0 ) d (w, α 0 ) σ

(13) md (w,α^0 ),

146 R. Baeza-Yates and G. Navarro

which is not easy to solve analytically. For moderate m a practical simplified solution is

α 0 = 1 −

m /(σ

w) m^1 /

√w . Observe that for α > 1 − e /

σ , the cost is O ( jn ), i.e., no better than pattern partitioning with no superimposition. However, that value also marks the limit of the usability of pattern partitioning. It is interesting to compare this limit for the linearity of our algorithm with that of exact partitioning [8] (i.e., partitioning the pattern into k + 1 pieces and searching them with no errors, verifying each subpattern occurrence for a complete match). To analyze exact partitioning, we assume the use of an Aho–Corasick machine [1] to search the subpatterns in parallel in O ( n ) guaranteed search time (as explained, there are better alternatives in practice). Since the search for the subpatterns is of linear time, we find out now when the total amount of work due to verifications is also linear. We split the pattern into pieces of length b m /( k + 1 )c and d m /( k + 1 )e. In terms of probability of occurrence, the shorter pieces are σ times more probable than the others (where σ is the size of the alphabet). Since each occurrence of a subpattern is verified for a complete match at O ( m^2 ) cost, the total cost of verifications is no more than ( k + 1 ) m^2 /σ b m /( k +^1 )c^ n. This is linear approximately for α < α 0 ′, where α′ 0 is defined as

α 0 ′ =

σ 1 /α

′ 0

m^3

where a reasonable approximation is α′ 0 = 1 /(3 logσ m ). This limit is less restricting than our α 0 of (13) for sufficiently large m (a very rough approximation is m > σ

w/2). For typical text searching the error level tolerated by our algorithm is higher (i.e., α 0 > α′ 0 ). As we show in the experiments, however, exact partitioning is faster in practice, and therefore it should be preferred whenever α < α 0 ′.

5.6. Mixed Partitioning. We now analyze the general partitioning strategy: partition the pattern in a number of subpatterns, and then partition each automaton. To obtain the optimal strategy, consider that if we partition in j subpatterns, we must perform j searches with b k / j c errors. For α < 1 − e /

σ , the cost of solving j subproblems by partitioning the automaton is (recall (7))

(( ke / j )/(

σ − e )) ( k / j + 1 ) w − 1

(15) jn ,

which shows that the lowest cost is obtained with the largest j value, and therefore mixed partitioning should not be used if pure pattern partitioning is possible. However, there is still place for this algorithm. The point is that the limit of usefulness for α is reduced when j grows (see (9)). Hence, for α > α 1 we may use a smaller j (and partition the automata) to keep the verifications negligible. We use the first part of (9) to obtain the maximum j value allowed by α, which is b( m − k ) log m (

σ ( 1 − α)/ e )c. By counting the cost of carrying out j searches with the resulting subautomata (using (15)), we have the complexity of this scheme. It is possible to use superimposition with this scheme. We cannot, however, first select j and then superimpose subsets, because if we can superimpose two patterns, it means that the error level would allow us to use a larger j (and therefore our se- lection was not optimal). We try instead to optimize j and r simultaneously. Suppose