Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Modeling/3.2/SimpleStableCorrelationCoefficientEvaluator.cs @ 3188

Last change on this file since 3188 was 2844, checked in by gkronber, 15 years ago

Added a check to SimpleStableCorrelationCoefficientEvaluator so that a r2 of 0.0 is returned instead of NaN (in case of division by zero). Also removed unnecessary try {} catch block in SimplePearsonCorrelationCoefficientEvaluator. #881

File size: 2.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7using HeuristicLab.DataAnalysis;
8
9namespace HeuristicLab.Modeling {
10  public class SimpleStableCorrelationCoefficientEvaluator : SimpleEvaluatorBase {
11
12    public override string OutputVariableName {
13      get {
14        return "R2";
15      }
16    }
17
18    public override double Evaluate(double[,] values) {
19      try {
20        return Calculate(values);
21      }
22      catch (ArgumentException) {
23        return double.NegativeInfinity;
24      }
25    }
26
27    public static double Calculate(double[,] values) {
28      double sum_sq_x = 0.0;
29      double sum_sq_y = 0.0;
30      double sum_coproduct = 0.0;
31      if (IsInvalidValue(values[0, ORIGINAL_INDEX]) || IsInvalidValue(values[0, ESTIMATION_INDEX])) {
32        throw new ArgumentException("Correlation coefficient is not defined for variables with NaN or infinity values.");
33      }
34      double mean_x = values[0, ORIGINAL_INDEX];
35      double mean_y = values[0, ESTIMATION_INDEX];
36      for (int i = 1; i < values.GetLength(0); i++) {
37        double sweep = (i - 1.0) / i;
38        if (IsInvalidValue(values[i, ORIGINAL_INDEX]) || IsInvalidValue(values[i, ESTIMATION_INDEX])) {
39          throw new ArgumentException("Correlation coefficient is not defined for variables with NaN or infinity values.");
40        }
41        double delta_x = values[i, ORIGINAL_INDEX] - mean_x;
42        double delta_y = values[i, ESTIMATION_INDEX] - mean_y;
43        sum_sq_x += delta_x * delta_x * sweep;
44        sum_sq_y += delta_y * delta_y * sweep;
45        sum_coproduct += delta_x * delta_y * sweep;
46        mean_x += delta_x / i;
47        mean_y += delta_y / i;
48      }
49      double pop_sd_x = Math.Sqrt(sum_sq_x / values.GetLength(0));
50      double pop_sd_y = Math.Sqrt(sum_sq_y / values.GetLength(0));
51      double cov_x_y = sum_coproduct / values.GetLength(0);
52
53      if (pop_sd_x == 0.0 || pop_sd_y == 0.0)
54        return 0.0;
55      else {
56        double r = cov_x_y / (pop_sd_x * pop_sd_y);
57        return r * r;
58      }
59    }
60
61    private static bool IsInvalidValue(double d) {
62      return double.IsNaN(d) || double.IsInfinity(d);
63    }
64  }
65}
Note: See TracBrowser for help on using the repository browser.