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 *      http://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 */
017package org.apache.commons.text.similarity;
018
019import java.util.Arrays;
020
021import org.apache.commons.lang3.StringUtils;
022
023/**
024 * A similarity algorithm indicating the percentage of matched characters between two character sequences.
025 *
026 * <p>
027 * The Jaro measure is the weighted sum of percentage of matched characters
028 * from each file and transposed characters. Winkler increased this measure
029 * for matching initial characters.
030 * </p>
031 *
032 * <p>
033 * This implementation is based on the Jaro Winkler similarity algorithm
034 * from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">
035 * http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.
036 * </p>
037 *
038 * <p>
039 * This code has been adapted from Apache Commons Lang 3.3.
040 * </p>
041 *
042 * @since 1.7
043 */
044public class JaroWinklerSimilarity implements SimilarityScore<Double> {
045
046    /**
047     * This method returns the Jaro-Winkler string matches, half transpositions, prefix array.
048     *
049     * @param first the first string to be matched
050     * @param second the second string to be matched
051     * @return mtp array containing: matches, half transpositions, and prefix
052     */
053    protected static int[] matches(final CharSequence first, final CharSequence second) {
054        final CharSequence max;
055        final CharSequence min;
056        if (first.length() > second.length()) {
057            max = first;
058            min = second;
059        } else {
060            max = second;
061            min = first;
062        }
063        final int range = Math.max(max.length() / 2 - 1, 0);
064        final int[] matchIndexes = new int[min.length()];
065        Arrays.fill(matchIndexes, -1);
066        final boolean[] matchFlags = new boolean[max.length()];
067        int matches = 0;
068        for (int mi = 0; mi < min.length(); mi++) {
069            final char c1 = min.charAt(mi);
070            for (int xi = Math.max(mi - range, 0), xn = Math.min(mi + range + 1, max.length()); xi < xn; xi++) {
071                if (!matchFlags[xi] && c1 == max.charAt(xi)) {
072                    matchIndexes[mi] = xi;
073                    matchFlags[xi] = true;
074                    matches++;
075                    break;
076                }
077            }
078        }
079        final char[] ms1 = new char[matches];
080        final char[] ms2 = new char[matches];
081        for (int i = 0, si = 0; i < min.length(); i++) {
082            if (matchIndexes[i] != -1) {
083                ms1[si] = min.charAt(i);
084                si++;
085            }
086        }
087        for (int i = 0, si = 0; i < max.length(); i++) {
088            if (matchFlags[i]) {
089                ms2[si] = max.charAt(i);
090                si++;
091            }
092        }
093        int halfTranspositions = 0;
094        for (int mi = 0; mi < ms1.length; mi++) {
095            if (ms1[mi] != ms2[mi]) {
096                halfTranspositions++;
097            }
098        }
099        int prefix = 0;
100        for (int mi = 0; mi < Math.min(4, min.length()); mi++) {
101            if (first.charAt(mi) != second.charAt(mi)) {
102                break;
103            }
104            prefix++;
105        }
106        return new int[] {matches, halfTranspositions, prefix};
107    }
108
109    /**
110     * Computes the Jaro Winkler Similarity between two character sequences.
111     *
112     * <pre>
113     * sim.apply(null, null)          = IllegalArgumentException
114     * sim.apply("foo", null)         = IllegalArgumentException
115     * sim.apply(null, "foo")         = IllegalArgumentException
116     * sim.apply("", "")              = 1.0
117     * sim.apply("foo", "foo")        = 1.0
118     * sim.apply("foo", "foo ")       = 0.94
119     * sim.apply("foo", "foo  ")      = 0.91
120     * sim.apply("foo", " foo ")      = 0.87
121     * sim.apply("foo", "  foo")      = 0.51
122     * sim.apply("", "a")             = 0.0
123     * sim.apply("aaapppp", "")       = 0.0
124     * sim.apply("frog", "fog")       = 0.93
125     * sim.apply("fly", "ant")        = 0.0
126     * sim.apply("elephant", "hippo") = 0.44
127     * sim.apply("hippo", "elephant") = 0.44
128     * sim.apply("hippo", "zzzzzzzz") = 0.0
129     * sim.apply("hello", "hallo")    = 0.88
130     * sim.apply("ABC Corporation", "ABC Corp") = 0.91
131     * sim.apply("D N H Enterprises Inc", "D &amp; H Enterprises, Inc.") = 0.95
132     * sim.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
133     * sim.apply("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
134     * </pre>
135     *
136     * @param left the first CharSequence, must not be null
137     * @param right the second CharSequence, must not be null
138     * @return result similarity
139     * @throws IllegalArgumentException if either CharSequence input is {@code null}
140     */
141    @Override
142    public Double apply(final CharSequence left, final CharSequence right) {
143        final double defaultScalingFactor = 0.1;
144
145        if (left == null || right == null) {
146            throw new IllegalArgumentException("CharSequences must not be null");
147        }
148
149        if (StringUtils.equals(left, right)) {
150            return 1d;
151        }
152
153        final int[] mtp = matches(left, right);
154        final double m = mtp[0];
155        if (m == 0) {
156            return 0d;
157        }
158        final double j = (m / left.length() + m / right.length() + (m - (double) mtp[1] / 2) / m) / 3;
159        return j < 0.7d ? j : j + defaultScalingFactor * mtp[2] * (1d - j);
160    }
161
162}