Debian Codegraph @

dwtools/Table_extensions.cpp

raw symbols SCIP
1 /* Table_extensions.cpp
2 *
3 * Copyright (C) 1997-2023 David Weenink, 2011-2021,2023,2024,2026 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 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /*
20 djmw 20020619 GPL header
21 djmw 20040113 Added comment header for Peterson& Barney data.
22 djmw 20040512 Corrected Peterson& Barney ARPABET-labeling.
23 djmw 20041213 Added Table_createFromWeeninkData.
24 djmw 20080125 Corrected mislabeling of vowels in the Peterson& Barney dataset according to Watrous
25 djmw 20080508 Labeling back to original PB article.
26 djmw 20110329 Table_get(Numeric|String)Value is now Table_get(Numeric|String)Value_Assert
27 djmw 20131219 Improved Table_scatterPlotWithConfidenceIntervals
28 */
29 /* speaker type (m|w|c), sex(m|f), id, vowel_number, vowel_label
30 F0, F1, F2, F3
31 */
32
33 #include "Discriminant.h"
34 #include "Formula.h"
35 #include "GraphicsP.h"
36 #include "Graphics_extensions.h"
37 #include "Index.h"
38 #include "Matrix_extensions.h"
39 #include "NUM2.h"
40 #include "Strings_extensions.h"
41 #include "Covariance.h"
42 #include "Table_extensions.h"
43
44 autoTable FileInMemorySet_downto_Table (FileInMemorySet me, bool openFilesOnly) {
45 try {
46 const integer numberOfRows = my size; // FIXME: try open files only
47 const conststring32 columnNames [] = { U"path", U"size", U"position" };
48 autoTable thee = Table_createWithColumnNames (numberOfRows, ARRAY_TO_STRVEC (columnNames));
49 for (integer irow = 1; irow <= numberOfRows; irow ++) {
50 const FileInMemory fim = my at [irow]; // FIXME: try open files only
51 Table_setStringValue (thee.get(), irow, 1, fim -> string.get());
52 Table_setNumericValue (thee.get(), irow, 2, fim -> d_numberOfBytes);
53 Table_setNumericValue (thee.get(), irow, 3, fim -> d_position);
54 }
55 return thee;
56 } catch (MelderError) {
57 Melder_throw (me, U": no Table created.");
58 }
59 }
60
61 static bool intervalsIntersect (double x1, double x2, double xmin, double xmax, double *out_xc1, double *out_xc2) {
62 if (x1 > x2)
63 std::swap (x1, x2);
64 if (xmin > xmax)
65 std::swap (xmin, xmax);
66 double xc1 = x1;
67 double xc2 = x2;
68 bool intersect = true;
69 if (x2 <= xmin || x1 >= xmax)
70 intersect = false;
71 else {
72 if (x1 < xmin)
73 xc1 = xmin;
74 if (x2 > xmax)
75 xc2 = xmax;
76 }
77 if (out_xc1)
78 *out_xc1 = xc1;
79 if (out_xc2)
80 *out_xc2 = xc2;
81 return intersect;
82 }
83
84 void Table_horizontalErrorBarsPlot (Table me, Graphics g, integer xcolumn, integer ycolumn, double xmin, double xmax,
85 double ymin, double ymax, integer xci_min, integer xci_max, double bar_mm, bool garnish)
86 {
87 try {
88 const integer nrows = my rows.size;
89 if (xcolumn < 1 || xcolumn > nrows || ycolumn < 1 || ycolumn > nrows ||
90 (xci_min != 0 && xci_min > nrows) || (xci_max != 0 && xci_max > nrows))
91 return;
92 if (ymin >= ymax) {
93 Table_getExtrema (me, ycolumn, & ymin, & ymax);
94 if (ymin >= ymax) {
95 ymin -= 1.0;
96 ymax += 1.0;
97 }
98 }
99 double x1min, x1max;
100 if (xmin >= xmax) {
101 Table_getExtrema (me, xcolumn, & xmin, & xmax);
102 if (xci_min > 0) {
103 Table_getExtrema (me, xci_min, & x1min, & x1max);
104 xmin -= x1max;
105 }
106 if (xci_max > 0) {
107 Table_getExtrema (me, xci_max, & x1min, & x1max);
108 xmax += x1max;
109 }
110 if (xmin >= xmax) {
111 xmin -= 1.0;
112 xmax += 1.0;
113 }
114 }
115 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
116 Graphics_setInner (g);
117 double dy = Graphics_dyMMtoWC (g, bar_mm);
118 for (integer irow = 1; irow <= my rows.size; irow ++) {
119 const double x = Table_getNumericValue_a (me, irow, xcolumn);
120 const double y = Table_getNumericValue_a (me, irow, ycolumn);
121 const double dx1 =
122 xci_min > 0 ? Table_getNumericValue_a (me, irow, xci_min) : 0.0;
123 const double dx2 =
124 xci_max > 0 ? Table_getNumericValue_a (me, irow, xci_max) : 0.0;
125 const double x1 = x - dx1, x2 = x + dx2;
126
127 if (x <= xmax && x >= xmin && y <= ymax && y >= ymin) {
128 double xc1, yc1, xc2, yc2;
129 if (intervalsIntersect (x1, x2, xmin, xmax, & xc1, & xc2)) {
130 Graphics_line (g, xc1, y, xc2, y);
131 if (dy > 0 && intervalsIntersect (y - dy / 2.0, y + dy / 2.0, ymin, ymax, & yc1, & yc2)) {
132 if (xc1 >= xmin && dx1 > 0.0)
133 Graphics_line (g, xc1, yc1, xc1, yc2);
134 if (xc2 <= xmax && dx2 > 0.0)
135 Graphics_line (g, xc2, yc1, xc2, yc2);
136 }
137 }
138 }
139 }
140 Graphics_unsetInner (g);
141
142 if (garnish) {
143 Graphics_drawInnerBox (g);
144 Graphics_marksLeft (g, 2, true, true, false);
145 Graphics_marksBottom (g, 2, true, true, false);
146 }
147 } catch (MelderError) {
148 Melder_clearError ();
149 }
150 }
151
152 void Table_verticalErrorBarsPlot (Table me, Graphics g,
153 integer xcolumn, integer ycolumn, double xmin, double xmax,
154 double ymin, double ymax, integer yci_min, integer yci_max,
155 double bar_mm, bool garnish)
156 {
157 try {
158 const integer nrows = my rows.size;
159 if (xcolumn < 1 || xcolumn > nrows || ycolumn < 1 || ycolumn > nrows ||
160 (yci_min != 0 && yci_min > nrows) || (yci_max != 0 && yci_max > nrows))
161 return;
162 if (xmin >= xmax) {
163 Table_getExtrema (me, ycolumn, & ymin, & ymax);
164 if (xmin >= xmax) {
165 xmin -= 1.0;
166 xmax += 1.0;
167 }
168 }
169 if (ymin >= ymax) {
170 double y1min, y1max;
171 Table_getExtrema (me, ycolumn, & ymin, & ymax);
172 if (yci_min > 0.0) {
173 Table_getExtrema (me, yci_min, & y1min, & y1max);
174 ymin -= y1max;
175 }
176 if (yci_max > 0.0) {
177 Table_getExtrema (me, yci_max, & y1min, & y1max);
178 ymax += y1max;
179 }
180 if (ymin >= ymax) {
181 ymin -= 1.0;
182 ymax += 1.0;
183 }
184 }
185 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
186 Graphics_setInner (g);
187 const double dx = Graphics_dxMMtoWC (g, bar_mm);
188 for (integer irow = 1; irow <= my rows.size; irow ++) {
189 const double x = Table_getNumericValue_a (me, irow, xcolumn);
190 const double y = Table_getNumericValue_a (me, irow, ycolumn);
191 const double dy1 =
192 yci_min > 0 ? Table_getNumericValue_a (me, irow, yci_min) : 0.0;
193 const double dy2 =
194 yci_max > 0 ? Table_getNumericValue_a (me, irow, yci_max) : 0.0;
195 const double y1 = y - dy1, y2 = y + dy2;
196
197 if (x <= xmax && x >= xmin && y <= ymax && y >= ymin) {
198 double xc1, yc1, xc2, yc2;
199 if (intervalsIntersect (y1, y2, ymin, ymax, & yc1, & yc2)) {
200 Graphics_line (g, x, yc1, x, yc2);
201 if (dx > 0 && intervalsIntersect (x - dx / 2.0, x + dx / 2.0, xmin, xmax, & xc1, & xc2)) {
202 if (yc1 >= ymin && dy1 > 0.0)
203 Graphics_line (g, xc1, yc1, xc2, yc1);
204 if (yc2 <= ymax && dy2 > 0.0)
205 Graphics_line (g, xc1, yc2, xc2, yc2);
206 }
207 }
208 }
209 }
210 Graphics_unsetInner (g);
211
212 if (garnish) {
213 Graphics_drawInnerBox (g);
214 Graphics_marksLeft (g, 2, true, true, false);
215 Graphics_marksBottom (g, 2, true, true, false);
216 }
217 } catch (MelderError) {
218 Melder_clearError ();
219 }
220 }
221
222 double Table_getMedianAbsoluteDeviation (Table me, integer columnNumber) {
223 try {
224 autoVEC data = Table_getColumnVector (me, columnNumber);
225 double mad, location;
226 autoVEC workSpace = raw_VEC (data.size);
227 NUMmad (data.get(), & location, true, & mad, workSpace.get());
228 return mad;
229 } catch (MelderError) {
230 Melder_throw (me, U": cannot compute median absolute deviation of column ", columnNumber, U".");
231 }
232 }
233
234 autoVEC Table_getColumnVector (Table me, integer columnNumber) {
235 try {
236 Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
237 Table_numericize_a (me, columnNumber);
238 Melder_require (my rows.size > 0,
239 U"The table is empty.");
240 autoVEC result = raw_VEC (my rows.size);
241 for (integer irow = 1; irow <= my rows.size; irow ++) {
242 const TableRow row = my rows.at [irow];
243 result [irow] = row -> cells [columnNumber].number;
244 Melder_require (isdefined (result [irow]),
245 U"The cell in row ", irow, U" of column ", Table_messageColumn (me, columnNumber), U" is undefined.");
246 }
247 return result;
248 } catch (MelderError) {
249 Melder_throw (me, U": cannot get column vector.");
250 }
251 }
252
253 void Table_reportHuberMStatistics (Table me, integer columnNumber, double k_std, double tol, double *out_location, double *out_scale, integer maximumNumberOfIterations) {
254 try {
255 autoVEC data = Table_getColumnVector (me, columnNumber);
256 double location, scale;
257 autoVEC workSpace = raw_VEC (data.size);
258 NUMstatistics_huber (data.get(), & location, true, & scale, true, k_std, tol, maximumNumberOfIterations, workSpace.get());
259 if (out_location)
260 *out_location = location;
261 if (out_scale)
262 *out_scale = scale;
263 } catch (MelderError) {
264 Melder_throw (me, U": cannot compute median absolute deviation of column ", columnNumber, U".");
265 }
266 }
267
268 autoTable Table_getOneWayKruskalWallis (Table me, integer column, integer factorColumn, double *out_prob, double *out_kruskalWallis, double *out_df) {
269 try {
270 Melder_require (column > 0 && column <= my numberOfColumns,
271 U"Invalid column number.");
272 Melder_require (factorColumn > 0 && factorColumn <= my numberOfColumns && factorColumn != column,
273 U"Invalid group column number.");
274
275 const integer numberOfData = my rows.size;
276 Table_numericize_a (me, column);
277 autoVEC data = raw_VEC (numberOfData);
278 autoStringsIndex levels = Table_to_StringsIndex_column (me, factorColumn, kStrings_sorting::NUMBER_AWARE);
279 const integer numberOfLevels = levels -> classes->size;
280
281 Melder_require (numberOfLevels > 1,
282 U"There should be at least two levels.");
283
284 for (integer irow = 1; irow <= numberOfData; irow ++)
285 data [irow] = my rows.at [irow] -> cells [column]. number;
286
287 NUMsortTogether (data.get(), levels -> classIndex.get());
288 VECrankSorted (data.get());
289 /*
290 Get correctionfactor for ties (Hays pg. 831)
291 W. Hays (1988), Statistics, Fourth edition, Sauders college publishing.
292 */
293 longdouble c = 0.0;
294 integer jt, j = 1;
295 while (j < numberOfData) {
296 for (jt = j + 1; jt <= numberOfData && data [jt] == data [j]; jt ++);
297 const double multiplicity = jt - j;
298 if (multiplicity > 1)
299 c += multiplicity * (multiplicity *multiplicity - 1.0);
300 j = jt;
301 }
302 const double tiesCorrection = 1.0 - (double) c / (numberOfData * (numberOfData * numberOfData - 1.0));
303
304 autoINTVEC factorLevelSizes = zero_INTVEC (numberOfLevels);
305 autoVEC factorLevelSums = zero_VEC (numberOfLevels);
306 autoINTVEC ties = zero_INTVEC (numberOfLevels);
307 for (integer i = 1; i <= numberOfData; i ++) {
308 const integer index = levels -> classIndex [i];
309 factorLevelSizes [index] ++;
310 factorLevelSums [index] += data [i];
311 }
312
313 longdouble kruskalWallis = 0.0;
314 for (integer level = 1; level <= numberOfLevels; level ++) {
315 if (factorLevelSizes [level] < 2) {
316 SimpleString ss = (SimpleString) levels -> classes->at [level]; // FIXME cast
317 Melder_throw (U"Group ", ss -> string.get(), U" has fewer than two cases.");
318 }
319 /*
320 factorLevelMeans * groupMean * factorLevelSizes
321 */
322 kruskalWallis += factorLevelSums [level] * factorLevelSums [level] / factorLevelSizes [level];
323 }
324 kruskalWallis = (12.0 / (numberOfData * (numberOfData + 1.0))) * kruskalWallis - 3.0 * (numberOfData + 1);
325 kruskalWallis /= tiesCorrection;
326 const double df = numberOfLevels - 1.0;
327 if (out_df)
328 *out_df = df;
329 if (out_kruskalWallis)
330 *out_kruskalWallis = (double) kruskalWallis;
331 if (out_prob)
332 *out_prob = NUMchiSquareQ ((double) kruskalWallis, df);
333
334 const conststring32 columnNames [] = { U"Group(R)", U"Sums(R)", U"Cases" };
335 autoTable him = Table_createWithColumnNames (numberOfLevels, ARRAY_TO_STRVEC (columnNames));
336 for (integer irow = 1; irow <= numberOfLevels; irow ++) {
337 const SimpleString ss = (SimpleString) levels -> classes->at [irow];
338 Table_setStringValue (him.get(), irow, 1, ss -> string.get());
339 Table_setNumericValue (him.get(), irow, 2, factorLevelSums [irow]);
340 Table_setNumericValue (him.get(), irow, 3, factorLevelSizes [irow]);
341 }
342 Table_numericize_a (him.get(), 2);
343 Table_numericize_a (him.get(), 3);
344 return him;
345 } catch (MelderError) {
346 Melder_throw (me, U": no one-way Kruskal-Wallis performed.");
347 }
348 }
349
350 // Table with Group Means Cases
351 static void _Table_postHocTukeyHSD (Table me, double sumOfSquaresWithin, double degreesOfFreedomWithin, autoTable *out_meansDiff, autoTable *out_meansDiffProbabilities) {
352 try {
353 Table_numericize_a (me, 2);
354 Table_numericize_a (me, 3);
355 const integer numberOfMeans = my rows.size;
356 autoVEC means = raw_VEC (numberOfMeans);
357 autoVEC cases = raw_VEC (numberOfMeans);
358 autoTable meansD = Table_create (numberOfMeans - 1, numberOfMeans);
359 for (integer i = 1; i <= numberOfMeans; i ++) {
360 const TableRow row = my rows.at [i];
361 means [i] = row -> cells [2]. number;
362 cases [i] = row -> cells [3]. number;
363 }
364 for (integer i = 1; i <= numberOfMeans - 1; i ++) {
365 Table_setStringValue (meansD.get(), i, 1, my rows.at [i] -> cells [1]. string.get());
366 Table_renameColumn_e (meansD.get(), i + 1, my rows.at [i + 1] -> cells [1]. string.get());
367 }
368
369 for (integer irow = 1; irow <= numberOfMeans - 1; irow ++) {
370 for (integer icol = irow + 1; icol <= numberOfMeans; icol ++) {
371 const double dif = fabs (means [irow] - means [icol]);
372 Table_setNumericValue (meansD.get(), irow, icol, dif);
373 }
374 }
375 autoTable meansP = Data_copy (meansD.get());
376 for (integer irow = 1; irow <= numberOfMeans - 1; irow ++) {
377 for (integer icol = irow + 1; icol <= numberOfMeans; icol ++) {
378 /*
379 Tukey-Kramer correction for unequal sample sizes
380 */
381 const double oneOverNstar = 0.5 * (1.0 / cases [icol] + 1.0 / cases [irow]);
382 const double s = sqrt (sumOfSquaresWithin * oneOverNstar);
383 const double q = fabs (means [irow] - means [icol]) / s;
384 const double p = NUMtukeyQ (q, numberOfMeans, degreesOfFreedomWithin, 1);
385 Table_setNumericValue (meansP.get(), irow, icol, p);
386 }
387 }
388 if (out_meansDiff)
389 *out_meansDiff = meansD.move();
390 if (out_meansDiffProbabilities)
391 *out_meansDiffProbabilities = meansP.move();
392 } catch (MelderError) {
393 Melder_throw (me, U": no post-hoc performed.");
394 }
395 }
396
397 // expect 6 columns, first text others numeric
398 void Table_printAsAnovaTable (Table me) {
399 autoMelderString s;
400 const integer width [7] = { 0, 25, 15, 10, 15, 10, 10 };
401 if (my numberOfColumns < 6)
402 return;
403 MelderInfo_writeLine (
404 Melder_padLeft (U"Source", width [1]), U"\t",
405 Melder_padLeft (U"SS", width [2]), U"\t",
406 Melder_padLeft (U"Df", width [3]), U"\t",
407 Melder_padLeft (U"MS", width [4]), U"\t",
408 Melder_padLeft (U"F", width [5]), U"\t",
409 Melder_padLeft (U"P", width [6])
410 );
411 for (integer icol = 2; icol <= 6; icol ++)
412 Table_numericize_a (me, icol);
413
414 for (integer i = 1; i <= my rows.size; i ++) {
415 const TableRow row = my rows.at [i];
416 MelderString_copy (& s, Melder_padOrTruncateLeft (row -> cells [1]. string.get(), width [1]), U"\t");
417 for (integer j = 2; j <= 6; j ++) {
418 const double value = row -> cells [j]. number;
419 if (isdefined (value))
420 MelderString_append (& s, Melder_padLeft (Melder_single (value), width [j]), j == 6 ? U"" : U"\t");
421 else
422 MelderString_append (& s, Melder_padLeft (U"", width [j]), j == 6 ? U"" : U"\t");
423 }
424 MelderInfo_writeLine (s.string);
425 }
426 }
427
428 void Table_printAsMeansTable (Table me) {
429 autoMelderString s;
430 for (integer icol = 2; icol <= my numberOfColumns; icol ++)
431 Table_numericize_a (me, icol);
432
433 for (integer j = 1; j <= my numberOfColumns; j ++)
434 MelderString_append (& s,
435 Melder_padOrTruncateLeft (( my columnHeaders [j]. label ? my columnHeaders [j]. label.get() : U"" ), 10),
436 ( j == my numberOfColumns ? U"" : U"\t" ));
437
438 MelderInfo_writeLine (s.string);
439 for (integer i = 1; i <= my rows.size; i ++) {
440 const TableRow row = my rows.at [i];
441 MelderString_copy (& s, Melder_padOrTruncateLeft (row -> cells [1]. string.get(), 10), U"\t");
442 for (integer j = 2; j <= my numberOfColumns; j ++) {
443 const double value = row -> cells [j].number;
444 if (isdefined (value))
445 MelderString_append (& s, Melder_padLeft (Melder_half (value), 10),
446 ( j == my numberOfColumns ? U"" : U"\t" ));
447 else
448 MelderString_append (& s, Melder_padLeft (U"", 10), ( j == my numberOfColumns ? U"" : U"\t" ));
449 }
450 MelderInfo_writeLine (s.string);
451 }
452 }
453
454 /*
455 W. Hays (1988), Statistics, Fourth edition, Sauders college publishing.
456 Chapter 10.14 outlines 12 steps to calculate the one-way analysis of variance.
457 */
458 autoTable Table_getOneWayAnalysisOfVarianceF (Table me, integer column, integer factorColumn, autoTable *means, autoTable *meansDiff, autoTable *meansDiffProbabilities) {
459 try {
460 Melder_require (column > 0 && column <= my numberOfColumns,
461 U"Invalid column number.");
462 Melder_require (factorColumn > 0 && factorColumn <= my numberOfColumns && factorColumn != column,
463 U"Invalid group column number.");
464 const integer numberOfData = my rows.size;
465 Table_numericize_a (me, column);
466 autoStringsIndex levels = Table_to_StringsIndex_column (me, factorColumn, kStrings_sorting::NUMBER_AWARE);
467 // copy data from Table
468 autoVEC data = raw_VEC (numberOfData);
469 for (integer irow = 1; irow <= numberOfData; irow ++)
470 data [irow] = my rows.at [irow] -> cells [column]. number;
471 const integer numberOfLevels = levels -> classes->size;
472 Melder_require (numberOfLevels > 1,
473 U"There should be at least two levels.");
474 autoINTVEC factorLevelSizes = zero_INTVEC (numberOfLevels);
475 autoVEC factorLevelMeans = zero_VEC (numberOfLevels);
476
477 const longdouble sumOfSquares = NUMsum2 (data.get()); // step 2
478 const longdouble sumOfRawScores = NUMsum (data.get()); // step 3
479 for (integer i = 1; i <= numberOfData; i ++) {
480 const integer index = levels -> classIndex [i];
481 factorLevelSizes [index] ++;
482 factorLevelMeans [index] += data [i];
483 }
484
485 longdouble c = 0.0; // step 5.
486 for (integer j = 1; j <= numberOfLevels; j ++) {
487 if (factorLevelSizes [j] < 2) {
488 const SimpleString ss = (SimpleString) levels -> classes->at [j];
489 Melder_throw (U"Level \"", ss -> string.get(), U"\" has less then two members.");
490 }
491 c += factorLevelMeans [j] * factorLevelMeans [j] / factorLevelSizes [j]; // order of these two is important!
492 factorLevelMeans [j] /= factorLevelSizes [j];
493 }
494
495 const double sumOfSquares_total = double (sumOfSquares - sumOfRawScores * sumOfRawScores / numberOfData); // step 6
496 const double sumOfSquares_between = double (c - sumOfRawScores * sumOfRawScores / numberOfData); // step 7
497 const double sumOfSquares_within = double (sumOfSquares - c); // step 8
498 const double degreesOfFreedom_within = numberOfData - numberOfLevels;
499 const double degreesOfFreedom_between = numberOfLevels - 1;
500
501 const conststring32 anovaColumnNames [] = { U"Source", U"SS", U"Df", U"MS", U"F", U"P" };
502 autoTable anova = Table_createWithColumnNames (3, ARRAY_TO_STRVEC (anovaColumnNames));
503 const integer col_s = 1, col_ss = 2, col_df = 3, col_ms = 4, col_f = 5, col_p = 6;
504 const integer row_b = 1, row_w = 2, row_t = 3;
505 Table_setStringValue (anova.get(), row_b, col_s, U"Between");
506 Table_setStringValue (anova.get(), row_w, col_s, U"Within");
507 Table_setStringValue (anova.get(), row_t, col_s, U"Total");
508
509 Table_setNumericValue (anova.get(), row_b, col_ss, sumOfSquares_between);
510 Table_setNumericValue (anova.get(), row_b, col_df, degreesOfFreedom_between);
511 const double ms_between = sumOfSquares_between / degreesOfFreedom_between; // step 9
512 Table_setNumericValue (anova.get(), row_b, col_ms, ms_between);
513
514 Table_setNumericValue (anova.get(), row_w, col_ss, sumOfSquares_within);
515 Table_setNumericValue (anova.get(), row_w, col_df, degreesOfFreedom_within);
516 const double ms_within = sumOfSquares_within / degreesOfFreedom_within; // step 10
517 Table_setNumericValue (anova.get(), row_w, col_ms, ms_within);
518 const double fisherF = ms_between / ms_within; // step 11
519 const double probability = NUMfisherQ (fisherF, degreesOfFreedom_between, degreesOfFreedom_within); // step 12
520
521 Table_setNumericValue (anova.get(), row_b, col_f, fisherF);
522 Table_setNumericValue (anova.get(), row_b, col_p, probability);
523
524 Table_setNumericValue (anova.get(), row_t, col_ss, sumOfSquares_total);
525 Table_setNumericValue (anova.get(), row_t, col_df, degreesOfFreedom_within + degreesOfFreedom_between);
526
527 const conststring32 ameansColumnNames [] = { U"Group", U"Mean", U"Cases" };
528 autoTable ameans = Table_createWithColumnNames (numberOfLevels, ARRAY_TO_STRVEC (ameansColumnNames));
529 for (integer irow = 1; irow <= numberOfLevels; irow ++) {
530 const SimpleString name = (SimpleString) levels -> classes->at [irow];
531 Table_setStringValue (ameans.get(), irow, 1, name -> string.get());
532 Table_setNumericValue (ameans.get(), irow, 2, factorLevelMeans [irow]);
533 Table_setNumericValue (ameans.get(), irow, 3, factorLevelSizes [irow]);
534 }
535 const integer sortingColumns [] = { 2 }; // sort by column 2
536 Table_sortRows_a (ameans.get(), ARRAY_TO_INTVEC (sortingColumns));
537 _Table_postHocTukeyHSD (ameans.get(), ms_within, degreesOfFreedom_within, meansDiff, meansDiffProbabilities);
538 if (means)
539 *means = ameans.move();
540 return anova;
541 } catch (MelderError) {
542 Melder_throw (me, U": no one-way anova performed.");
543 }
544 }
545
546 autoTable Table_getTwoWayAnalysisOfVarianceF (Table me, integer column, integer factorColumnA, integer factorColumnB, autoTable *out_means, autoTable *out_levelSizes) {
547 try {
548 Melder_require (column > 0 && column <= my numberOfColumns,
549 U"Invalid column number.");
550 Melder_require (factorColumnA > 0 && factorColumnA <= my numberOfColumns && factorColumnA != column,
551 U"Invalid A group column number.");
552 Melder_require (factorColumnB > 0 && factorColumnB <= my numberOfColumns && factorColumnB != column && factorColumnA != factorColumnB,
553 U"Invalid B group column number.");
554
555 const integer numberOfData = my rows.size;
556 Table_numericize_a (me, column);
557 autoStringsIndex levelsA = Table_to_StringsIndex_column (me, factorColumnA, kStrings_sorting::NUMBER_AWARE);
558 autoStringsIndex levelsB = Table_to_StringsIndex_column (me, factorColumnB, kStrings_sorting::NUMBER_AWARE);
559 /*
560 Copy data from Table
561 */
562 autoVEC data = raw_VEC (numberOfData);
563 for (integer irow = 1; irow <= numberOfData; irow ++)
564 data [irow] = my rows.at [irow] -> cells [column]. number;
565 const integer numberOfLevelsA = levelsA -> classes->size;
566 const integer numberOfLevelsB = levelsB -> classes->size;
567
568
569 conststring32 label_A = my columnHeaders [factorColumnA]. label.get();
570 conststring32 label_B = my columnHeaders [factorColumnB]. label.get();
571 Melder_require (numberOfLevelsA > 1,
572 U"There should be at least two levels in \"", label_A, U"\".");
573 Melder_require (numberOfLevelsB > 1,
574 U"There should be at least two levels in \"", label_B, U"\".");
575
576 /*
577 Formula's according to A. Khuri (1998), Unweighted sums of squares
578 in unbalanced analysis of variance, Journal of Statistical Planning
579 and Inference (74): 135--147.
580
581 Model:
582
583 y [i,j,k] = mu + alpha [i] + beta [j] + gamma [i,j] + eps [i,j,k]
584 i=1..r, j = 1..s, k=1..n [i,j]
585
586 ss(alpha) = nh * s * sum(i=1..r, (ystar [i.]-ystar [..])^2)
587 ss(beta) = nh * r * sum(j=1..s, (ystar [.j]-ystar [..])^2)
588 ss(alpha,beta) = nh * sum (i=1..r, sum (j=1..s, (ymean [ij.]-ystar [i.] - ystar [.j] + ystar [..])^2)),
589
590 where
591
592 nh = r * s / sum (i=1..r, sum (j=1..s, 1/n [ij])),
593 ymean [ij.] = sum (k=1..n [ij], y [ijk]/n [ij])
594 ystar [i.] = sum (j=1..s, ymean [ij.]) / s,
595 ystar [.j] = sum (i=1..r, ymean [ij.]) / r,
596 ystar [..] = sum (i=1..r, sum (j=1..s, ymean [ij.])) / (r * s)
597 */
598
599 autoMAT factorLevelSizes = zero_MAT (numberOfLevelsA + 1, numberOfLevelsB + 1); // sum + weighted sum
600 /*
601 Extra column for ystar [i.], extra row for ystar [.j]
602 */
603 autoMAT factorLevelMeans = zero_MAT (numberOfLevelsA + 1, numberOfLevelsB + 1); // weighted mean + mean
604
605 for (integer k = 1; k <= numberOfData; k ++) {
606 const integer indexA = levelsA -> classIndex [k];
607 const integer indexB = levelsB -> classIndex [k];
608 factorLevelSizes [indexA] [indexB] ++;
609 factorLevelMeans [indexA] [indexB] += data [k];
610 }
611 /*
612 Check for unfilled cells and calculate cell means
613 */
614 longdouble nh = 0.0;
615 for (integer i = 1; i <= numberOfLevelsA; i ++) {
616 for (integer j = 1; j <= numberOfLevelsB; j ++) {
617 SimpleString ai = static_cast <SimpleString> (levelsA -> classes -> at [i]);
618 SimpleString aj = static_cast <SimpleString> (levelsA -> classes -> at [j]);
619 Melder_require (factorLevelSizes [i] [j] > 0,
620 U"Level ", ai -> string.get(), U" of ", aj -> string.get(), U" has no data.");
621 factorLevelMeans [i] [j] /= factorLevelSizes [i] [j];
622 nh += 1.0 / factorLevelSizes [i] [j];
623 }
624 }
625 nh = numberOfLevelsA * numberOfLevelsB / nh;
626 /*
627 Row marginals (ystar [i.])
628 */
629 longdouble sum = 0.0;
630 for (integer i = 1; i <= numberOfLevelsA; i ++) {
631 for (integer j = 1; j <= numberOfLevelsB; j ++) {
632 factorLevelMeans [i] [numberOfLevelsB + 1] += factorLevelMeans [i] [j];
633 sum += factorLevelMeans [i] [j];
634 factorLevelSizes [i] [numberOfLevelsB + 1] += factorLevelSizes [i] [j];
635 }
636 factorLevelMeans [i] [numberOfLevelsB + 1] /= numberOfLevelsB;
637 }
638 const double mean = double (sum) / (numberOfLevelsA * numberOfLevelsB);
639 factorLevelMeans [numberOfLevelsA + 1] [numberOfLevelsB + 1] = mean;
640 factorLevelSizes [numberOfLevelsA + 1] [numberOfLevelsB + 1] = numberOfData;
641 /*
642 Column marginals (ystar [.j])
643 */
644 for (integer j = 1; j <= numberOfLevelsB; j ++) {
645 for (integer i = 1; i <= numberOfLevelsA; i ++) {
646 factorLevelMeans [numberOfLevelsA + 1] [j] += factorLevelMeans [i] [j];
647 factorLevelSizes [numberOfLevelsA + 1] [j] += factorLevelSizes [i] [j];
648 }
649 factorLevelMeans [numberOfLevelsA + 1] [j] /= numberOfLevelsA;
650 }
651 /*
652 The sums of squares
653 */
654 longdouble ss_T = 0.0;
655 for (integer k = 1; k <= numberOfData; k ++) {
656 const double dif = data [k] - mean;
657 ss_T += dif * dif;
658 }
659
660 longdouble ss_A = 0.0;
661 for (integer i = 1; i <= numberOfLevelsA; i ++) {
662 const double dif = factorLevelMeans [i] [numberOfLevelsB + 1] - mean;
663 ss_A += dif * dif;
664 }
665 ss_A *= nh * numberOfLevelsB;
666
667 longdouble ss_B = 0.0;
668 for (integer j = 1; j <= numberOfLevelsB; j ++) {
669 const double dif = factorLevelMeans [numberOfLevelsA + 1] [j] - mean;
670 ss_B += dif * dif;
671 }
672 ss_B *= nh * numberOfLevelsA;
673
674 longdouble ss_AB = 0.0;
675 for (integer i = 1; i <= numberOfLevelsA; i ++) {
676 for (integer j = 1; j <= numberOfLevelsB; j ++) {
677 const double dif = factorLevelMeans [i] [j] - factorLevelMeans [i] [numberOfLevelsB + 1] - factorLevelMeans [numberOfLevelsA + 1] [j] + mean;
678 ss_AB += dif * dif;
679 }
680 }
681 ss_AB *= nh;
682
683 double ss_E = double (ss_T - ss_A - ss_B - ss_AB);
684 /*
685 Are there any replications? If not then the error term is the AB interaction.
686 */
687 bool replications = true;
688 if (factorLevelSizes [numberOfLevelsA + 1] [1] == numberOfLevelsA)
689 replications = false;
690 /*
691 Construct the means Table (numberOfLevelsA+1)x(numberOfLevelsB + 1 + 1)
692 */
693 autoTable ameans = Table_createWithoutColumnNames (numberOfLevelsA + 1, numberOfLevelsB + 1 + 1);
694 for (integer k = 2; k <= numberOfLevelsB + 1; k ++) {
695 const SimpleString name = (SimpleString) levelsB -> classes->at [k - 1];
696 Table_renameColumn_e (ameans.get(), k, name -> string.get());
697 }
698 Table_renameColumn_e (ameans.get(), numberOfLevelsB + 1 + 1, U"Mean");
699 for (integer j = 1; j <= numberOfLevelsA; j ++) {
700 const SimpleString name = (SimpleString) levelsA -> classes->at [j];
701 Table_setStringValue (ameans.get(), j, 1, name -> string.get());
702 }
703 Table_setStringValue (ameans.get(), numberOfLevelsA + 1, 1, U"Mean");
704
705 for (integer i = 1; i <= numberOfLevelsA + 1; i ++)
706 for (integer j = 1; j <= numberOfLevelsB + 1; j ++)
707 Table_setNumericValue (ameans.get(), i, j + 1, factorLevelMeans [i] [j]);
708
709
710 if (out_levelSizes) {
711 autoTable asizes = Data_copy (ameans.get());
712 Table_renameColumn_e (asizes.get(), numberOfLevelsB + 1 + 1, U"Total");
713 Table_setStringValue (asizes.get(), numberOfLevelsA + 1, 1, U"Total");
714 for (integer i = 1; i <= numberOfLevelsA + 1; i ++)
715 for (integer j = 1; j <= numberOfLevelsB + 1; j ++)
716 Table_setNumericValue (asizes.get(), i, j + 1, factorLevelSizes [i] [j]);
717 *out_levelSizes = asizes.move();
718 }
719
720 const conststring32 anovaColumnNames [] = { U"Source", U"SS", U"Df", U"MS", U"F", U"P" };
721 autoTable anova = Table_createWithColumnNames (replications ? 5 : 4, ARRAY_TO_STRVEC (anovaColumnNames));
722 const integer col_s = 1, col_ss = 2, col_df = 3, col_ms = 4, col_f = 5, col_p = 6;
723 const integer row_A = 1, row_B = 2, row_AB = 3, row_E = replications ? 4 : 3, row_t = replications ? 5 : 4;
724 Table_setStringValue (anova.get(), row_A, col_s, label_A);
725 Table_setStringValue (anova.get(), row_B, col_s, label_B);
726 Table_setStringValue (anova.get(), row_AB, col_s, Melder_cat (label_A, U" x ", label_B));
727 if (replications)
728 Table_setStringValue (anova.get(), row_E, col_s, U"Error");
729
730 Table_setStringValue (anova.get(), row_t, col_s, U"Total");
731
732 double dof_A = numberOfLevelsA - 1, ms_A = ss_A / dof_A;
733 Table_setNumericValue (anova.get(), row_A, col_ss, ss_A);
734 Table_setNumericValue (anova.get(), row_A, col_df, dof_A);
735 Table_setNumericValue (anova.get(), row_A, col_ms, ms_A);
736
737 double dof_B = numberOfLevelsB - 1, ms_B = ss_B / dof_B;
738 Table_setNumericValue (anova.get(), row_B, col_ss, ss_B);
739 Table_setNumericValue (anova.get(), row_B, col_df, dof_B);
740 Table_setNumericValue (anova.get(), row_B, col_ms, ms_B);
741
742 const double dof_AB = dof_A * dof_B;
743 double dof_E, ms_E, ms_AB = 0.0;
744 if (replications) {
745 ms_AB = ss_AB / dof_AB;
746 dof_E = numberOfData - dof_A - dof_B - dof_AB - 1;
747 ms_E = ss_E / dof_E;
748 Table_setNumericValue (anova.get(), row_AB, col_ss, ss_AB);
749 Table_setNumericValue (anova.get(), row_AB, col_df, dof_AB);
750 Table_setNumericValue (anova.get(), row_AB, col_ms, ms_AB);
751 } else {
752 ss_E = ss_AB;
753 dof_E = numberOfData - dof_A - dof_B - 1;
754 ms_E = ss_AB / dof_E;
755 }
756 Table_setNumericValue (anova.get(), row_E, col_ss, ss_E);
757 Table_setNumericValue (anova.get(), row_E, col_df, dof_E);
758 Table_setNumericValue (anova.get(), row_E, col_ms, ms_E);
759 Table_setNumericValue (anova.get(), row_t, col_ss, ss_T);
760 Table_setNumericValue (anova.get(), row_t, col_df, numberOfData - 1);
761 /*
762 Get f and p values wrt ms_E
763 */
764 const double f_A = ms_A / ms_E;
765 const double f_B = ms_B / ms_E;
766 const double p_A = NUMfisherQ (f_A, dof_A, dof_E);
767 const double p_B = NUMfisherQ (f_B, dof_B, dof_E);
768 Table_setNumericValue (anova.get(), row_A, col_f, f_A);
769 Table_setNumericValue (anova.get(), row_B, col_f, f_B);
770 Table_setNumericValue (anova.get(), row_A, col_p, p_A);
771 Table_setNumericValue (anova.get(), row_B, col_p, p_B);
772 if (replications) {
773 const double f_AB = ms_AB / ms_E;
774 const double p_AB = NUMfisherQ (f_AB, dof_AB, dof_E);
775 Table_setNumericValue (anova.get(), row_AB, col_f, f_AB);
776 Table_setNumericValue (anova.get(), row_AB, col_p, p_AB);
777 }
778 if (out_means)
779 *out_means = ameans.move();
780 return anova;
781 } catch (MelderError) {
782 Melder_throw (me, U": two-way anova not created.");
783 }
784 }
785
786 void Table_normalProbabilityPlot (Table me, Graphics g, integer column, integer numberOfQuantiles,
787 double numberOfSigmas, double labelSize, conststring32 label, bool garnish)
788 {
789 try {
790 if (column < 1 || column > my numberOfColumns)
791 return;
792 Table_numericize_a (me, column);
793 const integer numberOfData = my rows.size;
794 autoVEC data = raw_VEC (numberOfData);
795 for (integer irow = 1; irow <= numberOfData; irow ++)
796 data [irow] = my rows.at [irow] -> cells [column]. number;
797
798 MelderGaussianStats stats = NUMmeanStdev (data.all());
799 double xmin = 100.0, xmax = -xmin, ymin = 1e308, ymax = -ymin;
800 if (numberOfSigmas != 0) {
801 xmin = -numberOfSigmas;
802 xmax = numberOfSigmas;
803 ymin = stats.mean - numberOfSigmas * stats.stdev;
804 ymax = stats.mean + numberOfSigmas * stats.stdev;
805 }
806 sort_e_VEC_inout (data.get());
807 numberOfQuantiles = numberOfData < numberOfQuantiles ? numberOfData : numberOfQuantiles;
808 autoTableOfReal thee = TableOfReal_create (numberOfQuantiles, 2);
809 TableOfReal_setColumnLabel (thee.get(), 1, U"Normal distribution quantiles");
810 TableOfReal_setColumnLabel (thee.get(), 2, my columnHeaders [column]. label.get());
811 const double un = pow (0.5, 1.0 / numberOfQuantiles);
812 for (integer irow = 1; irow <= numberOfQuantiles; irow ++) {
813 const double ui = irow == 1 ? 1.0 - un : (irow == numberOfQuantiles ? un : (irow - 0.3175) / (numberOfQuantiles + 0.365));
814 const double q = NUMquantile (data.all(), ui);
815 const double zq = - NUMinvGaussQ (ui);
816 thy data [irow] [1] = zq; // along x
817 thy data [irow] [2] = q; // along y
818 if (numberOfSigmas == 0.0) {
819 xmin = zq < xmin ? zq : xmin;
820 xmax = zq > xmax ? zq : xmax;
821 ymin = q < ymin ? q : ymin;
822 ymax = q > ymax ? q : ymax;
823 }
824 }
825
826 TableOfReal_drawScatterPlot (thee.get(), g, 1, 2, 1, numberOfQuantiles, xmin, xmax, ymin, ymax, labelSize, false, label, garnish);
827
828 Graphics_setInner (g);
829 Graphics_setLineType (g, Graphics_DOTTED);
830 Graphics_line (g, xmin, ymin, xmax, ymax);
831 Graphics_setLineType (g, Graphics_DRAWN);
832 Graphics_unsetInner (g);
833
834 } catch (MelderError) {
835 Melder_clearError (); // drawing errors shall be ignored
836 }
837 }
838
839 void Table_quantileQuantilePlot_betweenLevels (Table me, Graphics g,
840 integer dataColumn, integer factorColumn, conststring32 xlevel, conststring32 ylevel, integer numberOfQuantiles,
841 double xmin, double xmax, double ymin, double ymax, double labelSize, conststring32 plotLabel, bool garnish)
842 {
843 try {
844 if (dataColumn < 1 || dataColumn > my numberOfColumns || factorColumn < 1 || factorColumn > my numberOfColumns)
845 return;
846 Table_numericize_a (me, dataColumn);
847 const integer numberOfData = my rows.size;
848 autoVEC xdata = raw_VEC (numberOfData);
849 autoVEC ydata = raw_VEC (numberOfData);
850 integer xnumberOfData = 0, ynumberOfData = 0;
851 for (integer irow = 1; irow <= numberOfData; irow ++) {
852 char32 *label = my rows.at [irow] -> cells [factorColumn]. string.get();
853 const double val = my rows.at [irow] -> cells [dataColumn]. number;
854 if (Melder_equ (label, xlevel))
855 xdata [ ++ xnumberOfData] = val;
856 else if (Melder_equ (label, ylevel))
857 ydata [ ++ ynumberOfData] = val;
858 }
859 if (xnumberOfData == 0 || ynumberOfData == 0)
860 return;
861 xdata. resize (xnumberOfData);
862 ydata. resize (ynumberOfData);
863 if (xmin == xmax) {
864 NUMextrema_u (xdata.part (1, xnumberOfData), & xmin, & xmax);
865 if (xmin == xmax) {
866 xmin -= 1.0;
867 xmax += 1.0;
868 }
869 }
870 if (ymin == ymax) {
871 NUMextrema_u (ydata.part (1, ynumberOfData), & ymin, & ymax);
872 if (ymin == ymax) {
873 ymin -= 1.0;
874 ymax += 1.0;
875 }
876 }
877 if (isundef (xmin) || isundef (xmax) || isundef (ymin) || isundef (ymax))
878 return;
879 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
880 Graphics_setInner (g);
881 Graphics_quantileQuantilePlot (g, numberOfQuantiles, xdata.get(), ydata.get(),
882 xmin, xmax, ymin, ymax, labelSize, plotLabel);
883 Graphics_unsetInner (g);
884 if (garnish) {
885 Graphics_drawInnerBox (g);
886
887 Graphics_textBottom (g, true, Melder_cat (my columnHeaders [dataColumn]. label.get(), U" (", xlevel, U")"));
888 Graphics_marksBottom (g, 2, true, true, false);
889
890 Graphics_textLeft (g, true, Melder_cat (my columnHeaders [dataColumn]. label.get(), U" (", ylevel, U")"));
891 Graphics_marksLeft (g, 2, true, true, false);
892 }
893 } catch (MelderError) {
894 Melder_clearError (); // drawing errors shall be ignored
895 }
896 }
897
898 void Table_quantileQuantilePlot (Table me, Graphics g, integer xcolumn, integer ycolumn, integer numberOfQuantiles,
899 double xmin, double xmax, double ymin, double ymax, double labelSize, conststring32 plotLabel, bool garnish)
900 {
901 try {
902 if (xcolumn < 1 || xcolumn > my numberOfColumns || ycolumn < 1 || ycolumn > my numberOfColumns)
903 return;
904 Table_numericize_a (me, xcolumn);
905 Table_numericize_a (me, ycolumn);
906 const integer numberOfData = my rows.size;
907 autoVEC xdata = raw_VEC (numberOfData);
908 autoVEC ydata = raw_VEC (numberOfData);
909 for (integer irow = 1; irow <= numberOfData; irow ++) {
910 xdata [irow] = my rows.at [irow] -> cells [xcolumn]. number;
911 ydata [irow] = my rows.at [irow] -> cells [ycolumn]. number;
912 }
913 if (xmin == xmax) {
914 NUMextrema_u (xdata.get(), & xmin, & xmax);
915 if (xmin == xmax) {
916 xmin -= 1.0;
917 xmax += 1.0;
918 }
919 }
920 if (ymin == ymax) {
921 NUMextrema_u (ydata.get(), & ymin, & ymax);
922 if (ymin == ymax) {
923 ymin -= 1.0;
924 ymax += 1.0;
925 }
926 }
927 if (isundef (xmin) || isundef (xmax) || isundef (ymin) || isundef (ymax))
928 return;
929 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
930 Graphics_setInner (g);
931 Graphics_quantileQuantilePlot (g, numberOfQuantiles, xdata.get(), ydata.get(),
932 xmin, xmax, ymin, ymax, labelSize, plotLabel);
933 Graphics_unsetInner (g);
934 if (garnish) {
935 Graphics_drawInnerBox (g);
936 if (my columnHeaders [xcolumn].label)
937 Graphics_textBottom (g, true, my columnHeaders [xcolumn]. label.get());
938
939 Graphics_marksBottom (g, 2, true, true, false);
940 if (my columnHeaders [ycolumn].label)
941 Graphics_textLeft (g, true, my columnHeaders [ycolumn]. label.get());
942
943 Graphics_marksLeft (g, 2, true, true, false);
944 }
945 } catch (MelderError) {
946 Melder_clearError (); // drawing errors shall be ignored
947 }
948 }
949
950 void Table_boxPlots (Table me, Graphics g, integer dataColumn, integer factorColumn, double ymin, double ymax, bool garnish) {
951 try {
952 if (dataColumn < 1 || dataColumn > my numberOfColumns || factorColumn < 1 || factorColumn > my numberOfColumns)
953 return;
954 Table_numericize_a (me, dataColumn);
955 const integer numberOfData = my rows.size;
956 autoStringsIndex si = Table_to_StringsIndex_column (me, factorColumn, kStrings_sorting::NUMBER_AWARE);
957 const integer numberOfLevels = si -> classes->size;
958 if (ymin == ymax) {
959 ymax = Table_getMaximum (me, dataColumn);
960 ymin = Table_getMinimum (me, dataColumn);
961 if (ymax == ymin) {
962 ymax += 1.0;
963 ymin -= 1.0;
964 }
965 }
966 Graphics_setWindow (g, 1.0 - 0.5, numberOfLevels + 0.5, ymin, ymax);
967 Graphics_setInner (g);
968 autoVEC data = raw_VEC (numberOfData);
969 for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
970 integer numberOfDataInLevel = 0;
971 for (integer k = 1; k <= numberOfData; k ++)
972 if (si -> classIndex [k] == ilevel)
973 data [++ numberOfDataInLevel] = Table_getNumericValue_a (me, k, dataColumn);
974 Graphics_boxAndWhiskerPlot (g, data.part (1, numberOfDataInLevel), ilevel, 0.2, 0.35, ymin, ymax);
975 }
976 Graphics_unsetInner (g);
977 if (garnish) {
978 Graphics_drawInnerBox (g);
979 for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
980 const SimpleString ss = (SimpleString) si -> classes->at [ilevel];
981 Graphics_markBottom (g, ilevel, false, true, false, ss -> string.get());
982 }
983 Graphics_marksLeft (g, 2, true, true, false);
984 }
985 } catch (MelderError) {
986 Melder_clearError (); // drawing errors shall be ignored
987 }
988 }
989
990 void Table_boxPlots (Table me, Graphics g, constINTVEC const& dataColumnNumbers, integer factorColumnNumber, double ymin, double ymax,
991 bool garnish)
992 {
993 try {
994 const integer numberOfSelectedColumns = dataColumnNumbers.size;
995 if (numberOfSelectedColumns == 0)
996 return;
997 const integer numberOfData = my rows.size;
998 autoStringsIndex si = Table_to_StringsIndex_column (me, factorColumnNumber, kStrings_sorting::NUMBER_AWARE);
999 const integer numberOfLevels = si -> classes->size;
1000 if (ymin == ymax) {
1001 ymin = 1e308, ymax = - ymin;
1002 for (integer icol = 1; icol <= numberOfSelectedColumns; icol ++) {
1003 double ymini = 1e30, ymaxi = - ymini;
1004 Table_getExtrema (me, dataColumnNumbers [icol], & ymini, & ymax);
1005 if (ymaxi > ymax)
1006 ymax = ymaxi;
1007 if (ymini < ymin)
1008 ymin = ymini;
1009 }
1010 if (ymax == ymin) {
1011 ymax += 1.0;
1012 ymin -= 1.0;
1013 }
1014 }
1015 Graphics_setWindow (g, 1.0 - 0.5, numberOfLevels + 0.5, ymin, ymax);
1016 Graphics_setInner (g);
1017 const double boxWidth = 4.0, spaceBetweenBoxesInGroup = 1.0, barWidth = boxWidth / 3.0;
1018 const double spaceBetweenGroupsdiv2 = 3.0 / 2.0;
1019 const double widthUnit = 1.0 / (numberOfSelectedColumns * boxWidth + (numberOfSelectedColumns - 1) * spaceBetweenBoxesInGroup + spaceBetweenGroupsdiv2 + spaceBetweenGroupsdiv2);
1020 autoVEC data = raw_VEC (numberOfData);
1021 for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
1022 const double xlevel = ilevel;
1023 for (integer icol = 1; icol <= numberOfSelectedColumns; icol ++) {
1024 integer numberOfDataInLevelColumn = 0;
1025 for (integer irow = 1; irow <= numberOfData; irow ++)
1026 if (si -> classIndex [irow] == ilevel)
1027 data [++ numberOfDataInLevelColumn] = Table_getNumericValue_a (me, irow, dataColumnNumbers [icol]);
1028 if (numberOfDataInLevelColumn > 0) {
1029 /*
1030 Determine position
1031 */
1032 const double xc = xlevel - 0.5 + (spaceBetweenGroupsdiv2 + (icol - 1) * (boxWidth + spaceBetweenBoxesInGroup) + boxWidth / 2) * widthUnit;
1033 Graphics_boxAndWhiskerPlot (g, data.part (1, numberOfDataInLevelColumn), xc, 0.5 * barWidth * widthUnit , 0.5 * boxWidth * widthUnit, ymin, ymax);
1034 }
1035 }
1036 }
1037 Graphics_unsetInner (g);
1038 if (garnish) {
1039 Graphics_drawInnerBox (g);
1040 for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
1041 const SimpleString ss = (SimpleString) si -> classes->at [ilevel];
1042 Graphics_markBottom (g, ilevel, false, true, false, ss -> string.get());
1043 }
1044 Graphics_marksLeft (g, 2, true, true, false);
1045 }
1046 } catch (MelderError) {
1047 Melder_clearError (); // drawing errors shall be ignored
1048 }
1049 }
1050
1051 void Table_boxPlotsWhere (Table me, Graphics g, constINTVEC const& dataColumnNumbers, integer factorColumnNumber, double ymin, double ymax,
1052 bool garnish, conststring32 formula, Interpreter interpreter)
1053 {
1054 try {
1055 const integer numberOfSelectedColumns = dataColumnNumbers.size;
1056 if (numberOfSelectedColumns == 0)
1057 return;
1058 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
1059 Formula_Result result;
1060 const integer numberOfData = my rows.size;
1061 autoStringsIndex si = Table_to_StringsIndex_column (me, factorColumnNumber, kStrings_sorting::NUMBER_AWARE);
1062 const integer numberOfLevels = si -> classes->size;
1063 if (ymin == ymax) {
1064 ymin = 1e308, ymax = - ymin;
1065 for (integer icol = 1; icol <= numberOfSelectedColumns; icol ++) {
1066 double ymini = 1e308, ymaxi = - ymini;
1067 Table_getExtrema (me, dataColumnNumbers [icol], & ymini, & ymaxi);
1068 if (ymaxi > ymax)
1069 ymax = ymaxi;
1070 if (ymini < ymin)
1071 ymin = ymini;
1072 }
1073 if (ymax == ymin) {
1074 ymax += 1.0;
1075 ymin -= 1.0;
1076 }
1077 }
1078 Graphics_setWindow (g, 1.0 - 0.5, numberOfLevels + 0.5, ymin, ymax);
1079 Graphics_setInner (g);
1080 const double boxWidth = 4.0, spaceBetweenBoxesInGroup = 1.0, barWidth = boxWidth / 3.0;
1081 const double spaceBetweenGroupsdiv2 = 3.0 / 2.0;
1082 const double widthUnit = 1.0 / (numberOfSelectedColumns * boxWidth + (numberOfSelectedColumns - 1) * spaceBetweenBoxesInGroup + spaceBetweenGroupsdiv2 + spaceBetweenGroupsdiv2);
1083 autoVEC data = raw_VEC (numberOfData);
1084 for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
1085 const double xlevel = ilevel;
1086 for (integer icol = 1; icol <= numberOfSelectedColumns; icol ++) {
1087 integer numberOfDataInLevelColumn = 0;
1088 for (integer irow = 1; irow <= numberOfData; irow ++) {
1089 if (si -> classIndex [irow] == ilevel) {
1090 Formula_run (irow, dataColumnNumbers [icol], & result);
1091 if (result. numericResult != 0.0)
1092 data [++ numberOfDataInLevelColumn] = Table_getNumericValue_a (me, irow, dataColumnNumbers [icol]);
1093 }
1094 }
1095 if (numberOfDataInLevelColumn > 0) {
1096 /*
1097 Determine position
1098 */
1099 const double xc = xlevel - 0.5 + (spaceBetweenGroupsdiv2 + (icol - 1) * (boxWidth + spaceBetweenBoxesInGroup) + boxWidth / 2) * widthUnit;
1100 Graphics_boxAndWhiskerPlot (g, data.part (1, numberOfDataInLevelColumn), xc, 0.5 * barWidth * widthUnit , 0.5 * boxWidth * widthUnit, ymin, ymax);
1101 }
1102 }
1103 }
1104 Graphics_unsetInner (g);
1105 if (garnish) {
1106 Graphics_drawInnerBox (g);
1107 for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
1108 const SimpleString ss = (SimpleString) si -> classes->at [ilevel];
1109 Graphics_markBottom (g, ilevel, false, true, false, ss -> string.get());
1110 }
1111 Graphics_marksLeft (g, 2, true, true, false);
1112 }
1113 } catch (MelderError) {
1114 Melder_clearError (); // drawing errors shall be ignored
1115 }
1116 }
1117
1118 void Table_distributionPlot (Table me, Graphics g, integer dataColumn, double minimum, double maximum, integer nBins, double freqMin, double freqMax, bool garnish) {
1119 try {
1120 if (dataColumn < 1 || dataColumn > my numberOfColumns)
1121 return;
1122 Table_numericize_a (me, dataColumn);
1123 integer mrow = 0;
1124 autoMatrix thee = Matrix_create (1.0, 1.0, 1, 1.0, 1.0, 0.0, my rows.size + 1.0, my rows.size, 1.0, 1.0);
1125 for (integer irow = 1; irow <= my rows.size; irow ++)
1126 thy z [1] [++ mrow] = Table_getNumericValue_a (me, irow, dataColumn);
1127 Matrix_drawDistribution (thee.get(), g, 0, 1, 0.5, mrow + 0.5, minimum, maximum, nBins, freqMin, freqMax, false, false);
1128 if (garnish) {
1129 Graphics_drawInnerBox (g);
1130 Graphics_marksBottom (g, 2, true, true, false);
1131 if (my columnHeaders [dataColumn]. label)
1132 Graphics_textBottom (g, true, my columnHeaders [dataColumn]. label.get());
1133 Graphics_marksLeft (g, 2, true, true, false);
1134 Graphics_textLeft (g, true, U"Number / bin");
1135 }
1136 } catch (MelderError) {
1137 Melder_clearError ();
1138 }
1139 }
1140
1141 integer Table_getNumberOfRowsWhere (Table me, conststring32 formula, Interpreter interpreter) {
1142 integer numberOfRows = 0;
1143 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
1144 Formula_Result result;
1145 for (integer irow = 1; irow <= my rows.size; irow ++) {
1146 Formula_run (irow, 1, & result);
1147 if (result. numericResult != 0.0)
1148 numberOfRows ++;
1149 }
1150 return numberOfRows;
1151 }
1152
1153 autoINTVEC Table_listRowNumbersWhere (Table me, conststring32 formula, Interpreter interpreter) {
1154 try {
1155 const integer numberOfMatches = Table_getNumberOfRowsWhere (me, formula, interpreter);
1156 if (numberOfMatches == 0)
1157 return autoINTVEC();
1158 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
1159 Formula_Result result;
1160 autoINTVEC selectedRows = zero_INTVEC (numberOfMatches);
1161 integer n = 0;
1162 for (integer irow = 1; irow <= my rows.size; irow ++) {
1163 Formula_run (irow, 1, & result);
1164 if (result. numericResult != 0.0)
1165 selectedRows [++ n] = irow;
1166 }
1167 Melder_assert (n == numberOfMatches);
1168 return selectedRows;
1169 } catch (MelderError) {
1170 Melder_throw (me, U": cannot find matches.");
1171 }
1172 }
1173
1174 void Table_barPlot (Table me, Graphics g,
1175 constINTVEC columnNumbers, double ymin, double ymax, integer labelColumnNumber,
1176 double xoffsetFraction, double interbarFraction, double interbarsFraction, constSTRVEC colours,
1177 double angle, bool garnish)
1178 {
1179 try {
1180 if (ymax <= ymin) { // autoscaling
1181 ymin = 1e308;
1182 ymax = - ymin;
1183 for (integer icol = 1; icol <= columnNumbers.size; icol ++) {
1184 double cmin, cmax;
1185 Table_getExtrema (me, columnNumbers [icol], & cmin, & cmax);
1186 if (cmin < ymin)
1187 ymin = cmin;
1188 if (cmax > ymax)
1189 ymax = cmax;
1190 }
1191 Melder_clipRight (& ymin, 0.0);
1192 Melder_clipLeft (0.0, & ymax);
1193 }
1194 if (ymin == ymax)
1195 return; // Table still could have equal or zero entries
1196 Graphics_setInner (g);
1197 Graphics_setWindow (g, 0, 1, ymin, ymax);
1198
1199 const integer numberOfGroups = my rows.size;
1200 const integer groupSize = columnNumbers.size;
1201 const double bar_width = 1.0 / (numberOfGroups * groupSize + 2.0 * xoffsetFraction + (numberOfGroups - 1) * interbarsFraction + numberOfGroups * (groupSize - 1) * interbarFraction);
1202 const double dx = (interbarsFraction + groupSize + (groupSize - 1) * interbarFraction) * bar_width;
1203
1204 for (integer icol = 1; icol <= groupSize; icol ++) {
1205 const double xb = xoffsetFraction * bar_width + (icol - 1) * (1 + interbarFraction) * bar_width;
1206 double x1 = xb;
1207 const integer index = std::min (icol, colours.size);
1208 MelderColour colour = MelderColour_fromColourNameOrNumberStringOrRGBString (colours [index]);
1209 if (! colour.valid())
1210 colour = Melder_GREY;
1211 for (integer irow = 1; irow <= my rows.size; irow ++) {
1212 const double x2 = x1 + bar_width;
1213 const double y2 = Melder_clipped (ymin, Table_getNumericValue_a (me, irow, columnNumbers [icol]), ymax);
1214 const double y1 = Melder_clippedLeft (0.0, ymin);
1215
1216 Graphics_setColour (g, colour);
1217 Graphics_fillRectangle (g, x1, x2, y1, y2);
1218 Graphics_setGrey (g, 0.0); // black
1219 Graphics_rectangle (g, x1, x2, y1, y2);
1220
1221 x1 += dx;
1222 }
1223 }
1224
1225 if (garnish) {
1226 if (labelColumnNumber > 0) {
1227 double y = ymin, xb = (xoffsetFraction + 0.5 * (groupSize + (groupSize - 1) * interbarFraction)) * bar_width;
1228 const double lineSpacing = Graphics_dyMMtoWC (g, 1.5 * Graphics_inqFontSize (g) * 25.4 / 72.0);
1229 const double currentFontSize = Graphics_inqFontSize (g);
1230 Graphics_setTextRotation (g, angle);
1231 if (angle < 0.0) {
1232 y -= 0.3 * lineSpacing;
1233 xb -= 0.5 * bar_width;
1234 Graphics_setFontSize (g, currentFontSize - ( currentFontSize > 12.0 ? 2.0 : 1.0 ));
1235 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_TOP);
1236 } else if (angle > 0.0) {
1237 y -= 0.3*lineSpacing;
1238 xb += 0.5 * bar_width;
1239 Graphics_setFontSize (g, currentFontSize - ( currentFontSize > 12.0 ? 2.0 : 1.0 ));
1240 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_TOP);
1241 } else {
1242 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_TOP);
1243 }
1244 for (integer irow = 1; irow <= numberOfGroups; irow ++) {
1245 conststring32 label = Table_getStringValue_a (me, irow, labelColumnNumber);
1246 if (label)
1247 Graphics_text (g, xb, ymin - g -> vertTick, label); // was y
1248 xb += dx;
1249 }
1250 Graphics_setFontSize (g, currentFontSize);
1251 Graphics_setTextRotation (g, 0);
1252 }
1253 }
1254 Graphics_unsetInner (g);
1255 if (garnish) {
1256 if (ymin * ymax < 0.0)
1257 Graphics_markLeft (g, 0.0, true, true, true, nullptr);
1258 Graphics_drawInnerBox (g);
1259 Graphics_marksLeft (g, 2, true, true, false);
1260 }
1261 } catch (MelderError) {
1262 Melder_clearError (); // drawing errors shall be ignored
1263 }
1264 }
1265
1266 // TODO extra parameter font size
1267 static bool Graphics_getConnectingLine (Graphics g, conststring32 text1, double fontSize, double x1, double y1, conststring32 text2, double x2, double y2, double *x3, double *y3, double *x4, double *y4) {
1268 bool drawLine = false;
1269 const double width1 = Graphics_textWidth (g, text1);
1270 const double width2 = Graphics_textWidth (g, text2);
1271 const double h = Graphics_dyMMtoWC (g, 1.5 * fontSize * 25.4 / 72.0) / 1.5;
1272 const double xleft = x1 < x2 ? x1 : x2, xright = x2 > x1 ? x2 : x1;
1273 double xi [3], yi [3];
1274 int numberOfIntersections = NUMgetIntersectionsWithRectangle (x1, y1, x2, y2, xleft - width1 / 2.0, y1 - h/2, xleft + width1 / 2.0, y1 + h/2, xi, yi);
1275 if (numberOfIntersections == 1) {
1276 *x3 = xi [1];
1277 *y3 = yi [1];
1278 numberOfIntersections = NUMgetIntersectionsWithRectangle (x1, y1, x2, y2, xright - width2 / 2.0, y2 - h/2, xright + width2 / 2.0, y2 + h/2, xi, yi);
1279 if (numberOfIntersections == 1) {
1280 *x4 = xi [1];
1281 *y4 = yi [1];
1282 drawLine = true;
1283 }
1284 }
1285 return drawLine;
1286 }
1287
1288 /*
1289 Take the xcolumn as labels if non-numeric column else as numbers and arrange distances accordingly.
1290 TODO We need an extra argument Label size!
1291 */
1292 void Table_lineGraph (Table me, Graphics g, integer xcolumn, double xmin, double xmax, integer ycolumn, double ymin, double ymax, conststring32 symbol, double symbolFontSize, double angle, bool garnish) {
1293 try {
1294 if (ycolumn < 1 || ycolumn > my numberOfColumns || xcolumn < 0 || xcolumn > my numberOfColumns)
1295 return;
1296 if (ymax <= ymin)
1297 Table_getExtrema (me, ycolumn, & ymin, & ymax);
1298
1299 bool xIsNumeric = true;
1300 for (integer irow = 1; irow <= my rows.size; irow ++)
1301 if (! Table_isCellNumeric_ErrorFalse (me, irow, xcolumn)) {
1302 xIsNumeric = false;
1303 break;
1304 }
1305 if (xmin >= xmax) {
1306 if (xIsNumeric)
1307 Table_getExtrema (me, xcolumn, & xmin, & xmax);
1308 else {
1309 xmin = 0.0;
1310 xmax = my rows.size + 1;
1311 }
1312 }
1313 double currentFontSize = Graphics_inqFontSize (g);
1314 Graphics_setInner (g);
1315 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1316 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1317 const double lineSpacing = Graphics_dyMMtoWC (g, 1.5 * Graphics_inqFontSize (g) * 25.4 / 72.0);
1318 //double symbolHeight = lineSpacing / 1.5;
1319 double x1, y1;
1320 Graphics_setFontSize (g, symbolFontSize);
1321 for (integer irow = 1; irow <= my rows.size; irow ++) {
1322 const double y2 = Table_getNumericValue_a (me, irow, ycolumn);
1323 double x2 = xIsNumeric ? Table_getNumericValue_a (me, irow, xcolumn) : irow;
1324 //double symbolWidth = 0;
1325 if (x2 >= xmin && (x2 <= xmax || x1 < xmax)) {
1326 if (symbol && y2 >= ymin && y2 <= ymax && x2 <= xmax)
1327 Graphics_text (g, x2, y2, symbol);
1328 if (irow > 1) {
1329 double x3, y3, x4, y4, xo1, yo1, xo2, yo2;
1330 if (Graphics_getConnectingLine (g, symbol, symbolFontSize, x1, y1, symbol, x2, y2, & x3, & y3, & x4, & y4) &&
1331 NUMclipLineWithinRectangle (x3, y3, x4, y4, xmin, ymin, xmax, ymax, & xo1, & yo1, & xo2, & yo2))
1332 Graphics_line (g, xo1, yo1, xo2, yo2);
1333 }
1334 } else {
1335 x2 = x2 < xmin ? xmin : xmax;
1336 }
1337 x1 = x2;
1338 y1 = y2;
1339 }
1340 Graphics_setFontSize (g, currentFontSize);
1341
1342 if (garnish && ! xIsNumeric && xcolumn > 0) {
1343 double y = ymin, dx = 0.0;
1344 Graphics_setTextRotation (g, angle);
1345 if (angle < 0.0) {
1346 y -= 0.3 * lineSpacing;
1347 dx = - 0.5;
1348 Graphics_setFontSize (g, currentFontSize - (currentFontSize > 12 ? 2 : 1));
1349 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_TOP);
1350 } else if (angle > 0.0) {
1351 y -= 0.3 * lineSpacing;
1352 dx = 0.5;
1353 Graphics_setFontSize (g, currentFontSize - (currentFontSize > 12 ? 2 : 1));
1354 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_TOP);
1355 } else {
1356 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_TOP);
1357 }
1358 for (integer irow = 1; irow <= my rows.size; irow ++) {
1359 const double x2 = double (irow);
1360 if (x2 >= xmin && x2 <= xmax) {
1361 conststring32 label = Table_getStringValue_a (me, irow, xcolumn);
1362 if (label)
1363 Graphics_text (g, x2 + dx, ymin - g -> vertTick, label); // was y
1364 }
1365 }
1366 Graphics_setFontSize (g, currentFontSize);
1367 Graphics_setTextRotation (g, 0);
1368 }
1369 Graphics_unsetInner (g);
1370
1371 if (garnish) {
1372 Graphics_drawInnerBox (g);
1373 Graphics_marksLeft (g, 2, true, true, false);
1374 if (xIsNumeric)
1375 Graphics_marksBottom (g, 2, true, true, false);
1376 }
1377 } catch (MelderError) {
1378 Melder_clearError (); // drawing errors shall be ignored
1379 }
1380 }
1381
1382 void Table_lineGraph_old (Table me, Graphics g, integer xcolumn, double xmin, double xmax, integer ycolumn, double ymin, double ymax, conststring32 symbol, double angle, bool garnish) {
1383 double fontSize = Graphics_inqFontSize (g);
1384 Table_lineGraph (me, g, xcolumn, xmin, xmax, ycolumn, ymin, ymax, symbol, fontSize, angle, garnish);
1385 }
1386
1387 void Table_lagPlot (Table me, Graphics g, integer column, integer lag, double xmin, double xmax,
1388 conststring32 symbol, double labelSize, bool garnish)
1389 {
1390 try {
1391 if (column < 1 || column > my rows.size)
1392 return;
1393 if (xmax <= xmin) // autoscaling
1394 Table_getExtrema (me, column, & xmin, & xmax);
1395 autoVEC x = raw_VEC (my rows.size);
1396 for (integer irow = 1; irow <= my rows.size; irow ++)
1397 x [irow] = Table_getNumericValue_a (me, irow, column);
1398 Graphics_setInner (g);
1399 Graphics_setWindow (g, xmin, xmax, xmin, xmax);
1400 Graphics_lagPlot (g, x.get(), xmin, xmax, lag, labelSize, symbol);
1401 Graphics_unsetInner (g);
1402 if (garnish) {
1403 Graphics_drawInnerBox (g);
1404 Graphics_marksBottom (g, 2, true, true, false);
1405 Graphics_marksLeft (g, 2, true, true, false);
1406 if (my columnHeaders [column].label) {
1407 Graphics_textLeft (g, true, my columnHeaders [column].label.get());
1408 Graphics_textBottom (g, true, Melder_cat (my columnHeaders [column]. label.get(), U" (lag = ", lag, U")"));
1409 }
1410 }
1411 } catch (MelderError) {
1412 Melder_clearError (); // drawing errors shall be ignored
1413 }
1414 }
1415
1416 autoTable Table_extractRowsWhere (Table me, conststring32 formula, Interpreter interpreter) {
1417 try {
1418 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
1419 Formula_Result result;
1420 autoTable thee = Table_create (0, my numberOfColumns);
1421 for (integer icol = 1; icol <= my numberOfColumns; icol ++)
1422 thy columnHeaders [icol].label = Melder_dup (my columnHeaders [icol].label.get());
1423 for (integer irow = 1; irow <= my rows.size; irow ++) {
1424 Formula_run (irow, 1, & result);
1425 if (result. numericResult != 0.0) {
1426 const TableRow row = my rows.at [irow];
1427 autoTableRow newRow = Data_copy (row);
1428 thy rows. addItem_move (newRow.move());
1429 }
1430 }
1431 return thee;
1432 } catch (MelderError) {
1433 Melder_throw (me, U": no Table could be extracted.");
1434 }
1435 }
1436
1437
1438 autoTable Table_extractRowsWhere_e (Table me, conststring32 formula, Interpreter interpreter) {
1439 try {
1440 autoTable result = Table_extractRowsWhere (me, formula, interpreter);
1441 Melder_require (result -> rows.size > 0,
1442 U"No row matches criterion.");
1443 return result;
1444 } catch (MelderError) {
1445 Melder_throw (me, U": no Table could be extracted.");
1446 }
1447 }
1448
1449 static autoTableOfReal Table_to_TableOfReal_selectedColumns (Table me, INTVEC const& columnNumbers, integer labelColumnNumber) {
1450 try {
1451 Melder_require (columnNumbers.size > 0,
1452 U"No columns selected.");
1453 if (labelColumnNumber != 0)
1454 Melder_require (labelColumnNumber > 0 && labelColumnNumber <= my numberOfColumns,
1455 U"The label column number (", labelColumnNumber, U") in not valid.");
1456 autoTableOfReal thee = TableOfReal_create (my rows.size, columnNumbers.size);
1457 for (integer irow = 1; irow <= my rows.size; irow ++) {
1458 for (integer icol = 1; icol <= columnNumbers.size; icol ++)
1459 thy data [irow] [icol] = Table_getNumericValue_a (me, irow, columnNumbers [icol]);
1460 if (labelColumnNumber > 0)
1461 TableOfReal_setRowLabel (thee.get(), irow, Table_getStringValue_a (me, irow, labelColumnNumber));
1462 }
1463 for (integer icol = 1; icol <= columnNumbers.size; icol ++)
1464 TableOfReal_setColumnLabel (thee.get(), icol, my columnHeaders [columnNumbers [icol]].label.get());
1465 return thee;
1466 } catch (MelderError) {
1467 Melder_throw (me, U": could not create TableOfReal for selected columns.");
1468 }
1469 }
1470
1471 static integer SSCPList_findIndexOfGroupLabel (SSCPList me, conststring32 label) {
1472 for (integer i = 1; i <= my size; i ++)
1473 if (Melder_equ (Thing_getName (my at [i]), label))
1474 return i;
1475 return 0;
1476 }
1477
1478 static autoTable Table_SSCPList_extractMahalanobis (Table me, SSCPList thee, kMelder_number which, double numberOfSigmas, integer factorColumnNumber) {
1479 try {
1480 const integer numberOfGroups = thy size;
1481 Melder_assert (numberOfGroups > 0);
1482
1483 const SSCP sscp = thy at [1];
1484 const integer numberOfColumns = sscp -> numberOfColumns; // can be absent
1485 autoINTVEC columnIndex = raw_INTVEC (numberOfColumns);
1486 autoVEC vector = raw_VEC (numberOfColumns);
1487 for (integer icol = 1; icol <= numberOfColumns; icol ++)
1488 columnIndex [icol] = Table_columnNameToNumber_e (me, sscp -> columnLabels [icol].get()); // throw if not present
1489 autoTable him = Table_create (0, my numberOfColumns);
1490 for (integer icol = 1; icol <= my numberOfColumns; icol ++)
1491 his columnHeaders [icol].label = Melder_dup (my columnHeaders [icol]. label.get());
1492 OrderedOf<structCovariance> covs;
1493 for (integer igroup = 1; igroup <= numberOfGroups; igroup ++) {
1494 autoCovariance cov = SSCP_to_Covariance (thy at [igroup], 1);
1495 SSCP_expandWithLowerCholeskyInverse (cov.get());
1496 covs. addItem_move (cov.move());
1497 }
1498 for (integer irow = 1; irow <= my rows.size; irow ++) {
1499 integer igroup = 1;
1500 if (factorColumnNumber > 0) {// if factorColumnNumber == 0 we don't need labels
1501 conststring32 label = Table_getStringValue_a (me, irow, factorColumnNumber);
1502 igroup = SSCPList_findIndexOfGroupLabel (thee, label);
1503 Melder_require (igroup > 0,
1504 U"The label \"", label, U"\" in row ", irow, U" is not valid in this context.");
1505 }
1506 const Covariance covi = covs.at [igroup];
1507 for (integer icol = 1; icol <= numberOfColumns; icol ++)
1508 vector [icol] = Table_getNumericValue_a (me, irow, columnIndex [icol]);
1509 const double dm2 = NUMmahalanobisDistanceSquared (covi -> lowerCholeskyInverse.get(), vector.get(), covi -> centroid.get());
1510 if (Melder_numberMatchesCriterion (sqrt (dm2), which, numberOfSigmas)) {
1511 const TableRow row = my rows.at [irow];
1512 autoTableRow newRow = Data_copy (row);
1513 his rows. addItem_move (newRow.move());
1514 }
1515 }
1516 return him;
1517 } catch (MelderError) {
1518 Melder_throw (me, U"Table (mahalanobis) not extracted.");
1519 }
1520 }
1521
1522 autoTable Table_extractMahalanobis (Table me, INTVEC const& columnNumbers,
1523 kMelder_number which, double numberOfSigmas, integer factorColumnNumber)
1524 {
1525 try {
1526 autoTableOfReal thee = Table_to_TableOfReal_selectedColumns (me, columnNumbers, factorColumnNumber);
1527 autoSSCPList him = TableOfReal_to_SSCPList_byLabel (thee.get());
1528 autoTable result = Table_SSCPList_extractMahalanobis (me, him.get(), which, numberOfSigmas, factorColumnNumber);
1529 return result;
1530 } catch (MelderError) {
1531 Melder_throw (me, U"Table not extracted.");
1532 }
1533 }
1534
1535 void Table_drawEllipses (Table me, Graphics g, integer xcolumn, integer ycolumn, integer factorColumn,
1536 double xmin, double xmax, double ymin, double ymax, double numberOfSigmas, double labelSize, bool garnish)
1537 {
1538 try {
1539 autoTableOfReal thee = TableOfReal_create (my rows.size, 2);
1540 for (integer irow = 1; irow <= my rows.size; irow ++) {
1541 const conststring32 label = Table_getStringValue_a (me, irow, factorColumn);
1542 TableOfReal_setRowLabel (thee.get(), irow, label);
1543 thy data [irow] [1] = Table_getNumericValue_a (me, irow, xcolumn);
1544 thy data [irow] [2] = Table_getNumericValue_a (me, irow, ycolumn);
1545 }
1546 autoSSCPList him = TableOfReal_to_SSCPList_byLabel (thee.get());
1547 constexpr bool confidence = false;
1548 if (xmax == xmin || ymax == ymin) { // autoscaling
1549 double xmin_as, xmax_as, ymin_as, ymax_as;
1550 SSCPList_getEllipsesBoundingBoxCoordinates (him.get(), numberOfSigmas, confidence, & xmin_as, & xmax_as, & ymin_as, & ymax_as);
1551 if (xmax == xmin) {
1552 xmax = xmax_as;
1553 xmin = xmin_as;
1554 }
1555 if (ymax == ymin) {
1556 ymax = ymax_as;
1557 ymin = ymin_as;
1558 }
1559 }
1560 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1561 Graphics_setInner (g);
1562 for (integer i = 1; i <= his size; i ++) {
1563 const SSCP sscpi = his at [i];
1564 const double scalei = SSCP_getEllipseScalefactor (sscpi, numberOfSigmas, confidence);
1565 if (scalei > 0.0)
1566 SSCP_drawTwoDimensionalEllipse_inside (sscpi, g, scalei, Thing_getName (sscpi), labelSize);
1567 }
1568 Graphics_unsetInner (g);
1569
1570 if (garnish) {
1571 Graphics_drawInnerBox (g);
1572 Graphics_marksBottom (g, 2, true, true, false);
1573 Graphics_marksLeft (g, 2, true, true, false);
1574 if (my columnHeaders [xcolumn]. label)
1575 Graphics_textBottom (g, true, my columnHeaders [xcolumn]. label.get());
1576 if (my columnHeaders [ycolumn]. label)
1577 Graphics_textLeft (g, true, my columnHeaders [ycolumn]. label.get());
1578 }
1579 } catch (MelderError) {
1580 Melder_clearError (); // drawing errors shall be ignored
1581 }
1582 }
1583
1584 autoTable Table_extractColumnsByNumber (Table me, constINTVECVU const& columnNumbers) {
1585 try {
1586 Table_checkSpecifiedColumnNumbersWithinRange (me, columnNumbers);
1587 const integer numberOfRows = my rows.size;
1588 autoTable thee = Table_createWithoutColumnNames (numberOfRows, columnNumbers.size);
1589 for (integer icol = 1; icol <= columnNumbers.size; icol ++)
1590 Table_renameColumn_e (thee.get(), icol, my v_getColStr (columnNumbers [icol]));
1591 for (integer irow = 1; irow <= numberOfRows; irow ++) {
1592 for (integer icol = 1; icol <= columnNumbers.size; icol ++) {
1593 const conststring32 value = Table_getStringValue_a (me, irow, columnNumbers [icol]);
1594 Table_setStringValue (thee.get(), irow, icol, value);
1595 }
1596 }
1597 return thee;
1598 } catch (MelderError) {
1599 Melder_throw (me, U": no column range extracted.");
1600 }
1601 }
1602
1603 /* End of file Table_extensions.cpp */