1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.hipparchus.stat.descriptive.vector;
23
24 import java.io.Serializable;
25 import java.util.Arrays;
26
27 import org.hipparchus.exception.MathIllegalArgumentException;
28 import org.hipparchus.linear.MatrixUtils;
29 import org.hipparchus.linear.RealMatrix;
30 import org.hipparchus.util.MathArrays;
31
32
33
34
35 public class VectorialCovariance implements Serializable {
36
37
38 private static final long serialVersionUID = 4118372414238930270L;
39
40
41 private final double[] sums;
42
43
44 private final double[] productsSums;
45
46
47 private final boolean isBiasCorrected;
48
49
50 private long n;
51
52
53
54
55
56
57 public VectorialCovariance(int dimension, boolean isBiasCorrected) {
58 sums = new double[dimension];
59 productsSums = new double[dimension * (dimension + 1) / 2];
60 n = 0;
61 this.isBiasCorrected = isBiasCorrected;
62 }
63
64
65
66
67
68
69 public void increment(double[] v) throws MathIllegalArgumentException {
70 MathArrays.checkEqualLength(v, sums);
71 int k = 0;
72 for (int i = 0; i < v.length; ++i) {
73 sums[i] += v[i];
74 for (int j = 0; j <= i; ++j) {
75 productsSums[k++] += v[i] * v[j];
76 }
77 }
78 n++;
79 }
80
81
82
83
84
85 public RealMatrix getResult() {
86
87 int dimension = sums.length;
88 RealMatrix result = MatrixUtils.createRealMatrix(dimension, dimension);
89
90 if (n > 1) {
91 double c = 1.0 / (n * (isBiasCorrected ? (n - 1) : n));
92 int k = 0;
93 for (int i = 0; i < dimension; ++i) {
94 for (int j = 0; j <= i; ++j) {
95 double e = c * (n * productsSums[k++] - sums[i] * sums[j]);
96 result.setEntry(i, j, e);
97 result.setEntry(j, i, e);
98 }
99 }
100 }
101
102 return result;
103
104 }
105
106
107
108
109
110 public long getN() {
111 return n;
112 }
113
114
115
116
117 public void clear() {
118 n = 0;
119 Arrays.fill(sums, 0.0);
120 Arrays.fill(productsSums, 0.0);
121 }
122
123
124 @Override
125 public int hashCode() {
126 final int prime = 31;
127 int result = 1;
128 result = prime * result + (isBiasCorrected ? 1231 : 1237);
129 result = prime * result + (int) (n ^ (n >>> 32));
130 result = prime * result + Arrays.hashCode(productsSums);
131 result = prime * result + Arrays.hashCode(sums);
132 return result;
133 }
134
135
136 @Override
137 public boolean equals(Object obj) {
138 if (this == obj) {
139 return true;
140 }
141 if (!(obj instanceof VectorialCovariance)) {
142 return false;
143 }
144 VectorialCovariance other = (VectorialCovariance) obj;
145 if (isBiasCorrected != other.isBiasCorrected) {
146 return false;
147 }
148 if (n != other.n) {
149 return false;
150 }
151 if (!Arrays.equals(productsSums, other.productsSums)) {
152 return false;
153 }
154 if (!Arrays.equals(sums, other.sums)) {
155 return false;
156 }
157 return true;
158 }
159
160 }