1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using HeuristicLab.Core;
|
---|
6 | using HeuristicLab.Data;
|
---|
7 | using HeuristicLab.DataAnalysis;
|
---|
8 |
|
---|
9 | namespace 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 | }
|
---|