Debian Codegraph @

dwtools/Covariance.cpp

raw
1 /* Covariance.cpp
2 *
3 * Copyright (C) 1993-2023 David Weenink
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "Covariance.h"
20 #include "Eigen.h"
21 #include "NUMlapack.h"
22 #include "NUM2.h"
23 #include "SVD.h"
24
25 Thing_implement (Covariance, SSCP, 0);
26 Thing_implement (CovarianceList, SSCPList, 0);
27
28 autoTableOfReal Covariance_TableOfReal_mahalanobis (Covariance me, TableOfReal thee, bool useTableCentroid) {
29 try {
30 Melder_require (my numberOfColumns == thy numberOfColumns,
31 U"The number of dimensions of the Covariance should be equal to that of the TableOfReal.");
32 autoTableOfReal him = TableOfReal_create (thy numberOfRows, 1);
33 autoVEC centroid = copy_VEC (my centroid.get());
34 autoMAT covari = copy_MAT (my data.get());
35 /*
36 Mahalanobis distance calculation. S = L.L' -> S**-1 = L**-1' . L**-1
37 (x-m)'S**-1 (x-m) = (x-m)'L**-1' . L**-1. (x-m) =
38 (L**-1.(x-m))' . (L**-1.(x-m))
39
40 Get inverse of covari in lower triangular part.
41 */
42 MATlowerCholeskyInverse_inplace (covari.get(), nullptr);
43
44 if (useTableCentroid)
45 columnMeans_VEC_out (centroid.get(), thy data.get());
46 for (integer k = 1; k <= thy numberOfRows; k ++) {
47 his data [k] [1] = sqrt (NUMmahalanobisDistanceSquared (covari.get(), thy data.row (k), centroid.get()));
48 if (thy rowLabels [k])
49 TableOfReal_setRowLabel (him.get(), k, thy rowLabels [k].get());
50 }
51 TableOfReal_setColumnLabel (him.get(), 1, U"d");
52 return him;
53 } catch (MelderError) {
54 Melder_throw (me, U"no Mahalanobis distances created.");
55 }
56 }
57
58 /* For nxn matrix only ! */
59 void Covariance_PCA_generateOneVector_inline (Covariance me, PCA thee, VECVU vec, VEC buf) {
60 Melder_require (thy dimension == my numberOfRows,
61 U"The PCA should have the same number of dimensions as the Covariance.");
62 Melder_require (vec.size == buf.size && my numberOfColumns == buf.size,
63 U"The vectors and the PCA should have the same number of dimensions.");
64 /*
65 Generate the multi-normal vector elements N(0,sigma)
66 */
67 for (integer j = 1; j <= my numberOfColumns; j ++)
68 buf [j] = NUMrandomGauss (0.0, sqrt (thy eigenvalues [j]));
69 /*
70 Rotate back
71 */
72 mul_VEC_out (vec, buf, thy eigenvectors.get());
73 vec += my centroid.get();
74 }
75
76 autoTableOfReal Covariance_to_TableOfReal_randomSampling (Covariance me, integer numberOfData) {
77 try {
78 if (numberOfData <= 0)
79 numberOfData = Melder_ifloor (my numberOfObservations);
80 autoPCA pca = SSCP_to_PCA (me);
81 autoTableOfReal thee = TableOfReal_create (numberOfData, my numberOfColumns);
82 autoVEC buf = raw_VEC (my numberOfColumns);
83 for (integer i = 1; i <= numberOfData; i ++)
84 Covariance_PCA_generateOneVector_inline (me, pca.get(), thy data.row (i), buf.get());
85 thy columnLabels.all() <<= my columnLabels.all();
86 return thee;
87 } catch (MelderError) {
88 Melder_throw (me, U": not random sampled.");
89 }
90 }
91
92 autoTableOfReal Covariance_TableOfReal_extractDistanceQuantileRange (Covariance me, TableOfReal thee, double qlow, double qhigh) {
93 try {
94 autoTableOfReal him = Covariance_TableOfReal_mahalanobis (me, thee, false);
95
96 const double low = TableOfReal_getColumnQuantile (him.get(), 1, qlow);
97 const double high = TableOfReal_getColumnQuantile (him.get(), 1, qhigh);
98 /*
99 Count the number filtered.
100 nsel = (qhigh - qlow) * nrows is sometimes one off
101 */
102 integer nsel = 0;
103 for (integer i = 1; i <= thy numberOfRows; i ++)
104 if (low <= his data [i] [1] && his data [i] [1] < high)
105 nsel ++;
106 Melder_require (nsel > 0,
107 U"Not enough data in quantile interval.");
108
109 autoTableOfReal r = TableOfReal_create (nsel, thy numberOfColumns);
110 r -> columnLabels.all() <<= thy columnLabels.all();
111
112 integer k = 0;
113 for (integer i = 1; i <= thy numberOfRows; i ++)
114 if (low <= his data [i] [1] && his data [i] [1] < high)
115 TableOfReal_copyOneRowWithLabel (thee, r.get(), i, ++ k);
116 return r;
117 } catch (MelderError) {
118 Melder_throw (U"TableOfReal with distance quantile range not created.");
119 }
120 }
121
122 autoCovariance TableOfReal_to_Covariance (TableOfReal me) {
123 try {
124 autoSSCP sscp = TableOfReal_to_SSCP (me, 0, 0, 0, 0);
125 autoCovariance thee = SSCP_to_Covariance (sscp.get(), 1);
126 return thee;
127 } catch (MelderError) {
128 Melder_throw (me, U": covariances not created.");
129 }
130 }
131
132 autoCovariance CovarianceList_to_Covariance_within (CovarianceList me) {
133 try {
134 autoCovariance thee = Data_copy (my at [1]);
135 SSCP_reset (thee.get());
136 for (integer i = 1; i <= my size; i ++) {
137 const Covariance covi = my at [i];
138 Melder_require (thy numberOfColumns == covi -> numberOfColumns && thy numberOfRows == covi -> numberOfRows,
139 U"The dimensions of item ", i, U" do not conform.");
140 thy data.all() += covi -> data.all() * (covi -> numberOfObservations - 1.0);
141 thy numberOfObservations += covi -> numberOfObservations;
142 }
143 thy data.all() *= 1.0 / (thy numberOfObservations - 1.0);
144 return thee;
145 } catch (MelderError) {
146 Melder_throw (me, U": no Covariance (within) created.");
147 }
148 }
149
150 autoCovariance CovarianceList_to_Covariance_between (CovarianceList me) {
151 try {
152 autoCovariance thee = Data_copy (my at [1]);
153 SSCP_reset (thee.get());
154
155 // First the new centroid,
156
157 for (integer i = 1; i <= my size; i ++) {
158 const Covariance covi = my at [i];
159 Melder_require (thy numberOfColumns == covi -> numberOfColumns && thy numberOfRows == covi -> numberOfRows,
160 U"The dimensions of item ", i, U" do not conform.");
161 thy centroid.all() += covi -> centroid.all() * covi -> numberOfObservations;
162 thy numberOfObservations += covi -> numberOfObservations;
163 }
164 thy centroid.all() *= 1.0 / thy numberOfObservations;
165
166 autoVEC mean = raw_VEC (thy numberOfColumns);
167 autoMAT outer = raw_MAT (thy numberOfColumns, thy numberOfColumns);
168 for (integer i = 1; i <= my size; i ++) {
169 const Covariance covi = my at [i];
170 mean.all() <<= covi -> centroid.all() - thy centroid.all();
171 outer_MAT_out (outer.all(), mean.all(), mean.all());
172 if (thy numberOfRows == 1)
173 thy data.row (1) += outer.diagonal() * covi -> numberOfObservations;
174 else
175 thy data.all() += outer.all() * covi -> numberOfObservations; // Y += aX
176 }
177 thy data.all() *= 1.0 / (thy numberOfObservations - 1.0);
178 return thee;
179 } catch (MelderError) {
180 Melder_throw (me, U": no Covariance (between) created.");
181 }
182 }
183
184 autoCovariance CovarianceList_to_Covariance_pool (CovarianceList me) { // Morrison sec 3.5, page 100
185 try {
186 autoCovariance thee = Data_copy (my at [1]);
187 SSCP_reset (thee.get());
188 for (integer i = 1; i <= my size; i ++) {
189 const Covariance covi = my at [i];
190 Melder_require (covi -> numberOfRows == thy numberOfRows,
191 U"The dimension of item ", i, U" should agree.");
192 thy numberOfObservations += covi -> numberOfObservations;
193 /*
194 Sum the sscp's and weigh the centroid.
195 */
196 for (integer k = 1; k <= thy numberOfRows; k ++) // catch 1xn
197 thy data.row (k) += covi -> data.row (k) * (covi -> numberOfObservations - 1.0);
198
199 thy centroid.all() += covi -> centroid.all() * covi -> numberOfObservations;
200 }
201 thy centroid.all() *= 1.0 / thy numberOfObservations;
202 thy data.all() *= 1.0 / (thy numberOfObservations - my size);
203 return thee;
204 } catch (MelderError) {
205 Melder_throw (me, U": not pooled.");
206 }
207 }
208
209 autoCovariance Covariance_create (integer dimension) {
210 try {
211 autoCovariance me = Thing_new (Covariance);
212 SSCP_init (me.get(), dimension, kSSCPstorage::COMPLETE);
213 return me;
214 } catch (MelderError) {
215 Melder_throw (U"Covariance not created.");
216 }
217 }
218
219 autoCovariance Covariance_create_reduceStorage (integer dimension, kSSCPstorage storage) {
220 try {
221 autoCovariance me = Thing_new (Covariance);
222 SSCP_init (me.get(), dimension, storage);
223 return me;
224 } catch (MelderError) {
225 Melder_throw (U"Reduced storage covariance not created.");
226 }
227 }
228
229
230
231 autoCovariance Covariance_createSimple (constVECVU const& covariances, constVECVU const& centroid, integer numberOfObservations) {
232 try {
233 const integer numberOfCovariances_wanted = centroid.size * (centroid.size + 1) / 2;
234 Melder_require (covariances.size == numberOfCovariances_wanted,
235 U"The number of covariance matrix elements and the number of centroid elements should agree. "
236 "If there are d centroid values, there should be d(d+1)/2 covariance values, "
237 "so if there are ", centroid.size, U" centroid values, there should be ", numberOfCovariances_wanted, U" covariance values.");
238
239 autoCovariance me = Covariance_create (centroid.size);
240 /*
241 Construct the full covariance matrix from the upper-diagonal elements
242 */
243 integer rowNumber = 1;
244 for (integer inum = 1; inum <= covariances.size; inum ++) {
245 const integer nmissing = (rowNumber - 1) * rowNumber / 2;
246 const integer inumc = inum + nmissing;
247 rowNumber = (inumc - 1) / centroid.size + 1;
248 integer icol = ((inumc - 1) % centroid.size) + 1;
249 my data [rowNumber] [icol] = my data [icol] [rowNumber] = covariances [inum];
250 if (icol == centroid.size)
251 rowNumber ++;
252 }
253
254 // Check if a valid covariance, first check variances then covariances
255
256 for (integer irow = 1; irow <= centroid.size; irow ++)
257 Melder_require (my data [irow] [irow] > 0.0,
258 U"The diagonal matrix elements should all be positive numbers.");
259
260 for (integer irow = 1; irow <= centroid.size; irow ++)
261 for (integer icol = irow + 1; icol <= centroid.size; icol ++)
262 Melder_require (fabs (my data [irow] [icol] / sqrt (my data [irow] [irow] * my data [icol] [icol])) <= 1.0,
263 U"The covariance in cell [", irow, U",", icol, U"], i.e. input item ",
264 (irow - 1) * centroid.size + icol - (irow - 1) * irow / 2, U" is too large.");
265 my centroid.all() <<= centroid;
266 my numberOfObservations = numberOfObservations;
267 return me;
268 } catch (MelderError) {
269 Melder_throw (U"Simple Covariance not created.");
270 }
271 }
272
273 autoCovariance SSCP_to_Covariance (SSCP me, integer numberOfConstraints) {
274 try {
275 Melder_assert (numberOfConstraints >= 0);
276 autoCovariance thee = Thing_new (Covariance);
277 my structSSCP :: v1_copy (thee.get());
278
279 for (integer irow = 1; irow <= my numberOfRows; irow ++)
280 for (integer icol = irow; icol <= my numberOfColumns; icol ++) // a covariance matrix is symmetric
281 thy data [icol] [irow] = thy data [irow] [icol] /= my numberOfObservations - numberOfConstraints;
282 return thee;
283 } catch (MelderError) {
284 Melder_throw (me, U"; Covariance not created.");
285 }
286 }
287
288 static autoCovariance Covariances_pool (Covariance me, Covariance thee) {
289 try {
290 Melder_require (my numberOfRows == thy numberOfRows && my numberOfColumns == thy numberOfColumns,
291 U"Matrices should have equal dimensions.");
292 autoSSCPList sscps = SSCPList_create ();
293 autoSSCP sscp1 = Covariance_to_SSCP (me);
294 sscps -> addItem_move (sscp1.move());
295 autoSSCP sscp2 = Covariance_to_SSCP (thee);
296 sscps -> addItem_move (sscp2.move());
297 autoSSCP pool = SSCPList_to_SSCP_pool (sscps.get());
298 autoCovariance him = SSCP_to_Covariance (pool.get(), 2);
299 return him;
300 } catch (MelderError) {
301 Melder_throw (me, U"not pooled.");
302 }
303 }
304
305 static double traceOfSquaredMatrixProduct (constMAT const& s1, constMAT const& s2) {
306 // tr ((s1*s2)^2), s1, s2 are symmetric
307 autoMAT m = mul_MAT (s1, s2);
308 const double trace = NUMtrace2 (m.get(), m.get());
309 return trace;
310 }
311
312 double Covariance_getProbabilityAtPosition_string (Covariance me, conststring32 vector_string) {
313 autoSTRVEC vector = splitByWhitespace_STRVEC (vector_string);
314 autoVEC v = zero_VEC (my numberOfColumns);
315 for (integer i = 1; i <= vector.size; i ++) {
316 v [i] = Melder_atof (vector [i].get());
317 if (i == my numberOfColumns)
318 break;
319 }
320 const double prob = Covariance_getProbabilityAtPosition (me, v.get());
321 return prob;
322 }
323
324 double Covariance_getProbabilityAtPosition (Covariance me, constVEC x) {
325 Melder_require (x.size == my numberOfColumns,
326 U"The dimensions of the Covariance and the vector should agree.");
327 if (NUMisEmpty (my lowerCholeskyInverse.get()))
328 SSCP_expandWithLowerCholeskyInverse (me);
329 const double dsq = NUMmahalanobisDistanceSquared (my lowerCholeskyInverse.get(), x, my centroid.get());
330 const double lnN = - 0.5 * (my numberOfColumns * log (NUM2pi) + my lnd + dsq);
331 const double prob = exp (lnN);
332 return prob;
333 }
334
335 double Covariance_getMarginalProbabilityAtPosition (Covariance me, constVECVU const& vector, double x) {
336 double mu, stdev;
337 Covariance_getMarginalDensityParameters (me, vector, & mu, & stdev);
338 const double dx = (x - mu) / stdev;
339 const double prob = (NUM1_sqrt2pi / stdev) * exp (- 0.5 * dx * dx);
340 return prob;
341 }
342
343 /* Precondition ||v|| = 1 */
344 void Covariance_getMarginalDensityParameters (Covariance me, constVECVU const& v, double *out_mean, double *out_stdev) {
345 Melder_assert (v.size == my numberOfColumns);
346 if (out_mean)
347 *out_mean = NUMinner (v, my centroid.get());
348 if (out_stdev) {
349 longdouble stdev = 0.0;
350 if (my numberOfRows == 1) // 1xn diagonal matrix
351 for (integer m = 1; m <= my numberOfColumns; m ++)
352 stdev += v [m] * my data [1] [m] * v [m];
353 else
354 for (integer k = 1; k <= my numberOfRows; k ++)
355 for (integer m = 1; m <= my numberOfColumns; m ++)
356 stdev += v [k] * my data [k] [m] * v [m];
357 *out_stdev = sqrt (double (stdev));
358 }
359 }
360
361 double Covariances_getMultivariateCentroidDifference (Covariance me, Covariance thee, int equalCovariances, double *out_prob, double *out_fisher, double *out_ndof1, double *out_ndof2) {
362 const integer nrow = my numberOfRows, N = Melder_ifloor (my numberOfObservations + thy numberOfObservations);
363 const integer N1 = Melder_ifloor (my numberOfObservations), n1 = N1 - 1;
364 const integer N2 = Melder_ifloor (thy numberOfObservations), n2 = N2 - 1;
365 const double ndof1 = nrow;
366 double ndof2 = N - nrow - 1;
367
368 Melder_require (ndof2 >= 1.0,
369 U"Not enough observations (", N, U") for this test.");
370 Melder_require (nrow <= N1 && nrow <= N2,
371 U"The number of observations should be larger than the number of variables.");
372 double dif = 0.0;
373 for (integer i = 1; i <= nrow; i ++) {
374 const double dist = my centroid [i] - thy centroid [i];
375 dif += dist * dist;
376 }
377 dif = sqrt (dif);
378 double fisher = undefined;
379 if (equalCovariances) {
380 /*
381 Morrison, page 141
382 */
383 autoCovariance pool = Covariances_pool (me, thee);
384 Melder_assert (my data.ncol == nrow); // ppgb 20180913
385 autoMAT s = copy_MAT (my data.get());
386 double lndet;
387 MATlowerCholeskyInverse_inplace (s.get(), & lndet);
388
389 const double mahalanobis = NUMmahalanobisDistanceSquared (s.get(), my centroid.get(), thy centroid.get());
390 const double hotelling_tsq = mahalanobis * N1 * N2 / N;
391 fisher = hotelling_tsq * ndof2 / ( (N - 2) * ndof1);
392 } else {
393 /*
394 Krishnamoorthy-Yu (2004): Modified Nel and Van der Merwe test
395
396 Hotelling t^2 = (x1-x2)'*S^-1*(x1 -x2) follows nu*nrow*Fisher(nrow,nu-nrow+1)/(nu-nrow+1)
397
398 Approximate number of degrees of freedom (their formula 7, page 164)
399 nu = (nrow+nrow^2)/((1/n1)(tr (S1*S^-1)^2 + (tr(S1*S^-1))^2)) +(1/n2)(tr (S2*S^-1)^2 + (tr(S2*S^-1))^2)))
400 the matrices S1 and S2 are the covariance matrices 'my data' and 'thy data' divided by N1 and N2 respectively.
401 S is the pooled covar divided by N.
402 */
403 autoMAT s1 = raw_MAT (nrow, nrow), s2 = raw_MAT (nrow, nrow), s = raw_MAT (nrow, nrow);
404 for (integer i = 1; i <= nrow; i ++) {
405 for (integer j = 1; j <= nrow; j ++) {
406 s1 [i] [j] = my data [i] [j] / my numberOfObservations;
407 s2 [i] [j] = thy data [i] [j] / thy numberOfObservations;
408 s [i] [j] = s1 [i] [j] + s2 [i] [j];
409 }
410 }
411 double lndet;
412 MATlowerCholeskyInverse_inplace (s.get(), & lndet);
413 /*
414 Krishan... formula 2, page 162
415 */
416 const double hotelling_tsq = NUMmahalanobisDistanceSquared (s.get(), my centroid.get(), thy centroid.get());
417
418 autoMAT si = newMATinverse_fromLowerCholeskyInverse (s.get());
419 const double tr_s1sisqr = traceOfSquaredMatrixProduct (s1.get(), si.get());
420 const double tr_s1si = NUMtrace2 (s1.get(), si.get());
421 const double tr_s2sisqr = traceOfSquaredMatrixProduct (s2.get(), si.get());
422 const double tr_s2si = NUMtrace2 (s2.get(), si.get());
423
424 const double nu = (nrow + nrow * nrow) / ( (tr_s1sisqr + tr_s1si * tr_s1si) / n1 + (tr_s2sisqr + tr_s2si * tr_s2si) / n2);
425 ndof2 = nu - nrow + 1;
426 fisher = hotelling_tsq * (nu - nrow + 1) / (nu * nrow);
427 }
428
429 if (out_prob)
430 *out_prob = NUMfisherQ (fisher, ndof1, ndof2);
431 if (out_fisher)
432 *out_fisher = fisher;
433 if (out_ndof1)
434 *out_ndof1 = ndof1;
435 if (out_ndof2)
436 *out_ndof2 = ndof2;
437 return dif;
438 }
439
440 /* Schott 2001 */
441 void Covariances_equality (CovarianceList me, int method, double *out_prob, double *out_chisq, double *out_ndof) {
442 try {
443
444 const integer numberOfMatrices = my size;
445 Melder_require (numberOfMatrices > 1,
446 U"We need at least two matrices");
447
448 autoCovariance pool = CovarianceList_to_Covariance_pool (me);
449 const double ns = pool -> numberOfObservations - my size;
450 const integer nrow = pool -> numberOfRows;
451
452 double chisq = undefined, ndof = undefined;
453 if (method == 1) {
454 /*
455 Bartlett (see Morrison page 297)
456 The hypothesis H0 : Sigma [1] = .... = Sigma [k] of the equality of the covariance matrices of k nrow-dimensional
457 multinormal populations can be tested against the alternative by a modified generalized likelihood-ratio statistic.
458 Let S [i] be the unbiased estimate of Sigma [i] based on n [i] degrees of freedom, where n [i] = N [i]-1 for
459 the usual case of a random sample of N [i] observation vectors from the i-th population. When H0 is true
460 S = 1/(sum(i=1..k, n [i])) sum(i=1..k, n [i]*S [i])
461 is the pooled estimate of the common covariance matrix. The test statistic is
462 M = sum(i=1..k,n [i])*ln|S| - sum(i=1..k, n [i]*ln|S [i]|).
463 Box (1949), "A general distribution theory for a class of likelihood criteria",
464 Biomerika, vol 36, pp. 317-346. has shown that if the scale factor
465 C^(-1) = 1 - (2p^2+3p-1)/(6(nrow+1)(k-1)) * (sum(i=1..k, 1/n [i]) - 1 / sum(i=1..k, n [i])) is introduced,
466 the quatity M/C is approximately distributed as a chi-squared variate with (k-1)nrow(nrow+1)/2 degrees of freedom
467 as the n [i] become large.
468 It is well known that this likelihood ratio test is very sensitive to violations of the normality assumption,
469 and so other more robust procedures have been proposed.
470 */
471 double lnd;
472 try {
473 lnd = NUMdeterminant_fromSymmetricMatrix (pool -> data.get());
474 } catch (MelderError) {
475 Melder_throw (U"Pooled covariance matrix is singular.");
476 }
477
478 double nsi = 0.0, m = ns * lnd; // First part of eq (3) page 297
479
480 for (integer i = 1; i <= numberOfMatrices; i ++) {
481 const Covariance ci = my at [i];
482 try {
483 lnd = NUMdeterminant_fromSymmetricMatrix (ci -> data.get());
484 } catch (MelderError) {
485 Melder_throw (U"Covariance matrix ", i, U" is singular.");
486 }
487 nsi += 1.0 / (ci -> numberOfObservations - 1);
488 m -= (ci -> numberOfObservations - 1) * lnd; // Last part of eq (3) page 297
489 }
490 /*
491 Eq (4) page 297
492 */
493 const double c1 = 1.0 - (2.0 * nrow * nrow + 3.0 * nrow - 1.0) / (6.0 * (nrow + 1) * (numberOfMatrices - 1)) * (nsi - 1.0 / ns);
494
495 ndof = (numberOfMatrices - 1.0) * nrow * (nrow + 1) / 2.0;
496 chisq = m * c1;
497 } else if (method == 2) { // Schott (2001) Wald 1
498 /*
499 T1 = sum(i=1..k, n [i]/n *tr((S [i]*S^-1)^2)- sum(i=1..k, sum(j=1..k, (n [i]/n)*(n [j]/n) *tr(S [i]*S^-1*S [j]*sS^-1))) =
500 sum(i=1..k, (ni/n -(ni/n)^2) tr((si*s^-1)^2)
501 - 2 * sum (i=1..k, sum(j=1..i-1, (ni/n)*(nj/n) *tr(si*s^-1*sj*s^-1)))
502 */
503 double trace = 0.0;
504 MATlowerCholeskyInverse_inplace (pool -> data.get(), nullptr);
505 autoMAT si = newMATinverse_fromLowerCholeskyInverse (pool -> data.get());
506 for (integer i = 1; i <= numberOfMatrices; i ++) {
507 const Covariance ci = my at [i];
508 const double ni = ci -> numberOfObservations - 1;
509 autoMAT s1 = mul_MAT (ci -> data.get(), si.get());
510 const double trace_ii = NUMtrace2 (s1.get(), s1.get());
511 trace += (ni / ns) * (1 - (ni / ns)) * trace_ii;
512 for (integer j = i + 1; j <= numberOfMatrices; j ++) {
513 const Covariance cj = my at [j];
514 const double nj = cj -> numberOfObservations - 1;
515 autoMAT s2 = mul_MAT (cj -> data.get(), si.get());
516 const double trace_ij = NUMtrace2 (s1.get(), s2.get());
517 trace -= 2.0 * (ni / ns) * (nj / ns) * trace_ij;
518 }
519 }
520 ndof = (numberOfMatrices - 1) * nrow * (nrow + 1) / 2.0;
521 chisq = (ns / 2.0) * trace;
522 } else {
523 return;
524 }
525 if (out_prob)
526 *out_prob = NUMchiSquareQ (chisq, ndof);
527 if (out_ndof)
528 *out_ndof = ndof;
529 if (out_chisq)
530 *out_chisq = chisq;
531 } catch (MelderError) {
532 Melder_throw (U"Equality could not be tested.");
533 }
534 }
535
536 double Covariance_TableOfReal_normalityTest_BHEP (Covariance me, TableOfReal thee, constVEC const& responsibilities, double *inout_beta, double *out_tnb, double *out_lnmu, double *out_lnvar, bool *out_covarianceIsSingular) {
537 try {
538 const MAT data = thy data.get();
539 Melder_require (data.nrow > data.ncol,
540 U"The number of data should be larger than the dimension of the data.");
541 Melder_require (my numberOfColumns == data.ncol,
542 U"The number of columns of the covariance and the data should be equal.");
543
544 const bool weighting = responsibilities.size > 0;
545 bool covarianceIsSingular = false;
546 const double d = data.ncol;
547 double n = data.nrow, testStatistic;
548 if (weighting) {
549 Melder_require (responsibilities.size == data.nrow,
550 U"The size of the responsibilities vector should equal the number of data.");
551 n = NUMsum (responsibilities);
552 }
553
554 *inout_beta = ( *inout_beta > 0.0 ? NUMsqrt1_2 / *inout_beta : NUMsqrt1_2 * pow ( (1.0 + 2.0 * d) / 4.0, 1.0 / (d + 4.0)) * pow (n, 1.0 / (d + 4.0)) );
555 const double d2 = d / 2.0, beta2 = *inout_beta * *inout_beta, gamma = 1.0 + 2.0 * beta2;
556
557 autoVEC buf = raw_VEC (data.nrow);
558
559 try { // in case the covariance matrix is singular and its inverse cannot be determined
560 SSCP_expandWithLowerCholeskyInverse (me);
561 const MAT lowerInverse = my lowerCholeskyInverse.get();
562 /*
563 Heinze & Wagner (1997), on page 3 in the formula for W(n,beta) scaled residuals
564 Y(i)=S^(-1/2)*(X(i)-mean) are used.
565 However, we can work with the original data and use squared Mahalanobis distances in this calculation because
566 ||Y(j)-Y(k)||^2 = (X(j)-X(k))'S^-1((X(j)-X(k)), where X(i) and Y(i) are d-dimensional vectors.
567 This expression is symmetric in j and k.
568 */
569 double doubleSum = 0.0;
570 for (integer j = 1; j <= data.nrow - 1; j ++) {
571 for (integer k = j + 1; k <= data.nrow; k ++) {
572 const double djk_sq = NUMmahalanobisDistanceSquared (lowerInverse, data.row (j), data.row (k));
573 buf [k] = exp (- 0.5 * beta2 * djk_sq);
574 }
575 if (weighting)
576 doubleSum += 2.0 * responsibilities [j] * NUMinner (buf.part (j + 1, data.nrow), responsibilities.part (j + 1, data.nrow));
577 else
578 doubleSum += 2.0 * NUMsum (buf.part (j + 1, data.nrow));
579 }
580 doubleSum += n; // contribution of all the terms in the double sum where j == k
581
582 double singleSum = 0.0;
583 for (integer j = 1; j <= data.nrow; j ++) {
584 const double djj_sq = NUMmahalanobisDistanceSquared (lowerInverse, data.row (j), my centroid.get());
585 buf [j] = exp (- 0.5 * beta2 * djj_sq / (1.0 + beta2));
586 }
587 if (weighting)
588 singleSum += NUMinner (buf.get(), responsibilities);
589 else
590 singleSum += NUMsum (buf.get());
591 /*
592 The test statistic is n times the W(n,beta) of page 3.
593 */
594 testStatistic = doubleSum / n - 2.0 * pow (1.0 + beta2, - d2) * singleSum + n * pow (gamma, - d2);
595 } catch (MelderError) {
596 Melder_clearError ();
597 testStatistic = 4.0 * n;
598 covarianceIsSingular = true;
599 }
600 const double beta4 = beta2 * beta2, beta8 = beta4 * beta4;
601 const double gamma2 = gamma * gamma, gamma4 = gamma2 * gamma2; // page 15
602 const double delta = 1.0 + beta2 * (4.0 + 3.0 * beta2), delta2 = delta * delta; // page 15
603
604 const double mu = 1.0 - pow (gamma, -d2) * (1.0 + d * beta2 / gamma + d * (d + 2.0) * beta4 / (2.0 * gamma2));
605 const double var = 2.0 * pow (1.0 + 4.0 * beta2, -d2)
606 + 2.0 * pow (gamma, -d) * (1.0 + 2.0 * d * beta4 / gamma2 + 3.0 * d * (d + 2) * beta8 / (4.0 * gamma4))
607 - 4.0 * pow (delta, -d2) * (1.0 + 3.0 * d * beta4 / (2.0 * delta) + d * (d + 2) * beta8 / (2.0 * delta2));
608 const double mu2 = mu * mu;
609 const double lnmu = log (sqrt (mu2 * mu2 / (mu2 + var)));
610 const double lnvar = sqrt (log ((mu2 + var) / mu2));
611 if (out_lnmu)
612 *out_lnmu = lnmu;
613 if (out_lnvar)
614 *out_lnvar = lnvar;
615 if (out_tnb)
616 *out_tnb = testStatistic;
617 if (out_covarianceIsSingular)
618 *out_covarianceIsSingular = covarianceIsSingular;
619 double prob = NUMlogNormalQ (testStatistic, lnmu, lnvar);
620 return prob;
621 } catch (MelderError) {
622 Melder_throw (me, U": Could not determine BHEP statistic.");
623 }
624 }
625
626 void Covariance_difference (Covariance me, Covariance thee, double *out_prob, double *out_chisq, double *out_ndof) {
627 const integer nrow = my numberOfRows;
628 integer numberOfObservations = Melder_ifloor (my numberOfObservations);
629 Melder_require (my numberOfRows == thy numberOfRows,
630 U"Matrices should have equal dimensions.");
631 if (my numberOfObservations != thy numberOfObservations) {
632 numberOfObservations = Melder_ifloor (std::min (my numberOfObservations, thy numberOfObservations));
633 Melder_warning (U"Covariance_difference: numbers of observations of the two matrices do not agree.\n"
634 U"The lesser of the two (", numberOfObservations, U") is used.");
635 }
636 Melder_require (numberOfObservations > 1,
637 U"Number of observations too small.");
638 Melder_assert (thy data.ncol == nrow);
639 autoMAT linv = copy_MAT (thy data.get());
640 double ln_thee;
641 MATlowerCholeskyInverse_inplace (linv.get(), & ln_thee);
642 const double ln_me = NUMdeterminant_fromSymmetricMatrix (my data.get());
643 /*
644 We need trace (A B^-1). We have A and the inverse L^(-1) of the
645 Cholesky decomposition L^T L of B in the lower triangle + diagonal.
646 Always: tr (A B) = tr (B A)
647 tr (A B^-1) = tr (A (L L^T)^-1) = tr (A L^-1 (L^T)^-1)
648 trace = sum(i=1..nrow, j=1..nrow, l=max(i,j)..nrow, A [i] [j]Lm [l] [j]Lm [l] [i],
649 where Lm = L^(-1)
650 */
651 double trace = 0.0;
652 for (integer i = 1; i <= nrow; i ++) {
653 for (integer j = 1; j <= nrow; j ++) {
654 const integer lp = std::max (j, i);
655 for (integer l = lp; l <= nrow; l ++)
656 trace += my data [i] [j] * linv [l] [j] * linv [l] [i];
657 }
658 }
659
660 const double l = (numberOfObservations - 1) * fabs (ln_thee - ln_me + trace - nrow);
661 const double chisq = l * fabs (1.0 - (2.0 * nrow + 1.0 - 2.0 / (nrow + 1)) / (numberOfObservations - 1) / 6.0);
662 const double ndof = nrow * (nrow + 1) / 2.0;
663
664 if (out_prob)
665 *out_prob = NUMchiSquareQ (chisq, ndof);
666 if (out_chisq)
667 *out_chisq = chisq;
668 if (out_ndof)
669 *out_ndof = ndof;
670 }
671
672 static void checkOneIndex (TableOfReal me, integer index) {
673 Melder_require (index > 0 && index <= my numberOfColumns,
674 U"Index should be in interval [1, ", my numberOfColumns, U"].");
675 }
676
677 static void checkTwoIndices (TableOfReal me, integer index1, integer index2) {
678 Melder_require (index1 > 0 && index1 <= my numberOfColumns && index2 > 0 && index2 <= my numberOfColumns,
679 U"Index should be in interval [1, ", my numberOfColumns, U"].");
680 Melder_require (index1 != index2,
681 U"Indices should be different.");
682 }
683
684 void Covariance_getSignificanceOfOneMean (Covariance me, integer index, double mu, double *out_prob, double *out_t, double *out_ndof) {
685 const double var = my data [index] [index];
686 double prob = undefined, t = undefined;
687 const double ndof = my numberOfObservations - 1.0;
688
689 checkOneIndex (me, index);
690
691 if (var > 0.0) {
692 t = (my centroid [index] - mu) / sqrt (var / my numberOfObservations);
693 if (out_prob)
694 prob = 2.0 * NUMstudentQ (fabs (t), ndof);
695 }
696 if (out_prob)
697 *out_prob = prob;
698 if (out_t)
699 *out_t = t;
700 if (out_ndof)
701 *out_ndof = ndof;
702 }
703
704 void Covariance_getSignificanceOfMeansDifference (Covariance me, integer index1, integer index2, double mu, int paired, int equalVariances, double *out_prob, double *out_t, double *out_ndof) {
705 integer n = Melder_ifloor (my numberOfObservations);
706
707 double prob = undefined, t = undefined;
708 double ndof = 2.0 * (n - 1);
709
710 checkTwoIndices (me, index1, index2);
711
712 const double var1 = my data [index1] [index1];
713 const double var2 = my data [index2] [index2];
714
715 double var_pooled = var1 + var2;
716 if (var_pooled == 0.0)
717 Melder_warning (U"The pooled variance turned out to be zero. Check your data.");
718 else {
719 if (paired) {
720 var_pooled -= 2.0 * my data [index1] [index2];
721 ndof /= 2.0;
722 }
723 if (var_pooled == 0.0) {
724 Melder_warning (U"The pooled variance with the paired correction turned out to be zero. ");
725 prob = 0.0;
726 } else {
727 t = (my centroid [index1] - my centroid [index2] - mu) / sqrt (var_pooled / n);
728 /*
729 Return two sided probability.
730 */
731 if (equalVariances)
732 prob = 2.0 * NUMstudentQ (fabs (t), ndof);
733 else {
734 ndof = (1.0 + 2.0 * var1 * var2 / (var1 * var1 + var2 * var2)) * (n - 1);
735 prob = NUMincompleteBeta (ndof / 2.0, 0.5, ndof / (ndof + t * t));
736 }
737 }
738 }
739 if (out_prob)
740 *out_prob = prob;
741 if (out_t)
742 *out_t = t;
743 if (out_ndof)
744 *out_ndof = ndof;
745 }
746
747 void Covariance_getSignificanceOfOneVariance (Covariance me, integer index, double sigmasq, double *out_prob, double *out_chisq, double *out_ndof) {
748 const double var = my data [index] [index];
749 double prob = undefined, chisq = undefined;
750 const double ndof = my numberOfObservations - 1.0;
751
752 checkOneIndex (me, index);
753
754 if (var > 0.0) {
755 chisq = ndof;
756 if (sigmasq > 0.0)
757 chisq = ndof * var / sigmasq;
758 if (out_prob)
759 prob = NUMchiSquareQ (chisq, ndof);
760 }
761 if (out_prob)
762 *out_prob = prob;
763 if (out_chisq)
764 *out_chisq = chisq;
765 if (out_ndof)
766 *out_ndof = ndof;
767 }
768
769 void Covariance_getSignificanceOfVariancesRatio (Covariance me, integer index1, integer index2, double ratio, double *out_prob, double *out_f, double *out_ndof) {
770 const double ndof = my numberOfObservations - 1.0;
771 double prob = undefined, f = undefined;
772 checkTwoIndices (me, index1, index2);
773
774 const double var1 = my data [index1] [index1];
775 const double var2 = my data [index2] [index2];
776
777 if (var1 > 0.0 && var2 > 0.0) {
778 double ratio2 = (var1 / var2) / ratio;
779 f = ratio2;
780 if (var2 > var1)
781 ratio2 = (var2 / var1) * ratio;
782 if (out_prob) {
783 prob = 2.0 * NUMfisherQ (ratio2, ndof, ndof);
784 if (prob > 1.0)
785 prob = 2.0 - prob;
786 }
787 }
788 if (out_prob)
789 *out_prob = prob;
790 if (out_ndof)
791 *out_ndof = ndof;
792 if (out_f)
793 *out_f = f;
794 }
795
796 /* End of file Covariance.cpp */