Debian Codegraph @

dwtools/Configuration.cpp

raw
1 /* Configuration.cpp
2 *
3 * Copyright (C) 1993-2021 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 20010920 +Configuration_getDilationFactor
21 djmw 20020315 GPL header
22 djmw 20030513 applied change in numeric label generation
23 djmw 20030801 Configuration_drawConcentrationEllipses extra argument
24 djmw 20040303 Moved containsPrintableCharacter to NUM2.c
25 djmw 20041026 Removed non-used code.
26 djmw 20050314 Configuration_draw crashed when rowlabel==nullptr
27 djmw 20061212 Changed info to Melder_writeLine<x> format.
28 djmw 20071009 wchar
29 djmw 20071012 Added: o_CAN_WRITE_AS_ENCODING.h
30 djmw 20100302 Extra test in Configuration_rotate
31 djmw 20110304 Thing_new
32 */
33
34 #include "SVD.h"
35 #include "PCA.h"
36 #include "Configuration.h"
37 #include "Configuration_AffineTransform.h"
38 #include "TableOfReal_extensions.h"
39 #include "SSCP.h"
40
41 #include "oo_DESTROY.h"
42 #include "Configuration_def.h"
43 #include "oo_COPY.h"
44 #include "Configuration_def.h"
45 #include "oo_EQUAL.h"
46 #include "Configuration_def.h"
47 #include "oo_CAN_WRITE_AS_ENCODING.h"
48 #include "Configuration_def.h"
49 #include "oo_WRITE_TEXT.h"
50 #include "Configuration_def.h"
51 #include "oo_WRITE_BINARY.h"
52 #include "Configuration_def.h"
53 #include "oo_READ_TEXT.h"
54 #include "Configuration_def.h"
55 #include "oo_READ_BINARY.h"
56 #include "Configuration_def.h"
57 #include "oo_DESCRIPTION.h"
58 #include "Configuration_def.h"
59
60 Thing_implement (Configuration, TableOfReal, 0);
61
62 void structConfiguration :: v1_info () {
63 structDaata :: v1_info ();
64 MelderInfo_writeLine (U"Number of points: ", numberOfRows);
65 MelderInfo_writeLine (U"Number of dimensions: ", numberOfColumns);
66 MelderInfo_writeLine (U"Metric: ", metric);
67 }
68
69 autoConfiguration Configuration_create (integer numberOfPoints, integer numberOfDimensions) {
70 try {
71 autoConfiguration me = Thing_new (Configuration);
72 TableOfReal_init (me.get(), numberOfPoints, numberOfDimensions);
73 my w = raw_VEC (numberOfDimensions);
74 TableOfReal_setSequentialRowLabels (me.get(), 0, 0, nullptr, 1, 1);
75 TableOfReal_setSequentialColumnLabels (me.get(), 0, 0, U"dimension ", 1, 1);
76
77 my metric = 2;
78 Configuration_setDefaultWeights (me.get());
79 Configuration_randomize (me.get());
80 return me;
81 } catch (MelderError) {
82 Melder_throw (U"Configuration not created.");
83 }
84 }
85
86 void Configuration_setMetric (Configuration me, integer metric) {
87 my metric = metric;
88 }
89
90 void Configuration_setDefaultWeights (Configuration me) {
91 my w.all() <<= 1.0;
92 }
93
94 void Configuration_setSqWeights (Configuration me, const double weight []) {
95 for (integer icol = 1; icol <= my numberOfColumns; icol ++) {
96 my w [icol] = sqrt (weight [icol]);
97 }
98 }
99
100 void Configuration_normalize (Configuration me, double sumsq, bool columns) {
101 TableOfReal_centreColumns (me);
102 if (columns) {
103 sumsq = ( sumsq <= 0.0 ? 1.0 : sqrt (sumsq) );
104 MATnormalizeColumns_inplace (my data.get(), 2.0, sumsq);
105 } else {
106 if (sumsq <= 0.0)
107 sumsq = my numberOfRows;
108 MATnormalize_inplace (my data.get(), 2.0, sumsq);
109 }
110 }
111
112 void Configuration_randomize (Configuration me) {
113 for (integer irow = 1; irow <= my numberOfRows; irow ++)
114 for (integer icol = 1; icol <= my numberOfColumns; icol ++)
115 my data [irow] [icol] = NUMrandomUniform (-1.0, 1.0);
116 }
117
118 void Configuration_rotate (Configuration me, integer dimension1, integer dimension2, double angle_degrees) {
119 if (dimension1 == dimension2 || angle_degrees == 0)
120 return;
121 if (dimension1 > dimension2)
122 std::swap (dimension1, dimension2);
123 if (dimension1 < 1 || dimension2 > my numberOfColumns)
124 return;
125 const double phi = NUMpi * (2.0 - angle_degrees / 180.0);
126 const double cosa = cos (phi), sina = sin (phi);
127 for (integer irow = 1; irow <= my numberOfRows; irow ++) {
128 const double x1 = my data [irow] [dimension1];
129 const double x2 = my data [irow] [dimension2];
130 my data [irow] [dimension1] = cosa * x1 + sina * x2;
131 my data [irow] [dimension2] = - sina * x1 + cosa * x2;
132 }
133 }
134
135 void Configuration_invertDimension (Configuration me, int dimension) {
136 if (dimension < 1 || dimension > my numberOfColumns)
137 return;
138 for (integer irow = 1; irow <= my numberOfRows; irow ++)
139 my data [irow] [dimension] = - my data [irow] [dimension];
140 }
141
142 static double NUMsquaredVariance (MAT a, bool rawPowers) {
143 longdouble v4 = 0.0;
144 for (integer icol = 1; icol <= a.ncol; icol ++) {
145 longdouble sum4 = 0.0, mean = 0.0;
146 for (integer irow = 1; irow <= a.nrow; irow ++) {
147 const double sq = a [irow] [icol] * a [irow] [icol];
148 sum4 += sq * sq;
149 mean += sq;
150 }
151 v4 += sum4;
152 if (! rawPowers) {
153 v4 -= mean * mean / a.nrow;
154 }
155 }
156 return (double) v4;
157 }
158
159 /*
160 Varimax rotation, implementation according to:
161 Jos Ten Berge (1995), "Suppressing permutations or rigid
162 planar rotations: a remedy against nonoptimal varimax rotations",
163 Psychometrika 60, 437-446.
164 */
165 static void NUMvarimax (MAT xm, MAT ym, bool normalizeRows, bool quartimax, integer maximumNumberOfIterations, double tolerance) {
166 Melder_assert (xm.ncol == ym.ncol && xm.nrow == ym.nrow);
167
168 ym <<= xm;
169
170 if (xm.ncol == 1)
171 return;
172 if (xm.ncol == 2)
173 maximumNumberOfIterations = 1;
174
175 autoVEC u = raw_VEC (xm.nrow);
176 autoVEC v = raw_VEC (xm.nrow);
177 autoVEC norm = raw_VEC (xm.nrow);
178 /*
179 Normalize sum of squares of each row to one.
180 After rotation we have to rescale.
181 */
182 if (normalizeRows)
183 for (long irow = 1; irow <= ym.nrow; irow ++) {
184 norm [irow] = NUMnorm (ym.row (irow), 2.0);
185 ym.row (irow) /= norm [irow];
186 }
187 /*
188 Initial squared "variance".
189 */
190 double varianceSq = NUMsquaredVariance (ym, quartimax);
191
192 if (varianceSq == 0.0)
193 return;
194 /*
195 Treat columns pairwise.
196 */
197 double varianceSq_old;
198 integer numberOfIterations = 0;
199 do {
200 for (integer icol = 1; icol <= xm.ncol; icol ++) {
201 for (integer jcol = icol + 1; jcol <= xm.ncol; jcol ++) {
202 for (integer irow = 1; irow <= xm.nrow; irow ++) {
203 const double x = ym [irow] [icol];
204 const double y = ym [irow] [jcol];
205 u [irow] = x * x - y * y;
206 v [irow] = 2.0 * x * y;
207 }
208
209 if (! quartimax && xm.nrow != 1) {
210 centre_VEC_inout (u.get());
211 centre_VEC_inout (v.get());
212 }
213
214 const double a = 2.0 * NUMinner (u.get(), v.get());
215 const double b = NUMinner (u.get(), u.get()) - NUMinner (v.get(), v.get());
216
217 const double c = hypot (a, b);
218 double vc = sqrt ((c + b) / (2.0 * c)); // Eq. (1)
219 if (a > 0.0)
220 vc = -vc;
221 /*
222 Get the rotation matrix T
223 */
224 const double cost = sqrt (0.5 + 0.5 * vc);
225 const double sint = sqrt (0.5 - 0.5 * vc);
226 double t11 = cost;
227 double t12 = sint;
228 double t21 = -sint;
229 double t22 = cost;
230 /*
231 Prevent permutations: when v < 0, i.e., a > 0, swap columns of T:/
232 */
233 if (vc < 0.0) {
234 t11 = sint;
235 t12 = t21 = cost;
236 t22 = -sint;
237 }
238 /*
239 Rotate in the plane spanned by icol and jcol.
240 */
241 for (integer irow = 1; irow <= xm.nrow; irow ++) {
242 const double x = ym [irow] [icol], y = ym [irow] [jcol];
243 ym [irow] [icol] = x * t11 + y * t21;
244 ym [irow] [jcol] = x * t12 + y * t22;
245 }
246 }
247 }
248
249 numberOfIterations++;
250 varianceSq_old = varianceSq;
251 varianceSq = NUMsquaredVariance (ym, quartimax);
252
253 } while (fabs (varianceSq_old - varianceSq) > std::max (tolerance * varianceSq_old, NUMeps) &&
254 numberOfIterations < maximumNumberOfIterations);
255
256 if (normalizeRows)
257 for (integer irow = 1; irow <= xm.nrow; irow ++)
258 ym.row (irow) *= norm [irow];
259 }
260
261 autoConfiguration Configuration_varimax (Configuration me, bool normalizeRows, bool quartimax, integer maximumNumberOfIterations, double tolerance) {
262 try {
263 autoConfiguration thee = Data_copy (me);
264 NUMvarimax (my data.get(), thy data.get(), normalizeRows, quartimax, maximumNumberOfIterations, tolerance);
265 return thee;
266 } catch (MelderError) {
267 Melder_throw (me, U": varimax rotation not performed.");
268 }
269 }
270
271 autoConfiguration Configuration_congruenceRotation (Configuration me, Configuration thee, integer maximumNumberOfIterations, double tolerance) {
272 try {
273 autoAffineTransform at = Configurations_to_AffineTransform_congruence (me, thee, maximumNumberOfIterations, tolerance);
274 autoConfiguration him = Configuration_AffineTransform_to_Configuration (me, at.get());
275 return him;
276 } catch (MelderError) {
277 Melder_throw (me, U": congruence rotation not performed.");
278 }
279 }
280
281 void Configuration_rotateToPrincipalDirections (Configuration me) {
282 try {
283 autoMAT pc = MAT_asPrincipalComponents (my data.get(), my data.ncol);
284 my data.all() <<= pc.all();
285 } catch (MelderError) {
286 Melder_throw (me, U": not rotated to principal directions.");
287 }
288 }
289
290 void Configuration_draw (Configuration me, Graphics g, int horizontalDimension, int verticalDimension,
291 double xmin, double xmax, double ymin, double ymax, int labelSize, bool useRowLabels, conststring32 label, bool garnish)
292 {
293 Melder_require (horizontalDimension > 0,
294 U"The horizontal dimension should be positive, not ", horizontalDimension, U".");
295 Melder_require (horizontalDimension <= my numberOfColumns,
296 U"The horizontal dimension should not exceed the number of dimensions (", my numberOfColumns,
297 U"), but is in fact ", horizontalDimension, U"."
298 );
299 Melder_require (verticalDimension > 0,
300 U"The vertical dimension should be positive, not ", verticalDimension, U".");
301 Melder_require (verticalDimension <= my numberOfColumns,
302 U"The vertical dimension should not exceed the number of dimensions (", my numberOfColumns,
303 U"), but is in fact ", verticalDimension, U"."
304 );
305 Melder_require (horizontalDimension != verticalDimension,
306 U"The horizontal dimension and the vertical dimension should be different, but are in fact ",
307 horizontalDimension, U" and ", verticalDimension, U"."
308 );
309 const double fontSize = Graphics_inqFontSize (g);
310 int noLabel = 0;
311 if (labelSize == 0)
312 labelSize = fontSize;
313 autoVEC x = raw_VEC (my numberOfRows);
314 autoVEC y = raw_VEC (my numberOfRows);
315 for (integer irow = 1; irow <= my numberOfRows; irow ++) {
316 x [irow] = my data [irow] [horizontalDimension] * my w [horizontalDimension];
317 y [irow] = my data [irow] [verticalDimension] * my w [verticalDimension];
318 }
319 if (xmax <= xmin) {
320 xmin = NUMmin_u (x.get());
321 xmax = NUMmax_u (x.get());
322 }
323 if (xmax <= xmin) {
324 xmax += 1.0;
325 xmin -= 1.0;
326 }
327 if (ymax <= ymin) {
328 ymin = NUMmin_u (y.get());
329 ymax = NUMmax_u (y.get());
330 }
331 if (ymax <= ymin) {
332 ymax += 1.0;
333 ymin -= 1.0;
334 }
335 if (isundef (xmin) || isundef (xmax) || isundef (ymin) || isundef (ymax))
336 return;
337 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
338 Graphics_setInner (g);
339 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
340 Graphics_setFontSize (g, labelSize);
341 for (integer irow = 1; irow <= my numberOfRows; irow ++) {
342 if (x [irow] >= xmin && x [irow] <= xmax && y [irow] >= ymin && y [irow] <= ymax) {
343 const conststring32 plotLabel = ( useRowLabels ? my rowLabels [irow].get() : label );
344 if (Melder_findInk (plotLabel)) {
345 Graphics_text (g, x [irow], y [irow], plotLabel);
346 } else {
347 noLabel ++;
348 }
349 }
350 }
351 Graphics_setFontSize (g, fontSize);
352 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_BOTTOM);
353 Graphics_unsetInner (g);
354 if (garnish) {
355 Graphics_drawInnerBox (g);
356 Graphics_marksBottom (g, 2, true, true, false);
357 if (my numberOfColumns > 1) {
358 Graphics_marksLeft (g, 2, true, true, false);
359 if (my columnLabels [horizontalDimension])
360 Graphics_textBottom (g, true, my columnLabels [horizontalDimension].get());
361 if (my columnLabels [verticalDimension])
362 Graphics_textLeft (g, true, my columnLabels [verticalDimension].get());
363 }
364 }
365 if (noLabel > 0) {
366 Melder_warning (U"Configuration: Draw: ", noLabel, U" out of ", my numberOfRows,
367 U" labels are not visible, because they are empty or they contain only spaces and/or other non-printable characters.");
368 }
369 }
370
371 void Configuration_drawConcentrationEllipses (Configuration me, Graphics g, double scale, bool confidence, conststring32 label,
372 integer d1, integer d2, double xmin, double xmax, double ymin, double ymax, double fontSize, bool garnish)
373 {
374 autoSSCPList sscps = TableOfReal_to_SSCPList_byLabel (me);
375 SSCPList_drawConcentrationEllipses (sscps.get(), g, scale, confidence, label, d1, d2, xmin, xmax, ymin, ymax, fontSize, garnish);
376 }
377
378 autoConfiguration TableOfReal_to_Configuration (TableOfReal me) {
379 try {
380 autoConfiguration thee = Configuration_create (my numberOfRows, my numberOfColumns);
381 thy data.all() <<= my data.get();
382 TableOfReal_copyLabels (me, thee.get(), 1, 1);
383 return thee;
384 } catch (MelderError) {
385 Melder_throw (me, U": not converted.");
386 }
387 }
388
389 autoConfiguration TableOfReal_to_Configuration_pca (TableOfReal me, integer numberOfDimensions) {
390 try {
391 if (numberOfDimensions < 1 || numberOfDimensions > my numberOfColumns)
392 numberOfDimensions = my numberOfColumns;
393 autoPCA pca = TableOfReal_to_PCA_byRows (me);
394 autoConfiguration thee = PCA_TableOfReal_to_Configuration (pca.get(), me, numberOfDimensions);
395 return thee;
396 } catch (MelderError) {
397 Melder_throw (me, U": pca not performed.");
398 }
399 }
400
401 /********************** Examples *********************************************/
402
403 /*
404 20210614: Configuration_createLetterRExample. Revert to version without initialisation lists because
405 that version is buggy when compiled with gcc (Ubuntu 10.3.0-1ubuntu1) 10.3.0
406 It turn out that x1 and y2 will contain the same values as x2 and y2.
407 */
408 autoConfiguration Configuration_createLetterRExample (int choice) {
409 const double x1 [33] = { 0,
410 -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
411 -5, -4, -3, -2, -1, 0, 1, 2.25, 3, 3,
412 2.25, 1, 0, -1, -2, -3, -4, -1, 0, 1, 2, 3 };
413 const double y1 [33] = { 0,
414 -6, -5, -4, -3, -2, -1, 0, 1, 2, 3,
415 4, 4, 4, 4, 4, 4, 4, 3.5, 2, 1,
416 -0.5, -1, -1, -1, -1, -1, -1, -2, -3, -4, -5, -6 };
417 const double x2 [33] = {0, 0.94756043346272423, 0.73504466902509913,
418 0.4528453515175927, 0.46311499024105723, 0.30345454816993439,
419 0.075184942115601547, -0.090010071904764719, -0.19630977381424003,
420 -0.36341509807865086, -0.54216996409132612, -0.68704678013309872,
421 -0.67370169194623086, -0.69336494336440502, -0.67809065144478664,
422 -0.61382610572366281, -0.68656530656078996, -0.57704879646736551,
423 -0.63417502349009069, -0.37153350651419026, -0.091809666009009777,
424 0.054833807442559397, 0.1445593164362155, 0.055587230806920782,
425 0.18201798315035453, 0.048445620192953162, 0.081595930742961439,
426 0.20063623749033621, 0.28546520751183313, 0.39384438699721991,
427 0.62832258520372286, 0.78548335015622228, 1.0610707888793069 };
428 const double y2 [33] = {0, 0.49630791172076621, 0.53320347382055022,
429 0.62384637225470441, 0.47592708487655661, 0.50364353255684202,
430 0.55311720162084443, 0.55118713773007066, 0.50007736370068601,
431 0.40432332354648709, 0.49817059660482677, 0.49803436631629411,
432 0.33213829258059019, 0.14585700576425648, -0.022110500334692869,
433 -0.1752555003289698, -0.29448744336706828, -0.45639468287493545,
434 -0.59177815505008013, -0.74980550818568981, -0.78095916436791279,
435 -0.64447562732895125, -0.49526830813007033, -0.22443396573313243,
436 -0.066378148077667398, -0.03498490725857361, 0.16196028200653381,
437 0.30633527000982519, -0.14894460651161745, -0.30808798640907431,
438 -0.35920781945385832, -0.62766325578928184, -0.60389363590825562 };
439 try {
440 autoConfiguration me = Configuration_create (32, 2);
441 Thing_setName (me.get(), ( choice == 2 ? U"R_fit" : U"R" ));
442 for (integer irow = 1; irow <= 32; irow ++) {
443 char32 s [20];
444 Melder_sprint (s, 20, irow);
445 TableOfReal_setRowLabel (me.get(), irow, s);
446 my data [irow] [1] = ( choice == 2 ? x2 [irow] : x1 [irow] );
447 my data [irow] [2] = ( choice == 2 ? y2 [irow] : y1 [irow] );
448 }
449 return me;
450 } catch (MelderError) {
451 Melder_throw (U"Letter R Configuration not created.");
452 }
453 }
454
455 autoConfiguration Configuration_createCarrollWishExample () {
456 const double x [10] = {0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0 };
457 const double y [10] = {0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0 };
458 char32 const *label [] = { U"", U"A", U"B", U"C", U"D", U"E", U"F", U"G", U"H", U"I"};
459 try {
460 constexpr integer nObjects = 9;
461 autoConfiguration me = Configuration_create (nObjects, 2);
462 for (integer i = 1; i <= nObjects; i ++) {
463 my data [i] [1] = x [i];
464 my data [i] [2] = y [i];
465 TableOfReal_setRowLabel (me.get(), i, label [i]);
466 }
467 return me;
468 } catch (MelderError) {
469 Melder_throw (U"Carroll Wish Configuration not created.");
470 }
471 }
472
473 /************ CONFIGURATIONS **************************************/
474
475 Thing_implement (ConfigurationList, TableOfRealList, 0);
476
477 /* End of file Configuration.cpp */