summaryrefslogtreecommitdiffstats
path: root/lib/correlation_coefficient.c
blob: d20d1ea5395ce7aa65c5b59eb001b5e390d4037e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Correlation Coefficient
//
// correlation_coefficient - corr
//
// Pearson r = (n*Σxy - Σx*Σy) / √((n*Σx²-Σx²)(n*Σy²-Σy²))
//
// Inputs:    2
// Outputs:   1 (r)
// Constants: 1 (period)

#include <math.h>
#include "ts.h"

typedef struct {
    uint_t k;
} ts_correlation_coefficient_params_t;

ts_parameter_t const ts_correlation_coefficient_p = { .n_inputs = 2, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_correlation_coefficient_params_t) };

uint_t ts_correlation_coefficient_offset( ts_constant_t const *c )
{
	( void )c;
	return ( c ? ((ts_correlation_coefficient_params_t *)c)->k - 1 : 0 );
}

int ts_correlation_coefficient(
	fp_t * const *y, uint_t y_n,
	fp_t const * const *x, uint_t x_n,
	uint_t n, ts_constant_t const *c
)
{
	TS_PROLOGUE( ts_correlation_coefficient_p );
	if ( !c ) return -1;
    uint_t k = ((ts_correlation_coefficient_params_t *)c)->k;
    if (k == 0 || n < k) return -1;

    fp_t sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0;

    for ( uint_t i = 0; i < k; ++i )
    {
        fp_t xi = x[0][i];
        fp_t yi = x[1][i];
        sum_x += xi;
        sum_y += yi;
        sum_xy += xi * yi;
        sum_x2 += xi * xi;
        sum_y2 += yi * yi;
    }

    fp_t denom = ( k * sum_x2 - sum_x * sum_x ) * ( k * sum_y2 - sum_y * sum_y );
    fp_t numer = k * sum_xy - sum_x * sum_y;
    y[0][k - 1] = denom > 0 ? numer / sqrt( denom ) : 0;

    for ( uint_t i = k; i < n; ++i )
    {
        fp_t xi_old = x[0][i - k];
        fp_t yi_old = x[1][i - k];
        fp_t xi_new = x[0][i];
        fp_t yi_new = x[1][i];

        sum_x = sum_x - xi_old + xi_new;
        sum_y = sum_y - yi_old + yi_new;
        sum_xy = sum_xy - xi_old * yi_old + xi_new * yi_new;
        sum_x2 = sum_x2 - xi_old * xi_old + xi_new * xi_new;
        sum_y2 = sum_y2 - yi_old * yi_old + yi_new * yi_new;

        denom = ( k * sum_x2 - sum_x * sum_x ) * ( k * sum_y2 - sum_y * sum_y );
        numer = k * sum_xy - sum_x * sum_y;
        y[0][i] = denom > 0 ? numer / sqrt( denom ) : 0;
    }
	return 0;
}