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 * https://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 18 /* 19 * This is not the original file distributed by the Apache Software Foundation 20 * It has been modified by the Hipparchus project 21 */ 22 package org.hipparchus.clustering.distance; 23 24 import org.hipparchus.exception.MathIllegalArgumentException; 25 import org.hipparchus.util.FastMath; 26 import org.hipparchus.util.MathArrays; 27 28 /** 29 * Calculates the Earh Mover's distance (also known as Wasserstein metric) between two distributions. 30 * 31 * @see <a href="http://en.wikipedia.org/wiki/Earth_mover's_distance">Earth Mover's distance (Wikipedia)</a> 32 * 33 */ 34 public class EarthMoversDistance implements DistanceMeasure { 35 36 /** Serializable version identifier. */ 37 private static final long serialVersionUID = -5406732779747414922L; 38 39 /** Empty constructor. 40 * <p> 41 * This constructor is not strictly necessary, but it prevents spurious 42 * javadoc warnings with JDK 18 and later. 43 * </p> 44 * @since 3.0 45 */ 46 public EarthMoversDistance() { // NOPMD - unnecessary constructor added intentionally to make javadoc happy 47 // nothing to do 48 } 49 50 /** {@inheritDoc} */ 51 @Override 52 public double compute(double[] a, double[] b) 53 throws MathIllegalArgumentException { 54 MathArrays.checkEqualLength(a, b); 55 double lastDistance = 0; 56 double totalDistance = 0; 57 for (int i = 0; i < a.length; i++) { 58 final double currentDistance = (a[i] + lastDistance) - b[i]; 59 totalDistance += FastMath.abs(currentDistance); 60 lastDistance = currentDistance; 61 } 62 return totalDistance; 63 } 64 65 }