    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.text.similarity;
    019
    020import java.util.Arrays;
    021
    022/**
    023 * An algorithm for measuring the difference between two character sequences.
    024 *
    025 * <p>
    026 * This is the number of changes needed to change one sequence into another, where each change is a single character modification (deletion, insertion or
    027 * substitution).
    028 * </p>
    029 *
    030 * @since 1.0
    031 */
    032public class LevenshteinDetailedDistance implements EditDistance<LevenshteinResults> {
    033
    034    /**
    035     * The singleton instance.
    036     */
    037    private static final LevenshteinDetailedDistance INSTANCE = new LevenshteinDetailedDistance();
    038
    039    /**
    040     * Finds count for each of the three [insert, delete, substitute] operations needed. This is based on the matrix formed based on the two character sequence.
    041     *
    042     * @param <E>     The type of similarity score unit.
    043     * @param left    character sequence which need to be converted from.
    044     * @param right   character sequence which need to be converted to.
    045     * @param matrix  two dimensional array containing.
    046     * @param swapped tells whether the value for left character sequence and right character sequence were swapped to save memory.
    047     * @return result object containing the count of insert, delete and substitute and total count needed.
    048     */
    049    private static <E> LevenshteinResults findDetailedResults(final SimilarityInput<E> left, final SimilarityInput<E> right, final int[][] matrix,
    050            final boolean swapped) {
    051        int delCount = 0;
    052        int addCount = 0;
    053        int subCount = 0;
    054        int rowIndex = right.length();
    055        int columnIndex = left.length();
    056        int dataAtLeft = 0;
    057        int dataAtTop = 0;
    058        int dataAtDiagonal = 0;
    059        int data = 0;
    060        boolean deleted = false;
    061        boolean added = false;
    062        while (rowIndex >= 0 && columnIndex >= 0) {
    063            if (columnIndex == 0) {
    064                dataAtLeft = -1;
    065            } else {
    066                dataAtLeft = matrix[rowIndex][columnIndex - 1];
    067            }
    068            if (rowIndex == 0) {
    069                dataAtTop = -1;
    070            } else {
    071                dataAtTop = matrix[rowIndex - 1][columnIndex];
    072            }
    073            if (rowIndex > 0 && columnIndex > 0) {
    074                dataAtDiagonal = matrix[rowIndex - 1][columnIndex - 1];
    075            } else {
    076                dataAtDiagonal = -1;
    077            }
    078            if (dataAtLeft == -1 && dataAtTop == -1 && dataAtDiagonal == -1) {
    079                break;
    080            }
    081            data = matrix[rowIndex][columnIndex];
    082            // case in which the character at left and right are the same,
    083            // in this case none of the counters will be incremented.
    084            if (columnIndex > 0 && rowIndex > 0 && left.at(columnIndex - 1).equals(right.at(rowIndex - 1))) {
    085                columnIndex--;
    086                rowIndex--;
    087                continue;
    088            }
    089            // handling insert and delete cases.
    090            deleted = false;
    091            added = false;
    092            if (data - 1 == dataAtLeft && data <= dataAtDiagonal && data <= dataAtTop || dataAtDiagonal == -1 && dataAtTop == -1) { // NOPMD
    093                columnIndex--;
    094                if (swapped) {
    095                    addCount++;
    096                    added = true;
    097                } else {
    098                    delCount++;
    099                    deleted = true;
    100                }
    101            } else if (data - 1 == dataAtTop && data <= dataAtDiagonal && data <= dataAtLeft || dataAtDiagonal == -1 && dataAtLeft == -1) { // NOPMD
    102                rowIndex--;
    103                if (swapped) {
    104                    delCount++;
    105                    deleted = true;
    106                } else {
    107                    addCount++;
    108                    added = true;
    109                }
    110            }
    111            // substituted case
    112            if (!added && !deleted) {
    113                subCount++;
    114                columnIndex--;
    115                rowIndex--;
    116            }
    117        }
    118        return new LevenshteinResults(addCount + delCount + subCount, addCount, delCount, subCount);
    119    }
    120
    121    /**
    122     * Gets the default instance.
    123     *
    124     * @return The default instace
    125     */
    126    public static LevenshteinDetailedDistance getDefaultInstance() {
    127        return INSTANCE;
    128    }
    129
    130    /**
    131     * Finds the Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
    132     *
    133     * <p>
    134     * This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield and Chas Emerick's implementation of the Levenshtein distance
    135     * algorithm from <a href="http://www.merriampark.com/ld.htm" >http://www.merriampark.com/ld.htm</a>
    136     * </p>
    137     *
    138     * <pre>
    139     * limitedCompare(null, *, *)             = IllegalArgumentException
    140     * limitedCompare(*, null, *)             = IllegalArgumentException
    141     * limitedCompare(*, *, -1)               = IllegalArgumentException
    142     * limitedCompare("","", 0)               = 0
    143     * limitedCompare("aaapppp", "", 8)       = 7
    144     * limitedCompare("aaapppp", "", 7)       = 7
    145     * limitedCompare("aaapppp", "", 6))      = -1
    146     * limitedCompare("elephant", "hippo", 7) = 7
    147     * limitedCompare("elephant", "hippo", 6) = -1
    148     * limitedCompare("hippo", "elephant", 7) = 7
    149     * limitedCompare("hippo", "elephant", 6) = -1
    150     * </pre>
    151     *
    152     * @param <E>       The type of similarity score unit.
    153     * @param left      the first CharSequence, must not be null.
    154     * @param right     the second CharSequence, must not be null.
    155     * @param threshold the target threshold, must not be negative.
    156     * @return result distance, or -1.
    157     */
    158    private static <E> LevenshteinResults limitedCompare(SimilarityInput<E> left, SimilarityInput<E> right, final int threshold) { // NOPMD
    159        if (left == null || right == null) {
    160            throw new IllegalArgumentException("CharSequences must not be null");
    161        }
    162        if (threshold < 0) {
    163            throw new IllegalArgumentException("Threshold must not be negative");
    164        }
    165        /*
    166         * This implementation only computes the distance if it's less than or equal to the threshold value, returning -1 if it's greater. The advantage is
    167         * performance: unbounded distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only computing a diagonal stripe of width 2k + 1
    168         * of the cost table. It is also possible to use this to compute the unbounded Levenshtein distance by starting the threshold at 1 and doubling each
    169         * time until the distance is found; this is O(dm), where d is the distance.
    170         *
    171         * One subtlety comes from needing to ignore entries on the border of our stripe eg. p[] = |#|#|#|* d[] = *|#|#|#| We must ignore the entry to the left
    172         * of the leftmost member We must ignore the entry above the rightmost member
    173         *
    174         * Another subtlety comes from our stripe running off the matrix if the strings aren't of the same size. Since string s is always swapped to be the
    175         * shorter of the two, the stripe will always run off to the upper right instead of the lower left of the matrix.
    176         *
    177         * As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1. In this case we're going to walk a stripe of length 3. The
    178         * matrix would look like so:
    179         *
    180         * <pre> 1 2 3 4 5 1 |#|#| | | | 2 |#|#|#| | | 3 | |#|#|#| | 4 | | |#|#|#| 5 | | | |#|#| 6 | | | | |#| 7 | | | | | | </pre>
    181         *
    182         * Note how the stripe leads off the table as there is no possible way to turn a string of length 5 into one of length 7 in edit distance of 1.
    183         *
    184         * Additionally, this implementation decreases memory usage by using two single-dimensional arrays and swapping them back and forth instead of
    185         * allocating an entire n by m matrix. This requires a few minor changes, such as immediately returning when it's detected that the stripe has run off
    186         * the matrix and initially filling the arrays with large values so that entries we don't compute are ignored.
    187         *
    188         * See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion.
    189         */
    190        int n = left.length(); // length of left
    191        int m = right.length(); // length of right
    192        // if one string is empty, the edit distance is necessarily the length of the other
    193        if (n == 0) {
    194            return m <= threshold ? new LevenshteinResults(m, m, 0, 0) : new LevenshteinResults(-1, 0, 0, 0);
    195        }
    196        if (m == 0) {
    197            return n <= threshold ? new LevenshteinResults(n, 0, n, 0) : new LevenshteinResults(-1, 0, 0, 0);
    198        }
    199        boolean swapped = false;
    200        if (n > m) {
    201            // swap the two strings to consume less memory
    202            final SimilarityInput<E> tmp = left;
    203            left = right;
    204            right = tmp;
    205            n = m;
    206            m = right.length();
    207            swapped = true;
    208        }
    209        int[] p = new int[n + 1]; // 'previous' cost array, horizontally
    210        int[] d = new int[n + 1]; // cost array, horizontally
    211        int[] tempD; // placeholder to assist in swapping p and d
    212        final int[][] matrix = new int[m + 1][n + 1];
    213        // filling the first row and first column values in the matrix
    214        for (int index = 0; index <= n; index++) {
    215            matrix[0][index] = index;
    216        }
    217        for (int index = 0; index <= m; index++) {
    218            matrix[index][0] = index;
    219        }
    220        // fill in starting table values
    221        final int boundary = Math.min(n, threshold) + 1;
    222        for (int i = 0; i < boundary; i++) {
    223            p[i] = i;
    224        }
    225        // these fills ensure that the value above the rightmost entry of our
    226        // stripe will be ignored in following loop iterations
    227        Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
    228        Arrays.fill(d, Integer.MAX_VALUE);
    229        // iterates through t
    230        for (int j = 1; j <= m; j++) {
    231            final E rightJ = right.at(j - 1); // jth character of right
    232            d[0] = j;
    233            // compute stripe indices, constrain to array size
    234            final int min = Math.max(1, j - threshold);
    235            final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold);
    236            // the stripe may lead off of the table if s and t are of different sizes
    237            if (min > max) {
    238                return new LevenshteinResults(-1, 0, 0, 0);
    239            }
    240            // ignore entry left of leftmost
    241            if (min > 1) {
    242                d[min - 1] = Integer.MAX_VALUE;
    243            }
    244            // iterates through [min, max] in s
    245            for (int i = min; i <= max; i++) {
    246                if (left.at(i - 1).equals(rightJ)) {
    247                    // diagonally left and up
    248                    d[i] = p[i - 1];
    249                } else {
    250                    // 1 + minimum of cell to the left, to the top, diagonally left and up
    251                    d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]);
    252                }
    253                matrix[j][i] = d[i];
    254            }
    255            // copy current distance counts to 'previous row' distance counts
    256            tempD = p;
    257            p = d;
    258            d = tempD;
    259        }
    260        // if p[n] is greater than the threshold, there's no guarantee on it being the correct distance
    261        if (p[n] <= threshold) {
    262            return findDetailedResults(left, right, matrix, swapped);
    263        }
    264        return new LevenshteinResults(-1, 0, 0, 0);
    265    }
    266
    267    /**
    268     * Finds the Levenshtein distance between two Strings.
    269     *
    270     * <p>
    271     * A higher score indicates a greater distance.
    272     * </p>
    273     *
    274     * <p>
    275     * The previous implementation of the Levenshtein distance algorithm was from
    276     * <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a>
    277     * </p>
    278     *
    279     * <p>
    280     * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
    281     * strings.<br>
    282     * This implementation of the Levenshtein distance algorithm is from
    283     * <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a>
    284     * </p>
    285     *
    286     * <pre>
    287     * unlimitedCompare(null, *)             = IllegalArgumentException
    288     * unlimitedCompare(*, null)             = IllegalArgumentException
    289     * unlimitedCompare("","")               = 0
    290     * unlimitedCompare("","a")              = 1
    291     * unlimitedCompare("aaapppp", "")       = 7
    292     * unlimitedCompare("frog", "fog")       = 1
    293     * unlimitedCompare("fly", "ant")        = 3
    294     * unlimitedCompare("elephant", "hippo") = 7
    295     * unlimitedCompare("hippo", "elephant") = 7
    296     * unlimitedCompare("hippo", "zzzzzzzz") = 8
    297     * unlimitedCompare("hello", "hallo")    = 1
    298     * </pre>
    299     *
    300     * @param <E>   The type of similarity score unit.
    301     * @param left  the first CharSequence, must not be null.
    302     * @param right the second CharSequence, must not be null.
    303     * @return result distance, or -1.
    304     * @throws IllegalArgumentException if either CharSequence input is {@code null}.
    305     */
    306    private static <E> LevenshteinResults unlimitedCompare(SimilarityInput<E> left, SimilarityInput<E> right) {
    307        if (left == null || right == null) {
    308            throw new IllegalArgumentException("CharSequences must not be null");
    309        }
    310        /*
    311         * The difference between this impl. and the previous is that, rather than creating and retaining a matrix of size s.length() + 1 by t.length() + 1, we
    312         * maintain two single-dimensional arrays of length s.length() + 1. The first, d, is the 'current working' distance array that maintains the newest
    313         * distance cost counts as we iterate through the characters of String s. Each time we increment the index of String t we are comparing, d is copied to
    314         * p, the second int[]. Doing so allows us to retain the previous cost counts as required by the algorithm (taking the minimum of the cost count to the
    315         * left, up one, and diagonally up and to the left of the current cost count being calculated). (Note that the arrays aren't really copied anymore, just
    316         * switched...this is clearly much better than cloning an array or doing a System.arraycopy() each time through the outer loop.)
    317         *
    318         * Effectively, the difference between the two implementations is this one does not cause an out of memory condition when calculating the LD over two
    319         * very large strings.
    320         */
    321        int n = left.length(); // length of left
    322        int m = right.length(); // length of right
    323        if (n == 0) {
    324            return new LevenshteinResults(m, m, 0, 0);
    325        }
    326        if (m == 0) {
    327            return new LevenshteinResults(n, 0, n, 0);
    328        }
    329        boolean swapped = false;
    330        if (n > m) {
    331            // swap the input strings to consume less memory
    332            final SimilarityInput<E> tmp = left;
    333            left = right;
    334            right = tmp;
    335            n = m;
    336            m = right.length();
    337            swapped = true;
    338        }
    339        int[] p = new int[n + 1]; // 'previous' cost array, horizontally
    340        int[] d = new int[n + 1]; // cost array, horizontally
    341        int[] tempD; // placeholder to assist in swapping p and d
    342        final int[][] matrix = new int[m + 1][n + 1];
    343        // filling the first row and first column values in the matrix
    344        for (int index = 0; index <= n; index++) {
    345            matrix[0][index] = index;
    346        }
    347        for (int index = 0; index <= m; index++) {
    348            matrix[index][0] = index;
    349        }
    350        // indexes into strings left and right
    351        int i; // iterates through left
    352        int j; // iterates through right
    353        E rightJ; // jth character of right
    354        int cost; // cost
    355        for (i = 0; i <= n; i++) {
    356            p[i] = i;
    357        }
    358        for (j = 1; j <= m; j++) {
    359            rightJ = right.at(j - 1);
    360            d[0] = j;
    361            for (i = 1; i <= n; i++) {
    362                cost = left.at(i - 1).equals(rightJ) ? 0 : 1;
    363                // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
    364                d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
    365                // filling the matrix
    366                matrix[j][i] = d[i];
    367            }
    368            // copy current distance counts to 'previous row' distance counts
    369            tempD = p;
    370            p = d;
    371            d = tempD;
    372        }
    373        return findDetailedResults(left, right, matrix, swapped);
    374    }
    375
    376    /**
    377     * Threshold.
    378     */
    379    private final Integer threshold;
    380
    381    /**
    382     * <p>
    383     * This returns the default instance that uses a version of the algorithm that does not use a threshold parameter.
    384     * </p>
    385     *
    386     * @see LevenshteinDetailedDistance#getDefaultInstance()
    387     * @deprecated Use {@link #getDefaultInstance()}.
    388     */
    389    @Deprecated
    390    public LevenshteinDetailedDistance() {
    391        this(null);
    392    }
    393
    394    /**
    395     * If the threshold is not null, distance calculations will be limited to a maximum length.
    396     *
    397     * <p>
    398     * If the threshold is null, the unlimited version of the algorithm will be used.
    399     * </p>
    400     *
    401     * @param threshold If this is null then distances calculations will not be limited. This may not be negative.
    402     */
    403    public LevenshteinDetailedDistance(final Integer threshold) {
    404        if (threshold != null && threshold < 0) {
    405            throw new IllegalArgumentException("Threshold must not be negative");
    406        }
    407        this.threshold = threshold;
    408    }
    409
    410    /**
    411     * Computes the Levenshtein distance between two Strings.
    412     *
    413     * <p>
    414     * A higher score indicates a greater distance.
    415     * </p>
    416     *
    417     * <p>
    418     * The previous implementation of the Levenshtein distance algorithm was from
    419     * <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a>
    420     * </p>
    421     *
    422     * <p>
    423     * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
    424     * strings.<br>
    425     * This implementation of the Levenshtein distance algorithm is from
    426     * <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a>
    427     * </p>
    428     *
    429     * <pre>
    430     * distance.apply(null, *)             = IllegalArgumentException
    431     * distance.apply(*, null)             = IllegalArgumentException
    432     * distance.apply("","")               = 0
    433     * distance.apply("","a")              = 1
    434     * distance.apply("aaapppp", "")       = 7
    435     * distance.apply("frog", "fog")       = 1
    436     * distance.apply("fly", "ant")        = 3
    437     * distance.apply("elephant", "hippo") = 7
    438     * distance.apply("hippo", "elephant") = 7
    439     * distance.apply("hippo", "zzzzzzzz") = 8
    440     * distance.apply("hello", "hallo")    = 1
    441     * </pre>
    442     *
    443     * @param left  the first input, must not be null.
    444     * @param right the second input, must not be null.
    445     * @return result distance, or -1.
    446     * @throws IllegalArgumentException if either String input {@code null}.
    447     */
    448    @Override
    449    public LevenshteinResults apply(final CharSequence left, final CharSequence right) {
    450        return apply(SimilarityInput.input(left), SimilarityInput.input(right));
    451    }
    452
    453    /**
    454     * Computes the Levenshtein distance between two Strings.
    455     *
    456     * <p>
    457     * A higher score indicates a greater distance.
    458     * </p>
    459     *
    460     * <p>
    461     * The previous implementation of the Levenshtein distance algorithm was from
    462     * <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a>
    463     * </p>
    464     *
    465     * <p>
    466     * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
    467     * strings.<br>
    468     * This implementation of the Levenshtein distance algorithm is from
    469     * <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a>
    470     * </p>
    471     *
    472     * <pre>
    473     * distance.apply(null, *)             = IllegalArgumentException
    474     * distance.apply(*, null)             = IllegalArgumentException
    475     * distance.apply("","")               = 0
    476     * distance.apply("","a")              = 1
    477     * distance.apply("aaapppp", "")       = 7
    478     * distance.apply("frog", "fog")       = 1
    479     * distance.apply("fly", "ant")        = 3
    480     * distance.apply("elephant", "hippo") = 7
    481     * distance.apply("hippo", "elephant") = 7
    482     * distance.apply("hippo", "zzzzzzzz") = 8
    483     * distance.apply("hello", "hallo")    = 1
    484     * </pre>
    485     *
    486     * @param <E>   The type of similarity score unit.
    487     * @param left  the first input, must not be null.
    488     * @param right the second input, must not be null.
    489     * @return result distance, or -1.
    490     * @throws IllegalArgumentException if either String input {@code null}.
    491     * @since 1.13.0
    492     */
    493    public <E> LevenshteinResults apply(final SimilarityInput<E> left, final SimilarityInput<E> right) {
    494        if (threshold != null) {
    495            return limitedCompare(left, right, threshold);
    496        }
    497        return unlimitedCompare(left, right);
    498    }
    499
    500    /**
    501     * Gets the distance threshold.
    502     *
    503     * @return The distance threshold.
    504     */
    505    public Integer getThreshold() {
    506        return threshold;
    507    }
    508}