prho.hpp
1 // Copyright © 2020 Thomas Nagler
2 //
3 // This file is part of the wdm library and licensed under the terms of
4 // the MIT license. For a copy, see the LICENSE file in the root directory
5 // or https://github.com/tnagler/wdm/blob/master/LICENSE.
6 
7 #pragma once
8 
9 #include "utils.hpp"
10 
11 
12 namespace wdm {
13 
14 namespace impl {
15 
19 inline double prho(std::vector<double> x,
20  std::vector<double> y,
21  std::vector<double> weights = std::vector<double>())
22 {
23  utils::check_sizes(x, y, weights);
24  size_t n = x.size();
25  if (weights.size() == 0)
26  weights = std::vector<double>(x.size(), 1.0);
27 
28  // calculate means of x and y
29  double mu_x = 0.0, mu_y = 0.0, w_sum = 0.0;
30  for (size_t i = 0; i < n; i++) {
31  mu_x += x[i] * weights[i];
32  mu_y += y[i] * weights[i];
33  w_sum += weights[i];
34  }
35  mu_x /= w_sum;
36  mu_y /= w_sum;
37 
38  // substract mean from x and y
39  for (size_t i = 0; i < n; i++) {
40  x[i] -= mu_x;
41  y[i] -= mu_y;
42  }
43 
44  // compute variances and covariance
45  double v_x = 0.0, v_y = 0.0, cov = 0.0, wi_sq;
46  for (size_t i = 0; i < n; i++) {
47  wi_sq = weights[i] * weights[i];
48  v_x += x[i] * x[i] * wi_sq;
49  v_y += y[i] * y[i] * wi_sq;
50  cov += x[i] * y[i] * wi_sq;
51  }
52 
53  // compute correlation
54  return cov / std::sqrt(v_x * v_y);
55 }
56 
57 }
58 
59 }
Weighted dependence measures.
Definition: bbeta.hpp:11