PMCC.java [src/csip/cosu] Revision:   Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2022, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip.cosu;

/**
 * Pearsons Correlation
 */
class PMCC extends ObjFunc {

  @Override
  public String name() {
    return "Pearsons Correlation";
  }


  @Override
  public double eval(double[] obs, double[] sim, double missing) {
    checkArrays(sim, obs);
    double syy = 0.0;
    double sxy = 0.0;
    double sxx = 0.0;
    double ay = 0.0;
    double ax = 0.0;
    int n = 0;
    for (int j = 0; j < obs.length; j++) {
      if (obs[j] > missing) {
        ax += obs[j];
        ay += sim[j];
        n++;
      }
    }
    if (n == 0) {
      throw new RuntimeException("Pearson's Correlation cannot be calculated due to no observed values");
    }
    ax = ax / ((double) n);
    ay = ay / ((double) n);
    for (int j = 0; j < obs.length; j++) {
      if (obs[j] > missing) {
        double xt = obs[j] - ax;
        double yt = sim[j] - ay;
        sxx += xt * xt;
        syy += yt * yt;
        sxy += xt * yt;
      }
    }
    return sxy / Math.sqrt(sxx * syy);
  }


  @Override
  public int direction() {
    return 1;
  }


  @Override
  public int optimum() {
    return 1;
  }

}