Debian Codegraph @

dwtools/SSCP.cpp

raw
1 /* SSCP.cpp
2 *
3 * Copyright (C) 1993-2020 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 /*
20 djmw 20010614 Covariance_difference: corrected bug in calculation of
21 trace (A B^-1) that caused chisq values to be completely unreliable.
22 djmw 20010628 TableOfReal_to_SSCP: skip error-return when nrows < 2,
23 just issue warning.
24 djmw 20010906 TableOfReal_to_SSCP.
25 djmw 20020212 +getEllipse(s)BoundingBoxCoordinates.
26 djmw 20020313 corrected SSCP_Eigen_project.
27 djmw 20020327 Moved SSCP_Eigen_project to Eigen_SSCP.c.
28 djmw 20020418 Removed some causes for compiler warnings.
29 djmw 20020430 Changed explicit calculation of SSCP to svd in
30 TableOfReal_to_SSCP.
31 djmw 20030703 Replaced NUMincompletebeta with gsl_sf_beta_inc.
32 djmw 20030801 SSCPs_drawConcentrationEllipses extra label argument.
33 djmw 20030825 Replaced gsl_sf_beta_inc with NUMincompletebeta.
34 djmw 20031104 Added SSCP_to_CCA.
35 djmw 20031117 Added SSCP_extractCentroid.
36 djmw 20031127 Added Covariance_TableOfReal_extractDistanceQuantileRange.
37 djmw 20040211 Better warnings in TableOfReal_to_SSCPs_byLabel for single cases.
38 djmw 20040214 Fixed some compiler warnings.
39 djmw 20040219 SSCP_getTraceFraction added.
40 djmw 20040617 SSCP(s)_drawConcentrationEllipse(s) draw with reverse axes possible.
41 (not yet supported by commands in Picture window like 'One mark bottom...' because of reversed axes)!
42 djmw 20060202 Removed a bug in TableOfReal_to_SSCP that could crash Praat (if nrows < ncols).
43 djmw 20060503 Covariance_getSignificanceOfMeansDifference: set probability = 0 if
44 var_pooled = 0 and paired.
45 djmw 20060811 Removed bug in SSCP_TableOfReal_to_MahalanobisDistances that caused column labels always to be copied.
46 djmw 20061214 Corrected possible integer overflow in ellipseScalefactor.
47 djmw 20071012 Added: o_CAN_WRITE_AS_ENCODING.h
48 djmw 20071016 To Melder_error<n>
49 djmw 20071202 Melder_warning<n>
50 djmw 20080122 float -> double
51 djmw 20081119 TableOfReal_to_SSCP check if numbers are defined
52 djmw 20090617 TableOfReal_to_SSCPs_byLabel better warnings for singular cases.
53 djmw 20090629 +Covariances_getMultivariateCentroidDifference, Covariances_equality.
54 djmw 20100106 +Covariance_TableOfReal_mahalanobis.
55 djmw 20101019 Reduced storage Covariance.
56 djmw 20110304 Thing_new
57 */
58
59 #include "Covariance.h"
60 #include "Correlation.h"
61 #include "Eigen.h"
62 #include "NUMlapack.h"
63 #include "NUM2.h"
64 #include "SVD.h"
65
66 #include "oo_DESTROY.h"
67 #include "SSCP_def.h"
68 #include "oo_COPY.h"
69 #include "SSCP_def.h"
70 #include "oo_EQUAL.h"
71 #include "SSCP_def.h"
72 #include "oo_CAN_WRITE_AS_ENCODING.h"
73 #include "SSCP_def.h"
74 #include "oo_WRITE_TEXT.h"
75 #include "SSCP_def.h"
76 #include "oo_READ_TEXT.h"
77 #include "SSCP_def.h"
78 #include "oo_WRITE_BINARY.h"
79 #include "SSCP_def.h"
80 #include "oo_READ_BINARY.h"
81 #include "SSCP_def.h"
82 #include "oo_DESCRIPTION.h"
83 #include "SSCP_def.h"
84
85 #include "enums_getText.h"
86 #include "SSCP_enums.h"
87 #include "enums_getValue.h"
88 #include "SSCP_enums.h"
89
90 #define TOVEC(x) (&(x) - 1)
91
92 Thing_implement (SSCP, TableOfReal, 0);
93 Thing_implement (SSCPList, TableOfRealList, 0);
94
95 void structSSCP :: v1_info () {
96 structTableOfReal :: v1_info ();
97 const double zmin = NUMmin_u (our data.all());
98 const double zmax = NUMmax_u (our data.all());
99 MelderInfo_writeLine (U"Minimum value: ", zmin);
100 MelderInfo_writeLine (U"Maximum value: ", zmax);
101 }
102
103 /*
104 Calculate scale factor by which sqrt(eigenvalue) has to
105 be multiplied to obtain the length of an ellipse axis.
106 */
107 double SSCP_getEllipseScalefactor (SSCP me, double scale, bool confidence) {
108 const integer n = Melder_ifloor (SSCP_getNumberOfObservations (me));
109
110 if (confidence) {
111 if (n - my numberOfColumns < 1)
112 return -1.0;
113 /*
114 D.E. Johnson (1998), Applied Multivariate methods, page 410
115 */
116 const double f = NUMinvFisherQ (1.0 - scale, my numberOfColumns, n - my numberOfColumns);
117 scale = 2.0 * sqrt (f * my numberOfColumns * (n - 1) / ( ((double) n) * (n - my numberOfColumns)));
118 } else {
119 /*
120 Very ugly, temporary hack
121 */
122 scale *= 2.0 / (scale < 0.0 ? -1.0 : sqrt (n - 1));
123 }
124 return scale;
125 }
126
127 static void getEllipseBoundingBoxCoordinates (SSCP me, double scale, bool confidence, double *out_xmin, double *out_xmax, double *out_ymin, double *out_ymax) {
128 double a, b, cs, width, height;
129 NUMeigencmp22 (my data [1] [1], my data [1] [2], my data [2] [2], & a, & b, & cs, nullptr);
130 NUMgetEllipseBoundingBox (sqrt (a), sqrt (b), cs, & width, & height);
131
132 const double lscale = SSCP_getEllipseScalefactor (me, scale, confidence);
133 const double xmin = my centroid [1] - lscale * width / 2.0;
134 const double xmax = xmin + lscale * width;
135 const double ymin = my centroid [2] - lscale * height / 2.0;
136 const double ymax = ymin + lscale * height;
137 if (out_xmin)
138 *out_xmin = xmin;
139 if (out_xmax)
140 *out_xmax = xmax;
141 if (out_ymin)
142 *out_ymin = ymin;
143 if (out_ymax)
144 *out_ymax = ymax;
145 }
146
147 void SSCPList_getEllipsesBoundingBoxCoordinates (SSCPList me, double scale, bool confidence, double *out_xmin, double *out_xmax, double *out_ymin, double *out_ymax) {
148 MelderExtremaWithInit extremaX, extremaY;
149 for (integer i = 1; i <= my size; i ++) {
150 const SSCP s = my at [i];
151 double xmn, xmx, ymn, ymx;
152 getEllipseBoundingBoxCoordinates (s, scale, confidence, & xmn, & xmx, & ymn, & ymx);
153 if (xmn < extremaX.min)
154 extremaX.min = xmn;
155 if (xmx > extremaX.max)
156 extremaX.max = xmx;
157 if (ymn < extremaY.min)
158 extremaY.min = ymn;
159 if (ymx > extremaY.max)
160 extremaY.max = ymx;
161 }
162 if (out_xmin)
163 *out_xmin = extremaX.min;
164 if (out_xmax)
165 *out_xmax = extremaX.max;
166 if (out_ymin)
167 *out_ymin = extremaY.min;
168 if (out_ymax)
169 *out_ymax = extremaY.max;
170 }
171
172 static autoSSCP _SSCP_extractTwoDimensions (SSCP me, integer d1, integer d2) {
173 autoSSCP thee = SSCP_create (2);
174 if (my numberOfRows == 1) { // diagonal
175 thy data [1] [1] = my data [1] [d1];
176 thy data [2] [2] = my data [1] [d2];
177 } else {
178 thy data [1] [1] = my data [d1] [d1];
179 thy data [2] [2] = my data [d2] [d2];
180 thy data [2] [1] = thy data [1] [2] = my data [d1] [d2];
181 }
182 thy centroid [1] = my centroid [d1];
183 thy centroid [2] = my centroid [d2];
184 thy numberOfObservations = my numberOfObservations;
185
186 TableOfReal_setColumnLabel (thee.get(), 1, my columnLabels [d1].get());
187 TableOfReal_setColumnLabel (thee.get(), 2, my columnLabels [d2].get());
188 TableOfReal_setRowLabel (thee.get(), 1, my columnLabels [d1].get());
189 TableOfReal_setRowLabel (thee.get(), 2, my columnLabels [d2].get());
190 return thee;
191 }
192
193 autoSSCPList SSCPList_extractTwoDimensions (SSCPList me, integer d1, integer d2) {
194 try {
195 autoSSCPList thee = SSCPList_create ();
196 for (integer i = 1; i <= my size; i ++) {
197 autoSSCP t = _SSCP_extractTwoDimensions (my at [i], d1, d2);
198 Thing_setName (t.get(), Thing_getName (my at [i]));
199 thy addItem_move (t.move());
200 }
201 return thee;
202 } catch (MelderError) {
203 Melder_throw (me, U": cannot extract two dimensions.");
204 }
205 }
206
207 void SSCP_drawTwoDimensionalEllipse_inside (SSCP me, Graphics g, double scale, conststring32 label, double fontSize) {
208 try {
209 constexpr integer nsteps = 100;
210 autoVEC x = raw_VEC (nsteps + 1);
211 autoVEC y = raw_VEC (nsteps + 1);
212 /*
213 From the eigenvalues and eigenvectors of the symmetrical sscp matrix we
214 can calculate the length and directions of the principal axes of the ellipse.
215 */
216 double eval1, eval2, cosine, sine;
217 NUMeigencmp22 (my data [1] [1], my data [1] [2], my data [2] [2], & eval1, & eval2, & cosine, & sine);
218 /*
219 1. Parametrize as standard ellipse with horizontal radius a and vertical radius b and origin at (0,0) as
220 x = a cos(phi)
221 y = b sin(phi)
222 */
223 const double a = scale * sqrt (eval1) / 2.0;
224 const double b = scale * sqrt (eval2) / 2.0;
225 const double angle_inc = NUM2pi / nsteps;
226 for (integer i = 1; i <= nsteps + 1; i ++) {
227 const double phi = (i - 1) * angle_inc;
228 x [i] = a * cos (phi);
229 y [i] = b * sin (phi);
230 }
231 /*
232 2. Rotate x axis to the eigenvector 1 (cosine, sine)
233 |x'| | cosine -sine | |x|
234 | | = | | * | |
235 |y'| | sine cosine | |y|
236 */
237 for (integer i = 1; i <= nsteps + 1; i ++) {
238 double xp = cosine * x [i] - sine * y [i];
239 y [i] = sine * x [i] + cosine * y [i];
240 x [i] = xp;
241 }
242 /*
243 3. Translate to the centroid
244 */
245 x.get() += my centroid [1];
246 y.get() += my centroid [2];
247 Graphics_polyline (g, nsteps + 1, & x [1], & y [1]);
248
249 if (label && fontSize > 0.0) {
250 const double oldFontSize = Graphics_inqFontSize (g);
251 Graphics_setFontSize (g, fontSize);
252 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
253 Graphics_text (g, my centroid [1], my centroid [2], label);
254 Graphics_setFontSize (g, oldFontSize);
255 }
256 } catch (MelderError) {
257 Melder_clearError ();
258 }
259 }
260
261 autoSSCP SSCP_toTwoDimensions (SSCP me, constVECVU const& v1, constVECVU const& v2) {
262 try {
263 Melder_assert (v1.size == v2.size && v1.size == my numberOfColumns);
264 autoSSCP thee = SSCP_create (2);
265 /*
266 Projection P of S on v1 and v2 (given matrix V' with 2 rows) is P = V'SV
267 P [i] [j] = sum(k) sum(m) V' [i] [k]*S [k] [m]*V [m] [j] = V' [i] [k]*S [k] [m]*V' [j] [m]
268
269 For the new centroids cnew [i] = sum(m) V' [i] [m]*c [m]
270 */
271 if (my numberOfRows == 1) { // 1xn diagonal matrix
272 for (integer k = 1; k <= my numberOfColumns; k ++) {
273 thy data [1] [1] += v1 [k] * my data [1] [k] * v1 [k];
274 thy data [1] [2] += v1 [k] * my data [1] [k] * v2 [k];
275 thy data [2] [2] += v2 [k] * my data [1] [k] * v2 [k];
276 }
277 thy data [2] [1] = thy data [1] [2];
278 } else {
279 thy data [1] [1] = NUMmul (v1, my data.get(), v1);
280 thy data [2] [2] = NUMmul (v2, my data.get(), v2);
281 thy data [1] [2] = thy data [2] [1] = NUMmul (v1, my data.get(), v2);
282 }
283
284 thy centroid [1] = NUMinner (v1, my centroid.get());
285 thy centroid [2] = NUMinner (v2, my centroid.get());
286
287 thy numberOfObservations = SSCP_getNumberOfObservations (me);
288
289 return thee;
290 } catch (MelderError) {
291 Melder_throw (me, U": cannot extract two dimensions.");
292 }
293 }
294
295 void SSCP_init (SSCP me, integer dimension, kSSCPstorage storage) {
296 const integer numberOfRows = storage == kSSCPstorage::DIAGONAL ? 1 : dimension;
297 TableOfReal_init (me, numberOfRows, dimension);
298 my centroid = zero_VEC (dimension);
299 }
300
301 autoSSCP SSCP_create (integer dimension) {
302 try {
303 autoSSCP me = Thing_new (SSCP);
304 SSCP_init (me.get(), dimension, kSSCPstorage::COMPLETE);
305 return me;
306 } catch (MelderError) {
307 Melder_throw (U"SSCP not created.");
308 }
309 }
310
311 void SSCP_reset (SSCP me) {
312 my data.all() <<= 0.0;
313 my centroid.all() <<= 0.0;
314 my numberOfObservations = 0;
315 }
316
317 double SSCP_getConcentrationEllipseArea (SSCP me, double scale, bool confidence, integer d1, integer d2) {
318
319 Melder_require (d1 > 0 && d1 <= my numberOfRows && d2 > 0 && d2 <= my numberOfRows && d1 != d2,
320 U"Incorrect axes.");
321 autoSSCP thee = _SSCP_extractTwoDimensions (me, d1, d2);
322 scale = SSCP_getEllipseScalefactor (thee.get(), scale, confidence);
323 Melder_require (scale > 0,
324 U"The scale factor should be larger than zero.");
325 double a, b;
326 NUMeigencmp22 (thy data [1] [1], thy data [1] [2], thy data [2] [2], & a, & b, nullptr, nullptr);
327 /*
328 Take sqrt to get units of 'std_dev'
329 */
330 a = scale * sqrt (a) / 2.0;
331 b = scale * sqrt (b) / 2.0;
332 return NUMpi * a * b;
333 }
334
335 double SSCP_getFractionVariation (SSCP me, integer from, integer to) {
336 const integer n = my numberOfRows;
337
338 if (from < 1 || from > to || to > n)
339 return undefined;
340
341 double sum = 0.0, trace = 0.0;
342 for (integer i = 1; i <= n; i ++) {
343 trace += my numberOfRows == 1 ? my data [1] [i] : my data [i] [i];
344 if (i >= from && i <= to)
345 sum += my numberOfRows == 1 ? my data [1] [i] : my data [i] [i];
346 }
347 return trace > 0.0 ? sum / trace : undefined;
348 }
349
350 void SSCP_drawConcentrationEllipse (SSCP me, Graphics g, double scale, int confidence,
351 integer d1, integer d2, double xmin, double xmax, double ymin, double ymax, bool garnish)
352 {
353 Melder_require (d1 > 0 && d1 <= my numberOfRows && d2 > 0 && d2 <= my numberOfRows && d1 != d2,
354 U"Incorrect axes.");
355
356 autoSSCP thee = _SSCP_extractTwoDimensions (me, d1, d2);
357
358 double xmn, xmx, ymn, ymx;
359 getEllipseBoundingBoxCoordinates (thee.get(), scale, confidence, & xmn, & xmx, & ymn, & ymx);
360 if (xmax == xmin) {
361 xmin = xmn;
362 xmax = xmx;
363 }
364 if (ymax == ymin) {
365 ymin = ymn;
366 ymax = ymx;
367 }
368 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
369 Graphics_setInner (g);
370
371 scale = SSCP_getEllipseScalefactor (thee.get(), scale, confidence);
372 Melder_require (scale > 0,
373 U"The scale factor should be larger than zero.");
374
375 SSCP_drawTwoDimensionalEllipse_inside (thee.get(), g, scale, nullptr, 0);
376
377 Graphics_unsetInner (g);
378 if (garnish) {
379 Graphics_drawInnerBox (g);
380 Graphics_marksLeft (g, 2, true, true, false);
381 Graphics_marksBottom (g, 2, true, true, false);
382 }
383 }
384
385 void SSCP_setNumberOfObservations (SSCP me, double numberOfObservations) {
386 my numberOfObservations = numberOfObservations;
387 }
388
389 double SSCP_getNumberOfObservations (SSCP me) {
390 return my numberOfObservations;
391 }
392
393 double SSCP_getDegreesOfFreedom (SSCP me) {
394 return my numberOfObservations - 1;
395 }
396
397 double SSCP_getTotalVariance (SSCP me) {
398 return my numberOfRows == 1 ? NUMsum (my data.row (1)) : NUMtrace (my data.get());
399 }
400
401 double SSCP_getCumulativeContributionOfComponents (SSCP me, integer from, integer to) {
402 double ccoc = undefined;
403 if (to == 0)
404 to = my numberOfRows;
405 if (from > 0 && to <= my numberOfRows && from <= to) {
406 const double sum = SSCP_getTotalVariance (me);
407 if (sum > 0.0) {
408 double partial = 0.0;
409 for (integer i = from; i <= to; i ++)
410 partial += my numberOfRows == 1 ? my data [1] [i] : my data [i] [i];
411 ccoc = partial / sum;
412 }
413 }
414 return ccoc;
415 }
416
417 autoSSCP TableOfReal_to_SSCP (TableOfReal me, integer rowb, integer rowe, integer colb, integer cole) {
418 try {
419 Melder_require (NUMdefined (my data.get()),
420 U"All the table's elements should be defined.");
421 fixAndCheckRowRange (& rowb, & rowe, my data.get(), 1);
422 fixAndCheckColumnRange (& colb, & cole, my data.get(), 1);
423 autoMAT part = part_MAT (my data.get(), rowb, rowe, colb, cole);
424 if (part.nrow < part.ncol)
425 Melder_warning (U"The selected number of rows (", part.nrow,
426 U") is less than the selected number of columns (", part.ncol,
427 U").\nThe SSCP will not have full dimensionality. This may be a problem in later analysis steps."
428 );
429 autoSSCP thee = SSCP_create (part.ncol);
430 columnMeans_VEC_out (thy centroid.get(), part.get());
431 part.all() -= thy centroid.all();
432 SSCP_setNumberOfObservations (thee.get(), part.nrow);
433 mtm_MAT_out (thy data.get(), part.get()); // sum of squares and cross products = T'T
434 for (integer j = 1; j <= part.ncol; j ++) {
435 const conststring32 label = my columnLabels [colb - 1 + j].get();
436 TableOfReal_setColumnLabel (thee.get(), j, label);
437 TableOfReal_setRowLabel (thee.get(), j, label);
438 }
439 return thee;
440 } catch (MelderError) {
441 Melder_throw (me, U": SSCP not created.");
442 }
443 }
444
445 autoSSCP TableOfReal_to_SSCP_rowWeights (TableOfReal me, integer rowb, integer rowe, integer colb, integer cole, integer weightColumnNumber) {
446 try {
447 Melder_require (NUMdefined (my data.get()),
448 U"All the table's elements should be defined.");
449 fixAndCheckRowRange (& rowb, & rowe, my data.get(), 1);
450 fixAndCheckColumnRange (& colb, & cole, my data.get(), 1);
451 if (weightColumnNumber != 0)
452 Melder_require (weightColumnNumber < colb || weightColumnNumber > cole,
453 U"The weight columns must be outside the selected block.");
454 autoMAT part = part_MAT (my data.get(), rowb, rowe, colb, cole);
455 if (part.nrow < part.ncol)
456 Melder_warning (U"The selected number of data points (", part.nrow,
457 U") is less than the selected number of variables (", part.ncol,
458 U").\nThe SSCP will not have full dimensionality. This may be a problem in later analysis steps."
459 );
460 autoSSCP thee = SSCP_create (part.ncol);
461 columnMeans_VEC_out (thy centroid.get(), part.get());
462 part.all() -= thy centroid.all();
463 SSCP_setNumberOfObservations (thee.get(), part.nrow);
464 if (weightColumnNumber != 0) {
465 autoVEC rowWeights = column_VEC (my data.horizontalBand (rowb, rowe), weightColumnNumber);
466 MATmtm_weighRows (thy data.get(), part.get(), rowWeights.get());
467 } else
468 mtm_MAT_out (thy data.get(), part.get()); // sum of squares and cross products = T'T
469 for (integer j = 1; j <= part.ncol; j ++) {
470 const conststring32 label = my columnLabels [colb - 1 + j].get();
471 TableOfReal_setColumnLabel (thee.get(), j, label);
472 TableOfReal_setRowLabel (thee.get(), j, label);
473 }
474 return thee;
475 } catch (MelderError) {
476 Melder_throw (me, U": SSCP not created.");
477 }
478 }
479
480 autoTableOfReal SSCP_TableOfReal_extractDistanceQuantileRange (SSCP me, TableOfReal thee, double qlow, double qhigh) {
481 try {
482 autoCovariance cov = SSCP_to_Covariance (me, 1);
483 autoTableOfReal him = Covariance_TableOfReal_extractDistanceQuantileRange (cov.get(), thee, qlow, qhigh);
484 return him;
485 } catch (MelderError) {
486 Melder_throw (me, U": no distance quantile ranges created.");
487 }
488 }
489
490 autoSSCPList TableOfReal_to_SSCPList_byLabel (TableOfReal me) {
491 try {
492 autoSSCPList thee = SSCPList_create ();
493 autoTableOfReal mew = TableOfReal_sortOnlyByRowLabels (me);
494
495 Melder_warningOff ();
496 integer lastrow = 0, numberOfMatrices = 0, numberOfSingularMatrices = 0, index = 1;
497 conststring32 label = mew -> rowLabels [1].get();
498 for (integer i = 2; i <= my numberOfRows; i ++) {
499 integer numberOfRowsInCurrent = 0;
500 conststring32 currentLabel = mew -> rowLabels [i].get();
501 if (Melder_cmp (currentLabel, label) != 0) {
502 /*
503 Current label different from previous one(s)
504 */
505 numberOfRowsInCurrent = i - index;
506 lastrow = i - 1;
507 } else if (i == my numberOfRows) {
508 /*
509 Current (last) label is same as previous
510 */
511 numberOfRowsInCurrent = i - index + 1;
512 lastrow = i;
513 } else {
514 /*
515 Next one
516 */
517 continue;
518 }
519 /*
520 We found a new group
521 */
522 numberOfMatrices ++;
523 if (numberOfRowsInCurrent > 1) { // We need at least two rows for an SSCP
524 if (numberOfRowsInCurrent < my numberOfColumns)
525 numberOfSingularMatrices ++;
526 autoSSCP t = TableOfReal_to_SSCP (mew.get(), index, lastrow, 0, 0);
527 if (! (label = mew -> rowLabels [index].get()))
528 label = U"?";
529 Thing_setName (t.get(), label);
530 thy addItem_move (t.move());
531 }
532 label = currentLabel;
533 index = i;
534 }
535 if (lastrow != my numberOfRows)
536 numberOfMatrices ++;
537 Melder_warningOn ();
538 if (numberOfSingularMatrices > 0 || thy size != numberOfMatrices) {
539 const integer notIncluded = numberOfMatrices - thy size;
540 Melder_warning (numberOfMatrices, U" different groups detected: ", numberOfSingularMatrices + notIncluded,
541 U" group(s) with less rows than columns (of which ", notIncluded, U" with only one row).");
542 }
543 return thee;
544 } catch (MelderError) {
545 Melder_throw (me, U": SSCP not created from labels.");
546 }
547 }
548
549 autoPCA SSCP_to_PCA (SSCP me) {
550 try {
551 Melder_assert (my data.ncol == my numberOfColumns);
552 autoMAT mat;
553 if (my numberOfRows == 1) {
554 mat = zero_MAT (my numberOfColumns, my numberOfColumns);
555 mat.diagonal() <<= my data.row (1); // 1xn matrix -> nxn
556 } else if (my data.nrow == my numberOfColumns && my data.ncol == my numberOfColumns)
557 mat = copy_MAT (my data.get());
558 else
559 Melder_throw (me, U": the SSCP has the wrong dimensions.");
560 autoPCA thee = PCA_create (my numberOfColumns, my numberOfColumns);
561 Eigen_initFromSquareMAT (thee.get(), mat.get(), kMAT_TYPE::SYMMETRIC, my numberOfColumns, false);
562 thy centroid.all() <<= my centroid.all();
563 PCA_setNumberOfObservations (thee.get(), Melder_ifloor (my numberOfObservations));
564 thy labels.all() <<= my columnLabels.all();
565 return thee;
566 } catch (MelderError) {
567 Melder_throw (me, U": PCA not created.");
568 }
569 }
570
571 void SSCP_setValue (SSCP me, integer rowNumber, integer columnNumber, double value) {
572 checkColumnNumber (columnNumber, my numberOfColumns);
573 checkRowNumber (rowNumber, my numberOfRows);
574 Melder_require (! (rowNumber == columnNumber && value <= 0.0),
575 U"Diagonal element should always be a positive number.");
576
577 if (my numberOfRows == 1) { // diagonal
578 Melder_require (rowNumber == columnNumber,
579 U"Row and column number should be equal for a diagonal matrix.");
580 my data [1] [rowNumber] = value;
581 } else {
582 Melder_require (! (rowNumber != columnNumber && (fabs (value) > my data [rowNumber] [rowNumber] || fabs (value) > my data [columnNumber] [columnNumber])),
583 U"The off-diagonal values should not be larger than the diagonal values. Input diagonal elements first, or change this value.");
584 my data [rowNumber] [columnNumber] = my data [columnNumber] [rowNumber] = value;
585 }
586 }
587
588 void SSCP_setCentroid (SSCP me, integer component, double value) {
589 Melder_require (component > 0 && component <= my numberOfColumns, U"Component number should not exceed ", my numberOfColumns, U".");
590 my centroid [component] = value;
591 }
592
593 /************ SSCPList ***********************************************/
594
595 autoSSCP SSCPList_to_SSCP_pool (SSCPList me) {
596 try {
597 autoSSCP pool = Data_copy (my at [1]);
598
599 for (integer k = 2; k <= my size; k ++) {
600 const SSCP t = my at [k];
601 Melder_require (t -> numberOfRows == pool -> numberOfRows,
602 U"The dimension of item ", k, U" should agree.");
603 pool -> numberOfObservations += t -> numberOfObservations;
604 /*
605 Sum the sscp's and weigh the centroid.
606 */
607 pool -> data.all() += t -> data.all();
608 pool -> centroid.all() += t->centroid.all() * t -> numberOfObservations;
609 }
610
611 pool -> centroid.all() *= 1.0 / pool -> numberOfObservations;
612
613 return pool;
614 } catch (MelderError) {
615 Melder_throw (me, U": not pooled.");
616 }
617 }
618
619 void SSCPList_getHomegeneityOfCovariances_box (SSCPList me, double *out_prob, double *out_chisq, double *out_df) {
620 autoSSCP pooled = SSCPList_to_SSCP_pool (me);
621 const integer p = pooled -> numberOfColumns;
622 double ln_determinant, inv = 0.0, sum = 0.0, chisq = 0.0;
623 for (integer i = 1; i <= my size; i ++) {
624 const SSCP t = my at [i];
625 const double ni = t -> numberOfObservations - 1.0;
626 ln_determinant = NUMdeterminant_fromSymmetricMatrix (t -> data.get());
627 /*
628 Box-test is for covariance matrices -> scale determinant.
629 */
630 ln_determinant -= p * log (ni);
631 sum += ni;
632 inv += 1.0 / ni;
633 chisq -= ni * ln_determinant;
634 }
635
636 ln_determinant = NUMdeterminant_fromSymmetricMatrix (pooled -> data.get());
637 ln_determinant -= p * log (pooled -> numberOfObservations - my size);
638 chisq += sum * ln_determinant;
639
640 chisq *= 1.0 - (inv - 1.0 / sum) * (2.0 * p * p + 3.0 * p - 1.0) / (6.0 * (p + 1) * (my size - 1.0));
641 const double df = (my size - 1.0) * p * (p + 1) / 2.0;
642
643 if (out_prob)
644 *out_prob = NUMchiSquareQ (chisq, df);
645 if (out_chisq)
646 *out_chisq = chisq;
647 if (out_df)
648 *out_df = df;
649 }
650
651 autoSSCPList SSCPList_toTwoDimensions (SSCPList me, constVECVU const& v1, constVECVU const& v2) {
652 try {
653 autoSSCPList thee = SSCPList_create ();
654 for (integer i = 1; i <= my size; i ++) {
655 autoSSCP t = SSCP_toTwoDimensions (my at [i], v1, v2);
656 Thing_setName (t.get(), Thing_getName (my at [i]));
657 thy addItem_move (t.move());
658 }
659 return thee;
660 } catch (MelderError) {
661 Melder_throw (me, U": not reduced to two dimensions.");
662 }
663 }
664
665 void SSCPList_drawConcentrationEllipses (SSCPList me, Graphics g, double scale, bool confidence, conststring32 label,
666 integer dimension1, integer dimension2, double xmin, double xmax, double ymin, double ymax, double fontSize, bool garnish)
667 {
668 try {
669 const SSCP t = my at [1];
670
671 Melder_require (dimension1 > 0,
672 U"Dimension 1 should be positive, not ", dimension1, U".");
673 Melder_require (dimension1 <= t -> numberOfColumns,
674 U"Dimension 1 should not exceed the number of dimensions (", t -> numberOfColumns, U"), but is in fact ", dimension1, U".");
675 Melder_require (dimension2 > 0,
676 U"Dimension 2 should be positive, not ", dimension2, U".");
677 Melder_require (dimension2 <= t -> numberOfColumns,
678 U"Dimension 2 should not exceed the number of dimensions (", t -> numberOfColumns, U"), but is in fact ", dimension2, U".");
679 Melder_require (dimension1 != dimension2,
680 U"Dimension 1 and dimension 2 should be different, but are in fact ", dimension1, U" and ", dimension2, U".");
681 autoSSCPList thee = SSCPList_extractTwoDimensions (me, dimension1, dimension2);
682 /*
683 Autowindowing.
684 */
685 if (xmin == xmax || ymin == ymax) {
686 double boundingBox_xmin, boundingBox_xmax, boundingBox_ymin, boundingBox_ymax;
687 SSCPList_getEllipsesBoundingBoxCoordinates (thee.get(), scale, confidence,
688 & boundingBox_xmin, & boundingBox_xmax, & boundingBox_ymin, & boundingBox_ymax);
689 if (xmin == xmax) {
690 xmin = boundingBox_xmin;
691 xmax = boundingBox_xmax;
692 }
693 if (ymin == ymax) {
694 ymin = boundingBox_ymin;
695 ymax = boundingBox_ymax;
696 }
697 }
698
699 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
700 Graphics_setInner (g);
701
702 for (integer i = 1; i <= thy size; i ++) {
703 const SSCP ti = thy at [i];
704 const double lscale = SSCP_getEllipseScalefactor (ti, scale, confidence);
705 if (lscale < 0.0)
706 continue;
707 if (! label || Melder_cmp (label, Thing_getName (ti)) == 0)
708 SSCP_drawTwoDimensionalEllipse_inside (ti, g, lscale, Thing_getName (ti), fontSize);
709 }
710
711 Graphics_unsetInner (g);
712 if (garnish) {
713 const SSCP t1 = my at [1];
714 Graphics_drawInnerBox (g);
715 Graphics_marksLeft (g, 2, true, true, false);
716 Graphics_textLeft (g, true,
717 t1 -> columnLabels [dimension2] ? t1 -> columnLabels [dimension2].get() : Melder_cat (U"Dimension ", dimension2));
718 Graphics_marksBottom (g, 2, true, true, false);
719 Graphics_textBottom (g, true,
720 t1 -> columnLabels [dimension1] ? t1 -> columnLabels [dimension1].get() : Melder_cat (U"Dimension ", dimension1));
721 }
722 } catch (MelderError) {
723 Melder_throw (U"Concentration ellipses not drawn.");
724 }
725 }
726
727 autoTableOfReal SSCP_to_TableOfReal (SSCP me) {
728 try {
729 autoTableOfReal thee = Thing_new (TableOfReal);
730 my structTableOfReal :: v1_copy (thee.get());
731 return thee;
732 } catch (MelderError) {
733 Melder_throw (me, U": not copied.");
734 }
735 }
736
737 autoTableOfReal SSCP_extractCentroid (SSCP me) {
738 try {
739 autoTableOfReal thee = TableOfReal_create (1, my numberOfColumns);
740 thy data.row (1) <<= my centroid.all();
741 thy columnLabels.all() <<= my columnLabels.all();
742 return thee;
743 } catch (MelderError) {
744 Melder_throw (me, U": centroid not extracted.");
745 }
746 }
747
748 autoSSCP Covariance_to_SSCP (Covariance me) {
749 try {
750 autoSSCP thee = Thing_new (SSCP);
751 my structSSCP :: v1_copy (thee.get());
752 for (integer irow = 1; irow <= my numberOfRows; irow ++)
753 for (integer icol = irow; icol <= my numberOfColumns; icol ++)
754 thy data [icol] [irow] = thy data [irow] [icol] *= my numberOfObservations - 1;
755 return thee;
756 } catch (MelderError) {
757 Melder_throw (me, U": SSCP not created.");
758 }
759 }
760
761 double SSCP_getLnDeterminant (SSCP me) {
762 try {
763 return NUMdeterminant_fromSymmetricMatrix (my data.get());
764 } catch (MelderError) {
765 return undefined;
766 }
767 }
768
769 void SSCP_getDiagonality_bartlett (SSCP me, integer numberOfContraints, double *out_chisq, double *out_prob, double *out_df) {
770 autoCorrelation c = SSCP_to_Correlation (me);
771 Correlation_testDiagonality_bartlett (c.get(), numberOfContraints, out_chisq, out_prob, out_df);
772 }
773
774 void SSCP_expand (SSCP me) {
775 /* A reduced matrix has my numberOfRows < my numberOfColumns.
776 After expansion:
777 my numberOfRows == my numberOfColumns
778 my storageNumberOfRows == my numberOfRows (before)
779 my data (after) == my expansion;
780 my expansion == my data (before)
781 No expansion for a standard matrix or if already expanded and data has not changed!
782 */
783 if ((my expansionNumberOfRows == 0 && my numberOfRows == my numberOfColumns) ||
784 (my expansionNumberOfRows > 0 && ! my dataChanged))
785 return;
786
787 if (NUMisEmpty (my expansion.get()))
788 my expansion = zero_MAT (my numberOfColumns, my numberOfColumns);
789 for (integer ir = 1; ir <= my numberOfColumns; ir ++)
790 for (integer ic = ir; ic <= my numberOfColumns; ic ++) {
791 const integer dij = integer_abs (ir - ic);
792 my expansion [ir] [ic] = my expansion [ic] [ir] = ( dij < my numberOfRows ? my data [dij + 1] [ic] : 0.0 );
793 }
794
795 // Now make 'my data' point to 'my expansion' and vice versa
796 std::swap (my data, my expansion);
797 my expansionNumberOfRows = my numberOfRows;
798 my numberOfRows = my numberOfColumns;
799 my dataChanged = false;
800 }
801
802 void SSCP_unExpand (SSCP me) {
803 if (my expansionNumberOfRows == 0)
804 return;
805 my data = my expansion.move();
806 my numberOfRows = my expansionNumberOfRows;
807 my expansionNumberOfRows = 0;
808 my dataChanged = false;
809 }
810
811 void SSCP_expandWithLowerCholeskyInverse (SSCP me) {
812 if (NUMisEmpty (my lowerCholeskyInverse.get()))
813 my lowerCholeskyInverse = raw_MAT (my numberOfColumns, my numberOfColumns);
814 if (my numberOfRows == 1) { // diagonal
815 my lnd = 0.0;
816 for (integer j = 1; j <= my numberOfColumns; j ++) {
817 my lowerCholeskyInverse [1] [j] = 1.0 / sqrt (my data [1] [j]); // inverse is 1/stddev
818 my lnd += log (my data [1] [j]); // diagonal elmnt is variance
819 }
820 } else {
821 my lowerCholeskyInverse.all() <<= my data.all();
822 try {
823 MATlowerCholeskyInverse_inplace (my lowerCholeskyInverse.get(), & my lnd);
824 } catch (MelderError) {
825 // singular matrix: arrange a diagonal only inverse.
826 my lnd = 0.0;
827 for (integer i = 1; i <= my numberOfRows; i ++) {
828 for (integer j = i; j <= my numberOfColumns; j ++)
829 my lowerCholeskyInverse [i] [j] = my lowerCholeskyInverse [j] [i] = (i == j ? 1.0 / sqrt (my data [i] [i]) : 0.0);
830 my lnd += log (my data [i] [i]);
831 }
832 my lnd *= 2.0;
833 }
834 }
835 }
836
837 void SSCP_unExpandLowerCholesky (SSCP me) {
838 my lowerCholeskyInverse. reset();
839 my lnd = 0.0;
840 }
841
842 void SSCP_expandWithPCA (SSCP me) {
843 my pca = SSCP_to_PCA (me);
844 }
845
846 void SSCP_unExpandPCA (SSCP me) {
847 my pca. reset();
848 }
849
850 /* End of file SSCP.c */