Debian Codegraph @

dwtools/MDS.cpp

raw
1 /* MDS.cpp
2 *
3 * Copyright (C) 1993-2020,2026 David Weenink, 2015,2017 Paul Boersma
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 3 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 20020408 GPL
21 djmw 20020513 Applied TableOfReal_setSequential{Column/Row}Labels
22 djmw 20040309 Extra tests for empty objects.
23 djmw 20061218 Changed to Melder_information<x> format.
24 djmw 20071022 Removed unused code.
25 djmw 20071106 drawSplines: to wchar
26 djmw 20071201 Melder_warning<n>
27 djmw 20071213 Removed Preference.
28 djmw 20080724 Thing_classNameW ->Thing_className
29 djmw 20110304 Thing_new
30 */
31
32 #include "SVD.h"
33 #include "Matrix_extensions.h"
34 #include "TableOfReal_extensions.h"
35 #include "MDS.h"
36 #include "Proximity_and_Distance.h"
37 #include "SSCP.h"
38 #include "PCA.h"
39
40 #include "enums_getText.h"
41 #undef _MDS_enums_h_
42 #include "MDS_enums.h"
43 #include "enums_getValue.h"
44 #undef _MDS_enums_h_
45 #include "MDS_enums.h"
46
47 #define TINY 1e-30
48
49 Thing_implement (Kruskal, Thing, 0);
50
51 Thing_implement (Transformator, Thing, 0);
52 Thing_implement (RatioTransformator, Transformator, 0);
53 Thing_implement (MonotoneTransformator, Transformator, 0);
54 Thing_implement (ISplineTransformator, Transformator, 0);
55
56 Thing_implement (Weight, TableOfReal, 0);
57 Thing_implement (Salience, TableOfReal, 0);
58 Thing_implement (ScalarProduct, TableOfReal, 0);
59
60 Thing_implement (ConfusionList, TableOfRealList, 0);
61 Thing_implement (ProximityList, TableOfRealList, 0);
62 Thing_implement (ScalarProductList, TableOfRealList, 0);
63
64 Thing_implement (DissimilarityList, ProximityList, 0);
65 Thing_implement (Similarity, Proximity, 0);
66
67
68 /********************** NUMERICAL STUFF **************************************/
69
70
71 static void MATfromVEC_inplace (MATVU const& m, VECVU v) {
72 Melder_assert (m.nrow * m.ncol == v.size);
73 integer k = 1;
74 for (integer irow = 1; irow <= m.nrow; irow ++)
75 for (integer icol = 1; icol <= m.ncol; icol ++)
76 m [irow] [icol] = v [k ++];
77 }
78
79 static void MAT_divideRowByRowsum_inplace (MATVU const& m) {
80 for (integer i = 1; i <= m.nrow; i ++) {
81 const longdouble rowSum = NUMsum (m.row (i));
82 if (rowSum != 0.0)
83 m.row (i) *= double (1.0 / rowSum);
84 }
85 }
86
87 static integer NUMcountZeros (constMATVU const& m) {
88 integer numberOfZeros = 0;
89 for (integer i = 1; i <= m.nrow; i ++)
90 for (integer j = 1; j <= m.ncol; j ++)
91 if (m [i] [j] == 0.0)
92 numberOfZeros ++;
93 return numberOfZeros;
94 }
95
96 /************ ConfigurationList & Similarity **************************/
97
98 autoDistanceList ConfigurationList_to_DistanceList (ConfigurationList me) {
99 try {
100 autoDistanceList thee = DistanceList_create ();
101 for (integer i = 1; i <= my size; i ++) {
102 const Configuration conf = my at [i];
103 autoDistance d = Configuration_to_Distance (conf);
104 Thing_setName (d.get(), Thing_getName (conf));
105 thy addItem_move (d.move());
106 }
107 return thee;
108 } catch (MelderError) {
109 Melder_throw (U"DistanceList not created form Configurations.");
110 }
111 }
112
113 autoSimilarity ConfigurationList_to_Similarity_cc (ConfigurationList me, Weight weight) {
114 try {
115 autoDistanceList d = ConfigurationList_to_DistanceList (me);
116 autoSimilarity thee = DistanceList_to_Similarity_cc (d.get(), weight);
117 return thee;
118 } catch (MelderError) {
119 Melder_throw (U"Similarity not created form Configurations.");
120 }
121 }
122
123 autoSimilarity DistanceList_to_Similarity_cc (DistanceList me, Weight w) {
124 try {
125 Melder_require (my size > 0,
126 U"DistanceList should not be empty.");
127 Melder_require (TableOfRealList_haveIdenticalDimensions (my asTableOfRealList()),
128 U"All matrices should have the same dimensions.");
129
130 autoWeight aw;
131 if (! w) {
132 aw = Weight_create (my at [1] -> numberOfRows);
133 w = aw.get();
134 }
135
136 autoSimilarity thee = Similarity_create (my size);
137
138 for (integer i = 1; i <= my size; i ++) {
139 const Distance di = my at [i];
140 const conststring32 name = Thing_getName (di);
141 TableOfReal_setRowLabel (thee.get(), i, name);
142 TableOfReal_setColumnLabel (thee.get(), i, name);
143 thy data [i] [i] = 1;
144 for (integer j = i + 1; j <= my size; j ++) {
145 const Distance dj = my at [j];
146 thy data [i] [j] = thy data [j] [i] = Distance_Weight_congruenceCoefficient (di, dj, w);
147 }
148 }
149 return thee;
150 } catch (MelderError) {
151 Melder_throw (U"Similarity not created from DistanceList.");
152 }
153 }
154
155
156 /***************** Transformator **********************************************/
157
158 autoDistance structTransformator :: v_transform (MDSVec vec, Distance dist, Weight /* w */) {
159 try {
160 autoDistance thee = Distance_create (numberOfPoints);
161 TableOfReal_copyLabels (dist, thee.get(), 1, 1);
162
163 // Absolute scaling
164
165 for (integer i = 1; i <= vec -> numberOfProximities; i ++) {
166 const integer ii = vec -> rowIndex [i];
167 const integer jj = vec -> columnIndex [i];
168 thy data [ii] [jj] = thy data [jj] [ii] = vec -> proximity [i];
169 }
170 return thee;
171 } catch (MelderError) {
172 Melder_throw (U"Distance not created.");
173 }
174 }
175
176 void Transformator_init (Transformator me, integer numberOfPoints) {
177 my numberOfPoints = numberOfPoints;
178 my normalization = 1;
179 }
180
181 autoTransformator Transformator_create (integer numberOfPoints) {
182 try {
183 autoTransformator me = Thing_new (Transformator);
184 Transformator_init (me.get(), numberOfPoints);
185 my normalization = 0;
186 return me;
187 } catch (MelderError) {
188 Melder_throw (U"No Transformator created.");
189 }
190 }
191
192 autoDistance Transformator_transform (Transformator me, MDSVec vec, Distance d, Weight w) {
193 try {
194 Melder_require (my numberOfPoints == vec -> numberOfPoints && my numberOfPoints == d -> numberOfRows &&
195 d -> numberOfRows == w -> numberOfRows,
196 U"Dimensions should agree.");
197 return my v_transform (vec, d, w);
198 } catch (MelderError) {
199 Melder_throw (me, U"Distance not created.");
200 }
201 }
202
203 autoDistance structRatioTransformator :: v_transform (MDSVec vec, Distance d, Weight w) {
204 autoDistance thee = Distance_create (numberOfPoints);
205 TableOfReal_copyLabels (d, thee.get(), 1, 1);
206
207 // Determine ratio (eq. 9.4)
208
209 longdouble etaSq = 0.0, rho = 0.0;
210 for (integer i = 1; i <= vec -> numberOfProximities; i ++) {
211 const integer ii = vec -> rowIndex [i];
212 const integer jj = vec -> columnIndex [i];
213 const double delta_ij = vec -> proximity [i];
214 const double d_ij = d -> data [ii] [jj];
215 const double tmp = w -> data [ii] [jj] * delta_ij * delta_ij;
216 etaSq += tmp;
217 rho += tmp * d_ij * d_ij;
218 }
219
220 // transform
221
222 Melder_require (etaSq > 0.0,
223 U"Eta squared should not be zero.");
224
225 our ratio = rho / etaSq;
226 for (integer i = 1; i <= vec -> numberOfProximities; i ++) {
227 const integer ii = vec -> rowIndex [i];
228 const integer jj = vec -> columnIndex [i];
229 thy data [ii] [jj] = thy data [jj] [ii] = our ratio * vec -> proximity [i];
230 }
231
232 if (our normalization)
233 Distance_Weight_smacofNormalize (thee.get(), w);
234 return thee;
235 }
236
237 autoRatioTransformator RatioTransformator_create (integer numberOfPoints) {
238 try {
239 autoRatioTransformator me = Thing_new (RatioTransformator);
240 Transformator_init (me.get(), numberOfPoints);
241 return me;
242 } catch (MelderError) {
243 Melder_throw (U"RatioTransformator not created.");
244 }
245 }
246
247 autoDistance structMonotoneTransformator :: v_transform (MDSVec vec, Distance d, Weight w) {
248 try {
249 autoDistance thee = MDSVec_Distance_monotoneRegression (vec, d, tiesHandling);
250 if (normalization)
251 Distance_Weight_smacofNormalize (thee.get(), w);
252 return thee;
253 } catch (MelderError) {
254 Melder_throw (U"Distance not created.");
255 }
256 }
257
258 autoMonotoneTransformator MonotoneTransformator_create (integer numberOfPoints) {
259 try {
260 autoMonotoneTransformator me = Thing_new (MonotoneTransformator);
261 Transformator_init (me.get(), numberOfPoints);
262 my tiesHandling = kMDS_TiesHandling::PRIMARY_APPROACH;
263 return me;
264 } catch (MelderError) {
265 Melder_throw (U"MonotoneTransformator not created.");
266 }
267 }
268
269 void MonotoneTransformator_setTiesProcessing (MonotoneTransformator me, kMDS_TiesHandling tiesHandling) {
270 my tiesHandling = tiesHandling;
271 }
272
273 autoDistance structISplineTransformator :: v_transform (MDSVec vec, Distance dist, Weight w) {
274 const double tol = 1e-6;
275 const integer itermax = 20, numberOfProximities = vec -> numberOfProximities;
276 const integer nKnots = numberOfInteriorKnots + order + order + 2;
277
278 autoDistance thee = Distance_create (dist -> numberOfRows);
279 TableOfReal_copyLabels (dist, thee.get(), 1, -1);
280
281 autoVEC d = zero_VEC (numberOfProximities);
282
283 for (integer i = 1; i <= numberOfProximities; i ++)
284 d [i] = dist -> data [vec -> rowIndex [i]] [vec -> columnIndex [i]];
285 /*
286 Process knots. Put interior knots at quantiles.
287 Guarantee that for each proximity x [i]: knot [j] <= x [i] < knot [j+1]
288 */
289 for (integer i = 1; i <= order + 1; i ++) {
290 knot [i] = vec -> proximity [1];
291 knot [nKnots - i + 1] = vec -> proximity [numberOfProximities] * 1.000001;
292 }
293 for (integer i = 1; i <= numberOfInteriorKnots; i ++) {
294 const double fraction = (double) i / (numberOfInteriorKnots + 1);
295 knot [order + 1 + i] = NUMquantile (vec -> proximity.get(), fraction);
296 }
297 /*
298 Calculate data matrix m.
299 */
300 for (integer iprox = 1; iprox <= numberOfProximities; iprox ++) {
301 const double x = vec -> proximity [iprox];
302 m [iprox] [1] = 1.0;
303 double y;
304 for (integer ipar = 2; ipar <= numberOfParameters; ipar ++) {
305 try {
306 y = NUMispline (knot.get(), order, ipar - 1, x);
307 } catch (MelderError) {
308 Melder_throw (U"I-spline [", ipar - 1, U"], data [", iprox, U"d] = ", x);
309 }
310 m [iprox] [ipar] = y;
311 }
312 }
313
314 our b = solveNonnegativeLeastSquaresRegression_VEC (m.get(), d.get(), itermax, tol, 0);
315
316 for (integer iprox = 1; iprox <= numberOfProximities; iprox ++) {
317 const integer ii = vec->rowIndex [iprox];
318 const integer jj = vec->columnIndex [iprox];
319 const double r = NUMinner (m.row (iprox), b.all());
320 thy data [ii] [jj] = thy data [jj] [ii] = r;
321 }
322 if (normalization)
323 Distance_Weight_smacofNormalize (thee.get(), w);
324 return thee;
325 }
326
327 autoISplineTransformator ISplineTransformator_create (integer numberOfPoints, integer numberOfInteriorKnots, integer order) {
328 try {
329 autoISplineTransformator me = Thing_new (ISplineTransformator);
330 const integer nData = (numberOfPoints - 1) * numberOfPoints / 2;
331
332 Transformator_init (me.get(), numberOfPoints);
333 /*
334 1 extra parameter for the intercept.
335 2 extra knots for the I-spline.
336 */
337 my numberOfParameters = numberOfInteriorKnots + order + 1;
338 const integer numberOfKnots = numberOfInteriorKnots + order + order + 2;
339
340 my b = raw_VEC (my numberOfParameters);
341 my knot = raw_VEC (numberOfKnots);
342 my m = zero_MAT (nData, my numberOfParameters);
343
344 for (integer i = 1; i <= my numberOfParameters; i ++)
345 my b [i] = NUMrandomUniform (0.0, 1.0);
346
347 my numberOfInteriorKnots = numberOfInteriorKnots;
348 my order = order;
349 return me;
350 } catch (MelderError) {
351 Melder_throw (U"ISplineTransformator not created.");
352 }
353 }
354
355 /***************** CONTINGENCYTABLE **************************************/
356
357 autoConfiguration ContingencyTable_to_Configuration_ca (ContingencyTable me, integer numberOfDimensions, integer scaling) {
358 try {
359 const integer nrow = my numberOfRows, ncol = my numberOfColumns;
360 const integer dimmin = std::min (nrow, ncol);
361
362 autoMAT h = copy_MAT (my data.get());
363 autoVEC rowsum = rowSums_VEC (my data.get());
364 autoVEC colsum = columnSums_VEC (my data.get());
365 autoConfiguration thee = Configuration_create (nrow + ncol, numberOfDimensions);
366
367 if (numberOfDimensions == 0)
368 numberOfDimensions = dimmin - 1;
369 Melder_require (numberOfDimensions < dimmin,
370 U"Dimension should be lower than ", dimmin, U".");
371 /*
372 Ref: A. Gifi (1990), Nonlinear Multivariate Analysis, Wiley & Sons, reprinted 1996,
373 Chapter 8, Multidimensional scaling and Correspondence Analysis.
374
375 Get row and column marginals
376 */
377 longdouble sum = 0.0;;
378 for (integer irow = 1; irow <= nrow; irow ++) {
379 Melder_require (rowsum [irow] > 0.0,
380 U"Row number ", irow, U" should not be empty.");
381 sum += rowsum [irow];
382 }
383
384 for (integer icol = 1; icol <= ncol; icol ++)
385 Melder_require (colsum [icol] > 0.0,
386 U"Column number ", icol, U" should not be empty.");
387 /*
388 Remove trivial singular vectors (Eq. 8.24),
389 construct Dr^(-1/2) H Dc^(-1/2) - Dr^(1/2) uu' Dc^(1/2) / N
390 */
391 for (integer irow = 1; irow <= nrow; irow ++) {
392 for (integer icol = 1; icol <= ncol; icol ++) {
393 const double rc = sqrt (rowsum [irow] * colsum [icol]);
394 h [irow] [icol] = h [irow] [icol] / rc - rc / (double) sum;
395 }
396 }
397
398 autoSVD svd = SVD_createFromGeneralMatrix (h.get());
399 SVD_zeroSmallSingularValues (svd.get(), 0);
400 /*
401 Scale row vectors and column vectors to configuration.
402 */
403 for (integer j = 1; j <= numberOfDimensions; j ++) {
404 const double rootsum = sqrt ((double) sum), lambda = svd -> d [j];
405 double xfactor, yfactor;
406 if (scaling == 1) {
407 /*
408 Scale row points in the centre of gravity of column points (eq 8.5.a)
409 */
410 xfactor = rootsum * lambda;
411 yfactor = rootsum;
412 } else if (scaling == 2) {
413 /*
414 Scale column points in the centre of gravity of row points (8.5.b)
415 */
416 xfactor = rootsum;
417 yfactor = rootsum * lambda;
418 } else if (scaling == 3) {
419 /*
420 Treat row and columns symmetrically (8.5.c).
421 */
422 xfactor = yfactor = rootsum * sqrt (lambda);
423 } else {
424 break;
425 }
426 for (integer irow = 1; irow <= nrow; irow ++)
427 thy data [irow] [j] = svd -> u [irow] [j] * xfactor / sqrt (rowsum [irow]);
428 for (integer icol = 1; icol <= ncol; icol ++)
429 thy data [nrow + icol] [j] = svd -> v [icol] [j] * yfactor / sqrt (colsum [icol]);
430 }
431
432 TableOfReal_setSequentialColumnLabels (thee.get(), 0, 0, nullptr, 1, 1);
433 thy rowLabels.part (1, nrow) <<= my rowLabels.all();
434 thy rowLabels.part (nrow + 1, nrow + ncol) <<= my columnLabels.all();
435 return thee;
436 } catch (MelderError) {
437 Melder_throw (me, U": no Configuration created.");
438 }
439 }
440
441 autoDissimilarity TableOfReal_to_Dissimilarity (TableOfReal me) {
442 try {
443 Melder_require (my numberOfRows == my numberOfColumns,
444 U"The TableOfReal should be square.");
445 Melder_require (TableOfReal_isNonNegative (me),
446 U"No cell in the table should be negative.");
447 autoDissimilarity thee = Thing_new (Dissimilarity);
448 my structTableOfReal :: v1_copy (thee.get());
449 return thee;
450 } catch (MelderError) {
451 Melder_throw (me, U": not converted to Dissimilarity.");
452 }
453 }
454
455 autoSimilarity TableOfReal_to_Similarity (TableOfReal me) {
456 try {
457 Melder_require (my numberOfRows == my numberOfColumns,
458 U"The TableOfReal should be square.");
459 Melder_require (TableOfReal_isNonNegative (me),
460 U"No cell in the table should be negative.");
461 autoSimilarity thee = Thing_new (Similarity);
462 my structTableOfReal :: v1_copy (thee.get());
463 return thee;
464 } catch (MelderError) {
465 Melder_throw (me, U": not converted to Similarity.");
466 }
467 }
468
469 autoDistance TableOfReal_to_Distance (TableOfReal me) {
470 try {
471 Melder_require (my numberOfRows == my numberOfColumns,
472 U"The TableOfReal should be square.");
473 Melder_require (TableOfReal_isNonNegative (me),
474 U"No cell in the table should be negative.");
475 autoDistance thee = Thing_new (Distance);
476 my structTableOfReal :: v1_copy (thee.get());
477 return thee;
478 } catch (MelderError) {
479 Melder_throw (me, U": not converted to Distance.");
480 }
481 }
482
483 autoSalience TableOfReal_to_Salience (TableOfReal me) {
484 try {
485 Melder_require (TableOfReal_isNonNegative (me),
486 U"No cell in the table should be negative.");
487 autoSalience thee = Thing_new (Salience);
488 my structTableOfReal :: v1_copy (thee.get());
489 return thee;
490 } catch (MelderError) {
491 Melder_throw (me, U": not converted to Salience.");
492 }
493 }
494
495 autoWeight TableOfReal_to_Weight (TableOfReal me) {
496 try {
497 Melder_require (TableOfReal_isNonNegative (me),
498 U"No cell in the table should be negative.");
499 autoWeight thee = Thing_new (Weight);
500 my structTableOfReal :: v1_copy (thee.get());
501 return thee;
502 } catch (MelderError) {
503 Melder_throw (me, U": not converted to Weight.");
504 }
505 }
506
507 autoScalarProduct TableOfReal_to_ScalarProduct (TableOfReal me) {
508 try {
509 Melder_require (my numberOfRows == my numberOfColumns,
510 U"TableOfReal should be a square table.");
511 autoScalarProduct thee = Thing_new (ScalarProduct);
512 my structTableOfReal :: v1_copy (thee.get());
513 return thee;
514 } catch (MelderError) {
515 Melder_throw (me, U": not converted to ScalarProduct.");
516 }
517 }
518
519 /**************** Covariance & Correlation to Configuration *****************/
520
521 autoConfiguration SSCP_to_Configuration (SSCP me, integer numberOfDimensions) {
522 try {
523 autoConfiguration thee = Configuration_create (my numberOfRows, numberOfDimensions);
524 autoPCA a = SSCP_to_PCA (me);
525 TableOfReal_setSequentialColumnLabels (thee.get(), 0, 0, nullptr, 1, 1);
526
527 for (integer i = 1; i <= my numberOfRows; i ++) {
528 for (integer j = 1; j <= numberOfDimensions; j ++)
529 thy data [i] [j] = NUMinner (my data.column (i), a -> eigenvectors.column (j));
530 }
531 return thee;
532 } catch (MelderError) {
533 Melder_throw (me, U": no Configuration created.");
534 }
535 }
536
537 autoConfiguration Covariance_to_Configuration (Covariance me, integer numberOfDimensions) {
538 return SSCP_to_Configuration (me, numberOfDimensions);
539 }
540
541 autoConfiguration Correlation_to_Configuration (Correlation me, integer numberOfDimensions) {
542 return SSCP_to_Configuration (me, numberOfDimensions);
543 }
544
545 /**************************** Weight *****************************************/
546
547 autoWeight Weight_create (integer numberOfPoints) {
548 try {
549 autoWeight me = Thing_new (Weight);
550 TableOfReal_init (me.get(), numberOfPoints, numberOfPoints);
551 my data.all() <<= 1.0;
552 return me;
553 } catch (MelderError) {
554 Melder_throw (U"Weight not created.");
555 }
556 }
557
558
559 /**************** Salience *****************************************/
560
561 autoSalience Salience_create (integer numberOfSources, integer numberOfDimensions) {
562 try {
563 autoSalience me = Thing_new (Salience);
564 TableOfReal_init (me.get(), numberOfSources, numberOfDimensions);
565 Salience_setDefaults (me.get());
566 return me;
567 } catch (MelderError) {
568 Melder_throw (U"Salience not created.");
569 }
570 }
571
572 integer Salience_correctNegatives (Salience me) {
573 /*
574 The weights might be negative.
575 We correct this by simply making them positive.
576 */
577 integer nNegatives = 0;
578 for (integer i = 1; i <= my numberOfRows; i ++) {
579 for (integer j = 1; j <= my numberOfColumns; j ++) {
580 if (my data [i] [j] < 0.0) {
581 nNegatives ++;
582 my data [i] [j] = - my data [i] [j];
583 }
584 }
585 }
586 return nNegatives;
587 }
588
589 void Salience_setDefaults (Salience me) {
590 my data.all() <<= 1.0 / sqrt (my numberOfColumns);
591 for (integer j = 1; j <= my numberOfColumns; j ++)
592 TableOfReal_setColumnLabel (me, j, Melder_cat (U"dimension ", j));
593 }
594
595 void Salience_draw (Salience me, Graphics g, integer ix, integer iy, bool garnish) {
596 integer nc2, nc1 = ( ix < iy ? (nc2 = iy, ix) : (nc2 = ix, iy) );
597
598 if (ix < 1 || ix > my numberOfColumns || iy < 1 || iy > my numberOfColumns)
599 return;
600
601 double wmax = 1.0;
602 for (integer i = 1; i <= my numberOfRows; i ++) {
603 for (integer j = nc1; j <= nc2; j ++)
604 if (my data [i] [j] > wmax)
605 wmax = my data [i] [j];
606 }
607 const double xmin = 0.0, ymin = 0.0;
608 double ymax, xmax = ymax = wmax;
609 Graphics_setInner (g);
610 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
611 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
612
613 for (integer i = 1; i <= my numberOfRows; i ++)
614 if (my rowLabels [i])
615 Graphics_text (g, my data [i] [ix], my data [i] [iy], my rowLabels [i].get());
616
617 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_BOTTOM);
618 Graphics_line (g, xmin, ymax, xmin, ymin);
619 Graphics_line (g, xmin, ymin, xmax, ymin);
620 /* Graphics_arc (g, xmin, ymin, xmax - xmin, 0, 90); */
621 Graphics_unsetInner (g);
622
623 if (garnish) {
624 if (my columnLabels [ix])
625 Graphics_textBottom (g, false, my columnLabels [ix].get());
626 if (my columnLabels [iy])
627 Graphics_textLeft (g, false, my columnLabels [iy].get());
628 }
629 }
630
631 /************************** COonfusionList **************************************/
632
633 autoConfusion ConfusionList_sum (ConfusionList me) {
634 try {
635 autoTableOfReal sum = TableOfRealList_sum (my asTableOfRealList());
636 autoConfusion thee = TableOfReal_to_Confusion (sum.get());
637 return thee;
638 } catch (MelderError) {
639 Melder_throw (me, U": sum not created.");
640 }
641 }
642
643 /***************** ScalarProduct ***************************************/
644
645 autoScalarProduct ScalarProduct_create (integer numberOfPoints) {
646 try {
647 autoScalarProduct me = Thing_new (ScalarProduct);
648 TableOfReal_init (me.get(), numberOfPoints, numberOfPoints);
649 return me;
650 } catch (MelderError) {
651 Melder_throw (U"ScalarProduct not created.");
652 }
653 }
654
655 autoSimilarity Confusion_to_Similarity (Confusion me, bool normalize, integer symmetrizeMethod) {
656 try {
657 Melder_require (my numberOfColumns == my numberOfRows,
658 U"Confusion should be a square table.");
659
660 const integer nxy = my numberOfColumns;
661 autoSimilarity thee = Similarity_create (nxy);
662
663 TableOfReal_copyLabels (me, thee.get(), 1, 1);
664
665 thy data.all() <<= my data.all();
666
667 if (normalize)
668 MAT_divideRowByRowsum_inplace (thy data.get());
669
670 if (symmetrizeMethod == 1)
671 return thee;
672
673 if (symmetrizeMethod == 2) { // average data
674 for (integer i = 1; i <= nxy - 1; i ++)
675 for (integer j = i + 1; j <= nxy; j ++)
676 thy data [i] [j] = thy data [j] [i] = (thy data [i] [j] + thy data [j] [i]) / 2;
677 } else if (symmetrizeMethod == 3) { // method Houtgast
678 autoMAT p = copy_MAT (thy data.get());
679 for (integer i = 1; i <= nxy; i ++) {
680 for (integer j = i; j <= nxy; j ++) {
681 longdouble tmp = 0;
682 for (integer k = 1; k <= nxy; k ++)
683 tmp += std::min (p [i] [k], p [j] [k]);
684 thy data [j] [i] = thy data [i] [j] = (double) tmp;
685 }
686 }
687 }
688 return thee;
689 } catch (MelderError) {
690 Melder_throw (me, U": no Similarity created.");
691 }
692 }
693
694 autoDissimilarity Similarity_to_Dissimilarity (Similarity me, double maximumDissimilarity) {
695 try {
696 const integer nxy = my numberOfColumns;
697 autoDissimilarity thee = Dissimilarity_create (nxy);
698 TableOfReal_copyLabels (me, thee.get(), 1, 1);
699 thy data.all() <<= my data.all();
700
701 double max = 0.0;
702 for (integer i = 1; i <= nxy; i ++) {
703 for (integer j = 1; j <= nxy; j ++) {
704 if (thy data [i] [j] > max) {
705 max = thy data [i] [j];
706 }
707 }
708 }
709
710 if (maximumDissimilarity <= 0.0)
711 maximumDissimilarity = max;
712
713 if (maximumDissimilarity < max)
714 Melder_warning (U"Your maximumDissimilarity is smaller than the maximum similarity. Some data may be lost.");
715
716 for (integer i = 1; i <= nxy; i ++) {
717 for (integer j = 1; j <= nxy; j ++) {
718 const double d = maximumDissimilarity - thy data [i] [j];
719 thy data [i] [j] = std::max (d, 0.0);
720 }
721 }
722 return thee;
723 } catch (MelderError) {
724 Melder_throw (me, U": no Dissimilarity created.");
725 }
726 }
727
728
729 autoWeight Dissimilarity_to_Weight (Dissimilarity me) {
730 try {
731 autoWeight thee = Weight_create (my numberOfRows);
732 TableOfReal_copyLabels (me, thee.get(), 1, 1);
733 for (integer i = 1; i <= my numberOfRows; i ++) {
734 for (integer j = i; j <= my numberOfRows; j ++) {
735 if (my data [i] [j] > 0.0)
736 thy data [i] [j] = 1.0;
737 }
738 thy data [i] [i] = 0.0;
739 }
740 return thee;
741 } catch (MelderError) {
742 Melder_throw (me, U": no Weight created.");
743 }
744 }
745
746
747 autoDissimilarity Confusion_to_Dissimilarity_pdf (Confusion me, double minimumConfusionLevel) {
748 try {
749 Melder_require (my numberOfColumns == my numberOfRows,
750 U"Confusion should be a square table.");
751 Melder_require (minimumConfusionLevel > 0.0 && minimumConfusionLevel < 1.0,
752 U"The minimum confusion level should be positive and smaller than 1.0.");
753
754 autoDissimilarity thee = Dissimilarity_create (my numberOfColumns);
755 TableOfReal_copyLabels (me, thee.get(), 1, 1);
756 thy data.all() <<= my data.all();
757 /*
758 Set all zero responses to the minimumConfusionLevel.
759 */
760 for (integer i = 1; i <= my numberOfColumns; i ++)
761 for (integer j = 1; j <= my numberOfColumns; j ++)
762 if (thy data [i] [j] == 0.0)
763 thy data [i] [j] = minimumConfusionLevel;
764
765 MAT_divideRowByRowsum_inplace (thy data.get());
766
767 /*
768 Consider the fraction as the fraction overlap between two gaussians with unequal sigmas (1 & s).
769 We have two matrix elements p [i] [j] && p [j] [i]
770
771 N (x, m, s) = 1 / (s * sqrt(2 pi)) exp(-((x - m) / s)^2 / 2)
772 N1 (x) = N (x, 0, 1)
773 N2 (x) = N (x, m, s)
774 These two gaussians cross each other at a point X that can be found
775 by solving N1 (x) == N2 (x).
776 The solution that is important to us is:
777 X = (- m + s sqrt (m^2 - 2 (s^2 - 1) ln(s))) / (s^2 - 1) (1)
778
779 This point X must be the solution of F (X, 0, 1) == p [i] [j], where
780 F (x, m, s) = P (x>X, m, s) = Integral (x, infinity, N (x, m, s) dx)
781
782 We can solve for m and obtain:
783 m = X + s sqrt (X^2 + 2 ln (s)) (2)
784
785 We also have
786 Integral (-Infinity, X, N2 (x) dx) == p [j] [i];
787 By changing integration variables, (x - m) / s = y, we get
788 Integral ((x-m)/s, Infinity, N (y, 0, 1) dy) == p [j] [i]
789 Let this equation result in a value Y, i.e., (X - m) / s = Y (3)
790
791 (2) and (3) together and solve for m:
792
793 m = X + Y * exp ((Y * Y - X * X) / 2);
794
795 Make maximum dissimilarity equal to 4sigma.
796 */
797
798 for (integer i = 1; i <= my numberOfColumns; i ++) {
799 for (integer j = i + 1; j <= my numberOfColumns; j ++) {
800 const double px = std::min (thy data [i] [j], thy data [j] [i]);
801 const double py = std::max (thy data [i] [j], thy data [j] [i]);
802 const double x = NUMinvGaussQ (px);
803 const double y = NUMinvGaussQ (py);
804 const double d = x + y * exp ((y * y - x * x) / 2.0);
805 thy data [i] [j] = thy data [j] [i] = d;
806 }
807 }
808 return thee;
809 } catch (MelderError) {
810 Melder_throw (me, U": no Dissimilarity created from pdf.");
811 }
812 }
813
814 void Distance_Configuration_drawScatterDiagram (Distance me, Configuration him, Graphics g, double xmin, double xmax, double ymin, double ymax, double size_mm, conststring32 mark, bool garnish) {
815 autoDistance dist = Configuration_to_Distance (him);
816 Proximity_Distance_drawScatterDiagram (me, dist.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
817 }
818
819 autoConfiguration Distance_to_Configuration_torsca (Distance me, integer numberOfDimensions) {
820 try {
821 Melder_require (numberOfDimensions <= my numberOfRows,
822 U"Number of dimensions should not exceed ", my numberOfRows, U".");
823 autoScalarProduct sp = Distance_to_ScalarProduct (me, false);
824 autoConfiguration thee = Configuration_create (my numberOfRows, numberOfDimensions);
825 TableOfReal_copyLabels (me, thee.get(), 1, 0);
826 MAT_asPrincipalComponents_preallocated (thy data.get(), sp -> data.get(), numberOfDimensions);
827 return thee;
828 } catch (MelderError) {
829 Melder_throw (me, U": no Configuration created (torsca method).");
830 }
831 }
832
833 autoScalarProduct Distance_to_ScalarProduct (Distance me, bool normalize) {
834 try {
835 autoScalarProduct thee = ScalarProduct_create (my numberOfRows);
836 TableOfReal_copyLabels (me, thee.get(), 1, 1);
837 for (integer i = 1; i <= my numberOfRows - 1; i ++) {
838 for (integer j = i + 1; j <= my numberOfColumns; j ++) {
839 /*
840 Force symmetry by averaging!
841 */
842 const double d = 0.5 * (my data [i] [j] + my data [j] [i]);
843 thy data [i] [j] = thy data [j] [i] = - 0.5 * d * d;
844 }
845 // thy data [i] [i] = 0.0; // redundant
846 }
847 TableOfReal_doubleCentre (thee.get());
848
849 if (my name)
850 Thing_setName (thee.get(), my name.get());
851 if (normalize)
852 TableOfReal_normalizeTable (thee.get(), 1.0);
853
854 return thee;
855 } catch (MelderError) {
856 Melder_throw (me, U": no ScalarProduct created.");
857 }
858 }
859
860 /********** Configuration & ..... ***********************************/
861
862
863
864 void Proximity_Distance_drawScatterDiagram (Proximity me, Distance thee, Graphics g,
865 double xmin, double xmax, double ymin, double ymax, double size_mm, conststring32 mark, bool garnish) {
866 const integer n = my numberOfRows * (my numberOfRows - 1) / 2;
867
868 if (n == 0)
869 return;
870
871 Melder_require (NUMequal (my rowLabels.get(), thy rowLabels.get()) &&
872 NUMequal (my columnLabels.get(), thy columnLabels.get()),
873 U"The labels should be the same.");
874
875 constMAT x = my data.get(), y = thy data.get();
876 if (xmax <= xmin) {
877 MelderExtremaWithInit extrema;
878 for (integer i = 1; i <= thy numberOfRows - 1; i ++)
879 for (integer j = i + 1; j <= thy numberOfColumns; j ++)
880 extrema.update (x [i] [j]);
881 xmin = extrema.min;
882 xmax = extrema.max;
883 }
884 if (ymax <= ymin) {
885 MelderExtremaWithInit extrema;
886 for (integer i = 1; i <= my numberOfRows - 1; i ++)
887 for (integer j = i + 1; j <= my numberOfColumns; j ++)
888 extrema.update (y [i] [j]);
889 ymin = extrema.min;
890 ymax = extrema.max;
891 }
892 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
893 Graphics_setInner (g);
894 for (integer i = 1; i <= thy numberOfRows - 1; i ++)
895 for (integer j = i + 1; j <= thy numberOfColumns; j ++)
896 if (x [i] [j] >= xmin && x [i] [j] <= xmax && y [i] [j] >= ymin && y [i] [j] <= ymax)
897 Graphics_mark (g, x [i] [j], y [i] [j], size_mm, mark);
898
899 Graphics_unsetInner (g);
900 if (garnish) {
901 Graphics_drawInnerBox (g);
902 Graphics_textLeft (g, true, U"Distance");
903 Graphics_textBottom (g, true, U"Dissimilarity");
904 Graphics_marksBottom (g, 2, true, true, false);
905 Graphics_marksLeft (g, 2, true, true, false);
906 }
907 }
908
909 autoDistanceList MDSVecList_Distance_monotoneRegression (MDSVecList me, Distance thee, kMDS_TiesHandling tiesHandling) {
910 try {
911 autoDistanceList him = DistanceList_create ();
912 for (integer i = 1; i <= my size; i ++) {
913 const MDSVec vec = my at [i];
914 Melder_require (vec -> numberOfPoints == thy numberOfRows,
915 U"Dimension of MDSVec and Distance should be equal.");
916 autoDistance fit = MDSVec_Distance_monotoneRegression (vec, thee, tiesHandling);
917 his addItem_move (fit.move());
918 }
919 return him;
920 } catch (MelderError) {
921 Melder_throw (U"No DistanceList created from MDSVecList and Distance.");
922 }
923 }
924
925 autoDistance MDSVec_Distance_monotoneRegression (MDSVec me, Distance thee, kMDS_TiesHandling tiesHandling) {
926 try {
927 Melder_require (my numberOfPoints == thy numberOfColumns,
928 U"The dimensions of the Distance and the MDSVec should agree.");
929 Melder_require (thy numberOfRows == my numberOfPoints,
930 U"Distance and MDSVVec dimensions should agreee.");
931 const integer numberOfProximities = my numberOfProximities;
932 autoVEC distances = raw_VEC (numberOfProximities);
933 autoDistance him = Distance_create (thy numberOfRows);
934 TableOfReal_copyLabels (thee, him.get(), 1, 1);
935
936 for (integer i = 1; i <= numberOfProximities; i ++)
937 distances [i] = thy data [my rowIndex [i]] [my columnIndex [i]];
938
939 if (tiesHandling == kMDS_TiesHandling::PRIMARY_APPROACH || tiesHandling == kMDS_TiesHandling::SECONDARY_APPROACH) {
940 /*
941 Kruskal's primary approach to tie-blocks:
942 Sort corresponding distances, with rowIndex, and columnIndex.
943 Kruskal's secondary approach:
944 Substitute average distance in each tie block
945 */
946 integer ib = 1;
947 for (integer i = 2; i <= numberOfProximities; i ++) {
948 if (my proximity [i] == my proximity [i - 1])
949 continue;
950 if (i - ib > 1) {
951 if (tiesHandling == kMDS_TiesHandling::PRIMARY_APPROACH) {
952 // all equal
953 } else if (tiesHandling == kMDS_TiesHandling::SECONDARY_APPROACH) {
954 const double mean = NUMmean (distances.part (ib, i - 1));
955 distances.part (ib, i - 1) <<= mean;
956 }
957 }
958 ib = i;
959 }
960 }
961
962 autoVEC fit = newVECmonotoneRegression (distances.get());
963 /*
964 Fill Distance with monotone regressed distances
965 */
966 for (integer i = 1; i <= numberOfProximities; i ++) {
967 const integer irow = my rowIndex [i], icol = my columnIndex [i];
968 his data [irow] [icol] = his data [icol] [irow] = fit [i];
969 }
970 /*
971 Make rest of distances equal to the maximum fit.
972 */
973 for (integer i = 1; i <= his numberOfRows - 1; i ++) {
974 for (integer j = i + 1; j <= his numberOfColumns; j ++) {
975 if (his data [i] [j] == 0.0)
976 his data [i] [j] = his data [j] [i] = fit [numberOfProximities];
977 }
978 }
979 return him;
980 } catch (MelderError) {
981 Melder_throw (U"Distance not created.");
982 }
983 }
984
985
986 autoDistance Dissimilarity_Distance_monotoneRegression (Dissimilarity me, Distance thee, kMDS_TiesHandling tiesHandling) {
987 try {
988 Melder_require (thy numberOfRows == my numberOfRows, U"Dimensions should agree.");
989 autoMDSVec vec = Dissimilarity_to_MDSVec (me);
990 autoDistance him = MDSVec_Distance_monotoneRegression (vec.get(), thee, tiesHandling);
991 return him;
992 } catch (MelderError) {
993 Melder_throw (U"Distance not created.");
994 }
995 }
996
997 /*************** class Proximities **************************************/
998
999 autoScalarProductList DistanceList_to_ScalarProductList (DistanceList me, bool normalize) {
1000 try {
1001 autoScalarProductList thee = ScalarProductList_create ();
1002 for (integer i = 1; i <= my size; i ++) {
1003 autoScalarProduct sp = Distance_to_ScalarProduct (my at [i], normalize);
1004 thy addItem_move (sp.move());
1005 }
1006 return thee;
1007 } catch (MelderError) {
1008 Melder_throw (me, U": no ScalarProducts created.");
1009 }
1010 }
1011
1012 void DistanceList_to_Configuration_ytl (DistanceList me, integer numberOfDimensions, integer normalizeScalarProducts, autoConfiguration *out1, autoSalience *out2) {
1013 try {
1014 autoScalarProductList sp = DistanceList_to_ScalarProductList (me, normalizeScalarProducts);
1015 ScalarProductList_to_Configuration_ytl (sp.get(), numberOfDimensions, out1, out2);
1016 } catch (MelderError) {
1017 Melder_throw (me, U": no Configuration created (ytl method).");
1018 }
1019 }
1020
1021 /*
1022 Algorithm : F. Young, Y. Takane & R. Lewyckyj (1978), "Three notes on ALSCAL",
1023 Psychometrika 43, 433-435.
1024 */
1025 void ScalarProductList_to_Configuration_ytl (ScalarProductList me, integer numberOfDimensions, autoConfiguration *out1, autoSalience *out2) {
1026 try {
1027 const integer numberOfSources = my size;
1028 Melder_require (numberOfSources > 1,
1029 U"The number of sources should exceed one.");
1030 const integer nPoints = my at [1] -> numberOfRows;
1031
1032 autoConfiguration thee = Configuration_create (nPoints, numberOfDimensions);
1033 autoSalience mdsw = Salience_create (numberOfSources, numberOfDimensions);
1034 TableOfReal_copyLabels (my at [1], thee.get(), 1, 0);
1035
1036 Thing_setName (mdsw.get(), U"ytl");
1037 Thing_setName (thee.get(), U"ytl");
1038 TableOfReal_setLabelsFromCollectionItemNames (mdsw.get(), (Collection) me, true, false); // FIXME cast
1039
1040 /*
1041 Determine the average scalar product matrix (Pmean) of dimension [1..nPoints] [1..nPoints].
1042 */
1043 autoMAT pmean = zero_MAT (nPoints, nPoints);
1044
1045 for (integer i = 1; i <= numberOfSources; i ++) {
1046 ScalarProduct sp = my at [i];
1047 Melder_require (sp -> numberOfRows == nPoints,
1048 U"The dimension of ScalarProduct ", i, U" does not conform.");
1049 pmean.all() += sp -> data.all();
1050 }
1051
1052 pmean.all() *= 1.0 / numberOfSources;
1053
1054 /*
1055 Up to a rotation K, the initial configuration can be found by
1056 extracting the first 'numberOfDimensions' principal components of Pmean.
1057 */
1058
1059 autoMAT y = MAT_asPrincipalComponents (pmean.get (), numberOfDimensions);
1060
1061 thy data.all() <<= y.all();
1062
1063 /*
1064 Calculate the C [i] matrices [1..numberOfDimensions] [1..numberOfDimensions]
1065 from the P [i] by: C [i] = (y'.y)^-1 . y' . P [i] . y . (y'.y)^-1 == yinv P [i] yinv'
1066 */
1067
1068 autoMAT yinv = newMATpseudoInverse (y.get(), 1e-14);
1069 autoTEN3 ci = raw_TEN3 (numberOfSources, numberOfDimensions, numberOfDimensions);
1070
1071 for (integer i = 1; i <= numberOfSources; i ++) {
1072 const ScalarProduct sp = my at [i];
1073 MATmul3_XYXt (ci [i], yinv.get(), sp -> data.get()); //yinv.Data.yinv'
1074 }
1075
1076 /*
1077 Calculate the A [1..numberOfSources] [1..numberOfSources] matrix by (eq.12):
1078 a [i] [j] = trace (C [i]*C [j]) - trace (C [i]) * trace (C [j]) / numberOfDimensions;
1079 Get the first eigenvector and form matrix cl from a linear combination of the C [i]'s
1080 */
1081
1082 autoMAT a = raw_MAT (numberOfSources, numberOfSources);
1083
1084 for (integer i = 1; i <= numberOfSources; i ++) {
1085 for (integer j = i; j <= numberOfSources; j ++) {
1086 a [j] [i] = a [i] [j] = NUMtrace2 (ci [i], ci [j])
1087 - NUMtrace (ci [i]) * NUMtrace (ci [j]) / numberOfDimensions;
1088 }
1089 }
1090
1091 autoMAT evec;
1092
1093 MAT_getEigenSystemFromSymmetricMatrix (a.get(), & evec, nullptr, false);
1094
1095 autoMAT cl = zero_MAT (numberOfDimensions, numberOfDimensions);
1096 for (integer i = 1; i <= numberOfSources; i ++) {
1097 for (integer j = 1; j <= numberOfDimensions; j ++) {
1098 for (integer k = 1; k <= numberOfDimensions; k ++) {
1099 cl [j] [k] += ci [i] [j] [k] * evec [i] [1]; /* eq. (7) TODO first column??*/
1100 }
1101 }
1102 }
1103
1104 /*
1105 The rotation K is obtained from the eigenvectors of cl
1106 Is the following still correct??? eigensystem was not sorted??
1107 */
1108
1109 autoMAT K;
1110 MAT_getEigenSystemFromSymmetricMatrix (cl.get(), & K, nullptr, false);
1111
1112 mul_MAT_out (thy data.get(), y.get(), K.get()); // Y.K
1113
1114 Configuration_normalize (thee.get(), 0, true);
1115
1116 /*
1117 And finally the weights: W [i] = K' C [i] K (eq. (5)).
1118 We are only interested in the diagonal of the resulting matrix W [i].
1119 */
1120
1121 for (integer i = 1; i <= numberOfSources; i ++) {
1122 for (integer j = 1; j <= numberOfDimensions; j ++) {
1123 longdouble wt = 0.0;
1124 for (integer k = 1; k <= numberOfDimensions; k ++) {
1125 if (K [k] [j] != 0.0) {
1126 for (integer l = 1; l <= numberOfDimensions; l ++) {
1127 wt += K [k] [j] * ci [i] [k] [l] * K [l] [j];
1128 }
1129 }
1130 }
1131 mdsw -> data [i] [j] = (double) wt;
1132 }
1133 }
1134
1135 if (out1)
1136 *out1 = thee.move();
1137 if (out2)
1138 *out2 = mdsw.move();
1139
1140 } catch (MelderError) {
1141 Melder_throw (me, U": no Configuration (ytl) created.");
1142 }
1143 }
1144
1145 autoDissimilarityList DistanceList_to_DissimilarityList (DistanceList me) {
1146 try {
1147 autoDissimilarityList thee = DissimilarityList_create ();
1148 for (integer i = 1; i <= my size; i ++) {
1149 const conststring32 name = Thing_getName (my at [i]);
1150 autoDissimilarity him = Distance_to_Dissimilarity (my at [i]);
1151 Thing_setName (him.get(), ( name ? name : U"untitled" ));
1152 thy addItem_move (him.move());
1153 }
1154 return thee;
1155 } catch (MelderError) {
1156 Melder_throw (me, U": no DissimilaryList created.");
1157 }
1158 }
1159
1160 /***************** Kruskal *****************************************/
1161
1162 static void smacof_guttmanTransform (Configuration cx, Configuration cz, Distance disp, Weight weight, constMAT vplus) {
1163 const integer nPoints = cx -> numberOfRows, nDimensions = cx -> numberOfColumns;
1164
1165 autoMAT b = raw_MAT (nPoints, nPoints);
1166 autoDistance distZ = Configuration_to_Distance (cz);
1167 /*
1168 compute B(Z) (eq. 8.25)
1169 */
1170 for (integer i = 1; i <= nPoints; i ++) {
1171 longdouble sum = 0.0;
1172 for (integer j = 1; j <= nPoints; j ++) {
1173 const double dzij = distZ -> data [i] [j];
1174 if (i == j || dzij == 0.0)
1175 continue;
1176 b [i] [j] = - weight -> data [i] [j] * disp -> data [i] [j] / dzij;
1177 sum += b [i] [j];
1178 }
1179 b [i] [i] = - (double) sum;
1180 }
1181 /*
1182 Guttman transform: Xu = (V+)B(Z)Z (eq. 8.29)
1183 */
1184 for (integer i = 1; i <= nPoints; i ++) {
1185 for (integer j = 1; j <= nDimensions; j ++) {
1186 longdouble xij = 0.0;
1187 for (integer k = 1; k <= nPoints; k ++) {
1188 for (integer l = 1; l <= nPoints; l ++) {
1189 xij += vplus [i] [k] * b [k] [l] * cz -> data [l] [j];
1190 }
1191 }
1192 cx -> data [i] [j] = (double) xij;
1193 }
1194 }
1195 }
1196
1197 double Distance_Weight_stress (Distance fit, Distance conf, Weight weight, kMDS_stressMeasure stressMeasure) {
1198 double stress = undefined;
1199
1200 double eta_fit, eta_conf, rho;
1201 Distance_Weight_rawStressComponents (fit, conf, weight, & eta_fit, & eta_conf, & rho);
1202
1203 /*
1204 All formulas for stress, except for raw stress, are independent of the
1205 scale of the configuration, i.e., the distances conf [i] [j].
1206 */
1207
1208 if (stressMeasure == kMDS_stressMeasure::NORMALIZED) {
1209 const double denum = eta_fit * eta_conf;
1210 if (denum > 0.0)
1211 stress = 1.0 - rho * rho / denum;
1212 } else if (stressMeasure == kMDS_stressMeasure::KRUSKAL_1) {
1213 const double denum = eta_fit * eta_conf;
1214 if (denum > 0.0) {
1215 const double tmp = 1.0 - rho * rho / denum;
1216 if (tmp > 0.0)
1217 stress = sqrt (tmp);
1218 }
1219 } else if (stressMeasure == kMDS_stressMeasure::KRUSKAL_2) {
1220 /*
1221 Get average distance.
1222 */
1223 const integer nPoints = conf -> numberOfRows;
1224 longdouble m = 0.0, wsum = 0.0;
1225 for (integer i = 1; i <= nPoints - 1; i ++) {
1226 m += NUMinner (weight -> data.row (i).part (i + 1, nPoints),
1227 conf -> data.row (i).part (i + 1, nPoints));
1228 wsum += NUMsum (weight -> data.row (i).part (i + 1, nPoints));
1229 }
1230 m /= wsum;
1231 if (m > 0.0) {
1232 /*
1233 Get variance.
1234 */
1235 longdouble var = 0.0;
1236 for (integer i = 1; i <= nPoints - 1; i ++) {
1237 for (integer j = i + 1; j <= nPoints; j ++) {
1238 const longdouble tmp = conf -> data [i] [j] - m;
1239 var += weight -> data [i] [j] * tmp * tmp;
1240 }
1241 }
1242 const double denum = double (var) * eta_fit;
1243 if (denum > 0.0)
1244 stress = sqrt ((eta_fit * eta_conf - rho * rho) / denum);
1245 }
1246 } else if (stressMeasure == kMDS_stressMeasure::RAW) {
1247 stress = eta_fit + eta_conf - 2.0 * rho;
1248 }
1249 return stress;
1250 }
1251
1252 void Distance_Weight_rawStressComponents (Distance fit, Distance conf, Weight weight, double *out_etafit, double *out_etaconf, double *out_rho)
1253 {
1254 const integer nPoints = conf -> numberOfRows;
1255 longdouble etafit = 0.0, etaconf = 0.0, rho = 0.0;
1256 for (integer i = 1; i <= nPoints - 1; i ++) {
1257 constVEC wi = weight -> data.row (i);
1258 constVEC fiti = fit -> data.row (i);
1259 constVEC confi = conf -> data.row (i);
1260 for (integer j = i + 1; j <= nPoints; j ++) {
1261 etafit += wi [j] * fiti [j] * fiti [j];
1262 etaconf += wi [j] * confi [j] * confi [j];
1263 rho += wi [j] * fiti [j] * confi [j];
1264 }
1265 }
1266 if (out_etafit)
1267 *out_etafit = (double) etafit;
1268 if (out_etaconf)
1269 *out_etaconf = (double) etaconf;
1270 if (out_rho)
1271 *out_rho = (double) rho;
1272 }
1273
1274 double Dissimilarity_Configuration_Transformator_Weight_stress (Dissimilarity d, Configuration c, Transformator t, Weight w, kMDS_stressMeasure stressMeasure) {
1275 const integer nPoints = d -> numberOfRows;
1276 double stress = undefined;
1277 Melder_require (nPoints > 0 && nPoints == c -> numberOfRows && nPoints == t -> numberOfPoints ||
1278 (w && nPoints == w -> numberOfRows),
1279 U"Dimensions should agree.");
1280
1281 autoWeight aw;
1282 if (! w) {
1283 aw = Weight_create (nPoints);
1284 w = aw.get();
1285 }
1286 autoDistance cdist = Configuration_to_Distance (c);
1287 autoMDSVec mdsvec = Dissimilarity_to_MDSVec (d);
1288 autoDistance fit = Transformator_transform (t, mdsvec.get(), cdist.get(), w);
1289
1290 stress = Distance_Weight_stress (fit.get(), cdist.get(), w, stressMeasure);
1291 return stress;
1292 }
1293
1294 double Dissimilarity_Configuration_Weight_absolute_stress (Dissimilarity d, Configuration c, Weight w, kMDS_stressMeasure stressMeasure) {
1295 autoTransformator t = Transformator_create (d -> numberOfRows);
1296 double stress = Dissimilarity_Configuration_Transformator_Weight_stress (d, c, t.get(), w, stressMeasure);
1297 return stress;
1298 }
1299
1300 double Dissimilarity_Configuration_Weight_ratio_stress (Dissimilarity d, Configuration c, Weight w, kMDS_stressMeasure stressMeasure) {
1301 autoRatioTransformator t = RatioTransformator_create (d -> numberOfRows);
1302 const double stress = Dissimilarity_Configuration_Transformator_Weight_stress (d, c, t.get(), w, stressMeasure);
1303 return stress;
1304 }
1305
1306 double Dissimilarity_Configuration_Weight_interval_stress (Dissimilarity d, Configuration c, Weight w, kMDS_stressMeasure stressMeasure) {
1307 autoISplineTransformator t = ISplineTransformator_create (d -> numberOfRows, 0, 1);
1308 const double stress = Dissimilarity_Configuration_Transformator_Weight_stress (d, c, t.get(), w, stressMeasure);
1309 return stress;
1310 }
1311
1312 double Dissimilarity_Configuration_Weight_monotone_stress (Dissimilarity d, Configuration c, Weight w, kMDS_TiesHandling tiesHandling, kMDS_stressMeasure stressMeasure) {
1313 autoMonotoneTransformator t = MonotoneTransformator_create (d -> numberOfRows);
1314 MonotoneTransformator_setTiesProcessing (t.get(), tiesHandling);
1315 const double stress = Dissimilarity_Configuration_Transformator_Weight_stress (d, c, t.get(), w, stressMeasure);
1316 return stress;
1317 }
1318
1319 double Dissimilarity_Configuration_Weight_ispline_stress (Dissimilarity d, Configuration c, Weight w, integer numberOfInteriorKnots, integer order, kMDS_stressMeasure stressMeasure) {
1320 autoISplineTransformator t = ISplineTransformator_create (d -> numberOfRows, numberOfInteriorKnots, order);
1321 const double stress = Dissimilarity_Configuration_Transformator_Weight_stress (d, c, t.get(), w, stressMeasure);
1322 return stress;
1323 }
1324
1325 void Distance_Weight_smacofNormalize (Distance me, Weight w) {
1326 longdouble sumsq = 0.0;
1327 for (integer i = 1; i <= my numberOfRows - 1; i ++)
1328 for (integer j = i + 1; j <= my numberOfRows; j ++)
1329 sumsq += w -> data [i] [j] * my data [i] [j] * my data [i] [j];
1330
1331 const double scale = sqrt (my numberOfRows * (my numberOfRows - 1) / double (2.0 * sumsq));
1332 my data.all() *= scale;
1333 }
1334
1335 double Distance_Weight_congruenceCoefficient (Distance x, Distance y, Weight w) {
1336 const integer nPoints = x -> numberOfRows;
1337 if (y -> numberOfRows != nPoints || w -> numberOfRows != nPoints)
1338 return 0.0;
1339
1340 double xy = 0.0, x2 = 0.0, y2 = 0.0;
1341 for (integer i = 1; i <= nPoints - 1; i ++) {
1342 constVEC xi = x -> data.row (i);
1343 constVEC yi = y -> data.row (i);
1344 constVEC wi = w -> data.row (i);
1345 for (integer j = i + 1; j <= nPoints - 1; j ++) {
1346 xy += wi [j] * xi [j] * yi [j];
1347 x2 += wi [j] * xi [j] * xi [j];
1348 y2 += wi [j] * yi [j] * yi [j];
1349 }
1350 }
1351 return xy / (sqrt (x2) * sqrt (y2));
1352 }
1353
1354 autoConfiguration Dissimilarity_Configuration_Weight_Transformator_smacof (Dissimilarity me, Configuration conf, Weight weight, Transformator t, double tolerance, integer numberOfIterations, bool showProgress, double *out_stress) {
1355 try {
1356 const integer nPoints = conf -> numberOfRows;
1357 Melder_require (my numberOfRows == nPoints && t -> numberOfPoints == nPoints ||
1358 (weight && weight -> numberOfRows == nPoints),
1359 U"Dimensions should agree.");
1360
1361 autoWeight aw;
1362 if (! weight) {
1363 aw = Weight_create (nPoints);
1364 weight = aw.get();
1365 }
1366 autoMAT v = raw_MAT (nPoints, nPoints);
1367 autoConfiguration z = Data_copy (conf);
1368 autoMDSVec vec = Dissimilarity_to_MDSVec (me);
1369
1370 if (showProgress)
1371 Melder_progress (0.0, U"MDS analysis");
1372
1373 // Get V (eq. 8.19).
1374
1375 for (integer irow = 1; irow <= nPoints; irow ++) {
1376 longdouble wsum = 0.0;
1377 for (integer icol = 1; icol <= nPoints; icol ++) {
1378 if (irow != icol) {
1379 v [irow] [icol] = - weight -> data [irow] [icol];
1380 wsum += weight -> data [irow] [icol];
1381 }
1382 }
1383 v [irow] [irow] = (double) wsum;
1384 }
1385
1386 /*
1387 V is row and column centered and therefore: rank(V) <= nPoints-1.
1388 V^-1 does not exist -> get Moore-Penrose inverse.
1389 */
1390 constexpr double tol = 1e-6;
1391 autoMAT vplus = newMATpseudoInverse (v.get(), tol);
1392 double stressp = 1e308, stress = 0.0;
1393 for (integer iter = 1; iter <= numberOfIterations; iter ++) {
1394 autoDistance dist = Configuration_to_Distance (conf);
1395 /*
1396 transform & normalization
1397 */
1398 autoDistance fit = Transformator_transform (t, vec.get(), dist.get(), weight);
1399 /*
1400 Make conf the Guttman transform of z
1401 */
1402 smacof_guttmanTransform (conf, z.get(), fit.get(), weight, vplus.get());
1403 /*
1404 Compute stress
1405 */
1406 autoDistance cdist = Configuration_to_Distance (conf);
1407
1408 stress = Distance_Weight_stress (fit.get(), cdist.get(), weight, kMDS_stressMeasure::NORMALIZED);
1409 /*
1410 Check stop criterium
1411 */
1412 if (fabs (stress - stressp) / stressp < tolerance) break;
1413 /*
1414 Make Z = X
1415 */
1416 z -> data.all() <<= conf -> data.all();
1417
1418 stressp = stress;
1419 if (showProgress)
1420 Melder_progress ((double) iter / (numberOfIterations + 1), U"kruskal: stress ", stress);
1421 }
1422 if (showProgress)
1423 Melder_progress (1.0);
1424 if (out_stress)
1425 *out_stress = stress;
1426 return z;
1427 } catch (MelderError) {
1428 if (showProgress)
1429 Melder_progress (1.0);
1430 Melder_throw (me, U": no improved Configuration created (smacof method).");
1431 }
1432 }
1433
1434 autoConfiguration Dissimilarity_Configuration_Weight_Transformator_multiSmacof (Dissimilarity me, Configuration conf, Weight w, Transformator t, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1435 bool showMulti = showProgress && numberOfRepetitions > 1;
1436 try {
1437 const bool showSingle = showProgress && numberOfRepetitions == 1;
1438 autoConfiguration cstart = Data_copy (conf);
1439 autoConfiguration cbest = Data_copy (conf);
1440
1441 if (showMulti)
1442 Melder_progress (0.0, U"MDS many times");
1443
1444 double stress, stressmax = 1e308;
1445 for (integer i = 1; i <= numberOfRepetitions; i ++) {
1446 autoConfiguration cresult = Dissimilarity_Configuration_Weight_Transformator_smacof (me, cstart.get(), w, t, tolerance, numberOfIterations, showSingle, & stress);
1447 if (stress < stressmax) {
1448 stressmax = stress;
1449 cbest = cresult.move();
1450 }
1451 Configuration_randomize (cstart.get());
1452 TableOfReal_centreColumns (cstart.get());
1453
1454 if (showMulti)
1455 Melder_progress ((double) i / (numberOfRepetitions + 1), i, U" from ", numberOfRepetitions);
1456 }
1457 if (showMulti)
1458 Melder_progress (1.0);
1459 return cbest;
1460 } catch (MelderError) {
1461 if (showMulti)
1462 Melder_progress (1.0);
1463 Melder_throw (me, U": no improved Configuration created (smacodf method).");
1464 }
1465 }
1466
1467 autoConfiguration Dissimilarity_Configuration_Weight_absolute_mds (Dissimilarity me, Configuration cstart, Weight w, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1468 try {
1469 autoTransformator t = Transformator_create (my numberOfRows);
1470 autoConfiguration c = Dissimilarity_Configuration_Weight_Transformator_multiSmacof (me, cstart, w, t.get(), tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1471 return c;
1472 } catch (MelderError) {
1473 Melder_throw (me, U": no improved Configuration created (absolute mds method).");
1474 }
1475 }
1476
1477 autoConfiguration Dissimilarity_Configuration_Weight_ratio_mds (Dissimilarity me, Configuration cstart, Weight w, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1478 try {
1479 autoRatioTransformator t = RatioTransformator_create (my numberOfRows);
1480 autoConfiguration c = Dissimilarity_Configuration_Weight_Transformator_multiSmacof (me, cstart, w, t.get(), tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1481 return c;
1482 } catch (MelderError) {
1483 Melder_throw (me, U": no improved Configuration created (ratio mds method).");
1484 }
1485 }
1486
1487 autoConfiguration Dissimilarity_Configuration_Weight_interval_mds (Dissimilarity me, Configuration cstart, Weight w, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1488 try {
1489 autoISplineTransformator t = ISplineTransformator_create (my numberOfRows, 0, 1);
1490 autoConfiguration c = Dissimilarity_Configuration_Weight_Transformator_multiSmacof (me, cstart, w, t.get(), tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1491 return c;
1492 } catch (MelderError) {
1493 Melder_throw (me, U": no improved Configuration created (interval mds method).");
1494 }
1495 }
1496
1497 autoConfiguration Dissimilarity_Configuration_Weight_monotone_mds (Dissimilarity me, Configuration cstart, Weight w, kMDS_TiesHandling tiesHandling, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1498 try {
1499 autoMonotoneTransformator t = MonotoneTransformator_create (my numberOfRows);
1500 MonotoneTransformator_setTiesProcessing (t.get(), tiesHandling);
1501 autoConfiguration c = Dissimilarity_Configuration_Weight_Transformator_multiSmacof (me, cstart, w, t.get(), tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1502 return c;
1503 } catch (MelderError) {
1504 Melder_throw (me, U": no improved Configuration created (monotone mds method).");
1505 }
1506 }
1507
1508 autoConfiguration Dissimilarity_Configuration_Weight_ispline_mds (Dissimilarity me, Configuration cstart, Weight w, integer numberOfInteriorKnots, integer order, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1509 try {
1510 autoISplineTransformator t = ISplineTransformator_create (my numberOfRows, numberOfInteriorKnots, order);
1511 autoConfiguration c = Dissimilarity_Configuration_Weight_Transformator_multiSmacof (me, cstart, w, t.get(), tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1512 return c;
1513 } catch (MelderError) {
1514 Melder_throw (me, U": no improved Configuration created (ispline mds method).");
1515 }
1516 }
1517
1518 autoConfiguration Dissimilarity_Weight_absolute_mds (Dissimilarity me, Weight w, integer numberOfDimensions, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1519 try {
1520 autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::ABSOLUTE_);
1521 autoConfiguration cstart = Distance_to_Configuration_torsca (d.get(), numberOfDimensions);
1522 autoConfiguration c = Dissimilarity_Configuration_Weight_absolute_mds (me, cstart.get(), w, tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1523 return c;
1524 } catch (MelderError) {
1525 Melder_throw (me, U": no Configuration created (absolute mds method).");
1526 }
1527 }
1528
1529 autoConfiguration Dissimilarity_Weight_interval_mds (Dissimilarity me, Weight w, integer numberOfDimensions, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1530 try {
1531 autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::RATIO);
1532 autoConfiguration cstart = Distance_to_Configuration_torsca (d.get(), numberOfDimensions);
1533 autoConfiguration c = Dissimilarity_Configuration_Weight_interval_mds (me, cstart.get(), w, tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1534 return c;
1535 } catch (MelderError) {
1536 Melder_throw (me, U": no Configuration created (interval mds method).");
1537 }
1538 }
1539
1540 autoConfiguration Dissimilarity_Weight_monotone_mds (Dissimilarity me, Weight w, integer numberOfDimensions, kMDS_TiesHandling tiesHandling, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1541 try {
1542 autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::ORDINAL);
1543 autoConfiguration cstart = Distance_to_Configuration_torsca (d.get(), numberOfDimensions);
1544 autoConfiguration c = Dissimilarity_Configuration_Weight_monotone_mds (me, cstart.get(), w, tiesHandling, tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1545 return c;
1546 } catch (MelderError) {
1547 Melder_throw (me, U": no Configuration created (monotone mds method).");
1548 }
1549 }
1550
1551 autoConfiguration Dissimilarity_Weight_ratio_mds (Dissimilarity me, Weight w, integer numberOfDimensions, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1552 try {
1553 autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::RATIO);
1554 autoConfiguration cstart = Distance_to_Configuration_torsca (d.get(), numberOfDimensions);
1555 autoConfiguration c = Dissimilarity_Configuration_Weight_ratio_mds (me, cstart.get(), w, tolerance,
1556 numberOfIterations, numberOfRepetitions, showProgress);
1557 return c;
1558 } catch (MelderError) {
1559 Melder_throw (me, U": no Configuration created (ratio mds method).");
1560 }
1561 }
1562
1563 autoConfiguration Dissimilarity_Weight_ispline_mds (Dissimilarity me, Weight w, integer numberOfDimensions, integer numberOfInteriorKnots, integer order, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress) {
1564 try {
1565 autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::ORDINAL);
1566 autoConfiguration cstart = Distance_to_Configuration_torsca (d.get(), numberOfDimensions);
1567 autoConfiguration c = Dissimilarity_Configuration_Weight_ispline_mds (me, cstart.get(), w,
1568 numberOfInteriorKnots, order, tolerance, numberOfIterations, numberOfRepetitions, showProgress);
1569 return c;
1570 } catch (MelderError) {
1571 Melder_throw (me, U": no Configuration created (ispline mds method).");
1572 }
1573 }
1574
1575 /***** classical **/
1576
1577 static void MDSVec_Distances_getStressValues (MDSVec me, Distance ddist, Distance dfit, kMDS_KruskalStress stress_formula, double *out_stress, double *out_s, double *out_t, double *out_dbar) {
1578
1579 longdouble s = 0.0, t = 0.0, dbar = 0.0;
1580
1581 if (stress_formula == kMDS_KruskalStress::KRUSKAL_1) {
1582 for (integer i = 1; i <= my numberOfProximities; i ++) {
1583 dbar += ddist -> data [my rowIndex [i]] [my columnIndex [i]];
1584 }
1585 dbar /= my numberOfProximities;
1586 }
1587
1588 for (integer i = 1; i <= my numberOfProximities; i ++) {
1589 const integer ii = my rowIndex [i], jj = my columnIndex [i];
1590 const double st = ddist -> data [ii] [jj] - dfit -> data [ii] [jj];
1591 const double tt = ddist -> data [ii] [jj] - dbar;
1592 s += st * st;
1593 t += tt * tt;
1594 }
1595
1596 if (out_stress)
1597 *out_stress = ( t > 0.0 ? sqrt (s / t) : 0.0 );
1598 if (out_s)
1599 *out_s = s;
1600 if (out_t)
1601 *out_t = t;
1602 if (out_dbar)
1603 *out_dbar = dbar;
1604 }
1605
1606 autoKruskal Kruskal_create (integer numberOfPoints, integer numberOfDimensions) {
1607 try {
1608 autoKruskal me = Thing_new (Kruskal);
1609 my configuration = Configuration_create (numberOfPoints, numberOfDimensions);
1610 my proximities = ProximityList_create ();
1611 my dx = raw_MAT (numberOfPoints, numberOfDimensions);
1612 my tiesHandling = kMDS_TiesHandling::PRIMARY_APPROACH;
1613 my stress_formula = kMDS_KruskalStress::KRUSKAL_1;
1614 return me;
1615 } catch (MelderError) {
1616 Melder_throw (U"Kruskal not created.");
1617 }
1618 }
1619
1620 autoConfiguration Dissimilarity_to_Configuration_kruskal (Dissimilarity me, integer numberOfDimensions, integer /* metric */, kMDS_TiesHandling tiesHandling, kMDS_KruskalStress stress_formula, double tolerance, integer numberOfIterations, integer numberOfRepetitions) {
1621 try {
1622 //autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::RATIO);
1623 autoDistance d = Dissimilarity_to_Distance (me, kMDS_AnalysisScale::ORDINAL);
1624 autoConfiguration c = Distance_to_Configuration_torsca (d.get(), numberOfDimensions);
1625 Configuration_normalize (c.get(), 1.0, false);
1626 autoConfiguration thee = Dissimilarity_Configuration_kruskal (me, c.get(), tiesHandling, stress_formula, tolerance, numberOfIterations, numberOfRepetitions);
1627 return thee;
1628 } catch (MelderError) {
1629 Melder_throw (me, U": no Configuration created (kruskal method).");
1630 }
1631 }
1632
1633 void Dissimilarity_Configuration_drawShepardDiagram (Dissimilarity me, Configuration him, Graphics g,
1634 double xmin, double xmax, double ymin, double ymax,
1635 double size_mm, conststring32 mark, bool garnish) {
1636 autoDistance dist = Configuration_to_Distance (him);
1637 Proximity_Distance_drawScatterDiagram (me, dist.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1638 }
1639
1640 autoDistance Dissimilarity_Configuration_monotoneRegression (Dissimilarity dissimilarity, Configuration configuration, kMDS_TiesHandling tiesHandling) {
1641 try {
1642 autoDistance dist = Configuration_to_Distance (configuration);
1643 autoDistance result = Dissimilarity_Distance_monotoneRegression (dissimilarity, dist.get(), tiesHandling);
1644 return result;
1645 } catch (MelderError) {
1646 Melder_throw (U"No Distance created (monotone regression).");
1647 }
1648 }
1649
1650 autoDistanceList DissimilarityList_Configuration_monotoneRegression (DissimilarityList me, Configuration configuration, kMDS_TiesHandling tiesHandling) {
1651 try {
1652 autoDistanceList thee = DistanceList_create ();
1653 autoDistance dist = Configuration_to_Distance (configuration);
1654 for (integer i = 1; i <= my size; i ++) {
1655 autoDistance d = Dissimilarity_Distance_monotoneRegression (my at [i], dist.get(), tiesHandling);
1656 thy addItem_move (d.move());
1657 }
1658 return thee;
1659 } catch (MelderError) {
1660 Melder_throw (U"No DistanceList created (monotone regression).");
1661 }
1662 }
1663
1664 void Dissimilarity_Configuration_drawMonotoneRegression (Dissimilarity me, Configuration him, Graphics g, kMDS_TiesHandling tiesHandling, double xmin, double xmax, double ymin, double ymax, double size_mm, conststring32 mark, bool garnish)
1665 {
1666 /* obsolete replace by transformator */
1667 autoDistance fit = Dissimilarity_Configuration_monotoneRegression (me, him, tiesHandling);
1668 Proximity_Distance_drawScatterDiagram (me, fit.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1669 }
1670
1671 void Dissimilarity_Configuration_Weight_drawAbsoluteRegression (Dissimilarity d, Configuration c, Weight w, Graphics g,
1672 double xmin, double xmax, double ymin, double ymax,
1673 double size_mm, conststring32 mark, bool garnish) {
1674 autoTransformator t = Transformator_create (d -> numberOfRows);
1675 autoDistance fit = Dissimilarity_Configuration_Transformator_Weight_transform (d, c, t.get(), w);
1676 Proximity_Distance_drawScatterDiagram (d, fit.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1677 }
1678
1679 void Dissimilarity_Configuration_Weight_drawRatioRegression (Dissimilarity d, Configuration c, Weight w, Graphics g,
1680 double xmin, double xmax, double ymin, double ymax,
1681 double size_mm, conststring32 mark, bool garnish) {
1682 autoRatioTransformator t = RatioTransformator_create (d -> numberOfRows);
1683 autoDistance fit = Dissimilarity_Configuration_Transformator_Weight_transform (d, c, t.get(), w);
1684 Proximity_Distance_drawScatterDiagram (d, fit.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1685 }
1686
1687 void Dissimilarity_Configuration_Weight_drawIntervalRegression (Dissimilarity d, Configuration c, Weight w, Graphics g,
1688 double xmin, double xmax, double ymin, double ymax,
1689 double size_mm, conststring32 mark, bool garnish) {
1690 Dissimilarity_Configuration_Weight_drawISplineRegression (d, c, w, g, 0.0, 1.0, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1691 }
1692
1693 void Dissimilarity_Configuration_Weight_drawMonotoneRegression (Dissimilarity d, Configuration c, Weight w, Graphics g,
1694 kMDS_TiesHandling tiesHandling, double xmin, double xmax, double ymin, double ymax,
1695 double size_mm, conststring32 mark, bool garnish) {
1696 autoMonotoneTransformator t = MonotoneTransformator_create (d->numberOfRows);
1697 MonotoneTransformator_setTiesProcessing (t.get(), tiesHandling);
1698 autoDistance fit = Dissimilarity_Configuration_Transformator_Weight_transform (d, c, t.get(), w);
1699 Proximity_Distance_drawScatterDiagram (d, fit.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1700 }
1701
1702 void Dissimilarity_Configuration_Weight_drawISplineRegression (Dissimilarity d, Configuration c, Weight w, Graphics g,
1703 integer numberOfInternalKnots, integer order, double xmin, double xmax, double ymin, double ymax,
1704 double size_mm, conststring32 mark, bool garnish) {
1705 autoISplineTransformator t = ISplineTransformator_create (d->numberOfRows, numberOfInternalKnots, order);
1706 autoDistance fit = Dissimilarity_Configuration_Transformator_Weight_transform (d, c, t.get(), w);
1707 Proximity_Distance_drawScatterDiagram (d, fit.get(), g, xmin, xmax, ymin, ymax, size_mm, mark, garnish);
1708 }
1709
1710 autoDistance Dissimilarity_Configuration_Transformator_Weight_transform (Dissimilarity d, Configuration c, Transformator t, Weight w) {
1711 try {
1712 autoWeight aw;
1713 if (! w) {
1714 aw = Weight_create (d -> numberOfRows);
1715 w = aw.get();
1716 }
1717 autoDistance cdist = Configuration_to_Distance (c);
1718 autoMDSVec v = Dissimilarity_to_MDSVec (d);
1719 autoDistance thee = Transformator_transform (t, v.get(), cdist.get(), w);
1720 return thee;
1721 } catch (MelderError) {
1722 Melder_throw (U"Distance not created.");
1723 }
1724 }
1725
1726 double Dissimilarity_Configuration_Weight_Transformator_normalizedStress (Dissimilarity me, Configuration conf, Weight weight, Transformator t) {
1727 autoDistance cdist = Configuration_to_Distance (conf);
1728 autoMDSVec vec = Dissimilarity_to_MDSVec (me);
1729 autoDistance fdist = Transformator_transform (t, vec.get(), cdist.get(), weight);
1730 const double stress = Distance_Weight_stress (fdist.get(), cdist.get(), weight, kMDS_stressMeasure::NORMALIZED);
1731 return stress;
1732 }
1733
1734 double Dissimilarity_Configuration_getStress (Dissimilarity me, Configuration him, kMDS_TiesHandling tiesHandling, kMDS_KruskalStress stress_formula) {
1735 autoDistance dist = Configuration_to_Distance (him);
1736 autoMDSVec vec = Dissimilarity_to_MDSVec (me);
1737 autoDistance fit = MDSVec_Distance_monotoneRegression (vec.get(), dist.get(), tiesHandling);
1738 double stress;
1739 MDSVec_Distances_getStressValues (vec.get(), dist.get(), fit.get(), stress_formula, & stress, nullptr, nullptr, nullptr);
1740 return stress;
1741 }
1742
1743 static double func (Daata object, VEC const& p) {
1744 Kruskal me = (Kruskal) object;
1745 const MDSVec him = my vec.get();
1746 const MAT x = my configuration -> data.get();
1747 double s, t, dbar, stress;
1748 const integer numberOfDimensions = my configuration -> numberOfColumns;
1749 const integer numberOfPoints = my configuration -> numberOfRows;
1750 /*
1751 Substitute results of minimizer into configuration and
1752 normalize the configuration
1753 */
1754 MATfromVEC_inplace (x, p);
1755 centreEachColumn_MAT_inout (x);
1756 MATnormalize_inplace (x, 2.0, sqrt (numberOfPoints));
1757 /*
1758 Calculate interpoint distances from the configuration
1759 */
1760 autoDistance dist = Configuration_to_Distance (my configuration.get());
1761 /*
1762 Monotone regression
1763 */
1764 autoDistance fit = MDSVec_Distance_monotoneRegression (my vec.get(), dist.get(), my tiesHandling);
1765 /*
1766 Get numerator and denominator of stress
1767 */
1768 MDSVec_Distances_getStressValues (my vec.get(), dist.get(), fit.get(), my stress_formula, & stress, & s, & t, & dbar);
1769 /*
1770 Prevent overflow when stress is small
1771 */
1772 if (stress >= 1e-6) {
1773 my dx.all() <<= 0.0;
1774 for (integer i = 1; i <= his numberOfProximities; i ++) {
1775 const integer ii = my vec -> rowIndex [i], jj = my vec -> columnIndex [i];
1776 const double g1 = stress * ((dist -> data [ii] [jj] - fit -> data [ii] [jj]) / s - (dist -> data [ii] [jj] - dbar) / t);
1777 for (integer j = 1; j <= numberOfDimensions; j ++) {
1778 const double dj = x [ii] [j] - x [jj] [j];
1779 double g2 = g1 * pow (fabs (dj) / dist -> data [ii] [jj], my configuration -> metric - 1.0);
1780 if (dj < 0.0)
1781 g2 = -g2;
1782 my dx [ii] [j] += g2;
1783 my dx [jj] [j] -= g2;
1784 }
1785 }
1786 }
1787 (my minimizer -> numberOfFunctionCalls) ++;
1788 return stress;
1789 }
1790
1791 /*
1792 Precondition: configuration was not changed since previous call to func
1793 */
1794 static void dfunc (Daata object, VEC const& /* p */, VEC const& dp) {
1795 const Kruskal me = (Kruskal) object;
1796 const Configuration thee = my configuration.get();
1797
1798 integer k = 1;
1799 for (integer i = 1; i <= thy numberOfRows; i ++) {
1800 for (integer j = 1; j <= thy numberOfColumns; j ++)
1801 dp [k ++] = my dx [i] [j];
1802 }
1803 }
1804
1805 autoConfiguration Dissimilarity_Configuration_kruskal (Dissimilarity me, Configuration him, kMDS_TiesHandling tiesHandling, kMDS_KruskalStress stress_formula, double tolerance, integer numberOfIterations, integer numberOfRepetitions) {
1806 try {
1807 /*
1808 The Configuration is normalized: each dimension centred +
1809 total variance set to 1.0
1810 */
1811 const integer numberOfCoordinates = my numberOfRows * his numberOfColumns;
1812 const integer numberOfParameters = numberOfCoordinates - his numberOfColumns - 1;
1813 const integer numberOfData = my numberOfRows * (my numberOfRows - 1) / 2;
1814
1815 Melder_require (numberOfParameters <= numberOfData,
1816 U"The number of parameters should not exceed the number of data.");
1817
1818 autoKruskal thee = Kruskal_create (my numberOfRows, his numberOfColumns);
1819 TableOfReal_copyLabels (me, thy configuration.get(), 1, 0);
1820 autoDissimilarity dissimilarity = Data_copy (me);
1821 thy proximities -> addItem_move (dissimilarity.move());
1822 thy vec = Dissimilarity_to_MDSVec (me);
1823
1824 thy minimizer = VDSmagtMinimizer_create (numberOfCoordinates, (Daata) thee.get(), func, dfunc);
1825
1826 VECchainRows_preallocated (thy minimizer -> p.get(), his data.get());
1827
1828 thy stress_formula = stress_formula;
1829 thy tiesHandling = tiesHandling;
1830 Configuration_setMetric (thy configuration.get(), his metric);
1831
1832 Minimizer_minimizeManyTimes (thy minimizer.get(), numberOfIterations, numberOfRepetitions, tolerance);
1833
1834 // call the function to get the best configuration
1835
1836 (void) func ((Daata) thee.get(), thy minimizer -> p.get());
1837 return thy configuration.move();
1838 } catch (MelderError) {
1839 Melder_throw (me, U": no Configuration created.");
1840 }
1841 }
1842
1843 /************************** INDSCAL **************************************/
1844
1845 /*
1846 Ten Berge, Kiers & Krijnen (1993), Computational Solutions for the
1847 Problem of Negative Saliences and Nonsymmetry in INDSCAL, Journal of Classification 10, 115-124.
1848 */
1849
1850 static void indscal_iteration_tenBerge (ScalarProductList zc, Configuration xc, Salience weights) {
1851 const integer nPoints = xc -> numberOfRows, nDimensions = xc -> numberOfColumns;
1852 const integer nSources = zc->size;
1853
1854 const double tolerance = 1e-4; // reasonable for dominant eigenvector estimation.
1855 autoMAT wsih = raw_MAT (nPoints, nPoints);
1856 autoVEC solution = raw_VEC (nPoints);
1857
1858 for (integer h = 1; h <= nDimensions; h ++) {
1859 autoScalarProductList sprc = Data_copy (zc);
1860 wsih.all() <<= 0.0;
1861 for (integer i = 1; i <= nSources; i ++) {
1862 const ScalarProduct sih = sprc -> at [i];
1863 /*
1864 Construct the Sih matrices (eq. 6)
1865 */
1866 for (integer j = 1; j <= nDimensions; j ++) {
1867 if (j != h) {
1868 for (integer k = 1; k <= nPoints; k ++)
1869 for (integer l = 1; l <= nPoints; l ++)
1870 sih -> data [k] [l] -= xc -> data [k] [j] * xc -> data [l] [j] * weights -> data [i] [j];
1871 }
1872 }
1873 /*
1874 the weighted S matrix (eq. 8)
1875 */
1876 wsih.all() += sih -> data.all() * weights -> data [i] [h];
1877 }
1878
1879 solution.all() <<= xc -> data.column (h); // initial guess
1880 /*
1881 largest eigenvalue of wsih (nonsymmetric matrix!!) is optimal solution for this dimension
1882 */
1883 (void) VECdominantEigenvector_inplace (solution.get(), wsih.get(), tolerance);
1884 /*
1885 normalize the solution: centre and x'x = 1
1886 */
1887 double mean;
1888 centre_VEC_inout (solution.get(), & mean);
1889 if (mean == 0.0)
1890 continue;
1891 VECnormalize_inplace (solution.get(), 2.0, 1.0);
1892
1893 for (integer k = 1; k <= nPoints; k ++)
1894 xc -> data [k] [h] = solution [k];
1895 /*
1896 update weights. Make negative weights zero.
1897 */
1898 for (integer i = 1; i <= nSources; i ++) {
1899 const ScalarProduct spr = sprc -> at [i];
1900 longdouble wih = 0.0;
1901 for (integer k = 1; k <= nPoints; k ++) {
1902 for (integer l = 1; l <= nPoints; l ++)
1903 wih += xc -> data [k] [h] * spr -> data [k] [l] * xc -> data [l] [h];
1904 }
1905 if (wih < 0.0)
1906 wih = 0.0;
1907 weights -> data [i] [h] = double (wih);
1908 }
1909 }
1910 }
1911
1912
1913 void ScalarProductList_Configuration_Salience_indscal (ScalarProductList sp, Configuration configuration, Salience weights, double tolerance, integer numberOfIterations, bool showProgress, autoConfiguration *out_conf, autoSalience *out_sal, double *out_varianceAccountedFor) {
1914 try {
1915 autoConfiguration conf = Data_copy (configuration);
1916 autoSalience sal = Data_copy (weights);
1917 /*
1918 Solve for X, and W matrix via Alternating Least Squares.
1919 */
1920 if (showProgress)
1921 Melder_progress (0.0, U"INDSCAL analysis");
1922 double vafp = 0.0, varianceAccountedFor;
1923 const double tol = 1e-6;
1924 integer iter;
1925 for (iter = 1; iter <= numberOfIterations; iter ++) {
1926 indscal_iteration_tenBerge (sp, conf.get(), sal.get());
1927 /*
1928 Goodness of fit and test criterion.
1929 */
1930 ScalarProductList_Configuration_Salience_vaf (sp, conf.get(), sal.get(), & varianceAccountedFor);
1931
1932 if (varianceAccountedFor > 1.0 - tol || fabs (varianceAccountedFor - vafp) / vafp < tolerance)
1933 break;
1934
1935 vafp = varianceAccountedFor;
1936 if (showProgress) Melder_progress (iter / (numberOfIterations + 1.0),
1937 U"indscal: varianceAccountedFor ", varianceAccountedFor);
1938 }
1939 const integer numberOfZeros = NUMcountZeros (sal -> data.get());
1940
1941 if (out_conf) {
1942 Thing_setName (conf.get(), U"indscal");
1943 *out_conf = conf.move();
1944 }
1945 if (out_sal) {
1946 Thing_setName (sal.get(), U"indscal");
1947 TableOfReal_setLabelsFromCollectionItemNames (sal.get(), (Collection) sp, true, false); // FIXME cast
1948 *out_sal = sal.move();
1949 }
1950 if (out_varianceAccountedFor)
1951 *out_varianceAccountedFor = varianceAccountedFor;
1952 if (showProgress) {
1953 const integer nSources = sp->size;
1954 MelderInfo_writeLine (U"**************** INDSCAL results on Distances *******************\n\n",
1955 Thing_className (sp), U"number of objects: ", nSources);
1956 for (integer i = 1; i <= nSources; i ++)
1957 MelderInfo_writeLine (U" ", Thing_getName (sp->at [i]));
1958
1959 if (numberOfZeros > 0)
1960 MelderInfo_writeLine (U"WARNING: ", numberOfZeros, U" zero weight", ( numberOfZeros > 1 ? U"s" : U"" ), U"!");
1961
1962 MelderInfo_writeLine (U"\n\nVariance Accounted For = ", varianceAccountedFor, U"\nThe optimal configuration was reached in ", ( iter > numberOfIterations ? numberOfIterations : iter ), U" iterations.");
1963 MelderInfo_drain();
1964 }
1965 if (showProgress)
1966 Melder_progress (1.0);
1967 } catch (MelderError) {
1968 if (showProgress) {
1969 Melder_progress (1.0);
1970 }
1971 Melder_throw (U"No indscal configuration calculated.");
1972 }
1973 }
1974
1975 void DistanceList_Configuration_Salience_indscal (DistanceList distances, Configuration configuration, Salience weights, bool normalizeScalarProducts, double tolerance, integer numberOfIterations, bool showProgress, autoConfiguration *out1, autoSalience *out2, double *out_varianceAccountedFor) {
1976 try {
1977 autoScalarProductList sp = DistanceList_to_ScalarProductList (distances, normalizeScalarProducts);
1978 ScalarProductList_Configuration_Salience_indscal (sp.get(), configuration, weights, tolerance, numberOfIterations, showProgress, out1, out2, out_varianceAccountedFor);
1979 } catch (MelderError) {
1980 Melder_throw (U"No indscal configuration calculated.");
1981 }
1982 }
1983
1984 void DissimilarityList_Configuration_Salience_indscal (DissimilarityList dissims, Configuration conf, Salience weights, kMDS_TiesHandling tiesHandling, bool normalizeScalarProducts, double tolerance, integer numberOfIterations, bool showProgress, autoConfiguration *out_configuration, autoSalience *out_salience, double *out_varianceAccountedFor) {
1985 try {
1986 autoConfiguration configuration = Data_copy (conf);
1987 autoSalience salience = Data_copy (weights);
1988 autoMDSVecList mdsveclist = DissimilarityList_to_MDSVecList (dissims);
1989
1990 if (showProgress)
1991 Melder_progress (0.0, U"INDSCAL analysis");
1992
1993 const double tol = 1e-6;
1994 double vafp = 0.0, vaf;
1995 integer iter;
1996 for (iter = 1; iter <= numberOfIterations; iter ++) {
1997 autoDistanceList distances = MDSVecList_Configuration_Salience_monotoneRegression (mdsveclist.get(), configuration.get(), salience.get(), tiesHandling);
1998 autoScalarProductList sp = DistanceList_to_ScalarProductList (distances.get(), normalizeScalarProducts);
1999
2000 indscal_iteration_tenBerge (sp.get(), configuration.get(), salience.get());
2001 /*
2002 Goodness of fit and test criterion.
2003 */
2004 DistanceList_Configuration_Salience_vaf (distances.get(), configuration.get(), salience.get(), normalizeScalarProducts, & vaf);
2005
2006 if (vaf > 1.0 - tol || fabs (vaf - vafp) < vafp * tolerance)
2007 break;
2008 vafp = vaf;
2009 if (showProgress)
2010 Melder_progress ((double) iter / (numberOfIterations + 1), U"indscal: vaf ", vaf);
2011 }
2012 integer numberOfZeros = NUMcountZeros (salience -> data.get());
2013 Thing_setName (configuration.get(), U"indscal_mr");
2014 Thing_setName (salience.get(), U"indscal_mr");
2015 TableOfReal_setLabelsFromCollectionItemNames (salience.get(), (Collection) dissims, true, false); // FIXME cast
2016
2017 if (out_configuration)
2018 *out_configuration = configuration.move();
2019 if (out_salience)
2020 *out_salience = salience.move();
2021 if (out_varianceAccountedFor)
2022 *out_varianceAccountedFor = vaf;
2023
2024 if (showProgress) {
2025 const integer nSources = dissims->size;
2026 MelderInfo_writeLine (U"**************** INDSCAL with monotone regression *******************");
2027 MelderInfo_writeLine (Thing_className (dissims));
2028 MelderInfo_writeLine (U"Number of objects: ", nSources);
2029 for (integer i = 1; i <= nSources; i ++)
2030 MelderInfo_writeLine (U" ", Thing_getName (dissims->at [i]));
2031 if (numberOfZeros > 0)
2032 MelderInfo_writeLine (U"WARNING: ", numberOfZeros, U" zero weight", ( numberOfZeros > 1 ? U"s" : U"" ));
2033 MelderInfo_writeLine (U"Variance Accounted For: ", vaf);
2034 MelderInfo_writeLine (U"Based on MONOTONE REGRESSION");
2035 MelderInfo_writeLine (U"number of iterations: ", (iter > numberOfIterations ? numberOfIterations : iter));
2036 MelderInfo_drain();
2037 }
2038 if (showProgress)
2039 Melder_progress (1.0);
2040 } catch (MelderError) {
2041 if (showProgress)
2042 Melder_progress (1.0);
2043 Melder_throw (U"No inscal configuration calculated.");
2044 }
2045 }
2046
2047 void DistanceList_Configuration_indscal (DistanceList dists, Configuration conf, bool normalizeScalarProducts, double tolerance, integer numberOfIterations, bool showProgress, autoConfiguration *out1, autoSalience *out2) {
2048 try {
2049 autoSalience w = Salience_create (dists->size, conf -> numberOfColumns);
2050 double vaf;
2051 DistanceList_Configuration_Salience_indscal (dists, conf, w.get(), normalizeScalarProducts, tolerance, numberOfIterations, showProgress, out1, out2, & vaf);
2052 } catch (MelderError) {
2053 Melder_throw (U"No indscal performed.");
2054 }
2055 }
2056
2057 autoDistanceList MDSVecList_Configuration_Salience_monotoneRegression (MDSVecList vecs, Configuration conf, Salience weights, kMDS_TiesHandling tiesHandling) {
2058 try {
2059 autoVEC w = copy_VEC (conf -> w.get());
2060 autoDistanceList distances = DistanceList_create ();
2061 for (integer i = 1; i <= vecs->size; i ++) {
2062 conf -> w.all() <<= weights -> data.row (i);
2063 autoDistance dc = Configuration_to_Distance (conf);
2064 autoDistance dist = MDSVec_Distance_monotoneRegression (vecs->at [i], dc.get(), tiesHandling);
2065 distances -> addItem_move (dist.move());
2066 }
2067 Configuration_setDefaultWeights (conf);
2068 return distances;
2069 } catch (MelderError) {
2070 Melder_throw (U"No DistanceList created.");
2071 }
2072 }
2073
2074 autoSalience DistanceList_Configuration_to_Salience (DistanceList d, Configuration c, bool normalize) {
2075 try {
2076 autoScalarProductList sp = DistanceList_to_ScalarProductList (d, normalize);
2077 autoSalience w = ScalarProductList_Configuration_to_Salience (sp.get(), c);
2078 return w;
2079 } catch (MelderError) {
2080 Melder_throw (U"No Salience created.");
2081 }
2082 }
2083
2084 autoSalience ScalarProductList_Configuration_to_Salience (ScalarProductList me, Configuration him) {
2085 try {
2086 autoSalience salience = Salience_create (my size, his numberOfColumns);
2087 autoConfiguration cx = Data_copy (him);
2088 indscal_iteration_tenBerge (me, cx.get(), salience.get());
2089 return salience;
2090 } catch (MelderError) {
2091 Melder_throw (U"No Salience created.");
2092 }
2093 }
2094
2095 autoSalience DissimilarityList_Configuration_to_Salience (DissimilarityList me, Configuration him, kMDS_TiesHandling tiesHandling, bool normalizeScalarProducts) {
2096 try {
2097 autoDistanceList distances = DissimilarityList_Configuration_monotoneRegression (me, him, tiesHandling);
2098 autoSalience w = DistanceList_Configuration_to_Salience (distances.get(), him, normalizeScalarProducts);
2099 return w;
2100 } catch (MelderError) {
2101 Melder_throw (U"No Salience created.");
2102 }
2103 }
2104
2105 void DissimilarityList_Configuration_indscal (DissimilarityList dissims, Configuration conf, kMDS_TiesHandling tiesHandling, bool normalizeScalarProducts, double tolerance, integer numberOfIterations, bool showProgress, autoConfiguration *out1, autoSalience *out2) {
2106 try {
2107 autoDistanceList distances = DissimilarityList_Configuration_monotoneRegression (dissims, conf, tiesHandling);
2108 autoSalience weights = DistanceList_Configuration_to_Salience (distances.get(), conf, normalizeScalarProducts);
2109 double vaf;
2110 DissimilarityList_Configuration_Salience_indscal (dissims, conf, weights.get(), tiesHandling, normalizeScalarProducts, tolerance, numberOfIterations, showProgress, out1, out2, & vaf);
2111 } catch (MelderError) {
2112 Melder_throw (U"No indscal performed.");
2113 }
2114 }
2115
2116 void DissimilarityList_indscal (DissimilarityList me, integer numberOfDimensions, kMDS_TiesHandling tiesHandling, bool normalizeScalarProducts, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress, autoConfiguration *out_conf, autoSalience *out_sal) {
2117 bool showMulti = showProgress && numberOfRepetitions > 1;
2118 try {
2119 const bool showSingle = (showProgress && numberOfRepetitions == 1);
2120
2121 autoDistanceList distances = DissimilarityList_to_DistanceList (me, kMDS_AnalysisScale::ORDINAL);
2122 autoConfiguration cstart; autoSalience wstart;
2123 DistanceList_to_Configuration_ytl (distances.get(), numberOfDimensions, normalizeScalarProducts, & cstart, & wstart);
2124 autoConfiguration conf = Data_copy (cstart.get());
2125 autoSalience sal = Data_copy (wstart.get());
2126
2127 if (showMulti)
2128 Melder_progress (0.0, U"Indscal many times");
2129
2130 double vaf, vafmin = 0.0;
2131 for (integer iter = 1; iter <= numberOfRepetitions; iter ++) {
2132 autoConfiguration cresult;
2133 autoSalience wresult;
2134 DissimilarityList_Configuration_Salience_indscal (me, cstart.get(), wstart.get(), tiesHandling,
2135 normalizeScalarProducts, tolerance, numberOfIterations, showSingle, & cresult, & wresult, & vaf);
2136 if (vaf > vafmin) {
2137 vafmin = vaf;
2138 conf = cresult.move();
2139 sal = wresult.move();
2140 }
2141 Configuration_randomize (cstart.get());
2142 Configuration_normalize (cstart.get(), 1.0, true);
2143 Salience_setDefaults (wstart.get());
2144
2145 if (showMulti)
2146 Melder_progress ( (double) iter / (numberOfRepetitions + 1), iter, U" from ", numberOfRepetitions);
2147 }
2148
2149 if (out_conf)
2150 *out_conf = conf.move();
2151 if (out_sal)
2152 *out_sal = sal.move();
2153 if (showMulti)
2154 Melder_progress (1.0);
2155
2156 } catch (MelderError) {
2157 if (showMulti) {
2158 Melder_progress (1.0);
2159 }
2160 Melder_throw (me, U": no indscal performed.");
2161 }
2162 }
2163
2164 void DistanceList_to_Configuration_indscal (DistanceList distances, integer numberOfDimensions, bool normalizeScalarProducts, double tolerance, integer numberOfIterations, integer numberOfRepetitions, bool showProgress, autoConfiguration *out_conf, autoSalience *out_sal) {
2165 bool showMulti = showProgress && numberOfRepetitions > 1;
2166 try {
2167 const bool showSingle = (showProgress && numberOfRepetitions == 1);
2168 autoConfiguration cstart;
2169 autoSalience wstart;
2170 DistanceList_to_Configuration_ytl (distances, numberOfDimensions, normalizeScalarProducts, & cstart, & wstart);
2171 autoConfiguration conf = Data_copy (cstart.get());
2172 autoSalience sal = Data_copy (wstart.get());
2173
2174 if (showMulti)
2175 Melder_progress (0.0, U"Indscal many times");
2176
2177 double vaf, vafmin = 0.0;
2178 for (integer i = 1; i <= numberOfRepetitions; i ++) {
2179 autoConfiguration cresult;
2180 autoSalience wresult;
2181 DistanceList_Configuration_Salience_indscal (distances, cstart.get(), wstart.get(), normalizeScalarProducts, tolerance, numberOfIterations, showSingle, & cresult, & wresult, & vaf);
2182 if (vaf > vafmin) {
2183 vafmin = vaf;
2184 conf = cresult.move();
2185 sal = wresult.move();
2186 }
2187 Configuration_randomize (cstart.get());
2188 Configuration_normalize (cstart.get(), 1.0, true);
2189 Salience_setDefaults (wstart.get());
2190
2191 if (showMulti)
2192 Melder_progress ((double) i / (numberOfRepetitions + 1), i, U" from ", numberOfRepetitions);
2193 }
2194
2195 if (out_conf)
2196 *out_conf = conf.move();
2197 if (out_sal)
2198 *out_sal = sal.move();
2199 if (showMulti)
2200 Melder_progress (1.0);
2201
2202 } catch (MelderError) {
2203 if (showMulti)
2204 Melder_progress (1.0);
2205 Melder_throw (distances, U": no indscal performed.");
2206 }
2207 }
2208
2209 void DissimilarityList_Configuration_Salience_vaf (DissimilarityList me, Configuration thee, Salience him, kMDS_TiesHandling tiesHandling, bool normalizeScalarProducts, double *out_varianceAccountedFor) {
2210 autoDistanceList distances = DissimilarityList_Configuration_monotoneRegression (me, thee, tiesHandling);
2211 DistanceList_Configuration_Salience_vaf (distances.get(), thee, him, normalizeScalarProducts, out_varianceAccountedFor);
2212 }
2213
2214 void DistanceList_Configuration_vaf (DistanceList me, Configuration thee, bool normalizeScalarProducts, double *out_varianceAccountedFor) {
2215 autoSalience w = DistanceList_Configuration_to_Salience (me, thee, normalizeScalarProducts);
2216 DistanceList_Configuration_Salience_vaf (me, thee, w.get(), normalizeScalarProducts, out_varianceAccountedFor);
2217 }
2218
2219 void DissimilarityList_Configuration_vaf (DissimilarityList me, Configuration thee, kMDS_TiesHandling tiesHandling, bool normalizeScalarProducts, double *out_varianceAccountedFor) {
2220 autoSalience w = DissimilarityList_Configuration_to_Salience (me, thee, tiesHandling, normalizeScalarProducts);
2221 DissimilarityList_Configuration_Salience_vaf (me, thee, w.get(), tiesHandling, normalizeScalarProducts, out_varianceAccountedFor);
2222 }
2223
2224 void DistanceList_Configuration_Salience_vaf (DistanceList me, Configuration thee, Salience him, bool normalizeScalarProducts, double *out_varianceAccountedFor) {
2225 Melder_require (my size == his numberOfRows && thy numberOfColumns == his numberOfColumns,
2226 U"Dimensions should agree.");
2227 autoScalarProductList sp = DistanceList_to_ScalarProductList (me, normalizeScalarProducts);
2228 ScalarProductList_Configuration_Salience_vaf (sp.get(), thee, him, out_varianceAccountedFor);
2229 }
2230
2231 void ScalarProduct_Configuration_getVariances (ScalarProduct me, Configuration thee, double *out_varianceExplained, double *out_varianceTotal) {
2232 autoDistance distance = Configuration_to_Distance (thee);
2233 autoScalarProduct fit = Distance_to_ScalarProduct (distance.get(), 0);
2234 /*
2235 ScalarProduct is double centred, i.e., mean == 0.
2236 */
2237 double varianceExplained = 0.0, varianceTotal = 0.0;
2238 for (integer j = 1; j <= my numberOfRows; j ++) {
2239 for (integer k = 1; k <= my numberOfColumns; k ++) {
2240 const double d2 = my data [j] [k] - fit -> data [j] [k];
2241 varianceExplained += d2 * d2;
2242 varianceTotal += my data [j] [k] * my data [j] [k];
2243 }
2244 }
2245
2246 if (out_varianceExplained)
2247 *out_varianceExplained = varianceExplained;
2248 if (out_varianceTotal)
2249 *out_varianceTotal = varianceTotal;
2250
2251 }
2252
2253 void ScalarProductList_Configuration_Salience_vaf (ScalarProductList me, Configuration thee, Salience him, double *out_varianceAccountedFor) {
2254 autoVEC w = copy_VEC (thy w.get()); // save weights
2255 try {
2256 Melder_require (my size == his numberOfRows && thy numberOfColumns == his numberOfColumns,
2257 U"Dimensions should agree.");
2258
2259 double t = 0.0, n = 0.0;
2260 for (integer i = 1; i <= my size; i ++) {
2261 const ScalarProduct sp = my at [i];
2262 Melder_require (sp -> numberOfRows == thy numberOfRows,
2263 U"Dimension of ScalarProduct ", i, U" should match Configuration.");
2264 /*
2265 Weigh configuration before calculating variances
2266 */
2267 for (integer j = 1; j <= thy numberOfColumns; j ++)
2268 thy w [j] = sqrt (his data [i] [j]);
2269
2270 double vare, vart;
2271 ScalarProduct_Configuration_getVariances (sp, thee, & vare, & vart);
2272
2273 t += vare;
2274 n += vart;
2275 }
2276
2277 if (out_varianceAccountedFor)
2278 *out_varianceAccountedFor = ( n > 0.0 ? 1.0 - t / n : 0.0 );
2279 thy w.all() <<= w.all(); // restore weights
2280
2281 } catch (MelderError) {
2282 thy w.all() <<= w.all();
2283 Melder_throw (U"No out_varianceAccountedFor calculated.");
2284 }
2285 }
2286
2287 /********************** Examples *********************************************/
2288
2289 autoSalience Salience_createCarrollWishExample () {
2290 try {
2291 integer numberOfSources = 8;
2292 constexpr double wx [9] = {0, 1.0, 0.866, 0.707, 0.5, 0.1, 0.5, 0.354, 0.1};
2293 constexpr double wy [9] = {0, 0.1, 0.5, 0.707, 0.866, 1, 0.1, 0.354, 0.5};
2294 constexpr conststring32 name [] = { U"", U"1", U"2", U"3", U"4", U"5", U"6", U"7", U"8"};
2295 autoSalience me = Salience_create (numberOfSources, 2);
2296
2297 for (integer i = 1; i <= numberOfSources; i ++) {
2298 my data [i] [1] = wx [i];
2299 my data [i] [2] = wy [i];
2300 TableOfReal_setRowLabel (me.get(), i, name [i]);
2301 }
2302 return me;
2303 } catch (MelderError) {
2304 Melder_throw (U"Salience for Carroll Wish example not created.");
2305 }
2306 }
2307
2308 autoCollection INDSCAL_createCarrollWishExample (double noiseRange) {
2309 try {
2310 autoConfiguration c = Configuration_createCarrollWishExample ();
2311 const integer numberOfObjects = c -> numberOfRows, numberOfSources = 8;
2312 autoSalience s = Salience_createCarrollWishExample ();
2313 autoCollection me = Collection_create ();
2314 for (integer l = 1; l <= numberOfSources; l ++) {
2315 c -> w [1] = s -> data [l] [1];
2316 c -> w [2] = s -> data [l] [2];
2317 autoDistance d = Configuration_to_Distance (c.get());
2318 autoDissimilarity dissim = Distance_to_Dissimilarity (d.get());
2319 for (integer i = 1; i <= numberOfObjects - 1; i ++) {
2320 for (integer j = i + 1; j <= numberOfObjects; j ++)
2321 dissim -> data [i] [j] = (dissim -> data [j] [i] += NUMrandomUniform (0.0, noiseRange));
2322 }
2323 Thing_setName (dissim.get(), s -> rowLabels [l].get());
2324 my addItem_move (dissim.move());
2325 }
2326 Thing_setName (me.get(), U"CarrollWish");
2327 return me;
2328 } catch (MelderError) {
2329 Melder_throw (U"Collection not created.");
2330 }
2331 }
2332
2333 void drawSplines (Graphics g, double low, double high, double ymin, double ymax,
2334 kMDS_splineType splineType, integer order, conststring32 interiorKnots, bool garnish)
2335 {
2336 constexpr integer maximumNumberOfKnots = 100;
2337 integer k = order;
2338 double knot [maximumNumberOfKnots + 1];
2339 if (k > maximumNumberOfKnots)
2340 return;
2341 if (splineType == kMDS_splineType::I_SPLINE)
2342 k ++;
2343 for (integer i = 1; i <= k; i ++)
2344 knot [i] = low;
2345 integer numberOfKnots = k;
2346
2347 { // scope
2348 conststring8 start = Melder_peek32to8 (interiorKnots); // UGLY; because of non-availability of str32tod
2349 mutablestring8 end; // this is not actually mutated, but strtod's signature requires this
2350 while (*start) {
2351 const double value = strtod (start, & end);
2352 start = end;
2353 if (value < low || value > high) {
2354 Melder_warning (U"drawSplines: knots should be in interval (", low, U", ", high, U")");
2355 return;
2356 }
2357 if (numberOfKnots == maximumNumberOfKnots) {
2358 Melder_warning (U"drawSplines: too many knots (", maximumNumberOfKnots + 1, U")");
2359 return;
2360 }
2361 knot [++ numberOfKnots] = value;
2362 }
2363 }
2364
2365 const integer numberOfInteriorKnots = numberOfKnots - k;
2366 for (integer i = 1; i <= k; i ++) {
2367 if (numberOfKnots == maximumNumberOfKnots) {
2368 Melder_warning (U"drawSplines: too many knots (", maximumNumberOfKnots + 1, U")");
2369 return;
2370 }
2371 knot [++numberOfKnots] = high;
2372 }
2373
2374 const integer nSplines = order + numberOfInteriorKnots;
2375 if (nSplines == 0)
2376 return;
2377
2378 Graphics_setWindow (g, low, high, ymin, ymax);
2379 Graphics_setInner (g);
2380 constexpr integer numberOfPoints = 1000;
2381 autoVEC y = raw_VEC (numberOfPoints);
2382 const double dx = (high - low) / (numberOfPoints - 1);
2383 for (integer i = 1; i <= nSplines; i ++) {
2384 for (integer j = 1; j <= numberOfPoints; j ++) {
2385 const double x = low + dx * (j - 1);
2386 double yx;
2387 if (splineType == kMDS_splineType::M_SPLINE)
2388 yx = NUMmspline (constVEC (& knot [1], numberOfKnots), order, i, x);
2389 else
2390 yx = NUMispline (constVEC (& knot [1], numberOfKnots), order, i, x);
2391 y [j] = ( yx < ymin ? ymin : ( yx > ymax ? ymax : yx ) );
2392 }
2393 Graphics_function (g, y.asArgumentToFunctionThatExpectsOneBasedArray(), 1, numberOfPoints, low, high);
2394 }
2395 Graphics_unsetInner (g);
2396 if (garnish) {
2397 static MelderString ts;
2398 const integer lastKnot = ( splineType == kMDS_splineType::I_SPLINE ? numberOfKnots - 2 : numberOfKnots );
2399 Graphics_drawInnerBox (g);
2400 Graphics_textLeft (g, false, ( splineType == kMDS_splineType::M_SPLINE ? U"\\s{M}\\--spline" : U"\\s{I}\\--spline" ));
2401 Graphics_marksTop (g, 2, true, true, false);
2402 Graphics_marksLeft (g, 2, true, true, false);
2403 if (low <= knot [order]) {
2404 if (order == 1)
2405 MelderString_copy (& ts, U"t__1_");
2406 else if (order == 2)
2407 MelderString_copy (& ts, U"{t__1_, t__2_}");
2408 else
2409 MelderString_copy (& ts, U"{t__1_..t__", order, U"_}");
2410 Graphics_markBottom (g, low, false, false, false, ts.string);
2411 }
2412 for (integer i = 1; i <= numberOfInteriorKnots; i ++) {
2413 if (low <= knot [k + i] && knot [k + i] < high) {
2414 MelderString_copy (& ts, U"t__", order + i, U"_");
2415 Graphics_markBottom (g, knot [k + i], false, true, true, ts.string);
2416 Graphics_markTop (g, knot [k + i], true, false, false, nullptr);
2417 }
2418 }
2419 if (knot [lastKnot - order + 1] <= high) {
2420 if (order == 1)
2421 MelderString_copy (& ts, U"t__", lastKnot, U"_");
2422 else
2423 MelderString_copy (& ts, U"{t__", ( order == 2 ? lastKnot - 1 : lastKnot - order + 1 ), U"_, t__", lastKnot, U"_}");
2424 Graphics_markBottom (g, high, false, false, false, ts.string);
2425 }
2426 }
2427 }
2428
2429 void drawMDSClassRelations (Graphics g) {
2430 const integer nBoxes = 6;
2431 const double boxWidth = 0.3, boxWidth2 = boxWidth / 2.0, boxWidth3 = boxWidth / 3.0;
2432 const double boxHeight = 0.1, boxHeight2 = boxHeight / 2.0;
2433 const double boxHeight3 = boxHeight / 3.0;
2434 const double r_mm = 3, dxt = 0.025, dyt = 0.03;
2435 const double dboxx = 1.0 - 0.2 - 2.0 * boxWidth, dboxy = (1.0 - 4.0 * boxHeight) / 3.0;
2436 double x1, x2, xm, x23, x13, y1, y2, ym, y23, y13;
2437 const double x [7] = {0.0, 0.2, 0.2, 0.7, 0.2, 0.7, 0.2}; /* left */
2438 const double y [7] = {0.0, 0.9, 0.6, 0.6, 0.3, 0.3, 0.0}; /* bottom */
2439 const conststring32 text [7] = {U"", U"Confusion", U"Dissimilarity %\\de__%%ij%_", U"Similarity", U"Distance %d__%%ij%_, %d\\'p__%%ij%_", U"ScalarProduct", U"Configuration" };
2440
2441 Graphics_setWindow (g, -0.05, 1.05, -0.05, 1.05);
2442 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
2443 for (integer i = 1; i <= nBoxes; i ++) {
2444 x2 = x [i] + boxWidth;
2445 y2 = y [i] + boxHeight;
2446 xm = x [i] + boxWidth2;
2447 ym = y [i] + boxHeight2;
2448 Graphics_roundedRectangle (g, x [i], x2, y [i], y2, r_mm);
2449 Graphics_text (g, xm, ym, text [i]);
2450 }
2451
2452 Graphics_setLineWidth (g, 2);
2453 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_BOTTOM);
2454
2455 // Confusion to Dissimilarity
2456
2457 xm = x [1] + boxWidth2;
2458 y2 = y [2] + boxHeight;
2459 Graphics_arrow (g, xm, y [1], xm, y2);
2460 Graphics_text (g, xm + dxt, y2 + dboxy / 2, U"pdf");
2461
2462 // Confusion to Similarity
2463
2464 x1 = x [1] + boxWidth;
2465 xm = x [3] + boxWidth2;
2466 ym = y [1] + boxHeight2;
2467 y2 = y [3] + boxHeight;
2468 Graphics_line (g, x1, ym, xm, ym);
2469 Graphics_arrow (g, xm, ym, xm, y2);
2470 y2 += + dboxy / 2 + dyt / 2;
2471 Graphics_text (g, xm + dxt, y2, U"average");
2472 y2 -= dyt;
2473 Graphics_text (g, xm + dxt, y2, U"houtgast");
2474
2475 // Dissimilarity to Similarity
2476
2477 x1 = x [2] + boxWidth;
2478 y23 = y [2] + 2 * boxHeight3;
2479 Graphics_arrow (g, x1, y23, x [3], y23);
2480 y13 = y [2] + boxHeight3;
2481 Graphics_arrow (g, x [3], y13, x1, y13);
2482
2483 // Dissimilarity to Distance
2484
2485 x13 = x [4] + boxWidth3;
2486 y1 = y [4] + boxHeight;
2487 Graphics_arrow (g, x13, y1, x13, y [2]);
2488 x23 = x [4] + 2 * boxWidth3;
2489 Graphics_arrow (g, x23, y [2], x23, y1);
2490
2491 x1 = x23 + dxt;
2492 y1 = y [2] - dyt;
2493 x2 = 0 + dxt;
2494 y1 -= dyt;
2495 Graphics_text (g, x1, y1, U"%d\\'p__%%ij%_ = %\\de__%%ij%_");
2496 Graphics_text (g, x2, y1, U"absolute");
2497 y1 -= dyt;
2498 Graphics_text (g, x1, y1, U"%d\\'p__%%ij%_ = %b\\.c%\\de__%%ij%_");
2499 Graphics_text (g, x2, y1, U"ratio");
2500 y1 -= dyt;
2501 Graphics_text (g, x1, y1, U"%d\\'p__%%ij%_ = %b\\.c%\\de__%%ij%_+%a");
2502 Graphics_text (g, x2, y1, U"interval");
2503 y1 -= dyt;
2504 Graphics_text (g, x1, y1, U"%d\\'p__%%ij%_ = \\s{I}-spline (%\\de__%%ij%_)");
2505 Graphics_text (g, x2, y1, U"\\s{I}\\--spline");
2506 y1 -= dyt;
2507 Graphics_text (g, x1, y1, U"%d\\'p__%%ij%_ = monotone (%\\de__%%ij%_)");
2508 Graphics_text (g, x2, y1, U"monotone");
2509
2510 // Distance to ScalarProduct
2511
2512 x1 = x [4] + boxWidth;
2513 ym = y [4] + boxHeight2;
2514 Graphics_arrow (g, x1, ym, x [5], ym);
2515
2516 // Distance to Configuration
2517
2518 y1 = y [6] + boxHeight;
2519 Graphics_arrow (g, x13, y1, x13, y [4]);
2520
2521 // ScalarProduct to Configuration
2522
2523 x13 = x [5] + boxWidth3;
2524 x23 = x [6] + 2 * boxWidth3;
2525 y1 = y [5] - dboxy / 2;
2526 Graphics_line (g, x13, y [5], x13, y1);
2527 Graphics_line (g, x13, y1, x23, y1);
2528 Graphics_arrow (g, x23, y1, x23, y [6] + boxHeight);
2529 x1 = x [6] + boxWidth + dboxx / 2;
2530 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_BOTTOM);
2531 Graphics_text (g, x1, y1, U"\\s{TORSCA}");
2532 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_TOP);
2533 Graphics_text (g, x1, y1, U"\\s{YTL}");
2534
2535 Graphics_setLineType (g, Graphics_DOTTED);
2536
2537 x23 = x [5] + 2 * boxWidth3;
2538 ym = y [6] + boxHeight2;
2539 Graphics_line (g, x23, y [5], x23, ym);
2540 Graphics_arrow (g, x23, ym, x [6] + boxWidth, ym);
2541 x1 = x [6] + boxWidth + dboxx / 2 + boxWidth3;
2542 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_BOTTOM);
2543 Graphics_text (g, x1, ym, U"\\s{INDSCAL}");
2544
2545 // Dissimilarity to Configuration
2546
2547 ym = y [2] + boxHeight2;
2548 y2 = y [6] + boxHeight2;
2549 Graphics_line (g, x [2], ym, 0, ym);
2550 Graphics_line (g, 0, ym, 0, y2);
2551 Graphics_arrow (g, 0, y2, x [6], y2);
2552
2553 // Restore settings
2554
2555 Graphics_setLineType (g, Graphics_DRAWN);
2556 Graphics_setLineWidth (g, 1.0);
2557 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_BOTTOM);
2558 }
2559
2560 /* End of file MDS.cpp */