001    package org.hackystat.projectbrowser.page.trajectory.dtw;
002    
003    /**
004     * Provide implementation of various computational methods for the DTW.
005     * 
006     * @author Pavel Senin
007     * 
008     */
009    public class DTWUtilFactory {
010    
011      /**
012       * Binds two linear arrays, producing a 2D array.
013       * 
014       * @param axis The first component array.
015       * @param seriesData The second component array.
016       * @return Binded rows.
017       * @throws DTWException If error occures.
018       */
019      public static double[][] rBind(double[] axis, double[] seriesData) throws DTWException {
020        if (axis.length == seriesData.length) {
021          int len = axis.length;
022          double[][] res = new double[len][2];
023          for (int i = 0; i < len; i++) {
024            res[i][0] = axis[i];
025            res[i][1] = seriesData[i];
026          }
027          return res;
028        }
029        throw new DTWException("Error while binding rows: uneven arrays provided.");
030      }
031    
032      /**
033       * Compute the mean of the timeseries.
034       * 
035       * @param series The input timeseries.
036       * @return the mean of values.
037       */
038      public static double mean(double[] series) {
039        double res = 0D;
040        for (int i = 0; i < series.length; i++) {
041          res += series[i];
042        }
043        return res / ((Integer) series.length).doubleValue();
044      }
045    
046      /**
047       * Compute the variance of the timeseries.
048       * 
049       * @param series The input timeseries.
050       * @return the variance of values.
051       */
052      public static double var(double[] series) {
053        double res = 0D;
054        double mean = mean(series);
055        for (int i = 0; i < series.length; i++) {
056          res += (series[i] - mean) * (series[i] - mean);
057        }
058        return res / ((Integer) (series.length - 1)).doubleValue();
059      }
060    
061      /**
062       * Normalize timeseries.
063       * 
064       * @param series The input timeseries.
065       * @return the normalized time-series.
066       */
067      public static double[] normalize(double[] series) {
068        double[] res = new double[series.length];
069        double mean = mean(series);
070        double var = var(series);
071        for (int i = 0; i < res.length; i++) {
072          res[i] = (series[i] - mean) / var;
073        }
074        return res;
075      }
076    
077    }