001    package org.hackystat.projectbrowser.page.trajectory.dtw;
002    
003    /**
004     * The Euclidean distance implementation.
005     *
006     * @author Pavel Senin.
007     *
008     */
009    public class EuclideanDistance {
010    
011      /**
012       * Calculates the square of the Euclidean distance between two points.
013       *
014       * @param point1 The first point.
015       * @param point2 The second point.
016       * @return The Euclidean distance.
017       * @throws DTWException In the case of error.
018       */
019      private static Double distance2(double[] point1, double[] point2) throws DTWException {
020        if (point1.length == point2.length) {
021          Double sum = 0D;
022          for (int i = 0; i < point1.length; i++) {
023            sum = sum + (point2[i] - point1[i]) * (point2[i] - point1[i]);
024          }
025          return sum;
026        }
027        else {
028          throw new DTWException("Exception in Euclidean distance: array lengths are not equal");
029        }
030      }
031    
032      /**
033       * Calculates the Euclidean distance between two points.
034       *
035       * @param point1 The first point.
036       * @param point2 The second point.
037       * @return The Euclidean distance.
038       * @throws DTWException In the case of error.
039       */
040      public static double pointDistance(double[] point1, double[] point2) throws DTWException {
041        return Math.sqrt(distance2(point1, point2));
042      }
043    
044      /**
045       * Calculates euclidean distance between two time-series of equal length.
046       *
047       * @param query The timeseries1.
048       * @param template The timeseries2.
049       * @return The eclidean distance.
050       * @throws DTWException if error occures.
051       */
052      public static double getSeriesDistnace(double[][] query, double[][] template) 
053                                                                              throws DTWException {
054        if (query.length == template.length) {
055          Double res = 0D;
056          for (int i = 0; i < query.length; i++) {
057            res = res + distance2(query[i], template[i]);
058          }
059          return Math.sqrt(res);
060        }
061        else {
062          throw new DTWException("Exception in Euclidean distance: array lengths are not equal");
063        }
064      }
065    
066    }