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