LevenshteinDistance.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.text.similarity;

  18. import java.util.Arrays;

  19. /**
  20.  * An algorithm for measuring the difference between two character sequences.
  21.  *
  22.  * <p>
  23.  * This is the number of changes needed to change one sequence into another, where each change is a single character modification (deletion, insertion or
  24.  * substitution).
  25.  * </p>
  26.  * <p>
  27.  * This code has been adapted from Apache Commons Lang 3.3.
  28.  * </p>
  29.  *
  30.  * @since 1.0
  31.  */
  32. public class LevenshteinDistance implements EditDistance<Integer> {

  33.     /**
  34.      * Singleton instance.
  35.      */
  36.     private static final LevenshteinDistance INSTANCE = new LevenshteinDistance();

  37.     /**
  38.      * Gets the default instance.
  39.      *
  40.      * @return The default instance
  41.      */
  42.     public static LevenshteinDistance getDefaultInstance() {
  43.         return INSTANCE;
  44.     }

  45.     /**
  46.      * Find the Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
  47.      *
  48.      * <p>
  49.      * This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield and Chas Emerick's implementation of the Levenshtein distance
  50.      * algorithm from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a>
  51.      * </p>
  52.      *
  53.      * <pre>
  54.      * limitedCompare(null, *, *)             = IllegalArgumentException
  55.      * limitedCompare(*, null, *)             = IllegalArgumentException
  56.      * limitedCompare(*, *, -1)               = IllegalArgumentException
  57.      * limitedCompare("","", 0)               = 0
  58.      * limitedCompare("aaapppp", "", 8)       = 7
  59.      * limitedCompare("aaapppp", "", 7)       = 7
  60.      * limitedCompare("aaapppp", "", 6))      = -1
  61.      * limitedCompare("elephant", "hippo", 7) = 7
  62.      * limitedCompare("elephant", "hippo", 6) = -1
  63.      * limitedCompare("hippo", "elephant", 7) = 7
  64.      * limitedCompare("hippo", "elephant", 6) = -1
  65.      * </pre>
  66.      *
  67.      * @param left      the first SimilarityInput, must not be null
  68.      * @param right     the second SimilarityInput, must not be null
  69.      * @param threshold the target threshold, must not be negative
  70.      * @return result distance, or -1
  71.      */
  72.     private static <E> int limitedCompare(SimilarityInput<E> left, SimilarityInput<E> right, final int threshold) { // NOPMD
  73.         if (left == null || right == null) {
  74.             throw new IllegalArgumentException("CharSequences must not be null");
  75.         }
  76.         if (threshold < 0) {
  77.             throw new IllegalArgumentException("Threshold must not be negative");
  78.         }

  79.         /*
  80.          * 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
  81.          * 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
  82.          * 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
  83.          * time until the distance is found; this is O(dm), where d is the distance.
  84.          *
  85.          * 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
  86.          * of the leftmost member We must ignore the entry above the rightmost member
  87.          *
  88.          * 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
  89.          * shorter of the two, the stripe will always run off to the upper right instead of the lower left of the matrix.
  90.          *
  91.          * 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
  92.          * matrix would look like so:
  93.          *
  94.          * <pre> 1 2 3 4 5 1 |#|#| | | | 2 |#|#|#| | | 3 | |#|#|#| | 4 | | |#|#|#| 5 | | | |#|#| 6 | | | | |#| 7 | | | | | | </pre>
  95.          *
  96.          * 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.
  97.          *
  98.          * Additionally, this implementation decreases memory usage by using two single-dimensional arrays and swapping them back and forth instead of
  99.          * 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
  100.          * the matrix and initially filling the arrays with large values so that entries we don't compute are ignored.
  101.          *
  102.          * See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion.
  103.          */

  104.         int n = left.length(); // length of left
  105.         int m = right.length(); // length of right

  106.         // if one string is empty, the edit distance is necessarily the length
  107.         // of the other
  108.         if (n == 0) {
  109.             return m <= threshold ? m : -1;
  110.         }
  111.         if (m == 0) {
  112.             return n <= threshold ? n : -1;
  113.         }

  114.         if (n > m) {
  115.             // swap the two strings to consume less memory
  116.             final SimilarityInput<E> tmp = left;
  117.             left = right;
  118.             right = tmp;
  119.             n = m;
  120.             m = right.length();
  121.         }

  122.         // the edit distance cannot be less than the length difference
  123.         if (m - n > threshold) {
  124.             return -1;
  125.         }

  126.         int[] p = new int[n + 1]; // 'previous' cost array, horizontally
  127.         int[] d = new int[n + 1]; // cost array, horizontally
  128.         int[] tempD; // placeholder to assist in swapping p and d

  129.         // fill in starting table values
  130.         final int boundary = Math.min(n, threshold) + 1;
  131.         for (int i = 0; i < boundary; i++) {
  132.             p[i] = i;
  133.         }
  134.         // these fills ensure that the value above the rightmost entry of our
  135.         // stripe will be ignored in following loop iterations
  136.         Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
  137.         Arrays.fill(d, Integer.MAX_VALUE);

  138.         // iterates through t
  139.         for (int j = 1; j <= m; j++) {
  140.             final E rightJ = right.at(j - 1); // jth character of right
  141.             d[0] = j;

  142.             // compute stripe indices, constrain to array size
  143.             final int min = Math.max(1, j - threshold);
  144.             final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold);

  145.             // ignore entry left of leftmost
  146.             if (min > 1) {
  147.                 d[min - 1] = Integer.MAX_VALUE;
  148.             }

  149.             int lowerBound = Integer.MAX_VALUE;
  150.             // iterates through [min, max] in s
  151.             for (int i = min; i <= max; i++) {
  152.                 if (left.at(i - 1).equals(rightJ)) {
  153.                     // diagonally left and up
  154.                     d[i] = p[i - 1];
  155.                 } else {
  156.                     // 1 + minimum of cell to the left, to the top, diagonally
  157.                     // left and up
  158.                     d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]);
  159.                 }
  160.                 lowerBound = Math.min(lowerBound, d[i]);
  161.             }
  162.             // if the lower bound is greater than the threshold, then exit early
  163.             if (lowerBound > threshold) {
  164.                 return -1;
  165.             }

  166.             // copy current distance counts to 'previous row' distance counts
  167.             tempD = p;
  168.             p = d;
  169.             d = tempD;
  170.         }

  171.         // if p[n] is greater than the threshold, there's no guarantee on it
  172.         // being the correct
  173.         // distance
  174.         if (p[n] <= threshold) {
  175.             return p[n];
  176.         }
  177.         return -1;
  178.     }

  179.     /**
  180.      * Finds the Levenshtein distance between two Strings.
  181.      *
  182.      * <p>
  183.      * A higher score indicates a greater distance.
  184.      * </p>
  185.      *
  186.      * <p>
  187.      * The previous implementation of the Levenshtein distance algorithm was from
  188.      * <a href="https://web.archive.org/web/20120526085419/http://www.merriampark.com/ldjava.htm">
  189.      * https://web.archive.org/web/20120526085419/http://www.merriampark.com/ldjava.htm</a>
  190.      * </p>
  191.      *
  192.      * <p>
  193.      * This implementation only need one single-dimensional arrays of length s.length() + 1
  194.      * </p>
  195.      *
  196.      * <pre>
  197.      * unlimitedCompare(null, *)             = IllegalArgumentException
  198.      * unlimitedCompare(*, null)             = IllegalArgumentException
  199.      * unlimitedCompare("","")               = 0
  200.      * unlimitedCompare("","a")              = 1
  201.      * unlimitedCompare("aaapppp", "")       = 7
  202.      * unlimitedCompare("frog", "fog")       = 1
  203.      * unlimitedCompare("fly", "ant")        = 3
  204.      * unlimitedCompare("elephant", "hippo") = 7
  205.      * unlimitedCompare("hippo", "elephant") = 7
  206.      * unlimitedCompare("hippo", "zzzzzzzz") = 8
  207.      * unlimitedCompare("hello", "hallo")    = 1
  208.      * </pre>
  209.      *
  210.      * @param left  the first CharSequence, must not be null
  211.      * @param right the second CharSequence, must not be null
  212.      * @return result distance, or -1
  213.      * @throws IllegalArgumentException if either CharSequence input is {@code null}
  214.      */
  215.     private static <E> int unlimitedCompare(SimilarityInput<E> left, SimilarityInput<E> right) {
  216.         if (left == null || right == null) {
  217.             throw new IllegalArgumentException("CharSequences must not be null");
  218.         }
  219.         /*
  220.          * This implementation use two variable to record the previous cost counts, So this implementation use less memory than previous impl.
  221.          */
  222.         int n = left.length(); // length of left
  223.         int m = right.length(); // length of right

  224.         if (n == 0) {
  225.             return m;
  226.         }
  227.         if (m == 0) {
  228.             return n;
  229.         }
  230.         if (n > m) {
  231.             // swap the input strings to consume less memory
  232.             final SimilarityInput<E> tmp = left;
  233.             left = right;
  234.             right = tmp;
  235.             n = m;
  236.             m = right.length();
  237.         }
  238.         final int[] p = new int[n + 1];
  239.         // indexes into strings left and right
  240.         int i; // iterates through left
  241.         int j; // iterates through right
  242.         int upperLeft;
  243.         int upper;
  244.         E rightJ; // jth character of right
  245.         int cost; // cost
  246.         for (i = 0; i <= n; i++) {
  247.             p[i] = i;
  248.         }
  249.         for (j = 1; j <= m; j++) {
  250.             upperLeft = p[0];
  251.             rightJ = right.at(j - 1);
  252.             p[0] = j;

  253.             for (i = 1; i <= n; i++) {
  254.                 upper = p[i];
  255.                 cost = left.at(i - 1).equals(rightJ) ? 0 : 1;
  256.                 // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
  257.                 p[i] = Math.min(Math.min(p[i - 1] + 1, p[i] + 1), upperLeft + cost);
  258.                 upperLeft = upper;
  259.             }
  260.         }
  261.         return p[n];
  262.     }

  263.     /**
  264.      * Threshold.
  265.      */
  266.     private final Integer threshold;

  267.     /**
  268.      * This returns the default instance that uses a version of the algorithm that does not use a threshold parameter.
  269.      *
  270.      * @see LevenshteinDistance#getDefaultInstance()
  271.      * @deprecated Use {@link #getDefaultInstance()}.
  272.      */
  273.     @Deprecated
  274.     public LevenshteinDistance() {
  275.         this(null);
  276.     }

  277.     /**
  278.      * If the threshold is not null, distance calculations will be limited to a maximum length. If the threshold is null, the unlimited version of the algorithm
  279.      * will be used.
  280.      *
  281.      * @param threshold If this is null then distances calculations will not be limited. This may not be negative.
  282.      */
  283.     public LevenshteinDistance(final Integer threshold) {
  284.         if (threshold != null && threshold < 0) {
  285.             throw new IllegalArgumentException("Threshold must not be negative");
  286.         }
  287.         this.threshold = threshold;
  288.     }

  289.     /**
  290.      * Computes the Levenshtein distance between two Strings.
  291.      *
  292.      * <p>
  293.      * A higher score indicates a greater distance.
  294.      * </p>
  295.      *
  296.      * <p>
  297.      * The previous implementation of the Levenshtein distance algorithm was from
  298.      * <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a>
  299.      * </p>
  300.      *
  301.      * <p>
  302.      * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
  303.      * strings.<br>
  304.      * This implementation of the Levenshtein distance algorithm is from
  305.      * <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a>
  306.      * </p>
  307.      *
  308.      * <pre>
  309.      * distance.apply(null, *)             = IllegalArgumentException
  310.      * distance.apply(*, null)             = IllegalArgumentException
  311.      * distance.apply("","")               = 0
  312.      * distance.apply("","a")              = 1
  313.      * distance.apply("aaapppp", "")       = 7
  314.      * distance.apply("frog", "fog")       = 1
  315.      * distance.apply("fly", "ant")        = 3
  316.      * distance.apply("elephant", "hippo") = 7
  317.      * distance.apply("hippo", "elephant") = 7
  318.      * distance.apply("hippo", "zzzzzzzz") = 8
  319.      * distance.apply("hello", "hallo")    = 1
  320.      * </pre>
  321.      *
  322.      * @param left  the first input, must not be null
  323.      * @param right the second input, must not be null
  324.      * @return result distance, or -1
  325.      * @throws IllegalArgumentException if either String input {@code null}
  326.      */
  327.     @Override
  328.     public Integer apply(final CharSequence left, final CharSequence right) {
  329.         return apply(SimilarityInput.input(left), SimilarityInput.input(right));
  330.     }

  331.     /**
  332.      * Computes the Levenshtein distance between two inputs.
  333.      *
  334.      * <p>
  335.      * A higher score indicates a greater distance.
  336.      * </p>
  337.      *
  338.      * <pre>
  339.      * distance.apply(null, *)             = IllegalArgumentException
  340.      * distance.apply(*, null)             = IllegalArgumentException
  341.      * distance.apply("","")               = 0
  342.      * distance.apply("","a")              = 1
  343.      * distance.apply("aaapppp", "")       = 7
  344.      * distance.apply("frog", "fog")       = 1
  345.      * distance.apply("fly", "ant")        = 3
  346.      * distance.apply("elephant", "hippo") = 7
  347.      * distance.apply("hippo", "elephant") = 7
  348.      * distance.apply("hippo", "zzzzzzzz") = 8
  349.      * distance.apply("hello", "hallo")    = 1
  350.      * </pre>
  351.      *
  352.      * @param <E>   The type of similarity score unit.
  353.      * @param left  the first input, must not be null.
  354.      * @param right the second input, must not be null.
  355.      * @return result distance, or -1.
  356.      * @throws IllegalArgumentException if either String input {@code null}.
  357.      * @since 1.13.0
  358.      */
  359.     public <E> Integer apply(final SimilarityInput<E> left, final SimilarityInput<E> right) {
  360.         if (threshold != null) {
  361.             return limitedCompare(left, right, threshold);
  362.         }
  363.         return unlimitedCompare(left, right);
  364.     }

  365.     /**
  366.      * Gets the distance threshold.
  367.      *
  368.      * @return The distance threshold
  369.      */
  370.     public Integer getThreshold() {
  371.         return threshold;
  372.     }

  373. }