Debian Codegraph @

dwtools/KlattGrid.cpp

raw
1 /* KlattGrid.cpp
2 *
3 * Copyright (C) 2008-2023 David Weenink, 2015,2017,2022-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 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 djmw 20080917 Initial version
20 djmw 20090109 Add formulas for formant frequencies and bandwidths.
21 djmw 20090123 Add PlayOptions.
22 djmw 20090129 KlattGrid_draw text in boxes displays better
23 djmw 20090311 Add RealTier_valuesInRange
24 djmw 20090312 Add klattGrid_addFormantAndBandwidthTier
25 djmw 20090326 Changed DBSPL_to_A into DB_to_A for bypass and formant amplitudes.
26 djmw 20100223 Removed gsl dependency
27 djmw 20110304 Thing_new
28 djmw 20110308 struc connections -> struct structconnections
29 djmw 20110329 Table_get(Numeric|String)Value is now Table_get(Numeric|String)Value_Assert
30 djmw 20111011 Sound_VocalTractGrid_CouplingGrid_filter_cascade: group warnings
31 */
32
33 #include "FormantGrid_extensions.h"
34 #include "Formula.h"
35 #include "Graphics_extensions.h"
36 #include "KlattGrid.h"
37 #include "KlattTable.h"
38 #include "Resonator.h"
39 #include "Pitch_to_PitchTier.h"
40 #include "PitchTier_to_Sound.h"
41 #include "PitchTier_to_PointProcess.h"
42 #include "NUM2.h"
43 #include "Sound_to_Formant.h"
44 #include "Sound_to_Intensity.h"
45 #include "Sound_to_Pitch.h"
46
47 #include "oo_DESTROY.h"
48 #include "KlattGrid_def.h"
49 #include "oo_COPY.h"
50 #include "KlattGrid_def.h"
51 #include "oo_EQUAL.h"
52 #include "KlattGrid_def.h"
53 #include "oo_CAN_WRITE_AS_ENCODING.h"
54 #include "KlattGrid_def.h"
55 #include "oo_WRITE_TEXT.h"
56 #include "KlattGrid_def.h"
57 #include "oo_WRITE_BINARY.h"
58 #include "KlattGrid_def.h"
59 #include "oo_READ_TEXT.h"
60 #include "KlattGrid_def.h"
61 #include "oo_READ_BINARY.h"
62 #include "KlattGrid_def.h"
63 #include "oo_DESCRIPTION.h"
64 #include "KlattGrid_def.h"
65
66
67 #include "enums_getText.h"
68 #include "KlattGrid_enums.h"
69 #include "enums_getValue.h"
70 #include "KlattGrid_enums.h"
71
72 /*
73 * A KlattGrid consists of a great many tiers that can be independently modified.
74 *
75 * For any particular formant, the formant frequency tier and the formant bandwidth tier can only be added or removed jointly
76 * because they are part of a FormantGrid object. There will always be an equal number of formant frequency tiers and
77 * formant bandwidth tiers.
78 *
79 * For parallel synthesis we also need, besides the frequency and bandwidth tier, an additional amplitude tier for each formant.
80 * It is not necessary that there are an equal number of formant frequency tiers (nf) and amplitude tiers (na).
81 * During parallel synthesis we simply synthesize with min(nf,na) number of formants.
82 * These numbers nf and na can get out of sync because of the following (add, remove, replace) actions:
83 * - we replace a FormantGrid that has not the same number of tiers as the corresponding number of amplitude tiers
84 * - we remove/add a formant tier and a bandwidth tier together and not the corresponding amplitude tier
85 * - we remove/add an amplitude tier and not the corresponding formant&bandwidth tiers
86 *
87 * As of 20130113 the KlattGrid_addFormant (/remove) which also added automatically an amplitude tier has been split into two explicit actions
88 * KlattGrid_addFormantFrequencyAndBandwidth (/remove)
89 * KlattGrid_addFormantAmplitudeTier (/remove)
90 *
91 */
92
93 conststring32 KlattGrid_getFormantName (kKlattGridFormantType formantType) {
94 conststring32 result;
95 if (formantType == kKlattGridFormantType::ORAL)
96 result = U"oral formant";
97 else if (formantType == kKlattGridFormantType::NASAL)
98 result = U"nasal formant";
99 else if (formantType == kKlattGridFormantType::FRICATION)
100 result = U"frication Formant";
101 else if (formantType == kKlattGridFormantType::TRACHEAL)
102 result = U"tracheal formant";
103 else if (formantType == kKlattGridFormantType::NASAL_ANTI)
104 result = U"nasal Antiformant";
105 else if (formantType == kKlattGridFormantType::TRACHEAL_ANTI)
106 result = U"tracheal antiformant";
107 else if (formantType == kKlattGridFormantType::DELTA)
108 result = U"delta formant";
109 else
110 result = U"unknown formant";
111 return result;
112 }
113
114 #define KlattGrid_OPENPHASE_DEFAULT 0.7
115 #define KlattGrid_POWER1_DEFAULT 3
116 #define KlattGrid_POWER2_DEFAULT (KlattGrid_POWER1_DEFAULT+1)
117
118 /* Amplitude scaling: maximum amplitude (-1,+1) corresponds to 91 dB */
119
120 /*static double NUMinterpolateLinear (double x1, double y1, double x2, double y2, double x)
121 {
122 if (y1 == y2) return y1;
123 if (x1 == x2) return undefined;
124 return (y2 - y1) * (x - x1) / (x2 - x1) + y1;
125 }*/
126
127 /*
128 Scales relative widths
129 E.g.
130 Before: relativeWidths = {1, 2, 3}, totalWidth = 10
131 After: relativeWidths = {2, 4, 6}, accumulatedWidths = {2, 6, 10}
132 */
133 static void scaleRelativeAndAccumulatedWidths (VEC relativeWidths, VEC const& accumulatedWidths, double totalWidth) {
134 Melder_assert (relativeWidths.size == accumulatedWidths.size);
135 double rsum = NUMsum (relativeWidths);
136
137 if (rsum == 0.0)
138 return;
139
140 const double widthUnit = totalWidth / rsum;
141 double accumulatedWidth = 0.0;
142 for (integer i = 1; i <= relativeWidths.size; i ++) { // to absolute
143 relativeWidths [i] *= widthUnit;
144 accumulatedWidth += relativeWidths [i];
145 accumulatedWidths [i] = accumulatedWidth;
146 }
147 }
148
149 static bool RealTier_valuesInRange (RealTier me, double min, double max) {
150 for (integer i = 1; i <= my points.size; i ++) {
151 const RealPoint p = my points.at [i];
152 if (isdefined (min) && p -> value < min)
153 return false;
154 if (isdefined (max) && p -> value < max)
155 return false;
156 }
157 return true;
158 }
159
160 static double PointProcess_getPeriodAtIndex (PointProcess me, integer it, double maximumPeriod) {
161 double period = undefined;
162 if (it >= 2) {
163 period = my t [it] - my t [it - 1];
164 if (period > maximumPeriod)
165 period = undefined;
166 }
167 if (isundef (period)) {
168 if (it < my nt) {
169 period = my t [it + 1] - my t [it];
170 if (period > maximumPeriod)
171 period = undefined;
172 }
173 }
174 // undefined can only occur for a single isolated pulse.
175 return period;
176 }
177
178 #define UPDATE_TIER \
179 RealTier_addPoint (thee.get(), mytime, myvalue); \
180 lasttime = mytime; \
181 myindex ++; \
182 if (myindex <= numberOfValues) { \
183 mypoint = my points.at [myindex]; \
184 mytime = mypoint -> number; \
185 myvalue = mypoint -> value;\
186 } else { \
187 mytime = my xmax; \
188 }
189
190 static autoRealTier RealTier_updateWithDelta (RealTier me, RealTier delta, PhonationTier glottis, double openglottis_fadeFraction) {
191 try {
192 integer myindex = 1;
193 RealPoint mypoint = my points.at [myindex];
194 const integer numberOfValues = my points.size;
195 double mytime = mypoint -> number;
196 double myvalue = mypoint -> value;
197 double lasttime = my xmin - 0.001; // sometime before xmin
198 autoRealTier thee = RealTier_create (my xmin, my xmax);
199
200 if (openglottis_fadeFraction <= 0.0)
201 openglottis_fadeFraction = 0.0001;
202 if (openglottis_fadeFraction >= 0.5)
203 openglottis_fadeFraction = 0.4999;
204 for (integer ipoint = 1; ipoint <= glottis -> points.size; ipoint ++) {
205 const PhonationPoint point = glottis -> points.at [ipoint];
206 const double t4 = point -> number; // glottis closing
207 const double openDuration = point -> te;
208 const double t1 = t4 - openDuration;
209 const double t2 = t1 + openglottis_fadeFraction * openDuration;
210 const double t3 = t4 - openglottis_fadeFraction * openDuration;
211 /*
212 Add my points that lie before t1 and after previous t4.
213 */
214 while (mytime > lasttime && mytime < t1) {
215 UPDATE_TIER
216 }
217 if (t2 > t1) {
218 // Set new value at t1
219 const double myvalue1 = RealTier_getValueAtTime (me, t1);
220 RealTier_addPoint (thee.get(), t1, myvalue1);
221 // Add my points between t1 and t2
222 while (mytime > lasttime && mytime < t2) {
223 const double dvalue = RealTier_getValueAtTime (delta, mytime);
224 if (isdefined (dvalue)) {
225 const double fraction = (mytime - t1) / (openglottis_fadeFraction * openDuration);
226 myvalue += dvalue * fraction;
227 }
228 UPDATE_TIER
229 }
230 }
231
232 double myvalue2 = RealTier_getValueAtTime (me, t2);
233 double dvalue = RealTier_getValueAtTime (delta, t2);
234 if (isdefined (dvalue))
235 myvalue2 += dvalue;
236 RealTier_addPoint (thee.get(), t2, myvalue2);
237
238 // Add points between t2 and t3
239
240 while (mytime > lasttime && mytime < t3) {
241 dvalue = RealTier_getValueAtTime (delta, mytime);
242 if (isdefined (dvalue))
243 myvalue += dvalue;
244 UPDATE_TIER
245 }
246
247 // set new value at t3
248
249 double myvalue3 = RealTier_getValueAtTime (me, t3);
250 dvalue = RealTier_getValueAtTime (delta, t3);
251 if (isdefined (dvalue)) {
252 myvalue3 += dvalue;
253 }
254 RealTier_addPoint (thee.get(), t3, myvalue3);
255
256 if (t4 > t3) {
257 // Add my points between t3 and t4
258 while (mytime > lasttime && mytime < t4) {
259 dvalue = RealTier_getValueAtTime (delta, mytime);
260 if (isdefined (dvalue)) {
261 const double fraction = 1 - (mytime - t3) / (openglottis_fadeFraction * openDuration);
262 myvalue += dvalue * fraction;
263 }
264 UPDATE_TIER
265 }
266
267 // Set new value at t4
268 const double myvalue4 = RealTier_getValueAtTime (me, t4);
269 RealTier_addPoint (thee.get(), t4, myvalue4);
270 }
271 }
272 return thee;
273 } catch (MelderError) {
274 Melder_throw (me, U": not updated with delta.");
275 }
276 }
277
278 static bool FormantGrid_isFormantDefined (FormantGrid me, integer iformant) {
279 // formant and bandwidth are always in sync
280 const RealTier ftier = my formants.at [iformant];
281 const RealTier btier = my bandwidths.at [iformant];
282 return ftier -> points.size > 0 and btier -> points.size > 0;
283 }
284
285 static bool FormantGrid_Intensities_isFormantDefined (FormantGrid me, OrderedOf<structIntensityTier>* thee, integer iformant) {
286 bool exists = false;
287 if (iformant <= my formants.size && iformant <= my bandwidths.size && iformant <= thee->size) {
288 const RealTier ftier = my formants.at [iformant];
289 const RealTier btier = my bandwidths.at [iformant];
290 const IntensityTier atier = thy at [iformant];
291 exists = ( ftier -> points.size > 0 && btier -> points.size > 0 && atier -> points.size > 0 );
292 }
293 return exists;
294 }
295
296 static void check_formants (integer numberOfFormants, integer *ifb, integer *ife) {
297 if (numberOfFormants <= 0 || *ifb > numberOfFormants || *ife < *ifb || *ife < 1) {
298 *ife = 0; // overrules everything *ifb value is a don't care now
299 return;
300 }
301 if (*ifb <= 1)
302 *ifb = 1;
303 if (*ife > numberOfFormants)
304 *ife = numberOfFormants;
305 }
306
307 static autoSound Sound_createEmptyMono (double xmin, double xmax, double samplingFrequency) {
308 const integer nt = Melder_iceiling ((xmax - xmin) * samplingFrequency);
309 const double dt = 1.0 / samplingFrequency;
310 const double tmid = (xmin + xmax) / 2.0;
311 const double t1 = tmid - 0.5 * (nt - 1) * dt;
312
313 return Sound_create (1, xmin, xmax, nt, dt, t1);
314 }
315
316 static void _Sounds_add_inplace (Sound me, Sound thee) {
317 for (integer i = 1; i <= my nx; i ++)
318 my z [1] [i] += thy z [1] [i];
319 }
320
321 static autoSound _Sound_diff (Sound me, int scale) {
322 try {
323 autoSound thee = Data_copy (me);
324
325 // extremum
326 double amax1 = -1.0e34, amax2 = amax1, val, pval = 0.0;
327 if (scale) {
328 for (integer i = 1; i <= thy nx; i ++) {
329 val = fabs (thy z [1] [i]);
330 if (val > amax1)
331 amax1 = val;
332 }
333 }
334 // x [n]-x [n-1]
335 for (integer i = 1; i <= thy nx; i ++) {
336 val = thy z [1] [i];
337 thy z [1] [i] -= pval;
338 pval = val;
339 }
340 if (scale) {
341 for (integer i = 1; i <= thy nx; i ++) {
342 val = fabs (thy z [1] [i]);
343 if (val > amax2)
344 amax2 = val;
345 }
346 // scale
347 for (integer i = 1; i <= thy nx; i ++)
348 thy z [1] [i] *= amax1 / amax2;
349 }
350 return thee;
351 } catch (MelderError) {
352 Melder_throw (me, U": not differenced.");
353 }
354 }
355
356 /*static void _Sounds_addDifferentiated_inplace (Sound me, Sound thee)
357 {
358 double pval = 0, dx = my dx;
359 for (integer i = 1; i <= my nx; i ++)
360 {
361 const double val = thy z [1] [i];
362 my z [1] [i] += (val - pval) / dx; // dx makes amplitude of dz/dt independent of sampling.
363 pval = val;
364 }
365 }*/
366
367 typedef struct structconnections {
368 integer numberOfConnections;
369 autoVEC x, y;
370 } *connections;
371
372 static void connections_free (connections me) {
373 if (! me)
374 return;
375 Melder_free (me);
376 }
377
378 static connections connections_create (integer numberOfConnections) {
379 connections me = 0;
380 try {
381 me = (connections) Melder_calloc (structconnections, 1);
382 my numberOfConnections = numberOfConnections;
383 my x = zero_VEC (numberOfConnections);
384 my y = zero_VEC (numberOfConnections);
385 return me;
386 } catch (MelderError) {
387 connections_free (me);
388 Melder_throw (U"Connections not created.");
389 }
390 }
391
392 // Calculates the intersection point (xi,yi) of a line with a circle.
393 // The line starts at the origin and P (xp, yp) is on that line.
394 static void NUMcircle_radial_intersection_sq (double x, double y, double r, double xp, double yp, double *xi, double *yi) {
395 double dx = xp - x, dy = yp - y;
396 const double d = hypot (dx, dy);
397 if (d > 0) {
398 *xi = x + dx * r / d;
399 *yi = y + dy * r / d;
400 } else {
401 *xi = *yi = undefined;
402 }
403 }
404
405 static void summer_draw (Graphics g, double x, double y, double r, bool alternating) {
406 Graphics_setLineWidth (g, 2);
407 Graphics_circle (g, x, y, r);
408 const double dy = 3.0 * r / 4.0;
409 // + symbol
410 if (alternating)
411 y += r / 4.0;
412 Graphics_line (g, x, y + r / 2.0, x, y - r / 2.0);
413 Graphics_line (g, x - r / 2.0, y, x + r / 2.0, y);
414 if (alternating)
415 Graphics_line (g, x - r / 2.0, y - dy , x + r / 2.0, y - dy);
416 }
417
418 static void _summer_drawConnections (Graphics g, double x, double y, double r, connections thee, bool arrow, bool alternating, double horizontalFraction) {
419 summer_draw (g, x, y, r, alternating);
420
421 for (integer i = 1; i <= thy numberOfConnections; i ++) {
422 const double yp = thy y [i];
423 double xto, yto, xp = thy x [i];
424 if (horizontalFraction > 0) {
425 const double dx = x - xp;
426 if (dx > 0) {
427 xp += horizontalFraction * dx;
428 Graphics_line (g, thy x [i], yp, xp, yp);
429 }
430 }
431 NUMcircle_radial_intersection_sq (x, y, r, xp, yp, & xto, & yto);
432 if (isundef (xto) || isundef (yto))
433 continue;
434 if (arrow)
435 Graphics_arrow (g, xp, yp, xto, yto);
436 else
437 Graphics_line (g, xp, yp, xto, yto);
438 }
439 }
440
441 static void summer_drawConnections (Graphics g, double x, double y, double r, connections thee, bool arrow, double horizontalFraction) {
442 _summer_drawConnections (g, x, y, r, thee, arrow, false, horizontalFraction);
443 }
444
445 static void alternatingSummer_drawConnections (Graphics g, double x, double y, double r, connections thee, bool arrow, double horizontalFraction) {
446 _summer_drawConnections (g, x, y, r, thee, arrow, true, horizontalFraction);
447 }
448
449 static void drawLinesInBox (Graphics g, double xmin, double xmax, double ymin, double ymax, constSTRVEC const& lines) {
450 Melder_assert (lines.size > 0);
451 Graphics_rectangle (g, xmin, xmax, ymin, ymax);
452 const double dy = (ymax - ymin) / lines.size;
453 const double x = (xmax + xmin) / 2.0;
454 double y = ymax - 0.5 * dy;
455 Graphics_setTextAlignment (g, Graphics_CENTRE, Graphics_HALF);
456 for (integer iline = 1; iline <= lines.size; iline ++, y -= dy)
457 Graphics_text (g, x, y, lines [iline]);
458 }
459
460 // Maximum amplitue (-1,1) at 93.97940008672037 dB
461 #define DBSPL_to_A(x) (pow (10.0, x / 20.0) * 2.0e-5)
462 // Normal dB's
463 #define DB_to_A(x) (pow (10.0, x / 20.0))
464
465 /************************ Sound & FormantGrid *********************************************/
466
467 static void _Sound_FormantGrid_filterWithOneFormant_inplace (Sound me, FormantGrid thee, integer iformant, bool antiformant) {
468 if (iformant < 1 || iformant > thy formants.size) {
469 Melder_warning (U"Formant ", iformant, U" does not exist.");
470 return;
471 }
472 const RealTier ftier = thy formants.at [iformant];
473 const RealTier btier = thy bandwidths.at [iformant];
474 if (ftier -> points.size == 0 && btier -> points.size == 0)
475 return;
476 Melder_require (ftier -> points.size != 0 && btier -> points.size != 0,
477 U"Tier should not be empty,");
478 const double nyquist = 0.5 / my dx;
479 autoFilter r;
480 if (antiformant)
481 r = AntiResonator_create (my dx);
482 else
483 r = Resonator_create (my dx, true);
484
485 for (integer is = 1; is <= my nx; is ++) {
486 const double t = my x1 + (is - 1) * my dx;
487 const double f = RealTier_getValueAtTime (ftier, t);
488 const double b = RealTier_getValueAtTime (btier, t);
489 if (f <= nyquist && isdefined (b))
490 Filter_setCoefficients (r.get(), f, b);
491 my z [1] [is] = Filter_getOutput (r.get(), my z [1] [is]);
492 }
493 }
494
495 void Sound_FormantGrid_filterWithOneAntiFormant_inplace (Sound me, FormantGrid thee, integer iformant) {
496 _Sound_FormantGrid_filterWithOneFormant_inplace (me, thee, iformant, true);
497 }
498
499 void Sound_FormantGrid_filterWithOneFormant_inplace (Sound me, FormantGrid thee, integer iformant) {
500 _Sound_FormantGrid_filterWithOneFormant_inplace (me, thee, iformant, false);
501 }
502
503 void Sound_FormantGrid_Intensities_filterWithOneFormant_inplace (Sound me, FormantGrid thee, OrderedOf<structIntensityTier>* amplitudes, integer iformant) {
504 try {
505 Melder_require (iformant > 0 && iformant <= thy formants.size, U"Formant ", iformant, U" not defined.");
506
507 const double nyquist = 0.5 / my dx;
508
509 const RealTier ftier = thy formants.at [iformant];
510 const RealTier btier = thy bandwidths.at [iformant];
511 const IntensityTier atier = amplitudes->at [iformant];
512
513 if (ftier -> points.size == 0 || btier -> points.size == 0 || atier -> points.size == 0)
514 return; // nothing to do
515 autoResonator r = Resonator_create (my dx, false);
516 for (integer is = 1; is <= my nx; is ++) {
517 const double t = my x1 + (is - 1) * my dx;
518 const double f = RealTier_getValueAtTime (ftier, t);
519 const double b = RealTier_getValueAtTime (btier, t);
520 if (f <= nyquist && isdefined (b)) {
521 Filter_setCoefficients (r.get(), f, b);
522 const double a = RealTier_getValueAtTime (atier, t);
523 if (isdefined (a))
524 r -> a *= DB_to_A (a);
525 }
526 my z [1] [is] = Filter_getOutput (r.get(), my z [1] [is]);
527 }
528 } catch (MelderError) {
529 Melder_throw (me, U": not filtered with one formant filter.");
530 }
531 }
532
533 autoSound Sound_FormantGrid_Intensities_filter (Sound me, FormantGrid thee, OrderedOf<structIntensityTier>* amplitudes, integer iformantb, integer iformante, int alternatingSign) {
534 try {
535 if (iformantb > iformante) {
536 iformantb = 1;
537 iformante = thy formants.size;
538 }
539 Melder_require (iformantb > 0 && iformantb <= thy formants.size ,
540 U"From formant ", iformantb, U" not defined.");
541 Melder_require (iformante > 0 && iformante <= thy formants.size ,
542 U"To formant ", iformante, U" not defined.");
543
544 autoSound him = Sound_create (my ny, my xmin, my xmax, my nx, my dx, my x1);
545
546 for (integer iformant = iformantb; iformant <= iformante; iformant ++) {
547 if (FormantGrid_Intensities_isFormantDefined (thee, amplitudes, iformant)) {
548 autoSound tmp = Data_copy (me);
549 Sound_FormantGrid_Intensities_filterWithOneFormant_inplace (tmp.get(), thee, amplitudes, iformant);
550 for (integer is = 1; is <= my nx; is ++)
551 his z [1] [is] += ( alternatingSign >= 0 ? tmp -> z [1] [is] : - tmp -> z [1] [is] );
552 if (alternatingSign != 0)
553 alternatingSign = - alternatingSign;
554 }
555 }
556 return him;
557 } catch (MelderError) {
558 Melder_throw (me, U": not filtered.");
559 }
560 }
561
562 /********************* PhonationTier ************************/
563
564 Thing_implement (PhonationPoint, AnyPoint, 0);
565
566 autoPhonationPoint PhonationPoint_create (double time, double period, double openPhase, double collisionPhase, double te, double power1, double power2, double pulseScale) {
567 try {
568 autoPhonationPoint me = Thing_new (PhonationPoint);
569 my number = time;
570 my period = period;
571 my openPhase = openPhase;
572 my collisionPhase = collisionPhase;
573 my te = te;
574 my power1 = power1;
575 my power2 = power2;
576 my pulseScale = pulseScale;
577 return me;
578 } catch (MelderError) {
579 Melder_throw (U"PhonationPoint not created.");
580 }
581 }
582
583 Thing_implement (PhonationTier, AnyTier, 0);
584
585 autoPhonationTier PhonationTier_create (double tmin, double tmax) {
586 try {
587 autoPhonationTier me = Thing_new (PhonationTier);
588 Function_init (me.get(), tmin, tmax);
589 return me;
590 } catch (MelderError) {
591 Melder_throw (U"PhonationTier not created.");
592 }
593 }
594
595 autoPointProcess PhonationTier_to_PointProcess_closures (PhonationTier me) {
596 try {
597 const integer nt = my points.size;
598 autoPointProcess thee = PointProcess_create (my xmin, my xmax, nt);
599 for (integer ip = 1; ip <= nt; ip ++) {
600 const PhonationPoint fp = my points.at [ip];
601 PointProcess_addPoint (thee.get(), fp -> number);
602 }
603 return thee;
604 } catch (MelderError) {
605 Melder_throw (me, U": no PointProcess with closure times created.");
606 }
607 }
608
609 /********************** PhonationGridPlayOptions **********************/
610
611 Thing_implement (PhonationGridPlayOptions, Daata, 0);
612
613 static void PhonationGridPlayOptions_setDefaults (PhonationGridPlayOptions me) {
614 my flowDerivative = my voicing = 1;
615 my aspiration = my breathiness = 1;
616 my flutter = my doublePulsing = 1;
617 my collisionPhase = my spectralTilt = 1;
618 my flowFunction = 1; // User defined flow tiers (power1 & power2)
619 my maximumPeriod = 0;
620 }
621
622 autoPhonationGridPlayOptions PhonationGridPlayOptions_create () {
623 try {
624 autoPhonationGridPlayOptions me = Thing_new (PhonationGridPlayOptions);
625 return me;
626 } catch (MelderError) {
627 Melder_throw (U"PhonationGridPlayOptions not created.");
628 }
629 }
630
631 /********************** PhonationGrid **********************/
632
633
634 Thing_implement (PhonationGrid, Function, 0);
635
636 void structPhonationGrid :: v1_info () {
637 structDaata :: v1_info ();
638 conststring32 in1 = U" ", in2 = U" ";
639 MelderInfo_writeLine (in1, U"Time domain:");
640 MelderInfo_writeLine (in2, U"Start time: ", xmin, U" seconds");
641 MelderInfo_writeLine (in2, U"End time: ", xmax, U" seconds");
642 MelderInfo_writeLine (in2, U"Total duration: ", xmax - xmin, U" seconds");
643 MelderInfo_writeLine (in1, U"\nNumber of points in the PHONATION tiers:");
644 MelderInfo_writeLine (in2, U"pitch: ", pitch -> points.size);
645 MelderInfo_writeLine (in2, U"voicingAmplitude: ", voicingAmplitude -> points.size);
646 MelderInfo_writeLine (in2, U"openPhase: ", openPhase -> points.size);
647 MelderInfo_writeLine (in2, U"collisionPhase: ", collisionPhase -> points.size);
648 MelderInfo_writeLine (in2, U"power1: ", power1 -> points.size);
649 MelderInfo_writeLine (in2, U"power2: ", power2 -> points.size);
650 MelderInfo_writeLine (in2, U"flutter: ", flutter -> points.size);
651 MelderInfo_writeLine (in2, U"doublePulsing: ", doublePulsing -> points.size);
652 MelderInfo_writeLine (in2, U"spectralTilt: ", spectralTilt -> points.size);
653 MelderInfo_writeLine (in2, U"aspirationAmplitude: ", aspirationAmplitude -> points.size);
654 MelderInfo_writeLine (in2, U"breathinessAmplitude:", breathinessAmplitude -> points.size);
655 }
656
657 void PhonationGrid_setNames (PhonationGrid me) {
658 Thing_setName (my pitch.get(), U"pitch");
659 Thing_setName (my voicingAmplitude.get(), U"voicingAmplitude");
660 Thing_setName (my openPhase.get(), U"openPhase");
661 Thing_setName (my collisionPhase.get(), U"collisionPhase");
662 Thing_setName (my power1.get(), U"power1");
663 Thing_setName (my power2.get(), U"power2");
664 Thing_setName (my flutter.get(), U"flutter");
665 Thing_setName (my doublePulsing.get(), U"doublePulsing");
666 Thing_setName (my spectralTilt.get(), U"spectralTilt");
667 Thing_setName (my aspirationAmplitude.get(), U"aspirationAmplitude");
668 Thing_setName (my breathinessAmplitude.get(), U"breathinessAmplitude");
669 }
670
671 autoPhonationGrid PhonationGrid_create (double tmin, double tmax) {
672 try {
673 autoPhonationGrid me = Thing_new (PhonationGrid);
674 Function_init (me.get(), tmin, tmax);
675 my pitch = PitchTier_create (tmin, tmax);
676 my voicingAmplitude = IntensityTier_create (tmin, tmax);
677 my openPhase = RealTier_create (tmin, tmax);
678 my collisionPhase = RealTier_create (tmin, tmax);
679 my power1 = RealTier_create (tmin, tmax);
680 my power2 = RealTier_create (tmin, tmax);
681 my flutter = RealTier_create (tmin, tmax);
682 my doublePulsing = RealTier_create (tmin, tmax);
683 my spectralTilt = IntensityTier_create (tmin, tmax);
684 my aspirationAmplitude = IntensityTier_create (tmin, tmax);
685 my breathinessAmplitude = IntensityTier_create (tmin, tmax);
686 my options = PhonationGridPlayOptions_create ();
687 PhonationGrid_setNames (me.get());
688 return me;
689 } catch (MelderError) {
690 Melder_throw (U"PhonationGrid not created.");
691 }
692 }
693
694 static void PhonationGrid_checkFlowFunction (PhonationGrid me) {
695 int hasPower1Points = my power1 -> points.size > 0;
696 int hasPower2Points = my power2 -> points.size > 0;
697
698 integer ipoint = 1;
699 do {
700 const double time = ( hasPower1Points ? my power1 -> points.at [ipoint] -> number : 0.5 * (my xmin + my xmax) );
701 double power1 = RealTier_getValueAtIndex (my power1.get(), ipoint);
702 if (isundef (power1))
703 power1 = KlattGrid_POWER1_DEFAULT;
704 Melder_require (power1 > 0.0,
705 U"All power1 values should greater than zero.");
706
707 double power2 = RealTier_getValueAtTime (my power2.get(), time);
708 if (isundef (power2))
709 power2 = KlattGrid_POWER2_DEFAULT;
710 Melder_require (power1 < power2,
711 U"At all times a power1 value should be smaller than the corresponding power2 value.");
712
713 } while ( ++ ipoint < my power1 -> points.size);
714
715 // Now check power2 values. This is necessary to catch situations where power2 has a valley:
716 // power1(0) = 3; power2(1)= 4; power2(1)= 4; power2(0.5) = 3;
717
718 ipoint = 1;
719 do {
720 const double time = ( hasPower2Points ? my power2 -> points.at [ipoint] -> number : 0.5 * (my xmin + my xmax) );
721 double power2 = RealTier_getValueAtIndex (my power2.get(), ipoint);
722 if (isundef (power2))
723 power2 = KlattGrid_POWER2_DEFAULT;
724 double power1 = RealTier_getValueAtTime (my power1.get(), time);
725 if (isundef (power1))
726 power1 = KlattGrid_POWER1_DEFAULT;
727 Melder_require (power1 < power2,
728 U"At all times a power1 value should be smaller than the corresponding power2 value.");
729
730 } while ( ++ ipoint < my power2 -> points.size);
731 }
732
733 static void PhonationGrid_draw_inside (PhonationGrid me, Graphics g, double xmin, double xmax, double ymin, double ymax, double dy, double *out_y) {
734 // dum voicing conn tilt conn summer
735 (void) me;
736 // { voicingBox, line, tiltBox, connection, summer }
737 autoVEC relativeWidths { 1.0, 0.5, 1.0, 0.5, 0.5 }, accumulatedWidths = zero_VEC (5);
738 double oldFontSize = Graphics_inqFontSize (g);
739 connections thee = connections_create (2);
740
741 scaleRelativeAndAccumulatedWidths (relativeWidths.get(), accumulatedWidths.get(), xmax - xmin);
742
743 dy = (ymax - ymin) / (1.0 + ( dy < 0.0 ? 0.0 : dy ) + 1.0);
744 double x1 = xmin, x2 = x1 + relativeWidths [1];
745 double y2 = ymax, y1 = y2 - dy;
746 autoSTRVEC voicingText { U"Voicing" };
747 double newFontSize = Graphics_getFontSizeInsideBox (g, relativeWidths [1], dy, 7.0, 1.5);
748 if (newFontSize < oldFontSize)
749 Graphics_setFontSize (g, newFontSize);
750 drawLinesInBox (g, x1, x2, y1, y2, voicingText.get());
751
752 x1 = x2;
753 x2 = x1 + relativeWidths [2];
754 double ymid = (y1 + y2) / 2.0;
755 Graphics_line (g, x1, ymid, x2, ymid);
756
757 x1 = x2;
758 x2 = x1 + relativeWidths [3];
759 autoSTRVEC tiltText { U"Tilt" };
760 drawLinesInBox (g, x1, x2, y1, y2, tiltText.get());
761
762 thy x [1] = x2;
763 thy y [1] = ymid;
764
765 y2 = y1 - 0.5 * dy;
766 y1 = y2 - dy;
767 ymid = (y1 + y2) / 2.0;
768 x2 = xmin + accumulatedWidths [3];
769 x1 = x2 - 1.5 * relativeWidths [3]; // some extra space
770 autoSTRVEC aspirationText { U"Aspiration" };
771 drawLinesInBox (g, x1, x2, y1, y2, aspirationText.get());
772
773 thy x [2] = x2;
774 thy y [2] = ymid;
775
776 const double r = relativeWidths [5] / 2.0;
777 const double xs = xmax - r, ys = (ymax + ymin) / 2.0;
778 const bool arrow = true;
779
780 summer_drawConnections (g, xs, ys, r, thee, arrow, 0.4);
781 connections_free (thee);
782
783 Graphics_setFontSize (g, oldFontSize); // restore
784
785 if (out_y)
786 *out_y = ys;
787 }
788
789 void PhonationGrid_draw (PhonationGrid me, Graphics g) {
790 const double xmin = 0.0, xmax2 = 0.9, xmax = 1.0, ymin = 0.0, ymax = 1.0, dy = 0.5;
791
792 Graphics_setInner (g);
793 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
794 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
795 double yout;
796 PhonationGrid_draw_inside (me, g, xmin, xmax2, ymin, ymax, dy, & yout);
797
798 Graphics_arrow (g, xmax2, yout, xmax, yout);
799 Graphics_unsetInner (g);
800 }
801
802 double PhonationGrid_getMaximumPeriod (PhonationGrid me) {
803 const double minimumPitch = RealTier_getMinimumValue (my pitch.get());
804 return 2.0 / ( isdefined (minimumPitch) && minimumPitch != 0.0 ? minimumPitch : my xmax - my xmin );
805 }
806
807 static autoPointProcess PitchTier_to_PointProcess_flutter (PitchTier pitch, RealTier flutter, double maximumPeriod) {
808 try {
809 autoPointProcess thee = PitchTier_to_PointProcess (pitch);
810 if (! flutter)
811 return thee;
812 double tsum = 0;
813 for (integer it = 2; it <= thy nt; it ++) {
814 const double t = thy t [it - 1];
815 const double period = thy t [it] - thy t [it - 1];
816 if (period < maximumPeriod && flutter -> points.size > 0) {
817 const double fltr = RealTier_getValueAtTime (flutter, t);
818 if (isdefined (fltr)) {
819 // newF0 = f0 * (1 + (val / 50) * (sin ... + ...));
820 const double newPeriod = period / (1.0 + (fltr / 50.0) * (sin (NUM2pi * 12.7 * t) + sin (NUM2pi * 7.1 * t) + sin (NUM2pi * 4.7 * t)));
821 tsum += newPeriod - period;
822 }
823 }
824 thy t [it] += tsum;
825 }
826 return thee;
827 } catch (MelderError) {
828 Melder_throw (pitch, U": no flutter PointProcess created.");
829 }
830 }
831
832 autoSound PhonationGrid_to_Sound_aspiration (PhonationGrid me, double samplingFrequency) {
833 try {
834 autoSound thee = Sound_createEmptyMono (my xmin, my xmax, samplingFrequency);
835
836 // Noise spectrum is tilted down by soft low-pass filter having a pole near
837 // the origin in the z-plane, i.e. y [n] = x [n] + (0.75 * y [n-1])
838 double lastval = 0.0;
839 if (my aspirationAmplitude -> points.size > 0) {
840 for (integer i = 1; i <= thy nx; i ++) {
841 const double t = thy x1 + (i - 1) * thy dx;
842 double val = NUMrandomUniform (-1.0, 1.0);
843 const double a = DBSPL_to_A (RealTier_getValueAtTime (my aspirationAmplitude.get(), t));
844 if (isdefined (a)) {
845 thy z [1] [i] = lastval = val + 0.75 * lastval;
846 lastval = (val += 0.75 * lastval); // soft low-pass
847 thy z [1] [i] = val * a;
848 }
849 }
850 }
851 return thee;
852 } catch (MelderError) {
853 Melder_throw (me, U": no aspiration Sound created.");
854 }
855 }
856
857 static void Sound_PhonationGrid_spectralTilt_inplace (Sound thee, PhonationGrid me) {
858 if (my spectralTilt -> points.size > 0) {
859 /* Spectral tilt
860 Filter y [n] = a * x [n] + b * y [n-1] => H(z) = a / (1 - bz^(-1)).
861 We need attenuation, i.e. low-pass. Therefore 0 <= b <= 1.
862 |H(f)| = a / sqrt (1 - 2*b*cos(2*pi*f*T) + b^2),
863 |H(0)|= a /(1 - b) => if |H(0)| == 1, then a = 1 - b.
864 Now solve 20 log|H(F)|= -c (at F=3 kHz and c > 0)
865 Solution: if q = (1 - D * cos(2*pi*F*T)) / (1 - D), with D = 10^(-c/10)
866 then b = q -sqrt(q^2 - 1)
867 */
868
869 const double cosf = cos (NUM2pi * 3000.0 * thy dx); // samplingFrequency > 6000.0 !
870 double ynm1 = 0.0;
871
872 for (integer i = 1; i <= thy nx; i ++) {
873 const double t = thy x1 + (i - 1) * thy dx;
874 const double tilt_db = RealTier_getValueAtTime (my spectralTilt.get(), t);
875
876 if (tilt_db > 0) {
877 const double d = pow (10.0, -tilt_db / 10.0);
878 const double q = (1.0 - d * cosf) / (1.0 - d);
879 const double b = q - sqrt (q * q - 1.0);
880 const double a = 1.0 - b;
881 thy z [1] [i] = a * thy z [1] [i] + b * ynm1;
882 ynm1 = thy z [1] [i];
883 }
884 }
885 }
886 }
887
888 struct nrfunction_struct {
889 double n;
890 double m;
891 double a;
892 };
893
894 static double nrfunction (double x, double *dfx, void *closure) {
895 const struct nrfunction_struct *nrfs = (struct nrfunction_struct *) closure;
896 const double mplusax = nrfs -> m + nrfs -> a * x;
897 const double mminn = nrfs -> m - nrfs -> n;
898 const double fx = pow (x, mminn) - (nrfs -> n + nrfs -> a * x) / mplusax;
899 *dfx = mminn * pow (x, mminn - 1) - nrfs -> a * mminn / (mplusax * mplusax);
900 return fx;
901 }
902
903 static double get_collisionPoint_x (double n, double m, double collisionPhase) {
904 double y = undefined;
905 /*
906 Domain [0, 1]:
907 The glottal flow is given by:
908 U(y) = y^n - y^m 0<= y <= x, and m > n
909 (x^n - x^m)exp(-a(y-x)) y >= x, where a = 1 / collisionPhase
910 The x where this occurs is the point where the amplitudes as well as the derivatives are equal.
911 I.e. the x where n x^(n-1) - m x^(m-1) = (x^n-x^m)(-a).
912 This can be simplified: find x in (0,1) where f(x) = x^(m-n) - (n+ax)/(m+ax) == 0.
913 For m - n == 1, f(x) is a second order equation f(x)= a x^2 + (m-a) x - n == 0.
914 In all other cases we solve with Newton-Raphson. For these cases we also need the derivative:
915 f'(x)= (m - n)x^(m - n - 1)- a(m - n) / (m + a x)^2
916 */
917 if (collisionPhase <= 0.0)
918 return 1.0;
919 double a = 1.0 / collisionPhase;
920 if (m - n == 1.0) {
921 const double b = m - a;
922 const double c = - n;
923 double y1, y2;
924 integer nroots = NUMsolveQuadraticEquation (a, b, c, &y1, &y2);
925 if (nroots == 2)
926 y = y2;
927 else if (nroots == 1)
928 y = y1;
929 } else { // Newton-Raphson
930 // search in the interval from where the flow is a maximum to 1
931 const double xmaxFlow = pow (n / m, 1.0 / (m - n));
932 struct nrfunction_struct nrfs = {n, m, a};
933 double root = NUMnrbis (& nrfunction, xmaxFlow, 1.0, & nrfs);
934 y = root;
935 }
936 return y;
937 }
938
939 autoPhonationTier PhonationGrid_to_PhonationTier (PhonationGrid me) {
940 try {
941 integer diplophonicPulseIndex = 0;
942 const PhonationGridPlayOptions pp = my options.get();
943
944 PhonationGrid_checkFlowFunction (me);
945 Melder_require (my pitch -> points.size > 0,
946 U"Pitch tier should not be empty.");
947
948 if (pp -> maximumPeriod == 0.0)
949 pp -> maximumPeriod = PhonationGrid_getMaximumPeriod (me);
950
951 autoPointProcess point = PitchTier_to_PointProcess_flutter (my pitch.get(), ( pp -> flutter ? my flutter.get() : nullptr ), pp -> maximumPeriod);
952
953 autoPhonationTier thee = PhonationTier_create (my xmin, my xmax);
954
955 /*
956 Cycle through the points of the point PointProcess. Each will become a period.
957 We assume that the planning for the pitch period occurs approximately at a time T before the glottal closure.
958 For each point t [i]:
959 Determine the f0 -> period T [i]
960 Determine time t [i]-T [i] the open quotient, power1, power2, collisionphase etc.
961 Generate the period.
962 */
963
964 for (integer it = 1; it <= point -> nt; it ++) {
965 double re = 0.0, t = point -> t [it]; // the glottis "closing" point
966 double pulseDelay = 0.0; // For alternate pulses in case of diplophonia
967 double pulseScale = 1.0; // For alternate pulses in case of diplophonia
968
969 double period = PointProcess_getPeriodAtIndex (point.get(), it, pp -> maximumPeriod);
970 if (isundef (period))
971 period = 0.5 * pp -> maximumPeriod; // some default value
972
973 // Calculate the point where the exponential decay starts:
974 // Query tiers where period starts .
975
976 double periodStart = t - period;
977 double collisionPhase = ( pp -> collisionPhase ? RealTier_getValueAtTime (my collisionPhase.get(), periodStart) : 0.0 );
978 if (isundef (collisionPhase))
979 collisionPhase = 0.0;
980 double power1 = ( pp -> flowFunction == 1 ? RealTier_getValueAtTime (my power1.get(), periodStart) : pp -> flowFunction );
981 if (isundef (power1))
982 power1 = KlattGrid_POWER1_DEFAULT;
983 double power2 = ( pp -> flowFunction == 1 ? RealTier_getValueAtTime (my power2.get(), periodStart) : pp -> flowFunction + 1 );
984 if (isundef (power2))
985 power2 = KlattGrid_POWER2_DEFAULT;
986 try {
987 re = get_collisionPoint_x (power1, power2, collisionPhase);
988 } catch (MelderError) {
989 Melder_warning (U"Illegal collision point at t = ", t, U" (power1=", power1, U", power2=", power2, U"colPhase=", collisionPhase, U")");
990 }
991
992 double openPhase = RealTier_getValueAtTime (my openPhase.get(), periodStart);
993 if (isundef (openPhase))
994 openPhase = KlattGrid_OPENPHASE_DEFAULT;
995
996 const double te = re * period * openPhase;
997
998 // In case of diplophonia alternate pulses get modified.
999 // A modified puls is delayed in time and its amplitude attenuated.
1000 // This delay scales to maximally equal the closed phase of the next period.
1001 // The doublePulsing scales the amplitudes as well as the delay linearly.
1002
1003 double doublePulsing = ( pp -> doublePulsing ? RealTier_getValueAtTime (my doublePulsing.get(), periodStart) : 0.0 );
1004 if (isundef (doublePulsing))
1005 doublePulsing = 0.0;
1006 if (doublePulsing > 0.0) {
1007 diplophonicPulseIndex ++;
1008 if (diplophonicPulseIndex % 2 == 1) { // the odd-numbered one
1009 double nextPeriod = PointProcess_getPeriodAtIndex (point.get(), it + 1, pp -> maximumPeriod);
1010 if (isundef (nextPeriod))
1011 nextPeriod = period;
1012 double openPhase2 = KlattGrid_OPENPHASE_DEFAULT;
1013 if (my openPhase -> points.size > 0)
1014 openPhase2 = RealTier_getValueAtTime (my openPhase.get(), t);
1015 const double maxDelay = period * (1.0 - openPhase2);
1016 pulseDelay = maxDelay * doublePulsing;
1017 pulseScale *= 1.0 - doublePulsing;
1018 }
1019 } else
1020 diplophonicPulseIndex = 0;
1021
1022 t += pulseDelay;
1023 autoPhonationPoint phonationPoint = PhonationPoint_create (t, period, openPhase, collisionPhase, te, power1, power2, pulseScale);
1024 AnyTier_addPoint_move (thee.get()->asAnyTier(), phonationPoint.move());
1025 }
1026 return thee;
1027 } catch (MelderError) {
1028 Melder_throw (me, U": no PhonationTier created.");
1029 }
1030 }
1031
1032 static autoSound PhonationGrid_PhonationTier_to_Sound_voiced (PhonationGrid me, PhonationTier thee, double samplingFrequency) {
1033 try {
1034 const PhonationGridPlayOptions p = my options.get();
1035 double lastVal = undefined;
1036
1037 Melder_require (my voicingAmplitude -> points.size > 0,
1038 U"Voicing amplitude tier should not be empty.");
1039
1040 autoSound him = Sound_createEmptyMono (my xmin, my xmax, samplingFrequency);
1041 autoSound breathy;
1042 if (p -> breathiness && my breathinessAmplitude -> points.size > 0)
1043 breathy = Sound_createEmptyMono (my xmin, my xmax, samplingFrequency);
1044
1045 /*
1046 Cycle through the points of the PhonationTier. Each will become a period.
1047 We assume that the planning for the pitch period occurs approximately at a time T before the glottal closure.
1048 For each point t [i]:
1049 Determine the f0 -> period T [i]
1050 Determine time t [i]-T [i] the open quotient, power1, power2, collisionphase etc.
1051 Generate the period.
1052 */
1053 VEC sound = his z.row (1);
1054 for (integer it = 1; it <= thy points.size; it ++) {
1055 PhonationPoint point = thy points.at [it];
1056 const double t = point -> number; // the glottis "closing" point
1057 const double te = point -> te;
1058 const double period = point -> period; // duration of the current period
1059 const double openPhase = point -> openPhase;
1060 const double collisionPhase = point -> collisionPhase;
1061 const double pulseScale = point -> pulseScale; // For alternate pulses in case of diplophonia
1062 const double power1 = point -> power1, power2 = point -> power2;
1063 double phase; // 0..1
1064 double flow;
1065
1066 //- double amplitude = pulseScale * (power1 + power2 + 1.0) / (power2 - power1);
1067 //- amplitude /= period * openPhase;
1068
1069 // Maximum of U(x) = x^n - x^m is where the derivative U'(x) = n x^(n-1) - m x^(m-1) == 0,
1070 // i.e. (n/m) = x^(m-n), so xmax = (n/m)^(1/(m-n))
1071 // U(xmax) = x^n (1-x^(m-n)) = (n/m)^(n/(m-n))(1-n/m)
1072
1073 const double amplitude = pulseScale / (pow (power1 / power2, 1.0 / (power2 / power1 - 1.0)) * (1.0 - power1 / power2));
1074
1075 // Fill in the samples to the left of the current point.
1076
1077 integer midSample = Sampled_xToLowIndex (him.get(), t), beginSample;
1078 beginSample = midSample - Melder_ifloor (te / his dx);
1079 if (beginSample < 1)
1080 beginSample = 0;
1081 if (midSample > his nx)
1082 midSample = his nx;
1083 for (integer i = beginSample; i <= midSample; i ++) {
1084 const double tsamp = his x1 + (i - 1) * his dx;
1085 phase = (tsamp - (t - te)) / (period * openPhase);
1086 if (phase > 0.0) {
1087 flow = amplitude * (pow (phase, power1) - pow (phase, power2));
1088 if (i == 0) {
1089 lastVal = flow; // For the derivative
1090 continue;
1091 }
1092 sound [i] += flow;
1093
1094 // Breathiness only during open part modulated by the flow
1095 if (breathy) {
1096 double val = flow * NUMrandomUniform (-1.0, 1.0);
1097 double a = RealTier_getValueAtTime (my breathinessAmplitude.get(), t);
1098 breathy -> z [1] [i] += val * DBSPL_to_A (a);
1099 }
1100 }
1101 }
1102
1103 // Determine the signal parameters at the current point.
1104
1105 phase = te / (period * openPhase);
1106
1107 //- double flow = amplitude * (period * openPhase) * (pow (phase, power1) - pow (phase, power2));
1108
1109 flow = amplitude * (pow (phase, power1) - pow (phase, power2));
1110
1111 // Fill in the samples to the right of the current point.
1112
1113 if (flow > 0.0) {
1114 const double ta = collisionPhase * (period * openPhase);
1115 const double factorPerSample = exp (- his dx / ta);
1116 double value = flow * exp (- (his x1 + midSample * his dx - t) / ta);
1117 integer endSample = midSample + Melder_ifloor (20.0 * ta / his dx);
1118 if (endSample > his nx)
1119 endSample = his nx;
1120 for (integer i = midSample + 1; i <= endSample; i ++) {
1121 sound [i] += value;
1122 value *= factorPerSample;
1123 }
1124 }
1125 }
1126
1127 // Scale voiced part and add breathiness during open phase
1128 if (p -> flowDerivative) {
1129 const double extremum = Vector_getAbsoluteExtremum (him.get(), 0.0, 0.0, kVector_peakInterpolation :: CUBIC);
1130 if (isundef (lastVal))
1131 lastVal = 0.0;
1132 for (integer i = 1; i <= his nx; i ++) {
1133 const double val = his z [1] [i];
1134 his z [1] [i] -= lastVal;
1135 lastVal = val;
1136 }
1137 Vector_scale (him.get(), extremum);
1138 }
1139
1140 for (integer i = 1; i <= his nx; i ++) {
1141 const double t = his x1 + (i - 1) * his dx;
1142 his z [1] [i] *= DBSPL_to_A (RealTier_getValueAtTime (my voicingAmplitude.get(), t));
1143 if (breathy)
1144 his z [1] [i] += breathy -> z [1] [i];
1145 }
1146 return him;
1147 } catch (MelderError) {
1148 Melder_throw (me, U": no Sound created.");
1149 }
1150 }
1151
1152 static autoSound PhonationGrid_to_Sound_voiced (PhonationGrid me, double samplingFrequency) {
1153 try {
1154 autoPhonationTier thee = PhonationGrid_to_PhonationTier (me);
1155 return PhonationGrid_PhonationTier_to_Sound_voiced (me, thee.get(), samplingFrequency);
1156 } catch (MelderError) {
1157 Melder_throw (me, U": no voiced Sound created.");
1158 }
1159 }
1160
1161 static autoSound PhonationGrid_to_Sound (PhonationGrid me, CouplingGrid him, double samplingFrequency) {
1162 try {
1163 PhonationGridPlayOptions pp = my options.get();
1164 autoSound thee;
1165 if (pp -> voicing) {
1166 if (him && his glottis -> points.size > 0)
1167 thee = PhonationGrid_PhonationTier_to_Sound_voiced (me, his glottis.get(), samplingFrequency);
1168 else
1169 thee = PhonationGrid_to_Sound_voiced (me, samplingFrequency);
1170 if (pp -> spectralTilt)
1171 Sound_PhonationGrid_spectralTilt_inplace (thee.get(), me);
1172 }
1173 if (pp -> aspiration) {
1174 autoSound aspiration = PhonationGrid_to_Sound_aspiration (me, samplingFrequency);
1175 if (thee)
1176 _Sounds_add_inplace (thee.get(), aspiration.get());
1177 else
1178 thee = aspiration.move();
1179 }
1180 if (! thee)
1181 thee = Sound_createEmptyMono (my xmin, my xmax, samplingFrequency);
1182 return thee;
1183 } catch (MelderError) {
1184 Melder_throw (me, U": no Sound created.");
1185 }
1186 }
1187
1188 static void formantsAmplitudes_create (OrderedOf<structIntensityTier>* me, double tmin, double tmax, integer numberOfFormants) {
1189 try {
1190 for (integer i = 1; i <= numberOfFormants; i ++) {
1191 autoIntensityTier a = IntensityTier_create (tmin, tmax);
1192 me -> addItem_move (a.move());
1193 }
1194 } catch (MelderError) {
1195 Melder_throw (U"No formants amplitudes created.");
1196 };
1197 }
1198
1199 /********************** VocalTractGridPlayOptions **********************/
1200
1201 Thing_implement (VocalTractGridPlayOptions, Daata, 0);
1202
1203 static void VocalTractGridPlayOptions_setDefaults (VocalTractGridPlayOptions me, VocalTractGrid thee) {
1204 my filterModel = kKlattGridFilterModel::CASCADE;
1205 my endOralFormant = std::min (thy oral_formants -> formants.size, thy oral_formants -> bandwidths.size);
1206 my startOralFormant = 1;
1207 my endNasalFormant = std::min (thy nasal_formants -> formants.size, thy nasal_formants -> bandwidths.size);
1208 my startNasalFormant = 1;
1209 my endNasalAntiFormant = std::min (thy nasal_antiformants -> formants.size, thy nasal_antiformants -> bandwidths.size);
1210 my startNasalAntiFormant = 1;
1211 }
1212
1213 autoVocalTractGridPlayOptions VocalTractGridPlayOptions_create () {
1214 try {
1215 autoVocalTractGridPlayOptions me = Thing_new (VocalTractGridPlayOptions);
1216 return me;
1217 } catch (MelderError) {
1218 Melder_throw (U"VocalTractGridPlayOptions not created.");
1219 }
1220 }
1221
1222 /********************** VocalTractGrid ***************************************/
1223
1224 static integer FormantGrid_getNumberOfFormantPoints (FormantGrid me, integer iformant) {
1225 if (iformant < 1 || iformant > my formants.size)
1226 return -1;
1227 const RealTier f = my formants.at [iformant];
1228 return f -> points.size;
1229 }
1230
1231 static integer FormantGrid_getNumberOfBandwidthPoints (FormantGrid me, integer iformant) {
1232 if (iformant < 1 || iformant > my bandwidths.size)
1233 return -1;
1234 const RealTier b = my bandwidths.at [iformant];
1235 return b -> points.size;
1236 }
1237
1238 static integer Ordered_getNumberOfAmplitudePoints (OrderedOf<structIntensityTier>* me, integer iformant) {
1239 if (! me || iformant < 1 || iformant > my size)
1240 return -1;
1241 const RealTier t = my at [iformant];
1242 return t -> points.size;
1243 }
1244
1245 static void FormantGrid_info (FormantGrid me, OrderedOf<structIntensityTier>* amplitudes, conststring32 in1, conststring32 in2) {
1246 const integer nformants = my formants.size;
1247 const integer namplitudes = ( amplitudes ? amplitudes->size : 0 );
1248 const integer nmax = std::max (nformants, namplitudes);
1249
1250 for (integer iformant = 1; iformant <= nmax; iformant ++) {
1251 MelderInfo_writeLine (in1, U"Formant ", iformant, U":");
1252 if (iformant <= my formants.size) {
1253 const integer nfp = FormantGrid_getNumberOfFormantPoints (me, iformant);
1254 const integer nbp = FormantGrid_getNumberOfBandwidthPoints (me, iformant);
1255 MelderInfo_writeLine (in2, U"formants: ", ( nfp >= 0 ? Melder_integer (nfp) : U"--undefined--" ));
1256 MelderInfo_writeLine (in2, U"bandwidths: ", ( nbp >= 0 ? Melder_integer (nbp) : U"--undefined--" ));
1257 }
1258 if (amplitudes) {
1259 const integer nap = Ordered_getNumberOfAmplitudePoints (amplitudes, iformant);
1260 MelderInfo_writeLine (in2, U"amplitudes: ", ( nap >= 0 ? Melder_integer (nap) : U"--undefined--" ));
1261 }
1262 }
1263 }
1264
1265 void structVocalTractGrid :: v1_info () {
1266 our structDaata :: v1_info ();
1267 const conststring32 in1 = U" ", in2 = U" ", in3 = U" ";
1268 MelderInfo_writeLine (in1, U"Time domain:");
1269 MelderInfo_writeLine (in2, U"Start time: ", our xmin, U" seconds");
1270 MelderInfo_writeLine (in2, U"End time: ", our xmax, U" seconds");
1271 MelderInfo_writeLine (in2, U"Total duration: ", our xmax - our xmin, U" seconds");
1272 MelderInfo_writeLine (in1, U"\nNumber of points in the ORAL FORMANT tiers:");
1273 FormantGrid_info (our oral_formants.get(), & our oral_formants_amplitudes, in2, in3);
1274 MelderInfo_writeLine (in1, U"\nNumber of points in the NASAL FORMANT tiers:");
1275 FormantGrid_info (our nasal_formants.get(), & our nasal_formants_amplitudes, in2, in3);
1276 MelderInfo_writeLine (in1, U"\nNumber of points in the NASAL ANTIFORMANT tiers:");
1277 FormantGrid_info (our nasal_antiformants.get(), nullptr, in2, in3);
1278 }
1279
1280 Thing_implement (VocalTractGrid, Function, 0);
1281
1282 void VocalTractGrid_setNames (VocalTractGrid me) {
1283 Thing_setName (my oral_formants.get(), U"oral_formants");
1284 Thing_setName (my nasal_formants.get(), U"nasal_formants");
1285 Thing_setName (my nasal_antiformants.get(), U"nasal_antiformants");
1286 //Thing_setName (my oral_formants_amplitudes.get(), U"oral_formants_amplitudes");
1287 //Thing_setName (my nasal_formants_amplitudes.get(), U"nasal_formants_amplitudes");
1288 }
1289
1290 autoVocalTractGrid VocalTractGrid_create (double tmin, double tmax, integer numberOfFormants, integer numberOfNasalFormants, integer numberOfNasalAntiFormants) {
1291 try {
1292 autoVocalTractGrid me = Thing_new (VocalTractGrid);
1293 Function_init (me.get(), tmin, tmax);
1294 my oral_formants = FormantGrid_createEmpty (tmin, tmax, numberOfFormants);
1295 my nasal_formants = FormantGrid_createEmpty (tmin, tmax, numberOfNasalFormants);
1296 my nasal_antiformants = FormantGrid_createEmpty (tmin, tmax, numberOfNasalAntiFormants);
1297 formantsAmplitudes_create (& my oral_formants_amplitudes, tmin, tmax, numberOfFormants);
1298 formantsAmplitudes_create (& my nasal_formants_amplitudes, tmin, tmax, numberOfNasalFormants);
1299 my options = VocalTractGridPlayOptions_create ();
1300 VocalTractGrid_setNames (me.get());
1301 return me;
1302 } catch (MelderError) {
1303 Melder_throw (U"VocalTractGrid not created.");
1304 }
1305 }
1306
1307 static void VocalTractGrid_CouplingGrid_drawCascade_inplace (VocalTractGrid me, CouplingGrid thee, Graphics g, double xmin, double xmax, double ymin, double ymax, double *out_yin, double *out_yout) {
1308 const integer numberOfOralFormants = my oral_formants -> formants.size;
1309 const integer numberOfNasalFormants = my nasal_formants -> formants.size;
1310 const integer numberOfNasalAntiFormants = my nasal_antiformants -> formants.size;
1311 const integer numberOfTrachealFormants = ( thee ? thy tracheal_formants -> formants.size : 0 );
1312 const integer numberOfTrachealAntiFormants = ( thee ? thy tracheal_antiformants -> formants.size : 0 );
1313 const double ddx = 0.2, ymid = (ymin + ymax) / 2.0;
1314 autoSTRVEC text { U"TF", U"TAF", U"NF", U"NAF", U""};
1315 autoINTVEC nf { numberOfTrachealFormants, numberOfTrachealAntiFormants, numberOfNasalFormants, numberOfNasalAntiFormants, numberOfOralFormants };
1316 autoSTRVEC sectionText (3);
1317 autoMelderString ff, fb;
1318 integer nsx = 0;
1319
1320 if (out_yin)
1321 *out_yin = ymid;
1322 if (out_yout)
1323 *out_yout = ymid;
1324 const integer numberOfFilters = numberOfNasalFormants + numberOfNasalAntiFormants + numberOfTrachealFormants + numberOfTrachealAntiFormants + numberOfOralFormants;
1325 double x1, x2;
1326 if (numberOfFilters == 0) {
1327 Graphics_line (g, xmin, ymid, xmax, ymid);
1328 return;
1329 }
1330
1331 for (integer isection = 1; isection <= nf.size; isection ++)
1332 if (nf [isection] > 0)
1333 nsx ++;
1334
1335 const double dx = (xmax - xmin) / (numberOfFilters + 1);
1336 const double boxWidth = (xmax - xmin) / (numberOfFilters + 1 + (nsx - 1) * ddx);
1337 const double oldFontSize = Graphics_inqFontSize (g);
1338 double newFontSize = Graphics_getFontSizeInsideBox (g, boxWidth, ymax - ymin, 4.0, 4.0);
1339 if (newFontSize < oldFontSize)
1340 Graphics_setFontSize (g, newFontSize);
1341
1342 x1 = xmin;
1343 for (integer isection = 1; isection <= nf.size; isection ++) {
1344 const integer numberOfFormants = nf [isection];
1345
1346 if (numberOfFormants == 0)
1347 continue;
1348 sectionText [1] = Melder_dup (text [isection].get());
1349 for (integer i = 1; i <= numberOfFormants; i ++) {
1350 MelderString_copy (& ff, U"F", i);
1351 MelderString_copy (& fb, U"B", i);
1352 sectionText [2] = Melder_dup (ff.string);
1353 sectionText [3] = Melder_dup (fb.string);
1354 x2 = x1 + boxWidth;
1355 drawLinesInBox (g, x1, x2, ymin, ymax, sectionText.get());
1356 x1 += dx;
1357 }
1358 x1 += ddx * dx;
1359 Graphics_line (g, x2, ymid, x1, ymid);
1360 }
1361 if (x1 < xmax)
1362 Graphics_line (g, x1, ymid, xmax, ymid);
1363 Graphics_setFontSize (g, oldFontSize);
1364 }
1365
1366 static void VocalTractGrid_CouplingGrid_drawParallel_inplace (VocalTractGrid me, CouplingGrid thee, Graphics g, double xmin, double xmax, double ymin, double ymax, double dy, double *out_yin, double *out_yout) {
1367 const integer numberOfNasalFormants = my nasal_formants -> formants.size;
1368 const integer numberOfOralFormants = my oral_formants -> formants.size;
1369 const integer numberOfTrachealFormants = ( thee ? thy tracheal_formants -> formants.size : 0 );
1370 const integer numberOfFormants = numberOfNasalFormants + numberOfOralFormants + numberOfTrachealFormants;
1371 const integer numberOfUpperPartFormants = numberOfNasalFormants + ( numberOfOralFormants > 0 ? 1 : 0 );
1372 const integer numberOfLowerPartFormants = numberOfFormants - numberOfUpperPartFormants;
1373 const conststring32 text [5] = { nullptr, U"Nasal", U"", U"", U"Tracheal" };
1374 autoINTVEC nffrom = { 1, 1, 2, 1 };
1375 autoINTVEC nfto = { numberOfNasalFormants, ( numberOfOralFormants > 0 ? 1 : 0 ), numberOfOralFormants, numberOfTrachealFormants };
1376 // (1: hor. line to split) (2: split to diff) (3: diff) (4: diff to split)
1377 // (5: split to filter) (6: filters) (7: conn to summer) (8: summer)
1378 autoVEC relativeWidths { 0.3, 0.2, 1.5, 0.5, 0.5, 1.0, 0.5, 0.5 }, accumulatedWidths = zero_VEC (relativeWidths.size);
1379 autoMelderString fba;
1380
1381 scaleRelativeAndAccumulatedWidths (relativeWidths.get(), accumulatedWidths.get(), xmax - xmin);
1382
1383 double y1, y2;
1384 if (numberOfFormants == 0) {
1385 y1 = y2 = (ymin + ymax) / 2.0;
1386 Graphics_line (g, xmin, y1, xmax, y1);
1387 if (out_yin)
1388 *out_yin = y1;
1389 if (out_yout)
1390 *out_yout = y2;
1391 return;
1392 }
1393
1394 const double ddy = ( dy < 0 ? 0.0 : dy);
1395 dy = (ymax - ymin) / (numberOfFormants * (1.0 + ddy) - ddy);
1396
1397 const connections local_in = connections_create (numberOfFormants);
1398 const connections local_out = connections_create (numberOfFormants);
1399
1400 // parallel section
1401 double x1 = xmin + accumulatedWidths [5];
1402 double x2 = x1 + relativeWidths [6];
1403 y2 = ymax;
1404 double x3 = xmin + accumulatedWidths [4];
1405 integer ic = 0;
1406 autoSTRVEC fbLines (2);
1407 double numberOfCharacters = 9.0 + (numberOfOralFormants < 10 ? 0 : 3 );
1408 double oldFontSize = Graphics_inqFontSize (g);
1409 double fontSizeFormants = Graphics_getFontSizeInsideBox (g, relativeWidths [6], dy, numberOfCharacters, 2.5);
1410 const double fontSizePreEmphasis = Graphics_getFontSizeInsideBox (g, relativeWidths [3], dy, 13.0, 1.5);
1411 double newFontSize = std::min (fontSizePreEmphasis, fontSizeFormants);
1412 if (newFontSize < oldFontSize)
1413 Graphics_setFontSize (g, newFontSize);
1414
1415 for (integer isection = 1; isection <= nffrom.size; isection ++) {
1416 const integer ifrom = nffrom [isection], ito = nfto [isection];
1417 if (ito < ifrom)
1418 continue;
1419 fbLines [1] = Melder_dup (text [isection]);
1420 for (integer i = ifrom; i <= ito; i ++) {
1421 y1 = y2 - dy;
1422 const double ymid = (y1 + y2) / 2.0;
1423 const conststring32 fi = Melder_integer (i);
1424 MelderString_copy (& fba, U"A", fi, U" F", fi, U" B", fi);
1425 fbLines [2] = Melder_dup (fba.string);
1426 drawLinesInBox (g, x1, x2, y1, y2, fbLines.get());
1427 Graphics_line (g, x3, ymid, x1, ymid); // to the left
1428 ic ++;
1429 local_in -> x [ic] = x3;
1430 local_out -> x [ic] = x2;
1431 local_in -> y [ic] = local_out -> y [ic] = ymid;
1432 y2 = y1 - 0.5 * dy;
1433 }
1434 }
1435
1436 ic = 0;
1437 x1 = local_in -> y [1];
1438 if (numberOfUpperPartFormants > 0) {
1439 x1 = local_in -> x [numberOfUpperPartFormants];
1440 y1 = local_in -> y [numberOfUpperPartFormants];
1441 if (numberOfUpperPartFormants > 1)
1442 Graphics_line (g, x1, y1, local_in -> x [1], local_in -> y [1]); // vertical
1443 x2 = xmin;
1444 if (numberOfLowerPartFormants > 0)
1445 x2 += relativeWidths [1];
1446 Graphics_line (g, x1, y1, x2, y1); // done
1447 }
1448 if (numberOfLowerPartFormants > 0) {
1449 const integer ifrom = numberOfUpperPartFormants + 1;
1450 x1 = local_in -> x [ifrom];
1451 y1 = local_in -> y [ifrom]; // at the split
1452 if (numberOfLowerPartFormants > 1)
1453 Graphics_line (g, x1, y1, local_in -> x [numberOfFormants], local_in -> y [numberOfFormants]); // vertical
1454 x2 = xmin + accumulatedWidths [3]; // right of diff
1455 Graphics_line (g, x1, y1, x2, y1); // from vertical to diff
1456 x1 = xmin + accumulatedWidths [2]; // left of diff
1457 autoSTRVEC preEmphasisLine { U"Pre-emphasis" };
1458 drawLinesInBox (g, x1, x2, y1 + 0.5 * dy, y1 - 0.5 * dy, preEmphasisLine.get());
1459 x2 = x1;
1460 if (numberOfUpperPartFormants > 0) {
1461 x2 = xmin + relativeWidths [1];
1462 y2 = y1; // at split
1463 Graphics_line (g, x1, y1, x2, y1); // to split
1464 y1 += (1 + ddy) * dy;
1465 Graphics_line (g, x2, y2, x2, y1); // vertical
1466 y1 -= 0.5 * (1.0 + ddy) * dy;
1467 }
1468 Graphics_line (g, xmin, y1, x2, y1);
1469 }
1470
1471 const double r = relativeWidths [8] / 2.0;
1472 x2 = xmax - r;
1473 y2 = (ymin + ymax) / 2.0;
1474
1475 alternatingSummer_drawConnections (g, x2, y2, r, local_out, true, 0.4);
1476
1477 connections_free (local_out);
1478 connections_free (local_in);
1479 Graphics_setFontSize (g, oldFontSize);
1480 if (out_yin)
1481 *out_yin = y1;
1482 if (out_yout)
1483 *out_yout = y2;
1484 }
1485
1486 static void VocalTractGrid_CouplingGrid_draw_inside (VocalTractGrid me, CouplingGrid thee, Graphics g, kKlattGridFilterModel filterModel, double xmin, double xmax, double ymin, double ymax, double dy, double *out_yin, double *out_yout) {
1487 if (filterModel == kKlattGridFilterModel::CASCADE)
1488 VocalTractGrid_CouplingGrid_drawCascade_inplace (me, thee, g, xmin, xmax, ymin, ymax, out_yin, out_yout);
1489 else if (filterModel == kKlattGridFilterModel::PARALLEL)
1490 VocalTractGrid_CouplingGrid_drawParallel_inplace (me, thee, g, xmin, xmax, ymin, ymax, dy, out_yin, out_yout);
1491 else
1492 ;// Not valid
1493 }
1494
1495 static void VocalTractGrid_CouplingGrid_draw (VocalTractGrid me, CouplingGrid thee, Graphics g, kKlattGridFilterModel filterModel) {
1496 const double xmin = 0.0, xmin1 = 0.05, xmax1 = 0.95, xmax = 1.0, ymin = 0.0, ymax = 1.0, dy = 0.5;
1497
1498 Graphics_setInner (g);
1499 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1500 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1501 Graphics_setLineWidth (g, 2);
1502 double yin, yout;
1503 VocalTractGrid_CouplingGrid_draw_inside (me, thee, g, filterModel, xmin1, xmax1, ymin, ymax, dy, & yin, & yout);
1504 Graphics_line (g, xmin, yin, xmin1, yin);
1505 Graphics_arrow (g, xmax1, yout, xmax, yout);
1506 Graphics_unsetInner (g);
1507 }
1508
1509 static autoSound Sound_VocalTractGrid_CouplingGrid_filter_cascade (Sound me, VocalTractGrid thee, CouplingGrid coupling) {
1510 try {
1511 const VocalTractGridPlayOptions pv = thy options.get();
1512 const CouplingGridPlayOptions pc = coupling -> options.get();
1513 const bool useOpenGlottisInfo = pc -> openglottis && coupling && coupling -> glottis && coupling -> glottis -> points.size > 0;
1514 const FormantGrid oral_formants = thy oral_formants.get();
1515 const FormantGrid nasal_formants = thy nasal_formants.get();
1516 const FormantGrid nasal_antiformants = thy nasal_antiformants.get();
1517 const FormantGrid tracheal_formants = coupling -> tracheal_formants.get();
1518 const FormantGrid tracheal_antiformants = coupling -> tracheal_antiformants.get();
1519
1520 const integer numberOfFormants = oral_formants -> formants.size;
1521 const integer numberOfTrachealFormants = tracheal_formants -> formants.size;
1522 const integer numberOfTrachealAntiFormants = tracheal_antiformants -> formants.size;
1523 const integer numberOfNasalFormants = nasal_formants -> formants.size;
1524 const integer numberOfNasalAntiFormants = nasal_antiformants -> formants.size;
1525 check_formants (numberOfFormants, & pv -> startOralFormant, & pv -> endOralFormant);
1526 check_formants (numberOfNasalFormants, & pv -> startNasalFormant, & pv -> endNasalFormant);
1527 check_formants (numberOfTrachealFormants, & pc -> startTrachealFormant, & pc -> endTrachealFormant);
1528 check_formants (numberOfNasalAntiFormants, & pv -> startNasalAntiFormant, & pv -> endNasalAntiFormant);
1529 check_formants (numberOfTrachealAntiFormants, & pc -> startTrachealAntiFormant, & pc -> endTrachealAntiFormant);
1530
1531 autoSound him = Data_copy (me);
1532
1533 autoFormantGrid formants;
1534 if (useOpenGlottisInfo) {
1535 formants = Data_copy (thy oral_formants.get());
1536 FormantGrid_CouplingGrid_updateOpenPhases (formants.get(), coupling);
1537 }
1538
1539 integer nasal_formant_warning = 0, any_warning = 0;
1540 if (pv -> endNasalFormant > 0) { // nasal formants
1541 for (integer iformant = pv -> startNasalFormant; iformant <= pv -> endNasalFormant; iformant ++) {
1542 if (FormantGrid_isFormantDefined (thy nasal_formants.get(), iformant)) {
1543 _Sound_FormantGrid_filterWithOneFormant_inplace (him.get(), thy nasal_formants.get(), iformant, false);
1544 } else {
1545 // Melder_warning ("Nasal formant", iformant, ": frequency and/or bandwidth missing.");
1546 nasal_formant_warning ++;
1547 any_warning ++;
1548 }
1549 }
1550 }
1551
1552 integer nasal_antiformant_warning = 0;
1553 if (pv -> endNasalAntiFormant > 0) { // nasal antiformants
1554 for (integer iformant = pv -> startNasalAntiFormant; iformant <= pv -> endNasalAntiFormant; iformant ++) {
1555 if (FormantGrid_isFormantDefined (thy nasal_antiformants.get(), iformant)) {
1556 _Sound_FormantGrid_filterWithOneFormant_inplace (him.get(), thy nasal_antiformants.get(), iformant, true);
1557 } else {
1558 // Melder_warning ("Nasal antiformant", iformant, ": frequency and/or bandwidth missing.");
1559 nasal_antiformant_warning ++;
1560 any_warning ++;
1561 }
1562 }
1563 }
1564
1565 integer tracheal_formant_warning = 0;
1566 if (pc -> endTrachealFormant > 0) { // tracheal formants
1567 for (integer iformant = pc -> startTrachealFormant; iformant <= pc -> endTrachealFormant; iformant ++) {
1568 if (FormantGrid_isFormantDefined (tracheal_formants, iformant)) {
1569 _Sound_FormantGrid_filterWithOneFormant_inplace (him.get(), tracheal_formants, iformant, false);
1570 } else {
1571 // Melder_warning ("Tracheal formant", iformant, ": frequency and/or bandwidth missing.");
1572 tracheal_formant_warning ++;
1573 any_warning ++;
1574 }
1575 }
1576 }
1577
1578 integer tracheal_antiformant_warning = 0;
1579 if (pc -> endTrachealAntiFormant > 0) { // tracheal antiformants
1580 for (integer iformant = pc -> startTrachealAntiFormant; iformant <= pc -> endTrachealAntiFormant; iformant ++) {
1581 if (FormantGrid_isFormantDefined (tracheal_antiformants, iformant)) {
1582 _Sound_FormantGrid_filterWithOneFormant_inplace (him.get(), tracheal_antiformants, iformant, true);
1583 } else {
1584 // Melder_warning ("Tracheal antiformant", iformant, ": frequency and/or bandwidth missing.");
1585 tracheal_antiformant_warning ++;
1586 any_warning ++;
1587 }
1588 }
1589 }
1590
1591 integer oral_formant_warning = 0;
1592 if (pv -> endOralFormant > 0) { // oral formants
1593 if (! formants)
1594 formants = Data_copy (thy oral_formants.get());
1595
1596 for (integer iformant = pv -> startOralFormant; iformant <= pv -> endOralFormant; iformant ++) {
1597 if (FormantGrid_isFormantDefined (formants.get(), iformant)) {
1598 _Sound_FormantGrid_filterWithOneFormant_inplace (him.get(), formants.get(), iformant, false);
1599 } else {
1600 // Melder_warning ("Oral formant", iformant, ": frequency and/or bandwidth missing.");
1601 oral_formant_warning ++;
1602 any_warning ++;
1603 }
1604 }
1605 }
1606 if (any_warning > 0)
1607 {
1608 autoMelderString warning;
1609 if (nasal_formant_warning > 0)
1610 MelderString_append (& warning, U"\tNasal formants: one or more are missing.\n");
1611 if (nasal_antiformant_warning)
1612 MelderString_append (& warning, U"\tNasal antiformants: one or more are missing.\n");
1613 if (tracheal_formant_warning)
1614 MelderString_append (& warning, U"\tTracheal formants: one or more are missing.\n");
1615 if (tracheal_antiformant_warning)
1616 MelderString_append (& warning, U"\tTracheal antiformants: one or more are missing.\n");
1617 if (oral_formant_warning)
1618 MelderString_append (& warning, U"\tOral formants: one or more are missing.\n");
1619 MelderInfo_write (U"\nWarning:\n", warning.string);
1620 MelderInfo_drain ();
1621 }
1622 return him;
1623 } catch (MelderError) {
1624 Melder_throw (me, U": not filtered by vocaltract and coupling grid.");
1625 }
1626 }
1627
1628 static autoSound Sound_VocalTractGrid_CouplingGrid_filter_parallel (Sound me, VocalTractGrid thee, CouplingGrid coupling) {
1629 try {
1630 const VocalTractGridPlayOptions pv = thy options.get();
1631 const CouplingGridPlayOptions pc = coupling -> options.get();
1632 autoSound him;
1633 FormantGrid oral_formants = thy oral_formants.get();
1634 autoFormantGrid aof;
1635 int alternatingSign = 0; // 0: no alternating signs in parallel adding of filter outputs, 1/-1 start sign
1636 const bool useOpenGlottisInfo = pc -> openglottis && coupling -> glottis && coupling -> glottis -> points.size > 0;
1637 int scale = 1;
1638 const integer numberOfFormants = thy oral_formants -> formants.size;
1639 const integer numberOfNasalFormants = thy nasal_formants -> formants.size;
1640 const integer numberOfTrachealFormants = coupling -> tracheal_formants -> formants.size;
1641
1642 check_formants (numberOfFormants, & (pv -> startOralFormant), & (pv -> endOralFormant));
1643 check_formants (numberOfNasalFormants, & (pv -> startNasalFormant), & (pv -> endNasalFormant));
1644 check_formants (numberOfTrachealFormants, & (pc -> startTrachealFormant), & (pc -> endTrachealFormant));
1645
1646 if (useOpenGlottisInfo) {
1647 aof = Data_copy (thy oral_formants.get());
1648 oral_formants = aof.get();
1649 FormantGrid_CouplingGrid_updateOpenPhases (oral_formants, coupling);
1650 }
1651
1652 if (pv -> endOralFormant > 0) {
1653 if (pv -> startOralFormant == 1) {
1654 him = Data_copy (me);
1655 if (oral_formants -> formants.size > 0)
1656 Sound_FormantGrid_Intensities_filterWithOneFormant_inplace (him.get(), oral_formants, & thy oral_formants_amplitudes, 1);
1657 }
1658 }
1659
1660 if (pv -> endNasalFormant > 0) {
1661 alternatingSign = 0;
1662 autoSound nasal = Sound_FormantGrid_Intensities_filter (me, thy nasal_formants.get(), & thy nasal_formants_amplitudes, pv -> startNasalFormant, pv -> endNasalFormant, alternatingSign);
1663
1664 if (! him)
1665 him = Data_copy (nasal.get());
1666 else
1667 _Sounds_add_inplace (him.get(), nasal.get());
1668 }
1669
1670 // Formants 2 and up, with alternating signs.
1671 // We perform pre-emphasis by differentiating.
1672 // Klatt (1980) states that a first difference for the higher formants is necessary to remove low-frequency
1673 // energy from them. This energy would otherwise distort the spectrum in the region of F1 during the synthesis
1674 // of some vowels.
1675
1676 autoSound me_diff = _Sound_diff (me, scale);
1677
1678 if (pv -> endOralFormant >= 2) {
1679 const integer startOralFormant2 = ( pv -> startOralFormant > 2 ? pv -> startOralFormant : 2 );
1680 alternatingSign = ( startOralFormant2 % 2 == 0 ? -1 : 1 ); // 2 starts with negative sign
1681 if (startOralFormant2 <= oral_formants -> formants.size) {
1682 autoSound vocalTract = Sound_FormantGrid_Intensities_filter (me_diff.get(), oral_formants, & thy oral_formants_amplitudes, startOralFormant2, pv -> endOralFormant, alternatingSign);
1683
1684 if (! him)
1685 him = Data_copy (vocalTract.get());
1686 else
1687 _Sounds_add_inplace (him.get(), vocalTract.get());
1688 }
1689 }
1690
1691 if (pc -> endTrachealFormant > 0) { // tracheal formants
1692 alternatingSign = 0;
1693 autoSound trachea = Sound_FormantGrid_Intensities_filter (me_diff.get(), coupling -> tracheal_formants.get(),
1694 & coupling -> tracheal_formants_amplitudes,
1695 pc -> startTrachealFormant, pc -> endTrachealFormant, alternatingSign);
1696
1697 if (! him)
1698 him = Data_copy (trachea.get());
1699 else
1700 _Sounds_add_inplace (him.get(), trachea.get());
1701 }
1702
1703 if (! him)
1704 him = Data_copy (me);
1705 return him;
1706 } catch (MelderError) {
1707 Melder_throw (me, U": not filtered in parallel.");
1708 }
1709 }
1710
1711 autoSound Sound_VocalTractGrid_CouplingGrid_filter (Sound me, VocalTractGrid thee, CouplingGrid coupling) {
1712 return thy options -> filterModel == kKlattGridFilterModel::CASCADE ?
1713 Sound_VocalTractGrid_CouplingGrid_filter_cascade (me, thee, coupling) :
1714 Sound_VocalTractGrid_CouplingGrid_filter_parallel (me, thee, coupling);
1715 }
1716
1717 /********************** CouplingGridPlayOptions **********************/
1718
1719 Thing_implement (CouplingGridPlayOptions, Daata, 0);
1720
1721 static void CouplingGridPlayOptions_setDefaults (CouplingGridPlayOptions me, CouplingGrid thee) {
1722 my fadeFraction = 0.1;
1723 my openglottis = 1;
1724 my endTrachealFormant = std::min (thy tracheal_formants -> formants.size, thy tracheal_formants -> bandwidths.size);
1725 my startTrachealFormant = 1;
1726 my endTrachealAntiFormant = std::min (thy tracheal_antiformants -> formants.size, thy tracheal_antiformants -> bandwidths.size);
1727 my startTrachealAntiFormant = 1;
1728 my startDeltaFormant = 1;
1729 my endDeltaFormant = thy delta_formants -> formants.size;
1730 my startDeltaBandwidth = 1;
1731 my endDeltaBandwidth = thy delta_formants -> bandwidths.size;
1732 }
1733
1734 autoCouplingGridPlayOptions CouplingGridPlayOptions_create () {
1735 try {
1736 autoCouplingGridPlayOptions me = Thing_new (CouplingGridPlayOptions);
1737 return me;
1738 } catch (MelderError) {
1739 Melder_throw (U"CouplingGridPlayOptions not created.");
1740 }
1741 }
1742
1743 /********************** CouplingGrid *************************************/
1744
1745 Thing_implement (CouplingGrid, Function, 0);
1746
1747 void structCouplingGrid :: v1_info () {
1748 structDaata :: v1_info ();
1749 conststring32 in1 = U" ", in2 = U" ", in3 = U" ";
1750 MelderInfo_writeLine (in1, U"Time domain:");
1751 MelderInfo_writeLine (in2, U"Start time: ", xmin, U" seconds");
1752 MelderInfo_writeLine (in2, U"End time: ", xmax, U" seconds");
1753 MelderInfo_writeLine (in2, U"Total duration: ", xmax - xmin, U" seconds");
1754 MelderInfo_writeLine (in1, U"\nNumber of points in the TRACHEAL FORMANT tiers:");
1755 FormantGrid_info (our tracheal_formants.get(), & tracheal_formants_amplitudes, in2, in3);
1756 MelderInfo_writeLine (in1, U"\nNumber of points in the TRACHEAL ANTIFORMANT tiers:");
1757 FormantGrid_info (our tracheal_antiformants.get(), nullptr, in2, in3);
1758 MelderInfo_writeLine (in1, U"\nNumber of points in the DELTA FORMANT tiers:");
1759 FormantGrid_info (our delta_formants.get(), nullptr, in2, in3);
1760 }
1761
1762 void CouplingGrid_setNames (CouplingGrid me) {
1763 Thing_setName (my tracheal_formants.get(), U"tracheal_formants");
1764 Thing_setName (my tracheal_antiformants.get(), U"tracheal_antiformants");
1765 //Thing_setName (my tracheal_formants_amplitudes.get(), U"tracheal_formants_amplitudes");
1766 Thing_setName (my delta_formants.get(), U"delta_formants");
1767 Thing_setName (my glottis.get(), U"glottis");
1768 }
1769
1770 autoCouplingGrid CouplingGrid_create (double tmin, double tmax, integer numberOfTrachealFormants, integer numberOfTrachealAntiFormants, integer numberOfDeltaFormants) {
1771 try {
1772 autoCouplingGrid me = Thing_new (CouplingGrid);
1773 Function_init (me.get(), tmin, tmax);
1774 my tracheal_formants = FormantGrid_createEmpty (tmin, tmax, numberOfTrachealFormants);
1775 my tracheal_antiformants = FormantGrid_createEmpty (tmin, tmax, numberOfTrachealAntiFormants);
1776 formantsAmplitudes_create (& my tracheal_formants_amplitudes, tmin, tmax, numberOfTrachealFormants);
1777 my delta_formants = FormantGrid_createEmpty (tmin, tmax, numberOfDeltaFormants);
1778 my glottis = PhonationTier_create (tmin, tmax);
1779 my options = CouplingGridPlayOptions_create ();
1780 CouplingGrid_setNames (me.get());
1781 return me;
1782 } catch (MelderError) {
1783 Melder_throw (U"CouplingGrid not created.");
1784 }
1785 }
1786
1787 /********************** FormantGrid & CouplingGrid *************************************/
1788
1789 void FormantGrid_CouplingGrid_updateOpenPhases (FormantGrid me, CouplingGrid thee) {
1790 try {
1791 CouplingGridPlayOptions pc = thy options.get();
1792 for (integer itier = 1; itier <= thy delta_formants -> formants.size; itier ++) {
1793 RealTier delta = thy delta_formants -> formants.at [itier];
1794 if (itier <= my formants.size) {
1795 if (delta -> points.size > 0) {
1796 autoRealTier rt = RealTier_updateWithDelta (my formants.at [itier], delta, thy glottis.get(), pc -> fadeFraction);
1797 Melder_require (RealTier_valuesInRange (rt.get(), 0, undefined),
1798 U"Formant ", itier, U" coupling should not give negative values.");
1799
1800 my formants. replaceItem_move (rt.move(), itier);
1801 }
1802 }
1803 delta = thy delta_formants -> bandwidths.at [itier];
1804 if (itier <= my bandwidths.size) {
1805 if (delta -> points.size > 0) {
1806 autoRealTier rt = RealTier_updateWithDelta (my bandwidths.at [itier], delta, thy glottis.get(), pc -> fadeFraction);
1807 Melder_require (RealTier_valuesInRange (rt.get(), 0, undefined),
1808 U"Bandwidth ", itier, U" coupling gives negative values.");
1809 my bandwidths. replaceItem_move (rt.move(), itier);
1810 }
1811 }
1812 }
1813 } catch (MelderError) {
1814 Melder_throw (me, U": not updated with open hase information.");
1815 }
1816 }
1817
1818 /********************** FricationGridPlayOptions **********************/
1819
1820 Thing_implement (FricationGridPlayOptions, Daata, 0);
1821
1822 static void FricationGridPlayOptions_setDefaults (FricationGridPlayOptions me, FricationGrid thee) {
1823 my endFricationFormant = std::min (thy frication_formants -> formants.size, thy frication_formants -> bandwidths.size);
1824 my startFricationFormant = 2;
1825 my bypass = 1;
1826 }
1827
1828 autoFricationGridPlayOptions FricationGridPlayOptions_create () {
1829 try {
1830 autoFricationGridPlayOptions me = Thing_new (FricationGridPlayOptions);
1831 return me;
1832 } catch (MelderError) {
1833 Melder_throw (U"FricationGridPlayOptions not created.");
1834 }
1835 }
1836
1837 /************************ FricationGrid (& Sound) *********************************************/
1838
1839 void structFricationGrid :: v1_info () {
1840 structDaata :: v1_info ();
1841 const static char32 *in1 = U" ", *in2 = U" ", *in3 = U" ";
1842 MelderInfo_writeLine (in1, U"Time domain:");
1843 MelderInfo_writeLine (in2, U"Start time: ", xmin, U" seconds");
1844 MelderInfo_writeLine (in2, U"End time: ", xmax, U" seconds");
1845 MelderInfo_writeLine (in2, U"Total duration: ", xmax - xmin, U" seconds");
1846 MelderInfo_writeLine (in1, U"\nNumber of points in the FRICATION tiers:");
1847 MelderInfo_writeLine (in2, U"fricationAmplitude: ", fricationAmplitude -> points.size);
1848 MelderInfo_writeLine (in2, U"bypass: ", bypass -> points.size);
1849 MelderInfo_writeLine (in1, U"\nNumber of points in the FRICATION FORMANT tiers:");
1850 FormantGrid_info (our frication_formants.get(), & our frication_formants_amplitudes, in2, in3);
1851 }
1852
1853 Thing_implement (FricationGrid, Function, 0);
1854
1855 void FricationGrid_setNames (FricationGrid me) {
1856 Thing_setName (my fricationAmplitude.get(), U"fricationAmplitude");
1857 Thing_setName (my frication_formants.get(), U"frication_formants");
1858 Thing_setName (my bypass.get(), U"bypass");
1859 //Thing_setName (my frication_formants_amplitudes.get(), U"frication_formants_amplitudes");
1860 }
1861
1862 autoFricationGrid FricationGrid_create (double tmin, double tmax, integer numberOfFormants) {
1863 try {
1864 autoFricationGrid me = Thing_new (FricationGrid);
1865 Function_init (me.get(), tmin, tmax);
1866 my fricationAmplitude = IntensityTier_create (tmin, tmax);
1867 my frication_formants = FormantGrid_createEmpty (tmin, tmax, numberOfFormants);
1868 my bypass = IntensityTier_create (tmin, tmax);
1869 formantsAmplitudes_create (& my frication_formants_amplitudes, tmin, tmax, numberOfFormants);
1870 my options = FricationGridPlayOptions_create ();
1871 FricationGrid_setNames (me.get());
1872 return me;
1873 } catch (MelderError) {
1874 Melder_throw (U"FricationGrid not created.");
1875 }
1876 }
1877
1878 static void FricationGrid_draw_inside (FricationGrid me, Graphics g, double xmin, double xmax, double ymin, double ymax, double dy, double *yout) {
1879 const integer numberOfFormants = my frication_formants -> formants.size;
1880 const integer numberOfParts = numberOfFormants + ( numberOfFormants > 1 ? 0 : 1 ) ; // 2..number + bypass
1881 // dum noise, connections, filter, connections, adder
1882 autoVEC relativeWidths { 2, 0.6, 1.5, 0.6, 0.5 }, accumulatedWidths = zero_VEC (relativeWidths.size);
1883 double x1, y1, x2, y2, x3, ymid = (ymin + ymax) / 2.0;
1884 double oldFontSize = Graphics_inqFontSize (g);
1885
1886 scaleRelativeAndAccumulatedWidths (relativeWidths.get(), accumulatedWidths.get(), xmax - xmin);
1887
1888 dy = std::max (dy, 0.0);
1889 dy = (ymax - ymin) / (numberOfParts * (1.0 + dy) - dy);
1890
1891 connections cp = connections_create (numberOfParts);
1892 if (cp == 0)
1893 return;
1894
1895 // section 1
1896 x1 = xmin;
1897 x2 = x1 + relativeWidths [1];
1898 y1 = ymid - 0.5 * dy;
1899 y2 = y1 + dy;
1900
1901 double fontSizeFrication = Graphics_getFontSizeInsideBox (g, relativeWidths [1], dy, 10.0, 2.0);
1902 double fontSizeFormants = Graphics_getFontSizeInsideBox (g, relativeWidths [3], dy, 9.0, 1.5);
1903 double newFontSize = std::min (fontSizeFrication, fontSizeFormants);
1904 if (newFontSize < oldFontSize)
1905 Graphics_setFontSize (g, newFontSize);
1906 autoSTRVEC fricationNoise { U"Frication", U"noise" };
1907 drawLinesInBox (g, x1, x2, y1, y2, fricationNoise.get());
1908
1909 // section 2, horizontal line halfway, vertical line
1910 x1 = x2;
1911 x2 = x1 + relativeWidths [2] / 2.0;
1912 Graphics_line (g, x1, ymid, x2, ymid);
1913 Graphics_line (g, x2, ymax - dy / 2, x2, ymin + dy / 2.0);
1914 x3 = x2;
1915 // final connection to section 2 , filters , connections to adder
1916 x1 = xmin + accumulatedWidths [2];
1917 x2 = x1 + relativeWidths [3];
1918 y2 = ymax;
1919 autoMelderString fba;
1920 autoSTRVEC fbai { U"" };
1921
1922 for (integer i = 1; i <= numberOfParts; i ++) {
1923 conststring32 fi = Melder_integer (i + 1);
1924 y1 = y2 - dy;
1925 if (i < numberOfParts)
1926 MelderString_copy (& fba, U"A", fi, U" F", fi, U" B", fi);
1927 else
1928 MelderString_copy (& fba, U"Bypass");
1929 fbai [1] = Melder_dup (fba.string);
1930 drawLinesInBox (g, x1, x2, y1, y2, fbai.get());
1931 double ymidi = (y1 + y2) / 2.0;
1932 Graphics_line (g, x3, ymidi, x1, ymidi); // from noise to filter
1933 cp -> x [i] = x2;
1934 cp -> y [i] = ymidi;
1935 y2 = y1 - 0.5 * dy;
1936 }
1937
1938 const double r = relativeWidths [5] / 2.0;
1939 const double xs = xmax - r;
1940 const double ys = ymid;
1941
1942 if (numberOfParts > 1)
1943 alternatingSummer_drawConnections (g, xs, ys, r, cp, 1, 0.4);
1944 else
1945 Graphics_line (g, cp -> x [1], cp -> y [1], xs + r, ys);
1946
1947 connections_free (cp);
1948 Graphics_setFontSize (g, oldFontSize);
1949 if (yout)
1950 *yout = ys;
1951 }
1952
1953 void FricationGrid_draw (FricationGrid me, Graphics g) {
1954 const double xmin = 0.0, xmax = 1.0, xmax2 = 0.9, ymin = 0.0, ymax = 1.0, dy = 0.5;
1955
1956 Graphics_setInner (g);
1957 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1958 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1959 Graphics_setLineWidth (g, 2);
1960
1961 double yout;
1962 FricationGrid_draw_inside (me, g, xmin, xmax2, ymin, ymax, dy, & yout);
1963
1964 Graphics_arrow (g, xmax2, yout, xmax, yout);
1965 Graphics_unsetInner (g);
1966 }
1967
1968 autoSound FricationGrid_to_Sound (FricationGrid me, double samplingFrequency) {
1969 try {
1970 autoSound thee = Sound_createEmptyMono (my xmin, my xmax, samplingFrequency);
1971
1972 double lastval = 0.0;
1973 for (integer i = 1; i <= thy nx; i ++) {
1974 const double t = thy x1 + (i - 1) * thy dx;
1975 double val = NUMrandomUniform (-1.0, 1.0);
1976 double a = 0.0;
1977 if (my fricationAmplitude -> points.size > 0) {
1978 const double dba = RealTier_getValueAtTime (my fricationAmplitude.get(), t);
1979 a = ( isdefined (dba) ? DBSPL_to_A (dba) : 0.0 );
1980 }
1981 lastval = (val += 0.75 * lastval); // TODO: soft low-pass coefficient should be Fs dependent!
1982 thy z [1] [i] = val * a;
1983 }
1984
1985 autoSound him = Sound_FricationGrid_filter (thee.get(), me);
1986 return him;
1987 } catch (MelderError) {
1988 Melder_throw (me, U": no frication Sound created.");
1989 }
1990 }
1991
1992 /************************ Sound & FricationGrid *********************************************/
1993
1994 autoSound Sound_FricationGrid_filter (Sound me, FricationGrid thee) {
1995 try {
1996 const FricationGridPlayOptions pf = thy options.get();
1997 autoSound him;
1998 const integer numberOfFricationFormants = thy frication_formants -> formants.size;
1999
2000 check_formants (numberOfFricationFormants, & (pf -> startFricationFormant), & (pf -> endFricationFormant));
2001
2002 if (pf -> endFricationFormant > 1) {
2003 const integer startFricationFormant2 = pf -> startFricationFormant > 2 ? pf -> startFricationFormant : 2;
2004 int alternatingSign = ( startFricationFormant2 % 2 == 0 ? 1 : -1 ); // 2 starts with positive sign
2005 him = Sound_FormantGrid_Intensities_filter (me, thy frication_formants.get(), & thy frication_formants_amplitudes, startFricationFormant2, pf -> endFricationFormant, alternatingSign);
2006 }
2007
2008 if (! him)
2009 him = Data_copy (me);
2010
2011 if (pf -> bypass) {
2012 for (integer is = 1; is <= his nx; is ++) { // Bypass
2013 const double t = his x1 + (is - 1) * his dx;
2014 double ab = 0.0;
2015 if (thy bypass -> points.size > 0) {
2016 const double val = RealTier_getValueAtTime (thy bypass.get(), t);
2017 ab = ( isundef (val) ? 0.0 : DB_to_A (val) );
2018 }
2019 his z [1] [is] += my z [1] [is] * ab;
2020 }
2021 }
2022 return him;
2023 } catch (MelderError) {
2024 Melder_throw (me, U": not filtered by frication filter.");
2025 }
2026 }
2027
2028 /********************** KlattGridPlayOptions **********************/
2029
2030 Thing_implement (KlattGridPlayOptions, Daata, 0);
2031
2032 static void KlattGridPlayOptions_setDefaults (KlattGridPlayOptions me, KlattGrid thee) {
2033 my samplingFrequency = 44100.0;
2034 my scalePeak = 1;
2035 my xmin = thy xmin;
2036 my xmax = thy xmax;
2037 }
2038
2039 autoKlattGridPlayOptions KlattGridPlayOptions_create () {
2040 try {
2041 autoKlattGridPlayOptions me = Thing_new (KlattGridPlayOptions);
2042 return me;
2043 } catch (MelderError) {
2044 Melder_throw (U"KlattGridPlayOptions not created.");
2045 }
2046 }
2047
2048 void KlattGrid_setDefaultPlayOptions (KlattGrid me) {
2049 KlattGridPlayOptions_setDefaults (my options.get(), me);
2050 PhonationGridPlayOptions_setDefaults (my phonation -> options.get());
2051 VocalTractGridPlayOptions_setDefaults (my vocalTract -> options.get(), my vocalTract.get());
2052 CouplingGridPlayOptions_setDefaults (my coupling -> options.get(), my coupling.get());
2053 FricationGridPlayOptions_setDefaults (my frication -> options.get(), my frication.get());
2054 }
2055
2056 /************************ KlattGrid *********************************************/
2057
2058 Thing_implement (KlattGrid, Function, 0);
2059
2060 void structKlattGrid :: v1_info () {
2061 structDaata :: v1_info ();
2062 MelderInfo_writeLine (U"Time domain:");
2063 MelderInfo_writeLine (U" Start time: ", xmin, U" seconds");
2064 MelderInfo_writeLine (U" End time: ", xmax, U" seconds");
2065 MelderInfo_writeLine (U" Total duration: ", xmax - xmin, U" seconds");
2066 MelderInfo_writeLine (U"\n--- PhonationGrid ---\n");
2067 our phonation -> v1_info ();
2068 MelderInfo_writeLine (U"\n--- VocalTractGrid ---\n");
2069 our vocalTract -> v1_info ();
2070 MelderInfo_writeLine (U"\n--- CouplingGrid ---\n");
2071 our coupling -> v1_info ();
2072 MelderInfo_writeLine (U"\n--- FricationGrid ---\n");
2073 our frication -> v1_info ();
2074 }
2075
2076 void KlattGrid_setNames (KlattGrid me) {
2077 Thing_setName (my phonation.get(), U"phonation");
2078 Thing_setName (my vocalTract.get(), U"vocalTract");
2079 Thing_setName (my coupling.get(), U"coupling");
2080 Thing_setName (my frication.get(), U"frication");
2081 Thing_setName (my gain.get(), U"gain");
2082 }
2083
2084 autoKlattGrid KlattGrid_create (double tmin, double tmax, integer numberOfFormants, integer numberOfNasalFormants, integer numberOfNasalAntiFormants, integer numberOfTrachealFormants, integer numberOfTrachealAntiFormants, integer numberOfFricationFormants, integer numberOfDeltaFormants) {
2085 try {
2086 autoKlattGrid me = Thing_new (KlattGrid);
2087 Function_init (me.get(), tmin, tmax);
2088 my phonation = PhonationGrid_create (tmin, tmax);
2089 my vocalTract = VocalTractGrid_create (tmin, tmax, numberOfFormants, numberOfNasalFormants, numberOfNasalAntiFormants);
2090 my coupling = CouplingGrid_create (tmin, tmax, numberOfTrachealFormants, numberOfTrachealAntiFormants, numberOfDeltaFormants);
2091 my frication = FricationGrid_create (tmin, tmax, numberOfFricationFormants);
2092 my gain = IntensityTier_create (tmin, tmax);
2093 my options = KlattGridPlayOptions_create ();
2094
2095 KlattGrid_setDefaultPlayOptions (me.get());
2096 KlattGrid_setNames (me.get());
2097 return me;
2098 } catch (MelderError) {
2099 Melder_throw (U"KlattGrid not created.");
2100 }
2101 }
2102
2103 autoKlattGrid KlattGrid_createExample () {
2104 try {
2105 autoKlattTable thee = KlattTable_createExample ();
2106 autoKlattGrid me = KlattTable_to_KlattGrid (thee.get(), 0.005);
2107 return me;
2108 } catch (MelderError) {
2109 Melder_throw (U"KlattGrid example not created.");
2110 };
2111 }
2112
2113 // y is the height in units of the height of one section,
2114 // y1 is the height from the top to the split between the upper, non-diffed, and lower diffed part
2115 static void _KlattGrid_queryParallelSplit (KlattGrid me, double dy, double *out_y, double *out_y1) {
2116 const integer ny = my vocalTract -> nasal_formants -> formants.size +
2117 my vocalTract -> oral_formants -> formants.size + my coupling -> tracheal_formants -> formants.size;
2118 const integer n1 = my vocalTract -> nasal_formants -> formants.size +
2119 ( my vocalTract -> oral_formants -> formants.size > 0 ? 1 : 0 );
2120
2121 const integer n2 = ny - n1;
2122 double y = 0.0, y1 = 0.0;
2123 if (ny != 0) {
2124 y = ny + (ny - 1) * dy;
2125
2126 if (n1 == 0)
2127 y1 = 0.5;
2128 else if (n2 == 0)
2129 y1 = y - 0.5;
2130 else
2131 y1 = n1 + (n1 - 1) * dy + 0.5 * dy;
2132 }
2133 if (out_y)
2134 *out_y = y;
2135 if (out_y1)
2136 *out_y1 = y1;
2137 return;
2138 }
2139
2140 static void getYpositions (double h1, double h2, double h3, double h4, double h5, double fractionOverlap, double *out_dy, double *out_ymin1, double *out_ymax1, double *out_ymin2, double *out_ymax2, double *out_ymin3, double *out_ymax3) {
2141 // Given: five 'blocks' with relative heights h1..h5 in arbitrary units.
2142 // Problem: scale all h1..h5 such that:
2143 // 1. blocks h1 and h2 form one unit, with h1 on top of h2, the quotient h1/h2 is fixed
2144 // 2. blocks h3 and h4 form one unit, with h3 on top of h4, the quotient h3/h4 is fixed
2145 // 3. blocks h1 and h3 have the same baseline.
2146 // 4. h5 is always underneath (h1,h2) but may partially overlap (0.45) with h4.
2147 // 5. After scaling the new h1+h2 >= 0.3
2148 // 6. Optimally use the vertical space from 0.. 1, i.e the top of h1 or h3 is at 1,
2149 // the bottom of h5 is at 0. Preferably scale all blocks with the same factor, if not possible than
2150 // scale h3,h4 and h5 the same
2151 //
2152 // h1 h3
2153 // h2 h4
2154 // h5
2155 /* Cases:
2156 x x ^
2157 x x x x x x |
2158 h1 x x x x x x x x h3 | h13
2159 -----------------------------------------------------------
2160 h2 x x x x x x x x h4
2161 x x x x x x
2162 x x
2163 x x x x x x
2164 h5 x x x x
2165 x x x x
2166 */
2167 double h; // h12_min = 0.3; not yet
2168 const double h13 = ( h1 > h3 ? h1 : h3 ); // baselines are now equal
2169 if (h2 >= h4) {
2170 h = h13 + h2 + h5;
2171 } else { // h2 < h4
2172 double maximumOverlap3 = fractionOverlap * h5;
2173 if (maximumOverlap3 < h1 + h2)
2174 maximumOverlap3 = 0.0;
2175 else if (maximumOverlap3 > h4 - h2)
2176 maximumOverlap3 = h4 - h2;
2177 h = h13 + h4 + h5 - maximumOverlap3;
2178 }
2179 const double dy = 1.0 / (1.1 * h);
2180 const double ymin1 = 1.0 - (h13 + h2) * dy;
2181 const double ymax1 = ymin1 + (h1 + h2) * dy;
2182 const double ymin2 = 1.0 - (h13 + h4) * dy;
2183 const double ymax2 = ymin2 + (h3 + h4) * dy;
2184 const double ymin3 = 0.0;
2185 const double ymax3 = h5 * dy;
2186 if (out_dy)
2187 *out_dy = dy;
2188 if (out_ymin1)
2189 *out_ymin1 = ymin1;
2190 if (out_ymax1)
2191 *out_ymax1 = ymax1;
2192 if (out_ymin2)
2193 *out_ymin2 = ymin2;
2194 if (out_ymax2)
2195 *out_ymax2 = ymax2;
2196 if (out_ymin3)
2197 *out_ymin3 = ymin3;
2198 if (out_ymax3)
2199 *out_ymax3 = ymax3;
2200 }
2201
2202 void KlattGrid_drawVocalTract (KlattGrid me, Graphics g, kKlattGridFilterModel filterModel, int withTrachea) {
2203 VocalTractGrid_CouplingGrid_draw (my vocalTract.get(), withTrachea ? my coupling.get() : nullptr, g, filterModel);
2204 }
2205
2206 void KlattGrid_draw (KlattGrid me, Graphics g, kKlattGridFilterModel filterModel) {
2207 const double xmin = 0.0, xmax = 1.0, ymin = 0.0, ymax = 1.0;
2208 const double xmax2 = 0.90, xmax3 = 0.95;
2209 const double dy_phonation = 0.5, dy_vocalTract_p = 0.5, dy_frication = 0.5;
2210
2211 connections tf;
2212 try {
2213 tf = connections_create (2);
2214 } catch (MelderError) {
2215 Melder_clearError ();
2216 return;
2217 }
2218
2219 Graphics_setInner (g);
2220
2221 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
2222 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
2223 Graphics_setLineWidth (g, 2);
2224
2225 const integer nff = my frication -> frication_formants -> formants.size - 1 + 1;
2226 const double yh_frication = ( nff > 0 ? nff + (nff - 1) * dy_frication : 1.0 );
2227 const double yh_phonation = 1.0 + dy_phonation + 1.0;
2228 double yout_phonation, yout_frication, yout_vocalTract;
2229 double height_phonation = 0.3;
2230 double dy = height_phonation / yh_phonation; // 1 vertical unit in source section height units
2231
2232 double xs1, xs2, ys1, ys2, xf1, xf2, yf1, yf2;
2233 double xp1, xp2, yp1, yp2, xc1, xc2, yc1, yc2;
2234 // {phonationPart, line, vocalTractPart,
2235 autoVEC relativeWidths { 1.75, 0.125, 3.0, 0.25, 0.125 }, accumulatedWidths = zero_VEC (relativeWidths.size);
2236 scaleRelativeAndAccumulatedWidths (relativeWidths.get(), accumulatedWidths.get(), xmax2 - xmin);
2237
2238 if (filterModel == kKlattGridFilterModel::CASCADE) { // Cascade section
2239 /*
2240 limit height of frication unit dy !
2241 */
2242 height_phonation = yh_phonation / (yh_phonation + yh_frication);
2243 if (height_phonation < 0.3)
2244 height_phonation = 0.3;
2245 dy = height_phonation / yh_phonation;
2246
2247 xs1 = xmin;
2248 xs2 = xs1 + relativeWidths [1];
2249 ys2 = ymax;
2250 ys1 = ys2 - height_phonation;
2251 PhonationGrid_draw_inside (my phonation.get(), g, xs1, xs2, ys1, ys2, dy_phonation, & yout_phonation);
2252
2253 // units in cascade have same height as units in source part.
2254
2255 xc1 = xmin + accumulatedWidths [2]; // end of phonation
2256 xc2 = xc1 + relativeWidths [3]; // same width as vocaltract
2257 yc2 = yout_phonation + dy / 2.0;
2258 yc1 = yc2 - dy;
2259 double yin_vocalTract_cascade;
2260 VocalTractGrid_CouplingGrid_drawCascade_inplace (my vocalTract.get(), my coupling.get(), g, xc1, xc2, yc1, yc2, & yin_vocalTract_cascade, & yout_vocalTract);
2261
2262 tf -> x [1] = xc2;
2263 tf -> y [1] = yout_vocalTract;
2264
2265 Graphics_line (g, xs2, yout_phonation, xc1, yin_vocalTract_cascade);
2266
2267 xf1 = xmin + accumulatedWidths [2];
2268 xf2 = xf1 + relativeWidths [3];
2269 yf2 = ymax - height_phonation;
2270 yf1 = 0.0;
2271
2272 FricationGrid_draw_inside (my frication.get(), g, xf1, xf2, yf1, yf2, dy_frication, &yout_frication);
2273 } else { // Parallel
2274 /*
2275 optimize the vertical space for source, parallel and frication
2276 source part is relatively fixed. let the number of vertical section units be the divisor
2277 connector line from source to parallel has to be horizontal
2278 determine y's of source and parallel section
2279 */
2280 double yf_parallel, yh_parallel, yh_overlap = 0.3, yin_vocalTract_parallel;
2281 _KlattGrid_queryParallelSplit (me, dy_vocalTract_p, &yh_parallel, & yf_parallel);
2282 if (yh_parallel == 0.0) {
2283 yh_parallel = yh_phonation;
2284 yf_parallel = yh_parallel / 2.0;
2285 yh_overlap = -0.1;
2286 }
2287
2288 height_phonation = yh_phonation / (yh_phonation + yh_frication);
2289 if (height_phonation < 0.3) {
2290 height_phonation = 0.3;
2291 }
2292 //double yunit = (ymax - ymin) / (yh_parallel + (1 - yh_overlap) * yh_frication); // some overlap
2293
2294 //double ycs = ymax - 0.5 * height_phonation; // source output connector
2295 //double ycp = ymax - yf_parallel * yunit; // parallel input connector
2296 //double ytrans_phonation = ycs > ycp ? ycp - ycs : 0;
2297 //double ytrans_parallel = ycp > ycs ? ycs - ycp : 0;
2298
2299 // source, tract, frication
2300 xs1 = xmin;
2301 xs2 = xs1 + relativeWidths [1];
2302
2303 const double h1 = yh_phonation / 2.0, h2 = h1, h3 = yf_parallel, h4 = yh_parallel - h3, h5 = yh_frication;
2304 getYpositions (h1, h2, h3, h4, h5, yh_overlap, & dy, & ys1, & ys2, & yp1, & yp2, & yf1, & yf2);
2305
2306 PhonationGrid_draw_inside (my phonation.get(), g, xs1, xs2, ys1, ys2, dy_phonation, & yout_phonation);
2307
2308 xp1 = xmin + accumulatedWidths [2];
2309 xp2 = xp1 + relativeWidths [3];
2310 VocalTractGrid_CouplingGrid_drawParallel_inplace (my vocalTract.get(), my coupling.get(), g, xp1, xp2, yp1, yp2, dy_vocalTract_p, & yin_vocalTract_parallel, & yout_vocalTract);
2311
2312 tf -> x [1] = xp2;
2313 tf -> y [1] = yout_vocalTract;
2314
2315 Graphics_line (g, xs2, yout_phonation, xp1, yin_vocalTract_parallel);
2316
2317 xf1 = xmin /* + 0.5 * accumulatedWidths [1] */;
2318 xf2 = xf1 + 0.55 * (relativeWidths [2] + accumulatedWidths [3]);
2319
2320 FricationGrid_draw_inside (my frication.get(), g, xf1, xf2, yf1, yf2, dy_frication, & yout_frication);
2321 }
2322
2323 tf -> x [2] = xf2;
2324 tf -> y [2] = yout_frication;
2325 const double r = (xmax3 - xmax2) / 2.0;
2326 const double xs = xmax2 + r / 2.0;
2327 const double ys = (yout_vocalTract + yout_frication) / 2.0;//(ymax - ymin) / 2.0;
2328
2329 summer_drawConnections (g, xs, ys, r, tf, true, 0.6);
2330
2331 Graphics_arrow (g, xs + r, ys, xmax, ys);
2332
2333 Graphics_unsetInner (g);
2334 connections_free (tf);
2335 }
2336
2337 /**** Query, Add, Remove, Extract Replace ********/
2338
2339 #define PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE(Name,name,tierType) \
2340 double KlattGrid_get##Name##AtTime (KlattGrid me, double t) \
2341 { return RealTier_getValueAtTime (my phonation -> name.get(), t); } \
2342 void KlattGrid_add##Name##Point (KlattGrid me, double t, double value) \
2343 { RealTier_addPoint (my phonation -> name.get(), t, value);} \
2344 void KlattGrid_remove##Name##Points (KlattGrid me, double t1, double t2) \
2345 { AnyTier_removePointsBetween (my phonation -> name.get()->asAnyTier(), t1, t2); } \
2346 auto##tierType KlattGrid_extract##Name##Tier (KlattGrid me) \
2347 { return Data_copy (my phonation -> name.get()); } \
2348 void KlattGrid_replace##Name##Tier (KlattGrid me, tierType thee) \
2349 { try {\
2350 Melder_require (my xmin == thy xmin && my xmax == thy xmax, U"Domains should be equal"); \
2351 auto##tierType any = Data_copy (thee); \
2352 my phonation -> name = any.move(); \
2353 } catch (MelderError) { Melder_throw (me, U": tier not replaced."); } \
2354 }
2355
2356 // Generate 55 functions
2357 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (Pitch, pitch, PitchTier)
2358 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (VoicingAmplitude, voicingAmplitude, IntensityTier)
2359 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (Flutter, flutter, RealTier)
2360 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (Power1, power1, RealTier)
2361 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (Power2, power2, RealTier)
2362 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (OpenPhase, openPhase, RealTier)
2363 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (CollisionPhase, collisionPhase, RealTier)
2364 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (DoublePulsing, doublePulsing, RealTier)
2365 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (SpectralTilt, spectralTilt, IntensityTier)
2366 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (AspirationAmplitude, aspirationAmplitude, IntensityTier)
2367 PhonationGrid_QUERY_ADD_REMOVE_EXTRACT_REPLACE (BreathinessAmplitude, breathinessAmplitude, IntensityTier)
2368
2369 autoFormantGrid* KlattGrid_getAddressOfFormantGrid (KlattGrid me, kKlattGridFormantType formantType) {
2370 return formantType == kKlattGridFormantType::ORAL ? & my vocalTract -> oral_formants :
2371 formantType == kKlattGridFormantType::NASAL ? & my vocalTract -> nasal_formants :
2372 formantType == kKlattGridFormantType::FRICATION ? & my frication -> frication_formants :
2373 formantType == kKlattGridFormantType::TRACHEAL ? & my coupling -> tracheal_formants :
2374 formantType == kKlattGridFormantType::NASAL_ANTI ? & my vocalTract -> nasal_antiformants :
2375 formantType == kKlattGridFormantType::TRACHEAL_ANTI ? & my coupling -> tracheal_antiformants :
2376 & my coupling -> delta_formants; // kKlattGridFormantType::Delta
2377 }
2378
2379 OrderedOf<structIntensityTier>* KlattGrid_getAddressOfAmplitudes (KlattGrid me, kKlattGridFormantType formantType) {
2380 return formantType == kKlattGridFormantType::ORAL ? & my vocalTract -> oral_formants_amplitudes :
2381 formantType == kKlattGridFormantType::NASAL ? & my vocalTract -> nasal_formants_amplitudes :
2382 formantType == kKlattGridFormantType::FRICATION ? & my frication -> frication_formants_amplitudes :
2383 formantType == kKlattGridFormantType::TRACHEAL ? & my coupling -> tracheal_formants_amplitudes : nullptr;
2384 }
2385
2386 #define KlattGrid_QUERY_ADD_REMOVE(Name) \
2387 double KlattGrid_get##Name##AtTime (KlattGrid me, kKlattGridFormantType formantType, integer iformant, double t) \
2388 { \
2389 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType); \
2390 return FormantGrid_get##Name##AtTime (fg->get(), iformant, t); \
2391 } \
2392 void KlattGrid_add##Name##Point (KlattGrid me, kKlattGridFormantType formantType, integer iformant, double t, double value) \
2393 { \
2394 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType); \
2395 FormantGrid_add##Name##Point (fg->get(), iformant, t, value); \
2396 } \
2397 void KlattGrid_remove##Name##Points (KlattGrid me, kKlattGridFormantType formantType, integer iformant, double t1, double t2) \
2398 { \
2399 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType); \
2400 FormantGrid_remove##Name##PointsBetween (fg->get(), iformant, t1, t2); \
2401 }
2402
2403 // 6 functions
2404 KlattGrid_QUERY_ADD_REMOVE (Formant)
2405 KlattGrid_QUERY_ADD_REMOVE (Bandwidth)
2406
2407 void KlattGrid_formula_frequencies (KlattGrid me, kKlattGridFormantType formantType, conststring32 expression, Interpreter interpreter) {
2408 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2409 FormantGrid_formula_frequencies (fg->get(), expression, interpreter, nullptr);
2410 }
2411
2412 void KlattGrid_formula_bandwidths (KlattGrid me, kKlattGridFormantType formantType, conststring32 expression, Interpreter interpreter) {
2413 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2414
2415 FormantGrid_formula_bandwidths (fg->get(), expression, interpreter, nullptr);
2416 }
2417
2418 void KlattGrid_formula_amplitudes (KlattGrid me, kKlattGridFormantType formantType, conststring32 expression, Interpreter interpreter) {
2419 try {
2420 const OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2421 for (integer irow = 1; irow <= ordered->size; irow ++) {
2422 const IntensityTier amplitudes = ordered->at [irow];
2423 Formula_compile (interpreter, amplitudes, expression, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2424 Formula_Result result;
2425 for (integer icol = 1; icol <= amplitudes -> points.size; icol ++) {
2426 Formula_run (irow, icol, & result);
2427 Melder_require (isdefined (result. numericResult),
2428 U"Cannot put an undefined value into the tier.\nFormula not finished.");
2429 amplitudes -> points.at [icol] -> value = result. numericResult;
2430 }
2431 }
2432 } catch (MelderError) {
2433 Melder_throw (me, U": formula not finished on amplitudes.");
2434 }
2435 }
2436
2437 double KlattGrid_getAmplitudeAtTime (KlattGrid me, kKlattGridFormantType formantType, integer iformant, double t) {
2438 const OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2439 if (iformant < 1 || iformant > ordered->size)
2440 return undefined;
2441 return RealTier_getValueAtTime (ordered->at [iformant], t);
2442 }
2443
2444 void KlattGrid_addAmplitudePoint (KlattGrid me, kKlattGridFormantType formantType, integer iformant, double t, double value) {
2445 const OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2446 Melder_require (iformant > 0 && iformant <= ordered->size,
2447 U"Formant amplitude tier ", iformant, U"does not exist.");
2448 RealTier_addPoint (ordered->at [iformant], t, value);
2449 }
2450
2451 void KlattGrid_removeAmplitudePoints (KlattGrid me, kKlattGridFormantType formantType, integer iformant, double t1, double t2) {
2452 const OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2453 if (ordered && iformant > 0 && iformant <= ordered->size) {
2454 AnyTier_removePointsBetween (ordered->at [iformant]->asAnyTier(), t1, t2);
2455 }
2456 }
2457
2458 autoIntensityTier KlattGrid_extractAmplitudeTier (KlattGrid me, kKlattGridFormantType formantType, integer iformant) {
2459 try {
2460 const OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2461 Melder_require (ordered != nullptr,
2462 U"This amplitude tier does not exist.");
2463 Melder_require (iformant > 0 && iformant <= ordered->size,
2464 U"Formant amplitude tier ", iformant, U"does not exist.");
2465 autoIntensityTier thee = Data_copy (ordered->at [iformant]);
2466 return thee;
2467 } catch (MelderError) {
2468 Melder_throw (me, U": no IntensityTier extracted.");
2469 }
2470 }
2471
2472 void KlattGrid_replaceAmplitudeTier (KlattGrid me, kKlattGridFormantType formantType, integer iformant, IntensityTier thee) {
2473 try {
2474 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
2475 U"Domains should be equal.");
2476 OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2477 Melder_require (ordered != nullptr,
2478 U"This amplitude tier does not exist.");
2479 Melder_require (iformant > 0 && iformant <= ordered->size,
2480 U"Formant amplitude tier ", iformant, U" does not exist.");
2481 autoIntensityTier any = Data_copy (thee);
2482 ordered -> replaceItem_move (any.move(), iformant);
2483 } catch (MelderError) {
2484 Melder_throw (me, U": no ampitude tier replaced.");
2485 }
2486 }
2487
2488 autoFormantGrid KlattGrid_extractFormantGrid (KlattGrid me, kKlattGridFormantType formantType) {
2489 try {
2490 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2491 Melder_require ((*fg) -> formants.size > 0,
2492 KlattGrid_getFormantName (formantType), U"s are not defined.");
2493 autoFormantGrid thee = Data_copy (fg->get());
2494 return thee;
2495 } catch (MelderError) {
2496 Melder_throw (me, U": no FormantGrid extracted.");
2497 }
2498 }
2499
2500 void KlattGrid_replaceFormantGrid (KlattGrid me, kKlattGridFormantType formantType, FormantGrid thee) {
2501 try {
2502 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
2503 U"Domains should be equal");
2504 autoFormantGrid *fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2505 *fg = Data_copy (thee);
2506 } catch (MelderError) {
2507 Melder_throw (me, U": no FormantGrid replaced.");
2508 }
2509 }
2510
2511 void KlattGrid_addFormantAmplitudeTier (KlattGrid me, kKlattGridFormantType formantType, integer position) {
2512 try {
2513 Melder_require (formantType != kKlattGridFormantType::NASAL_ANTI && formantType != kKlattGridFormantType::TRACHEAL_ANTI && formantType != kKlattGridFormantType::DELTA,
2514 U"Cannot add amplitude tier to this formant type.");
2515 OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2516 const integer noa = ordered->size;
2517 if (position > noa || position < 1)
2518 position = noa + 1;
2519 autoIntensityTier tier = IntensityTier_create (my xmin, my xmax);
2520 ordered -> addItemAtPosition_move (tier.move(), position);
2521 } catch (MelderError) {
2522 Melder_throw (me, U": no formant amplitude tier added.");
2523 }
2524 }
2525
2526 void KlattGrid_removeFormantAmplitudeTier (KlattGrid me, kKlattGridFormantType formantType, integer position) {
2527 try {
2528 Melder_require (formantType != kKlattGridFormantType::NASAL_ANTI && formantType != kKlattGridFormantType::TRACHEAL_ANTI && formantType != kKlattGridFormantType::DELTA,
2529 U"Cannot remove amplitude tier from this formant type.");
2530 OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2531 if (position > 0 && position <= ordered->size)
2532 ordered -> removeItem (position);
2533 } catch (MelderError) {
2534 Melder_throw (me, U": no formant amplitude tier removed.");
2535 }
2536 }
2537
2538 // The following two routines are deprecated.
2539 // We do this in two separate steps now
2540 void KlattGrid_addFormant (KlattGrid me, kKlattGridFormantType formantType, integer position) {
2541 try {
2542 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2543
2544 const integer nof = (*fg) -> formants.size;
2545 if (position > nof || position < 1)
2546 position = nof + 1;
2547
2548 if (formantType == kKlattGridFormantType::NASAL_ANTI || formantType == kKlattGridFormantType::TRACHEAL_ANTI ||
2549 formantType == kKlattGridFormantType::DELTA)
2550 {
2551 FormantGrid_addFormantAndBandwidthTiers (fg->get(), position);
2552 return;
2553 }
2554
2555 OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2556 const integer noa = ordered->size;
2557 Melder_require (nof == noa,
2558 U"The number of formants (", nof, U") and the number of amplitudes (", noa, U") should be equal.");
2559
2560 FormantGrid_addFormantAndBandwidthTiers (fg->get(), position);
2561 try {
2562 autoIntensityTier tier = IntensityTier_create (my xmin, my xmax);
2563 ordered -> addItemAtPosition_move (tier.move(), position);
2564 } catch (MelderError) { // restore original
2565 FormantGrid_removeFormantAndBandwidthTiers (fg->get(), position);
2566 }
2567 } catch (MelderError) {
2568 Melder_throw (me, U": no formant added.");
2569 }
2570 }
2571
2572 void KlattGrid_removeFormant (KlattGrid me, kKlattGridFormantType formantType, integer position) {
2573 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2574 const integer nof = (*fg) -> formants.size;
2575 if (formantType == kKlattGridFormantType::NASAL_ANTI || formantType == kKlattGridFormantType::TRACHEAL_ANTI ||
2576 formantType == kKlattGridFormantType::DELTA) {
2577 if (position < 1 || position > nof)
2578 return;
2579 FormantGrid_removeFormantAndBandwidthTiers (fg->get(), position);
2580 } else {
2581 // oral & nasal & tracheal formants can have amplitudes
2582 // only remove a formant and its amplitude tier if number of formants and amplitudes are the same
2583 OrderedOf<structIntensityTier>* ordered = KlattGrid_getAddressOfAmplitudes (me, formantType);
2584 const integer noa = ordered->size;
2585 if (position < 1 || position > nof || position > noa) {
2586 if (nof != noa) {
2587 Melder_warning (U"The number of formant tiers (", nof, U") and the number of amplitude tiers (",
2588 noa, U") don't match. Nothing removed.");
2589 }
2590 return;
2591 }
2592 FormantGrid_removeFormantAndBandwidthTiers (fg->get(), position);
2593 ordered -> removeItem (position);
2594 }
2595 }
2596
2597 void KlattGrid_addFormantFrequencyAndBandwidthTiers (KlattGrid me, kKlattGridFormantType formantType, integer position) {
2598 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2599 FormantGrid_addFormantAndBandwidthTiers (fg->get(), position);
2600 }
2601
2602 void KlattGrid_removeFormantFrequencyAndBandwidthTiers (KlattGrid me, kKlattGridFormantType formantType, integer position) {
2603 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, formantType);
2604 FormantGrid_removeFormantAndBandwidthTiers (fg->get(), position);
2605 }
2606
2607 double KlattGrid_getDeltaFormantAtTime (KlattGrid me, integer iformant, double t) {
2608 return FormantGrid_getFormantAtTime (my coupling -> delta_formants.get(), iformant, t);
2609 }
2610 void KlattGrid_addDeltaFormantPoint (KlattGrid me, integer iformant, double t, double value) {
2611 FormantGrid_addFormantPoint (my coupling -> delta_formants.get(), iformant, t, value);
2612 }
2613 void KlattGrid_removeDeltaFormantPoints (KlattGrid me, integer iformant, double t1, double t2) {
2614 FormantGrid_removeFormantPointsBetween (my coupling -> delta_formants.get(), iformant, t1, t2);
2615 }
2616 double KlattGrid_getDeltaBandwidthAtTime (KlattGrid me, integer iformant, double t) {
2617 return FormantGrid_getBandwidthAtTime (my coupling -> delta_formants.get(), iformant, t);
2618 }
2619 void KlattGrid_addDeltaBandwidthPoint (KlattGrid me, integer iformant, double t, double value) {
2620 FormantGrid_addBandwidthPoint (my coupling -> delta_formants.get(), iformant, t, value);
2621 }
2622 void KlattGrid_removeDeltaBandwidthPoints (KlattGrid me, integer iformant, double t1, double t2) {
2623 FormantGrid_removeBandwidthPointsBetween (my coupling -> delta_formants.get(), iformant, t1, t2);
2624 }
2625
2626 autoFormantGrid KlattGrid_extractDeltaFormantGrid (KlattGrid me) {
2627 try {
2628 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, kKlattGridFormantType::DELTA);
2629 autoFormantGrid thee = Data_copy (fg->get());
2630 return thee;
2631 } catch (MelderError) {
2632 Melder_throw (me, U": no delta FormantGrid extracted.");
2633 }
2634 }
2635
2636 void KlattGrid_replaceDeltaFormantGrid (KlattGrid me, FormantGrid thee) {
2637 try {
2638 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
2639 U"Domains should be equal");
2640 autoFormantGrid* fg = KlattGrid_getAddressOfFormantGrid (me, kKlattGridFormantType::DELTA);
2641 autoFormantGrid him = Data_copy (thee);
2642 *fg = him.move();
2643 } catch (MelderError) {
2644 Melder_throw (me, U": no delta FormantGrid replaced.");
2645 }
2646 }
2647
2648 autoFormantGrid KlattGrid_to_oralFormantGrid_openPhases (KlattGrid me, double fadeFraction) {
2649 try {
2650 Melder_require (my vocalTract -> oral_formants -> formants.size > 0 || my vocalTract -> oral_formants -> bandwidths.size > 0,
2651 U"Formant grid should not be empty.");
2652
2653 Melder_clipLeft (0.0, & fadeFraction);
2654 Melder_require (fadeFraction < 0.5,
2655 U"Fade fraction should be smaller than 0.5");
2656
2657 my coupling -> options -> fadeFraction = fadeFraction;
2658 autoFormantGrid thee = Data_copy ( (FormantGrid) my vocalTract -> oral_formants.get());
2659 KlattGrid_setGlottisCoupling (me);
2660 FormantGrid_CouplingGrid_updateOpenPhases (thee.get(), my coupling.get());
2661 return thee;
2662 } catch (MelderError) {
2663 Melder_throw (me, U": no \"open phase\" oral FormantGrid created.");
2664 }
2665 }
2666
2667 autoPointProcess KlattGrid_extractPointProcess_glottalClosures (KlattGrid me) {
2668 try {
2669 // Update PhonationTier
2670 autoPhonationTier pt = PhonationGrid_to_PhonationTier (my phonation.get());
2671 autoPointProcess thee = PhonationTier_to_PointProcess_closures (pt.get());
2672 return thee;
2673 } catch (MelderError) {
2674 Melder_throw (me, U": no glottal closure points extracted.");
2675 }
2676 }
2677
2678 double KlattGrid_getFricationAmplitudeAtTime (KlattGrid me, double t) {
2679 return RealTier_getValueAtTime (my frication -> fricationAmplitude.get(), t);
2680 }
2681
2682 void KlattGrid_addFricationAmplitudePoint (KlattGrid me, double t, double value) {
2683 RealTier_addPoint (my frication -> fricationAmplitude.get(), t, value);
2684 }
2685
2686 void KlattGrid_removeFricationAmplitudePoints (KlattGrid me, double t1, double t2) {
2687 AnyTier_removePointsBetween (my frication -> fricationAmplitude.get()->asAnyTier(), t1, t2);
2688 }
2689
2690 autoIntensityTier KlattGrid_extractFricationAmplitudeTier (KlattGrid me) {
2691 return Data_copy (my frication -> fricationAmplitude.get());
2692 }
2693
2694 void KlattGrid_replaceFricationAmplitudeTier (KlattGrid me, IntensityTier thee) {
2695 try {
2696 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
2697 U"Domains should be equal");
2698 my frication -> fricationAmplitude = Data_copy (thee);
2699 } catch (MelderError) {
2700 Melder_throw (me, U": no frication amplitude tier replaced.");
2701 }
2702 }
2703
2704 double KlattGrid_getFricationBypassAtTime (KlattGrid me, double t) {
2705 return RealTier_getValueAtTime (my frication -> bypass.get(), t);
2706 }
2707
2708 void KlattGrid_addFricationBypassPoint (KlattGrid me, double t, double value) {
2709 RealTier_addPoint (my frication -> bypass.get(), t, value);
2710 }
2711
2712 void KlattGrid_removeFricationBypassPoints (KlattGrid me, double t1, double t2) {
2713 AnyTier_removePointsBetween (my frication -> bypass.get()->asAnyTier(), t1, t2);
2714 }
2715
2716 autoIntensityTier KlattGrid_extractFricationBypassTier (KlattGrid me) {
2717 return Data_copy (my frication -> bypass.get());
2718 }
2719
2720 void KlattGrid_replaceFricationBypassTier (KlattGrid me, IntensityTier thee) {
2721 try {
2722 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
2723 U"Domains should be equal");
2724 my frication -> bypass = Data_copy (thee);
2725 } catch (MelderError) {
2726 Melder_throw (me, U": no frication bypass tier replaced.");
2727 }
2728 }
2729
2730 void KlattGrid_setGlottisCoupling (KlattGrid me) {
2731 try {
2732 my coupling -> glottis = PhonationGrid_to_PhonationTier (my phonation.get());
2733 Melder_require (my coupling -> glottis,
2734 U"Phonation tier should not be empty.");
2735 } catch (MelderError) {
2736 Melder_throw (me, U": no coupling could be set.");
2737 }
2738 }
2739
2740 #if 0
2741 static autoSound KlattGrid_to_Sound_aspiration (KlattGrid me, double samplingFrequency) {
2742 return PhonationGrid_to_Sound_aspiration (my phonation.get(), samplingFrequency);
2743 }
2744 #endif
2745
2746 autoSound KlattGrid_to_Sound_phonation (KlattGrid me) {
2747 return PhonationGrid_to_Sound (my phonation.get(), 0, my options -> samplingFrequency);
2748 }
2749
2750 autoSound KlattGrid_to_Sound (KlattGrid me) {
2751 try {
2752 autoSound thee;
2753 const PhonationGridPlayOptions pp = my phonation -> options.get();
2754 const FricationGridPlayOptions pf = my frication -> options.get();
2755 const double samplingFrequency = my options -> samplingFrequency;
2756
2757 if (pp -> voicing)
2758 KlattGrid_setGlottisCoupling (me);
2759
2760 if (pp -> aspiration || pp -> voicing) { // No vocal tract filtering if no glottal source signal present
2761 autoSound source = PhonationGrid_to_Sound (my phonation.get(), my coupling.get(), samplingFrequency);
2762 thee = Sound_VocalTractGrid_CouplingGrid_filter (source.get(), my vocalTract.get(), my coupling.get());
2763 }
2764
2765 if (pf -> endFricationFormant > 0 || pf -> bypass) {
2766 autoSound frication = FricationGrid_to_Sound (my frication.get(), samplingFrequency);
2767 if (thee)
2768 _Sounds_add_inplace (thee.get(), frication.get());
2769 else
2770 thee = frication.move();
2771 }
2772
2773 if (! thee)
2774 thee = Sound_createEmptyMono (my xmin, my xmax, samplingFrequency);
2775
2776 if (my options -> scalePeak)
2777 Vector_scale (thee.get(), 0.99);
2778
2779 return thee;
2780 } catch (MelderError) {
2781 Melder_throw (me, U": no Sound created.");
2782 }
2783 }
2784
2785 void KlattGrid_playSpecial (KlattGrid me, Sound_PlayCallback callback, Thing boss) {
2786 try {
2787 autoSound thee = KlattGrid_to_Sound (me);
2788 const KlattGridPlayOptions him = my options.get();
2789 if (his scalePeak)
2790 Vector_scale (thee.get(), 0.99);
2791 if (his xmin == 0.0 && his xmax == 0.0) {
2792 his xmin = my xmin;
2793 his xmax = my xmax;
2794 }
2795 Sound_playPart (thee.get(), his xmin, his xmax, callback, boss);
2796 } catch (MelderError) {
2797 Melder_throw (me, U": not played.");
2798 }
2799 }
2800
2801 void KlattGrid_play (KlattGrid me, Sound_PlayCallback callback, Thing boss) {
2802 KlattGrid_setDefaultPlayOptions (me);
2803 KlattGrid_playSpecial (me, callback, boss);
2804 }
2805
2806 /************************* Sound(s) & KlattGrid **************************************************/
2807
2808 autoSound Sound_KlattGrid_filter_frication (Sound me, KlattGrid thee) {
2809 return Sound_FricationGrid_filter (me, thy frication.get());
2810 }
2811
2812 autoSound Sound_KlattGrid_filterByVocalTract (Sound me, KlattGrid thee, kKlattGridFilterModel filterModel) {
2813 try {
2814 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
2815 U"Domains should be equal.");
2816 KlattGrid_setDefaultPlayOptions (thee);
2817 thy coupling -> options -> openglottis = 0; // don't trust openglottis info!
2818 thy vocalTract -> options -> filterModel = filterModel;
2819 return Sound_VocalTractGrid_CouplingGrid_filter (me, thy vocalTract.get(), thy coupling.get());
2820 } catch (MelderError) {
2821 Melder_throw (me, U": not filtered by KlattGrid.");
2822 }
2823 }
2824
2825 /******************* KlattTable to KlattGrid *********************/
2826
2827 autoKlattGrid KlattTable_to_KlattGrid (KlattTable me, double frameDuration) {
2828 try {
2829 Table kt = (Table) me;
2830
2831 const integer numberOfRows = my rows.size;
2832 const double tmin = 0, tmax = numberOfRows * frameDuration;
2833 constexpr double dBNul = -300;
2834 const double dB_offset = -20.0 * log10 (2.0e-5) - 87.0; // in KlattTable maximum in DB_to_LIN is at 87 dB : 32767
2835 const double dB_offset_voicing = 20.0 * log10 (320000 / 32767); // V' [n] in range (-320000,32000)
2836 const double dB_offset_noise = -20.0 * log10 (32.767 / 8.192); // noise in range (-8192,8192)
2837 // double dB_offset_noise = -20 * log10 (320000/32767) - 20 * log10 (32.767 / 8.192);
2838 const double ap [7] = {0, 0.4, 0.15, 0.06, 0.04, 0.022, 0.03 };
2839 const integer numberOfFormants = 6;
2840 const integer numberOfNasalFormants = 1;
2841 const integer numberOfNasalAntiFormants = numberOfNasalFormants;
2842 const integer numberOfTrachealFormants = 0;
2843 const integer numberOfTrachealAntiFormants = numberOfTrachealFormants;
2844 const integer numberOfFricationFormants = 6;
2845 const integer numberOfDeltaFormants = 1;
2846
2847 autoKlattGrid thee = KlattGrid_create (tmin, tmax, numberOfFormants, numberOfNasalFormants,
2848 numberOfNasalAntiFormants, numberOfTrachealFormants, numberOfTrachealAntiFormants,
2849 numberOfFricationFormants, numberOfDeltaFormants);
2850 for (integer irow = 1; irow <= numberOfRows; irow ++) {
2851 const double t = (irow - 1) * frameDuration;
2852
2853 integer icol = 1;
2854 double val = Table_getNumericValue_a (kt, irow, icol) / 10.0; // F0hz10
2855 const double f0 = val;
2856 RealTier_addPoint (thy phonation -> pitch.get(), t, f0);
2857
2858 val = Table_getNumericValue_a (kt, irow, ++ icol); // AVdb
2859 // dB values below 13 were put to zero in the DBtoLIN function
2860 val -= 7.0;
2861 if (val < 13.0)
2862 val = dBNul;
2863
2864 // RealTier_addPoint (thy source -> voicingAmplitude, t, val);
2865
2866 for (integer kf = 1; kf <= 6; kf ++) {
2867 const double fk = val = Table_getNumericValue_a (kt, irow, ++ icol); // Fhz
2868 RealTier_addPoint (thy vocalTract -> oral_formants -> formants.at [kf], t, val);
2869 RealTier_addPoint (thy frication -> frication_formants -> formants.at [kf], t, val); // only amplitudes and bandwidths in frication section
2870 val = Table_getNumericValue_a (kt, irow, ++ icol); // Bhz
2871 if (val <= 0.0)
2872 val = fk / 10.0;
2873 RealTier_addPoint (thy vocalTract -> oral_formants -> bandwidths.at [kf], t, val);
2874 }
2875
2876 val = Table_getNumericValue_a (kt, irow, ++ icol); // FNZhz
2877 RealTier_addPoint (thy vocalTract -> nasal_antiformants -> formants.at [1], t, val);
2878
2879 val = Table_getNumericValue_a (kt, irow, ++ icol); // BNZhz
2880 RealTier_addPoint (thy vocalTract -> nasal_antiformants -> bandwidths.at [1], t, val);
2881
2882 val = Table_getNumericValue_a (kt, irow, ++ icol); // FNPhz
2883 RealTier_addPoint (thy vocalTract -> nasal_formants -> formants.at [1], t, val);
2884
2885 val = Table_getNumericValue_a (kt, irow, ++ icol); // BNPhz
2886 RealTier_addPoint (thy vocalTract -> nasal_formants -> bandwidths.at [1], t, val);
2887
2888 val = Table_getNumericValue_a (kt, irow, ++ icol); // ah
2889 if (val < 13.0)
2890 val = dBNul;
2891 else
2892 val += 20.0 * log10 (0.05) + dB_offset_noise;
2893
2894 RealTier_addPoint (thy phonation -> aspirationAmplitude.get(), t, val);
2895
2896 val = Table_getNumericValue_a (kt, irow, ++ icol); // Kopen
2897 const double openPhase = ( f0 > 0.0 ? (val / 16000.0) * f0 : 0.7 );
2898 RealTier_addPoint (thy phonation -> openPhase.get(), t, openPhase);
2899
2900 val = Table_getNumericValue_a (kt, irow, ++ icol); // Aturb breathinessAmplitude during voicing (max is 8192)
2901 if (val < 13.0)
2902 val = dBNul;
2903 else
2904 val += 20.0 * log10 (0.1) + dB_offset_noise;
2905
2906 RealTier_addPoint (thy phonation -> breathinessAmplitude.get(), t, val);
2907
2908 val = Table_getNumericValue_a (kt, irow, ++ icol); // TLTdb
2909 RealTier_addPoint (thy phonation -> spectralTilt.get(), t, val);
2910
2911 val = Table_getNumericValue_a (kt, irow, ++ icol); // AF
2912 if (val < 13.0)
2913 val = dBNul;
2914 else
2915 val += 20.0 * log10 (0.25) + dB_offset_noise;
2916
2917 RealTier_addPoint (thy frication -> fricationAmplitude.get(), t, val);
2918
2919 val = Table_getNumericValue_a (kt, irow, ++ icol); // Kskew ???
2920 //RealTier_addPoint (, t, val);
2921
2922 for (integer kf = 1; kf <= 6; kf ++) {
2923 val = Table_getNumericValue_a (kt, irow, ++ icol); // Ap
2924 if (val < 13.0)
2925 val = dBNul;
2926 else
2927 val += 20.0 * log10 (ap [kf]) + dB_offset;
2928
2929 RealTier_addPoint (thy vocalTract -> oral_formants_amplitudes.at [kf], t, val);
2930 RealTier_addPoint (thy frication -> frication_formants_amplitudes.at [kf], t, val);
2931 val = Table_getNumericValue_a (kt, irow, ++ icol); // Bhz
2932 RealTier_addPoint (thy frication -> frication_formants -> bandwidths.at [kf], t, val);
2933 }
2934
2935 val = Table_getNumericValue_a (kt, irow, ++ icol); // ANP
2936 if (val < 13.0)
2937 val = dBNul;
2938 else
2939 val += 20.0 * log10 (0.6) + dB_offset;
2940
2941 RealTier_addPoint (thy vocalTract -> nasal_formants_amplitudes.at [1], t, val);
2942
2943 val = Table_getNumericValue_a (kt, irow, ++ icol); // AB
2944 if (val < 13.0)
2945 val = dBNul;
2946 else
2947 val += 20.0 * log10 (0.05) + dB_offset_noise;
2948
2949 RealTier_addPoint (thy frication -> bypass.get(), t, val);
2950
2951 val = Table_getNumericValue_a (kt, irow, ++ icol); // AVpdb
2952 RealTier_addPoint (thy phonation -> voicingAmplitude.get(), t, val + dB_offset_voicing);
2953
2954 val = Table_getNumericValue_a (kt, irow, ++ icol); // Gain0
2955 val -= 3.0;
2956 if (val <= 0.0)
2957 val = 57.0;
2958 RealTier_addPoint (thy gain.get(), t, val + dB_offset);
2959 }
2960 // We don't need the following low-pass: we do not use oversampling !!
2961 //RealTier_addPoint (thy tracheal_formants -> formants->at [1], 0.5*(tmin+tmax), 0.095*samplingFrequency);
2962 //RealTier_addPoint (thy tracheal_formants -> bandwidths->at [1], 0.5*(tmin+tmax), 0.063*samplingFrequency);
2963 return thee;
2964 } catch (MelderError) {
2965 Melder_throw (me, U": no KlattGrid created.");
2966 }
2967 }
2968
2969 autoKlattGrid Sound_to_KlattGrid_simple (Sound me, double timeStep, integer maximumNumberOfFormants, double maximumFormantFrequency,
2970 double windowLength, double preEmphasisFrequency, double pitchFloor, double pitchCeiling, double pitchFloorForIntensity, int subtractMean)
2971 {
2972 try {
2973 const integer numberOfFormants = maximumNumberOfFormants;
2974 const integer numberOfNasalFormants = 1;
2975 const integer numberOfNasalAntiFormants = numberOfNasalFormants;
2976 const integer numberOfTrachealFormants = 1;
2977 const integer numberOfTrachealAntiFormants = numberOfTrachealFormants;
2978 const integer numberOfFricationFormants = maximumNumberOfFormants;
2979 const integer numberOfDeltaFormants = 1;
2980 autoSound sound = Data_copy (me);
2981 Vector_subtractMean (sound.get());
2982 autoFormant formant = Sound_to_Formant_burg (sound.get(), timeStep, maximumNumberOfFormants,
2983 maximumFormantFrequency, windowLength, preEmphasisFrequency);
2984 autoFormantGrid formantGrid = Formant_downto_FormantGrid (formant.get());
2985 autoPitch pitch = Sound_to_Pitch (sound.get(), timeStep, pitchFloor, pitchCeiling);
2986 autoPitchTier pitchTier = Pitch_to_PitchTier (pitch.get());
2987 autoIntensity intensity = Sound_to_Intensity (sound.get(), pitchFloorForIntensity, timeStep, subtractMean);
2988 autoIntensityTier intensityTier = Intensity_downto_IntensityTier (intensity.get());
2989 autoKlattGrid thee = KlattGrid_create (my xmin, my xmax, numberOfFormants, numberOfNasalFormants, numberOfNasalAntiFormants,
2990 numberOfTrachealFormants, numberOfTrachealAntiFormants, numberOfFricationFormants, numberOfDeltaFormants);
2991 KlattGrid_replacePitchTier (thee.get(), pitchTier.get());
2992 KlattGrid_replaceFormantGrid (thee.get(), kKlattGridFormantType::ORAL, formantGrid.get());
2993 KlattGrid_replaceVoicingAmplitudeTier (thee.get(), intensityTier.get());
2994 return thee;
2995 } catch (MelderError) {
2996 Melder_throw (me, U": no simple KlattGrid created.");
2997 }
2998 }
2999
3000 autoKlattGrid KlattGrid_createFromVowel (double duration, double f0start, double f1, double b1, double f2, double b2, double f3, double b3, double f4,
3001 double bandWidthFraction, double formantFrequencyInterval)
3002 {
3003 const integer numberOfOralFormants = 15;
3004 const double tstart = 0.0;
3005 autoKlattGrid me = KlattGrid_create (0.0, duration, numberOfOralFormants, 0, 0, 0, 0, 0, 0);
3006 KlattGrid_addPitchPoint (me.get(), tstart, f0start);
3007 KlattGrid_addVoicingAmplitudePoint (me.get(), tstart, 90.0);
3008 if (f1 > 0.0) {
3009 KlattGrid_addFormantPoint (me.get(), kKlattGridFormantType::ORAL, 1, tstart, f1);
3010 KlattGrid_addBandwidthPoint (me.get(), kKlattGridFormantType::ORAL, 1, tstart, b1);
3011 }
3012 if (f2 > 0.0) {
3013 KlattGrid_addFormantPoint (me.get(), kKlattGridFormantType::ORAL, 2, tstart, f2);
3014 KlattGrid_addBandwidthPoint (me.get(), kKlattGridFormantType::ORAL, 2, tstart, b2);
3015 }
3016 if (f3 > 0.0) {
3017 KlattGrid_addFormantPoint (me.get(), kKlattGridFormantType::ORAL, 3, tstart, f3);
3018 KlattGrid_addBandwidthPoint (me.get(), kKlattGridFormantType::ORAL, 3, tstart, b3);
3019 }
3020 if (f4 > 0.0) {
3021 KlattGrid_addFormantPoint (me.get(), kKlattGridFormantType::ORAL, 4, tstart, f4);
3022 KlattGrid_addBandwidthPoint (me.get(), kKlattGridFormantType::ORAL, 4, tstart, f4 * bandWidthFraction);
3023 }
3024 if (formantFrequencyInterval > 0.0) {
3025 const double startFrequency = std::max (std::max (f1, f2), std::max (f3, f4));
3026 for (integer iformant = 5; iformant <= numberOfOralFormants; iformant ++) {
3027 const double frequency = startFrequency + (iformant - 4) * formantFrequencyInterval;
3028 KlattGrid_addFormantPoint (me.get(), kKlattGridFormantType::ORAL, iformant, tstart, frequency);
3029 KlattGrid_addBandwidthPoint (me.get(), kKlattGridFormantType::ORAL, iformant, tstart, frequency * bandWidthFraction);
3030 }
3031 }
3032 return me;
3033 }
3034
3035 /* End of file KlattGrid.cpp */