| 1 | /* NUM2.cpp |
| 2 | * |
| 3 | * Copyright (C) 1993-2025 David Weenink, 2017-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 | /* |
| 20 | djmw 20020819 GPL header |
| 21 | djmw 20020819 Split nonGLP part off. |
| 22 | djmw 20001109 Changed stop criteria in NUMsvdcmp and NUMtqli. |
| 23 | djmw 20020819 Split into GPL and nonGPL part. |
| 24 | djmw 20021008 Removed SVD_sort. |
| 25 | djmw 20030619 Removed calls to NRC svd-routines. |
| 26 | djmw 20030623 Removed tqli en tred calls. |
| 27 | djmw 20030703 Replaced NUMincompleteBeta with gsl_sf_beta_inc. |
| 28 | djmw 20030710 NUMminimize_brent now also returns the minimum function value. |
| 29 | djmw 20030731 NUMridders: better approximation for small d. |
| 30 | NUMinvFisherQ better approximation for p < 0.5 |
| 31 | djmw 20030813 Added NUMmad and NUMstatistics_huber. |
| 32 | djmw 20030825 Replaced gsl_sf_beta_inc with NUMincompleteBeta |
| 33 | pb 20030828 Improvements for invFisherQ, ridders, studentP, studentQ, |
| 34 | invStudentQ, invChiSquareQ: modifications for 'undefined' return values. |
| 35 | djmw 20030830 Corrected a bug in NUMtriangularfilter_amplitude |
| 36 | djmw 20031111 Added NUMdmatrix_transpose, NUMdmatrix_printMatlabForm |
| 37 | djmw 20040105 Added NUMmahalanobisDistanceSquared_chi |
| 38 | djmw 20040303 Added NUMstring_containsPrintableCharacter. |
| 39 | djmw 20050406 NUMprocrutus->NUMprocrustes |
| 40 | djmw 20060319 NUMinverse_cholesky: calculation of determinant is made optional |
| 41 | djmw 20060517 Added NUMregexp_compile |
| 42 | djmw 20060518 Treat NULL string as empty string in strs_replace_regexp/literal. Don't accept empty search in replace_regexStr |
| 43 | djmw 20060626 Extra NULL argument for ExecRE. |
| 44 | djmw 20070302 NUMclipLineWithinRectangle |
| 45 | djmw 20070614 updated to version 1.30 of regular expressions. |
| 46 | djmw 20071022 Removed function NUMfvector_moment2. |
| 47 | djmw 20071201 Melder_warning<n> |
| 48 | djmw 20080110 Corrected some bugs in replace_regexStr |
| 49 | djmw 20080122 Bug in replace_regexStr |
| 50 | djmw 20080317 +NUMsinc |
| 51 | pb 20080410 FisherQ from gsl |
| 52 | djmw 20090630 NUMlogNormalP/Q from gsl |
| 53 | djmw 20090707 Rename NUMinverse_cholesky to NUMlowerCholeskyInverse, |
| 54 | +NUMcovarianceFromColumnCentredMatrix, +NUMmultivariateKurtosis |
| 55 | djmw 20100311 +NUMsolveQuadraticEquation |
| 56 | djmw 20100426 replace wcstok by Melder_wcstok |
| 57 | djmw 20101209 removed NUMwcscmp is Melder_wcscmp now |
| 58 | djmw 20110304 Thing_new |
| 59 | djmw 20111110 use autostringvector |
| 60 | */ |
| 61 | |
| 62 | #include "SVD.h" |
| 63 | #include "Eigen.h" |
| 64 | #include "NUMlapack.h" |
| 65 | #include "NUM2.h" |
| 66 | #include "NUMmachar.h" |
| 67 | #include "melder.h" |
| 68 | |
| 69 | #include "gsl_randist.h" |
| 70 | |
| 71 | #include "gsl_errno.h" |
| 72 | #include "gsl_sf_bessel.h" |
| 73 | #include "gsl_sf_gamma.h" |
| 74 | #include "gsl_sf_erf.h" |
| 75 | #include "gsl_sf_trig.h" |
| 76 | #include "gsl_poly.h" |
| 77 | #include "gsl_cdf.h" |
| 78 | |
| 79 | int NUMcompareTwoIntegers (integer& a, integer& b) { |
| 80 | return a < b ? -1 : a > b ? 1 : 0; |
| 81 | } |
| 82 | |
| 83 | int NUMcompareTwoDoubles (double& a, double& b) { |
| 84 | return a < b ? -1 : a > b ? 1 : 0; |
| 85 | } |
| 86 | |
| 87 | #define SIGN(a,b) ((b < 0) ? -fabs(a) : fabs(a)) |
| 88 | |
| 89 | struct pdf1_struct { |
| 90 | double p; |
| 91 | double df; |
| 92 | }; |
| 93 | struct pdf2_struct { |
| 94 | double p; |
| 95 | double df1; |
| 96 | double df2; |
| 97 | }; |
| 98 | |
| 99 | void MATprintMatlabForm (constMATVU const& m, conststring32 name) { |
| 100 | constexpr integer npc = 5; |
| 101 | const ldiv_t n = ldiv (m.ncol, npc); |
| 102 | |
| 103 | MelderInfo_open (); |
| 104 | MelderInfo_write (name, U"= ["); |
| 105 | for (integer i = 1; i <= m.nrow; i ++) { |
| 106 | for (integer j = 1; j <= n.quot; j ++) { |
| 107 | for (integer k = 1; k <= npc; k ++) |
| 108 | MelderInfo_write (m [i] [(j - 1) * npc + k], (k < npc ? U", " : U"")); |
| 109 | MelderInfo_write (j < n.quot ? U",\n" : U""); |
| 110 | } |
| 111 | |
| 112 | for (integer k = 1; k <= n.rem; k ++) |
| 113 | MelderInfo_write (m [i] [n.quot * npc + k], (k < n.rem ? U", " : U"")); |
| 114 | MelderInfo_write (i < m.nrow ? U";\n" : U"];\n"); |
| 115 | } |
| 116 | MelderInfo_close (); |
| 117 | } |
| 118 | |
| 119 | void VECsmoothByMovingAverage_preallocated (VECVU const& out, constVECVU const& in, integer window) { |
| 120 | Melder_assert (out.size == in.size); |
| 121 | Melder_require (window > 0, |
| 122 | U"The averaging window should be larger than 0."); |
| 123 | for (integer i = 1; i <= out.size; i ++) { |
| 124 | integer jfrom = i - window / 2, jto = i + window / 2; |
| 125 | if (window % 2 == 0) |
| 126 | jto --; |
| 127 | Melder_clipLeft (1_integer, & jfrom); |
| 128 | Melder_clipRight (& jto, out.size); |
| 129 | out [i] = NUMmean (in.part (jfrom, jto)); |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | void VECsmooth_gaussian (VECVU const& out, constVECVU const& in, double sigma, NUMFourierTable fftTable) { |
| 134 | Melder_require (out.size == in.size, |
| 135 | U"The sizes of the input and output vectors should be equal."); |
| 136 | out <<= in; |
| 137 | VECsmooth_gaussian_inplace (out, sigma, fftTable); |
| 138 | } |
| 139 | |
| 140 | void VECsmooth_gaussian_inplace (VECVU const& in_out, double sigma, NUMFourierTable fftTable) { |
| 141 | Melder_require (in_out.size <= fftTable -> n, |
| 142 | U"The dimension of the table should at least equal the length of the input vector."); |
| 143 | autoVEC smooth = zero_VEC (fftTable -> n); |
| 144 | smooth.part (1, in_out.size) <<= in_out; |
| 145 | NUMfft_forward (fftTable, smooth.get()); |
| 146 | /* |
| 147 | Low pass filter with a Gaussian. |
| 148 | The Fourier Transform of h(x)= (exp(-a.x^2) is |
| 149 | H(f) = sqrt (pi/a) exp (-pi^2.f^2/a). |
| 150 | A Gaussian g(x)=sqrt(a/pi)h(x), where a = 1/(2s^2) |
| 151 | The "frequency" region is divided in fftTable -> n steps, |
| 152 | where one "frequency" unit f equals 1 / fftTable -> n. |
| 153 | */ |
| 154 | const double b = 2.0 * NUMpi * sigma * NUMpi * sigma ; |
| 155 | for (integer k = 2; k <= (fftTable -> n + 1) / 2; k ++) { |
| 156 | const double f = (k - 1) / (double) fftTable -> n; |
| 157 | const double weight = exp (- b * f * f); |
| 158 | smooth [k * 2 - 2] *= weight; // re |
| 159 | smooth [k * 2 - 1] *= weight; // im |
| 160 | } |
| 161 | if (fftTable -> n % 2 == 0) |
| 162 | smooth [fftTable -> n] *= exp (- b * 1 / 2 * 1 / 2); |
| 163 | NUMfft_backward (fftTable, smooth.get()); |
| 164 | /* |
| 165 | backwardFT (forwardFT (data)) = n * data; |
| 166 | */ |
| 167 | const double scaleFacor = 1.0 / fftTable -> n; |
| 168 | smooth.part (1, in_out.size) *= scaleFacor; |
| 169 | in_out <<= smooth.part (1, in_out.size); |
| 170 | } |
| 171 | |
| 172 | void VECsmooth_gaussian_inplace (VECVU const& in_out, double sigma) { |
| 173 | const integer nfft = Melder_iroundUpToPowerOfTwo (in_out.size); |
| 174 | autoNUMFourierTable fftTable = NUMFourierTable_create (nfft); |
| 175 | VECsmooth_gaussian_inplace (in_out, sigma, fftTable.get()); |
| 176 | } |
| 177 | |
| 178 | autoMAT MATcovarianceFromColumnCentredMatrix (constMATVU const& x, integer ndf) { |
| 179 | Melder_require (ndf >= 0 && x.nrow - ndf > 0, |
| 180 | U"Invalid arguments."); |
| 181 | autoMAT covar = mtm_MAT (x); |
| 182 | covar.all() *= 1.0 / (x.nrow - ndf); |
| 183 | return covar; |
| 184 | } |
| 185 | |
| 186 | static void MATweighRows (MATVU const& x, constVECVU const& y) { |
| 187 | Melder_assert (x.nrow == y.size); |
| 188 | for (integer irow = 1; irow <= x.nrow; irow ++) |
| 189 | x.row (irow) *= y [irow]; |
| 190 | } |
| 191 | |
| 192 | void MATmtm_weighRows (MATVU const& result, constMATVU const& data, constVECVU const& rowWeights) { |
| 193 | Melder_assert (data.nrow == rowWeights.size); |
| 194 | Melder_assert (data.ncol == result.ncol); |
| 195 | Melder_assert (result.nrow == result.ncol); |
| 196 | result <<= 0.0; |
| 197 | if (true) { |
| 198 | autoMAT outer = raw_MAT (result.ncol, result.ncol); |
| 199 | for (integer irow = 1; irow <= data.nrow; irow ++) { |
| 200 | outer_MAT_out (outer.all(), data.row (irow), data.row (irow)); |
| 201 | result += outer.all() * rowWeights [irow]; |
| 202 | } |
| 203 | } else { |
| 204 | autoVEC w = raw_VEC (rowWeights.size); |
| 205 | autoMAT d = copy_MAT (data); |
| 206 | for (integer irow = 1; irow <= w.size; irow ++) |
| 207 | w [irow] = sqrt (rowWeights [irow]); |
| 208 | MATweighRows (d.get(), w.get()); |
| 209 | mtm_MAT_out (result, d.get()); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | inline void MATmultiplyRows_inplace (MATVU const& x, constVECVU const& v) { |
| 214 | Melder_assert (x.nrow == v.size); |
| 215 | for (integer irow = 1; irow <= x.nrow; irow ++) |
| 216 | x.row (irow) *= v [irow]; // x [i,j] * v [i] |
| 217 | } |
| 218 | inline void MATmultiplyColumns_inplace (MATVU const& x, constVECVU const& v) { |
| 219 | Melder_assert (x.ncol == v.size); |
| 220 | for (integer icol = 1; icol <= x.nrow; icol ++) |
| 221 | x.column (icol) *= v [icol]; // x [i,j] * v [j] |
| 222 | } |
| 223 | |
| 224 | double NUMmultivariateKurtosis (constMATVU const& m, integer method) { |
| 225 | double kurt = undefined; |
| 226 | if (m.nrow < 5) |
| 227 | return kurt; |
| 228 | autoMAT x = copy_MAT (m); |
| 229 | autoVEC mean = columnMeans_VEC (x.get()); |
| 230 | x.all() -= mean.all(); |
| 231 | autoMAT covar = MATcovarianceFromColumnCentredMatrix (x.get(), 1); |
| 232 | |
| 233 | if (method == 1) { // Schott (2001, page 33) |
| 234 | kurt = 0.0; |
| 235 | for (integer l = 1; l <= x.ncol; l ++) { |
| 236 | const double sll2 = covar [l] [l] * covar [l] [l]; |
| 237 | double zl = 0.0, wl; |
| 238 | for (integer j = 1; j <= x.nrow; j ++) { |
| 239 | const double d = x [j] [l] - mean [l], d2 = d * d; |
| 240 | zl += d2 * d2; |
| 241 | } |
| 242 | zl = (zl - 6.0 * sll2) / (x.nrow - 4); |
| 243 | wl = (sll2 - zl / x.nrow) * x.nrow / (x.nrow - 1); |
| 244 | kurt += zl / wl; |
| 245 | } |
| 246 | kurt = kurt / (3.0 * x.ncol) - 1.0; |
| 247 | } |
| 248 | return kurt; |
| 249 | } |
| 250 | |
| 251 | /* |
| 252 | The following algorithm for monotone regession is on the average |
| 253 | 3.5 times faster than |
| 254 | Kruskal's algorithm for monotone regression (and much simpler). |
| 255 | Regression is ascending |
| 256 | */ |
| 257 | autoVEC newVECmonotoneRegression (constVEC x) { |
| 258 | autoVEC fit = copy_VEC (x); |
| 259 | double xt = undefined; // only to stop gcc from complaining "may be used uninitialized" |
| 260 | for (integer i = 2; i <= x.size; i ++) { |
| 261 | if (fit [i] >= fit [i - 1]) |
| 262 | continue; |
| 263 | longdouble sum = fit [i]; |
| 264 | integer nt = 1; |
| 265 | for (integer j = 1; j <= i - 1; j ++) { |
| 266 | sum += fit [i - j]; |
| 267 | nt ++; |
| 268 | xt = (double) sum / nt; // i >= 2 -> xt always gets a value |
| 269 | if (j < i - 1 && xt >= fit [i - j - 1]) |
| 270 | break; |
| 271 | } |
| 272 | for (integer j = i - nt + 1; j <= i; j ++) |
| 273 | fit [j] = xt; |
| 274 | } |
| 275 | return fit; |
| 276 | } |
| 277 | |
| 278 | #undef TINY |
| 279 | |
| 280 | double NUMdeterminant_fromSymmetricMatrix (constMAT m) { |
| 281 | Melder_assert (m.nrow == m.ncol); |
| 282 | autoMAT a = copy_MAT (m); |
| 283 | /* |
| 284 | Cholesky decomposition in lower, leave upper intact |
| 285 | */ |
| 286 | integer info; |
| 287 | NUMlapack_dpotf2_ ("U", a.nrow, & a [1] [1], m.nrow, & info); |
| 288 | Melder_require (info == 0, |
| 289 | U"dpotf2_ failed with error = ", info); |
| 290 | longdouble lnd = 0.0; |
| 291 | for (integer i = 1; i <= a.nrow; i ++) |
| 292 | lnd += log (a [i] [i]); |
| 293 | lnd *= 2.0; // because A = L . L' |
| 294 | return (double) lnd; |
| 295 | } |
| 296 | |
| 297 | autoMAT newMATlowerCholesky (constMATVU const& a, double *out_lnd) { |
| 298 | Melder_assert (a.nrow == a.ncol); |
| 299 | autoMAT result = copy_MAT (a); |
| 300 | MATlowerCholesky_inplace (result.get(), out_lnd); |
| 301 | for (integer irow = 1; irow <= a.nrow - 1; irow ++) |
| 302 | for (integer icol = irow + 1; icol <= a.nrow; icol ++) |
| 303 | result [irow] [icol] = 0.0; |
| 304 | return result; |
| 305 | } |
| 306 | |
| 307 | |
| 308 | autoMAT newMATlowerCholeslyInverse_fromLowerCholesky (constMAT const& m) { |
| 309 | Melder_assert (m.nrow == m.ncol); |
| 310 | autoMAT result = copy_MAT (m); |
| 311 | MATlowerCholeskyInverse_inplace (result.get(), nullptr); |
| 312 | return result; |
| 313 | } |
| 314 | |
| 315 | void MATlowerCholesky_inplace (MAT a, double *out_lnDeterminant) { |
| 316 | Melder_assert (a.nrow == a.ncol); |
| 317 | /* |
| 318 | Cholesky decomposition in lower, leave upper intact |
| 319 | Fortran storage -> use uplo='U' to get 'L'. |
| 320 | */ |
| 321 | integer info; |
| 322 | NUMlapack_dpotf2_ ("U", a.nrow, & a [1] [1], a.nrow, & info); |
| 323 | Melder_require (info == 0, |
| 324 | U"dpotf2 fails with code ", info, U"."); |
| 325 | /* |
| 326 | Determinant from diagonal, diagonal is now sqrt (a [i] [i]) ! |
| 327 | */ |
| 328 | if (out_lnDeterminant) { |
| 329 | longdouble lnDeterminant = 0.0; |
| 330 | for (integer i = 1; i <= a.nrow; i ++) |
| 331 | lnDeterminant += log (a [i] [i]); |
| 332 | lnDeterminant *= 2.0; /* because A = L . L' */ |
| 333 | *out_lnDeterminant = double (lnDeterminant); |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | void MATlowerCholeskyInverse_inplace (MAT a, double *out_lnd) { |
| 338 | Melder_assert (a.nrow == a.ncol); |
| 339 | MATlowerCholesky_inplace (a, out_lnd); |
| 340 | /* |
| 341 | Get the inverse |
| 342 | */ |
| 343 | integer info; |
| 344 | (void) NUMlapack_dtrtri_ ("U", "N", a.nrow, & a [1] [1], a.nrow, & info); |
| 345 | Melder_require (info == 0, |
| 346 | U"dtrtri_ fails with code ", info, U"."); |
| 347 | } |
| 348 | |
| 349 | autoMAT newMATinverse_fromLowerCholeskyInverse (constMAT m) { |
| 350 | Melder_assert (m.nrow == m.ncol); |
| 351 | autoMAT result = raw_MAT (m.nrow, m.nrow); |
| 352 | for (integer irow = 1; irow <= m.nrow; irow ++) { |
| 353 | for (integer icol = 1; icol <= irow; icol ++) { |
| 354 | longdouble sum = 0.0; |
| 355 | for (integer k = irow; k <= m.nrow; k ++) |
| 356 | sum += m [k] [irow] * m [k] [icol]; |
| 357 | result [irow] [icol] = result [icol] [irow] = (double) sum; |
| 358 | } |
| 359 | } |
| 360 | return result; |
| 361 | } |
| 362 | |
| 363 | autoMAT newMATsymmetricPositiveDefinte_inverse (constMAT m) { |
| 364 | autoMAT inverse; |
| 365 | try { |
| 366 | if (m.nrow == 1) { |
| 367 | inverse = copy_MAT (m); |
| 368 | inverse [1] [1] = ( m [1] [1] != 0.0 ? 1.0 / m [1] [1] : undefined ); |
| 369 | } else { |
| 370 | autoMAT mc = newMATlowerCholesky (m, nullptr); |
| 371 | inverse = newMATinverse_fromLowerCholeskyInverse (mc.get()); |
| 372 | } |
| 373 | } catch (MelderError) { |
| 374 | inverse = copy_MAT (m); |
| 375 | inverse.get() <<= undefined; |
| 376 | } |
| 377 | return inverse; |
| 378 | } |
| 379 | |
| 380 | autoMAT newMATsymmetric_inverse2 (constMAT m) { |
| 381 | Melder_assert (m.nrow == m.ncol); |
| 382 | autoINTVEC ipiv = zero_INTVEC (m.nrow); |
| 383 | autoMAT result = copy_MAT (m); |
| 384 | const integer lda = m.nrow, lwork = m.nrow * m.ncol; |
| 385 | /* |
| 386 | We don't query for the size of the work array, just make it big enough |
| 387 | */ |
| 388 | autoVEC work = raw_VEC (lwork); |
| 389 | integer info; |
| 390 | (void) NUMlapack_dsytrf_("L", m.nrow, & result [1] [1], lda, ipiv.asArgumentToFunctionThatExpectsZeroBasedArray(), |
| 391 | work.asArgumentToFunctionThatExpectsZeroBasedArray(), lwork, & info); |
| 392 | Melder_require (info == 0, |
| 393 | U"dsytrf_ fails with code ", info, U"."); |
| 394 | |
| 395 | (void) NUMlapack_dsytri_ ("L", m.nrow, & result [1] [1], lda, ipiv.asArgumentToFunctionThatExpectsZeroBasedArray(), |
| 396 | work.asArgumentToFunctionThatExpectsZeroBasedArray(), & info); |
| 397 | Melder_require (info == 0, |
| 398 | U"dsytri_ fails with code ", info, U"."); |
| 399 | |
| 400 | return result; |
| 401 | } |
| 402 | |
| 403 | autoMAT newMATinverse (constMAT m) { |
| 404 | Melder_assert (m.nrow == m.ncol); |
| 405 | try { |
| 406 | autoSVD svd = SVD_createFromGeneralMatrix (m); |
| 407 | autoMAT vp = raw_MAT (m.nrow, m.ncol); |
| 408 | for (integer irow = 1; irow <= m.nrow; irow ++) |
| 409 | for (integer icol = 1; icol <= m.ncol; icol ++) |
| 410 | vp [irow] [icol] = svd -> v [irow][icol] / svd -> d [icol]; |
| 411 | autoMAT inverse = mul_MAT (vp.get(), svd -> u.get()); |
| 412 | return inverse; |
| 413 | } catch (MelderError) { |
| 414 | Melder_throw (U"newMATinverse: cannot get inverse."); |
| 415 | } |
| 416 | } |
| 417 | double NUMmahalanobisDistanceSquared (constMAT lowerInverse, constVEC v, constVEC m) { |
| 418 | Melder_assert (lowerInverse.ncol == v.size && v.size == m.size); |
| 419 | longdouble chisq = 0.0; |
| 420 | if (lowerInverse.nrow == 1) { // diagonal matrix is one row matrix |
| 421 | for (integer icol = 1; icol <= v.size; icol ++) { |
| 422 | const double t = lowerInverse [1] [icol] * (v [icol] - m [icol]); |
| 423 | chisq += t * t; |
| 424 | } |
| 425 | } else { // square matrix |
| 426 | for (integer irow = v.size; irow > 0; irow --) { |
| 427 | longdouble t = 0.0; |
| 428 | for (integer icol = 1; icol <= irow; icol ++) |
| 429 | t += lowerInverse [irow] [icol] * (v [icol] - m [icol]); |
| 430 | chisq += t * t; |
| 431 | } |
| 432 | } |
| 433 | return (double) chisq; |
| 434 | } |
| 435 | |
| 436 | /* |
| 437 | G. Golub & C. van Loan (1996), Matrix computations, third edition, |
| 438 | The Johns Hopkins University Press Ltd., |
| 439 | London, (Par. 7.3.1 The Power Method) |
| 440 | */ |
| 441 | double VECdominantEigenvector_inplace (VEC inout_q, constMAT m, double tolerance) { |
| 442 | Melder_assert (m.nrow == m.ncol && inout_q.size == m.nrow); |
| 443 | |
| 444 | double lambda0, lambda = NUMmul (inout_q, m, inout_q); // q'. M . q |
| 445 | Melder_require (lambda > 0.0, |
| 446 | U"Zero matrices ??"); |
| 447 | autoVEC z = raw_VEC (m.nrow); |
| 448 | integer maximunNumberOfIterations = 30; |
| 449 | for (integer iter = 1; iter <= maximunNumberOfIterations; iter ++) { |
| 450 | lambda0 = lambda; |
| 451 | mul_VEC_out (z.get(), m, inout_q); |
| 452 | VECnormalize_inplace (z.get(), 2.0, 1.0); |
| 453 | lambda = NUMmul (z.get(), m, z.get()); // z'. M . z |
| 454 | if (fabs (lambda - lambda0) < tolerance) |
| 455 | break; |
| 456 | } |
| 457 | inout_q <<= z.all(); |
| 458 | return lambda; |
| 459 | } |
| 460 | |
| 461 | void MATprojectColumnsOnEigenspace_preallocated (MAT projection, constMATVU const& data, constMATVU const& eigenvectors) { |
| 462 | Melder_assert (data.nrow == eigenvectors.ncol && projection.nrow == eigenvectors.nrow); |
| 463 | for (integer icol = 1; icol <= data.ncol; icol ++) |
| 464 | for (integer irow = 1; irow <= eigenvectors.nrow; irow ++) |
| 465 | projection [irow] [icol] = NUMinner (eigenvectors.row (irow), data.column (icol)); |
| 466 | // MATmul_tt (data.get(), eigenvectors.get()) ?? |
| 467 | } |
| 468 | |
| 469 | integer NUMsolveQuadraticEquation (double a, double b, double c, double *out_x1, double *out_x2) { |
| 470 | double x1, x2; |
| 471 | integer result = gsl_poly_solve_quadratic (a, b, c, & x1, & x2); |
| 472 | if (out_x1) |
| 473 | *out_x1 = x1; |
| 474 | if (out_x2) |
| 475 | *out_x2 = x2; |
| 476 | return result; |
| 477 | } |
| 478 | |
| 479 | autoVEC solve_VEC (constMATVU const& a, constVECVU const& b, double tolerance) { |
| 480 | Melder_assert (a.nrow == b.size); |
| 481 | autoSVD me = SVD_createFromGeneralMatrix (a); |
| 482 | SVD_zeroSmallSingularValues (me.get(), tolerance); |
| 483 | autoVEC x = SVD_solve (me.get(), b); |
| 484 | return x; |
| 485 | } |
| 486 | |
| 487 | autoMAT solve_MAT (constMATVU const& a, constMATVU const& b, double tolerance) { |
| 488 | Melder_assert (a.nrow == b.nrow); |
| 489 | const double tol = ( tolerance > 0.0 ? tolerance : NUMfpp -> eps * a.nrow ); |
| 490 | |
| 491 | autoSVD me = SVD_createFromGeneralMatrix (a); |
| 492 | autoMAT x = raw_MAT (b.nrow, b.ncol); |
| 493 | |
| 494 | SVD_zeroSmallSingularValues (me.get(), tol); |
| 495 | |
| 496 | for (integer k = 1; k <= b.ncol; k ++) { |
| 497 | autoVEC xt = SVD_solve (me.get(), b.column (k)); |
| 498 | x.column (k) <<= xt.all(); |
| 499 | } |
| 500 | return x; |
| 501 | } |
| 502 | |
| 503 | /* |
| 504 | Non-negative least squares: Solve Ax = y, i.e |
| 505 | minimize || Ax - y ||^2 for vector x, where all x [i] >= 0.0 |
| 506 | */ |
| 507 | void VECsolveNonnegativeLeastSquaresRegression (VECVU const& x, constMATVU const& a, constVECVU const& y, integer maximumNumberOfIterations, double tol, integer infoLevel) { |
| 508 | Melder_assert (a.nrow == y.size); |
| 509 | Melder_assert (a.ncol == x.size); |
| 510 | for (integer i = 1; i <= x.size; i ++) |
| 511 | Melder_clipLeft (0.0, & x [i]); |
| 512 | autoVEC r = raw_VEC (y.size); |
| 513 | const double normSquared_y = NUMsum2 (y); |
| 514 | integer iter = 1; |
| 515 | bool farFromConvergence = true; |
| 516 | double difsq = undefined, difsq_previous = 1e100; // large enough |
| 517 | while (iter <= maximumNumberOfIterations && farFromConvergence) { |
| 518 | /* |
| 519 | Alternating Least Squares: Fixate all except x [icol] |
| 520 | */ |
| 521 | for (integer icol = 1; icol <= a.ncol; icol ++) { |
| 522 | r.all() <<= y; |
| 523 | for (integer jcol = 1; jcol <= a.ncol; jcol ++) |
| 524 | if (jcol != icol) |
| 525 | r.get() -= x [jcol] * a.column (jcol); |
| 526 | const double ajr = NUMinner (a.column (icol), r.all()); |
| 527 | const double ajaj = NUMsum2 (a.column (icol)); |
| 528 | x [icol] = std::max (0.0, ajr / ajaj); |
| 529 | } |
| 530 | /* |
| 531 | Calculate t(x) and compare with previous result. |
| 532 | */ |
| 533 | mul_VEC_out (r.get(), a, x); |
| 534 | r.get() -= y; |
| 535 | difsq = NUMsum2 (r.all()); |
| 536 | farFromConvergence = ( fabs (difsq - difsq_previous) > std::max (tol * normSquared_y, NUMeps) ); |
| 537 | if (infoLevel > 1) |
| 538 | MelderInfo_writeLine (U"\t\tIteration: ", iter, U", error: ", difsq); |
| 539 | difsq_previous = difsq; |
| 540 | iter ++; |
| 541 | } |
| 542 | iter --; |
| 543 | if (infoLevel >= 1) |
| 544 | MelderInfo_writeLine (U"\t\tNumber of iterations: ", iter, U"; Minimum: ", difsq); |
| 545 | if (infoLevel > 0) |
| 546 | MelderInfo_drain(); |
| 547 | } |
| 548 | |
| 549 | struct nr_struct { |
| 550 | double *y, *delta; |
| 551 | }; |
| 552 | |
| 553 | /* |
| 554 | f (lambda) = sum (y [i]^2 delta [i] / (delta [i]-lambda)^2, i=1..3) |
| 555 | f'(lambda) = 2 * sum (y [i]^2 delta [i] / (delta [i]-lambda)^3, i=1..3) |
| 556 | */ |
| 557 | |
| 558 | static double nr_func (double x, double *df, void *data) { |
| 559 | const struct nr_struct *me = (struct nr_struct *) data; |
| 560 | longdouble f = 0.0, derivative = 0.0; |
| 561 | for (integer i = 1; i <= 3; i ++) { |
| 562 | const longdouble t1 = (my delta [i] - x); |
| 563 | const longdouble t2 = my y [i] / t1; |
| 564 | const longdouble t3 = t2 * t2 * my delta [i]; |
| 565 | f += t3; |
| 566 | derivative += t3 * 2.0 / t1; |
| 567 | } |
| 568 | *df = (double) derivative; |
| 569 | return (double) f; |
| 570 | } |
| 571 | |
| 572 | void NUMsolveConstrainedLSQuadraticRegression (constMAT const& x, constVEC const& d, double *out_alpha, double *out_gamma) { |
| 573 | Melder_assert (x.ncol == x.nrow && d.size == x.ncol && d.size == 3); |
| 574 | Melder_assert (x.nrow >= x.ncol); |
| 575 | integer n3 = 3; |
| 576 | const double eps = 1e-6; |
| 577 | /* |
| 578 | Construct X'.X which will be 3x3 |
| 579 | */ |
| 580 | autoMAT xtx = mtm_MAT (x); |
| 581 | /* |
| 582 | Eq (2): get lower Cholesky decomposition from X'.X (3x3) |
| 583 | X'X -> lowerCholesky * lowerCholesky.transpose() |
| 584 | F'^-1 == lowerCholesky |
| 585 | F^-1 == lowerCholesky.transpose() |
| 586 | F = lowerCholeskyInverse.transpose() |
| 587 | */ |
| 588 | autoMAT lowerCholesky = newMATlowerCholesky (xtx.get(), nullptr); |
| 589 | autoMAT lowerCholeskyInverse = newMATlowerCholeslyInverse_fromLowerCholesky (lowerCholesky.get()); |
| 590 | /* |
| 591 | Construct G and its eigen-decomposition (eq. (4,5)) |
| 592 | Sort eigenvalues (& eigenvectors) ascending. |
| 593 | */ |
| 594 | autoMAT b = zero_MAT (n3, n3); |
| 595 | b [3] [1] = b [1] [3] = -0.5; |
| 596 | b [2] [2] = 1.0; |
| 597 | /* |
| 598 | G = F^-1 B (F')^-1 (eq. 4) |
| 599 | */ |
| 600 | autoMAT g = zero_MAT (n3, n3); |
| 601 | MATmul3_XYXt (g.get(), lowerCholesky.transpose(), b.get()); |
| 602 | /* |
| 603 | G's eigen-decomposition with eigenvalues (assumed ascending). (eq. 5) |
| 604 | */ |
| 605 | autoMAT p; |
| 606 | autoVEC delta; |
| 607 | MAT_getEigenSystemFromSymmetricMatrix (g.get(), & p, & delta, true); |
| 608 | /* |
| 609 | Construct y = P'*F'*O'*d = (F*P)'*(O'*d) (page 632) |
| 610 | We need F*P for later |
| 611 | */ |
| 612 | autoVEC otd = mul_VEC (x.transpose(), d); |
| 613 | autoMAT fp = mul_MAT (p.transpose(), lowerCholeskyInverse.transpose()); // F*P !! |
| 614 | autoVEC y = mul_VEC (fp.transpose(), otd.get()); // P'F' * O'd |
| 615 | /* |
| 616 | The solution (3 cases) |
| 617 | */ |
| 618 | autoVEC w = zero_VEC (n3); |
| 619 | autoVEC chi = raw_VEC (n3); |
| 620 | autoVEC diag = zero_VEC (n3); |
| 621 | |
| 622 | if (fabs (y [1]) < eps) { |
| 623 | /* |
| 624 | Case 1: page 633 |
| 625 | */ |
| 626 | const double t21 = y [2] / (delta [2] - delta [1]); |
| 627 | const double t31 = y [3] / (delta [3] - delta [1]); |
| 628 | w [1] = sqrt (- delta [1] * (t21 * t21 * delta [2] + t31 * t31 * delta [3])); |
| 629 | w [2] = t21 * delta [2]; |
| 630 | w [3] = t31 * delta [3]; |
| 631 | |
| 632 | mul_VEC_out (chi.get(), fp.get(), w.get()); // chi = F*P*w |
| 633 | |
| 634 | if (fabs (chi [3] / chi [1]) < eps) { |
| 635 | w [1] = - w [1]; |
| 636 | mul_VEC_out (chi.get(), fp.get(), w.get()); |
| 637 | } |
| 638 | } else if (fabs (y [2]) < eps) { |
| 639 | /* |
| 640 | Case 2: page 633 |
| 641 | */ |
| 642 | const double t12 = y [1] / (delta [1] - delta [2]); |
| 643 | const double t32 = y [3] / (delta [3] - delta [2]); |
| 644 | double t2; |
| 645 | w [1] = t12 * delta [1]; |
| 646 | if ( (delta [2] < delta [3] && (t2 = (t12 * t12 * delta [1] + t32 * t32 * delta [3])) <= 0.0)) { |
| 647 | w [2] = sqrt (- delta [2] * t2); /* +- */ |
| 648 | w [3] = t32 * delta [3]; |
| 649 | mul_VEC_out (chi.get(), p.get(), w.get()); |
| 650 | if (fabs (chi [3] / chi [1]) < eps) { |
| 651 | w [2] = -w [2]; |
| 652 | mul_VEC_out (chi.get(), fp.get(), w.get()); |
| 653 | } |
| 654 | } else if (fabs (delta [2] - delta [3]) < eps && fabs (y [3]) < eps) { |
| 655 | /* |
| 656 | Choose one value for w [2] from an infinite number |
| 657 | */ |
| 658 | w [2] = w [1]; |
| 659 | w [3] = sqrt (- t12 * t12 * delta [1] * delta [2] - w [2] * w [2]); |
| 660 | mul_VEC_out (chi.get(), fp.get(), w.get()); |
| 661 | } else { |
| 662 | // should not be here |
| 663 | } |
| 664 | } else { |
| 665 | /* |
| 666 | Case 3: page 634 use Newton-Raphson root finder |
| 667 | */ |
| 668 | struct nr_struct me; |
| 669 | me.y = y.asArgumentToFunctionThatExpectsOneBasedArray(); |
| 670 | me.delta = delta.asArgumentToFunctionThatExpectsOneBasedArray(); |
| 671 | |
| 672 | double lambda = NUMnrbis (nr_func, delta [1] + eps, delta [2] - eps, & me); |
| 673 | |
| 674 | for (integer i = 1; i <= 3; i++) |
| 675 | w [i] = y [i] / (1.0 - lambda / delta [i]); |
| 676 | mul_VEC_out (chi.get(), fp.get(), w.get()); |
| 677 | } |
| 678 | if (out_alpha) |
| 679 | *out_alpha = chi [1]; |
| 680 | if (out_gamma) |
| 681 | *out_gamma = chi [3]; |
| 682 | } |
| 683 | |
| 684 | /* |
| 685 | To find the value of b for which the derivative of psi(b) equals zero (Ten Berge, formula 4) |
| 686 | psi (b) = delta*b - b^2 /(4*alpha) - sum (i=1..n, x [i]^2 / (c [i] - b)) (formula 4) |
| 687 | psi'(b) = delta - b / (2 alpha) - sum (x [i]^2 / (c [i] - b)^2, i=1..n). (formula 5) |
| 688 | We use NewTon-Raphson with bisection because we can also use psi'(b)'s derivative: |
| 689 | f (b) = psi'(b) = delta - b / (2 alpha) - sum (x [i]^2 / (c [i] - b)^2, i=1..n) |
| 690 | f'(b) = psi''(b) = - 1 / (2 alpha) + 2 * sum (x [i]^2 / (c [i] - b)^3, i=1..n) |
| 691 | */ |
| 692 | struct nr2_struct { |
| 693 | integer numberOfTerms; |
| 694 | double delta, alpha; |
| 695 | VEC x, c; |
| 696 | }; |
| 697 | |
| 698 | static double bolzanoFunction (double b, void *data) { |
| 699 | const struct nr2_struct *me = (struct nr2_struct *) data; |
| 700 | longdouble f = my delta - 0.5 * b / my alpha; |
| 701 | for (integer i = 1; i <= my numberOfTerms; i ++) { |
| 702 | const longdouble c = my x [i] / (my c [i] - b); |
| 703 | f -= c * c; |
| 704 | } |
| 705 | return (double) f; |
| 706 | } |
| 707 | |
| 708 | static double NUMbolzanoSearch (double (*func) (double x, void *closure), double xmin, double xmax, void *closure) { |
| 709 | Melder_assert (xmin < xmax); |
| 710 | double fleft = (*func)(xmin, closure); |
| 711 | double fright = (*func)(xmax, closure); |
| 712 | if (fleft == 0.0) |
| 713 | return fleft; |
| 714 | if (fright == 0.0) |
| 715 | return fright; |
| 716 | Melder_require (fleft * fright < 0.0, |
| 717 | U"Invalid interval: the function values at the borders should have different signs."); |
| 718 | double xdifference = fabs (xmax - xmin), xdifference_old; |
| 719 | do { |
| 720 | const double xmid = 0.5 * (xmax + xmin); |
| 721 | const double fmid = (*func)(xmid, closure); |
| 722 | if (fmid == 0.0) |
| 723 | return fmid; |
| 724 | if (fleft * fmid < 0.0) |
| 725 | xmax = xmid; |
| 726 | else |
| 727 | xmin = xmid; |
| 728 | xdifference_old = xdifference; |
| 729 | xdifference = fabs (xmax - xmin); |
| 730 | } while (xdifference < xdifference_old); |
| 731 | return 0.5 * (xmax + xmin); |
| 732 | } |
| 733 | |
| 734 | autoVEC solveWeaklyConstrainedLinearRegression_VEC (constMAT const& a, constVEC const& y, double alpha, double delta) { |
| 735 | Melder_assert (a.nrow == y.size); |
| 736 | Melder_require (a.nrow >= a.ncol, |
| 737 | U"The number of rows should not be less than the number of columns."); |
| 738 | Melder_require (alpha >= 0.0, |
| 739 | U"The coefficient of the penalty function should not be negative."); |
| 740 | Melder_require (delta > 0, |
| 741 | U"The solution's vector length should be positive."); |
| 742 | |
| 743 | autoVEC c = zero_VEC (a.ncol); |
| 744 | autoSVD svd = SVD_createFromGeneralMatrix (a); |
| 745 | |
| 746 | if (alpha == 0.0) { |
| 747 | /* |
| 748 | Solve by standard least squares |
| 749 | */ |
| 750 | autoVEC result = SVD_solve (svd.get(), y); |
| 751 | return result; |
| 752 | } |
| 753 | /* |
| 754 | Step 1: (page 608) |
| 755 | Compute U and C from the eigendecomposition F'F = UCU' |
| 756 | U is from the SVD (F) = VCU' as in the paper (our notation would be: SVD(F)=UDV') |
| 757 | Therefore, the paper's U is our V but since our V is stored as the transpose: U == svd -> v.transpose()! |
| 758 | */ |
| 759 | constMATVU u = svd -> v.transpose(); |
| 760 | for (integer i = 1; i <= a.ncol; i++) { |
| 761 | const double ci = svd -> d [i]; |
| 762 | c [i] = ci * ci; |
| 763 | } |
| 764 | /* |
| 765 | Evaluate q, the multiplicity of the smallest eigenvalue in C. |
| 766 | The c [i] are ordered, i.e. c [i] >= c [i+1] for all i. |
| 767 | */ |
| 768 | integer q = 1; |
| 769 | const double tol = 1e-6; |
| 770 | while (q < a.ncol && (c [a.ncol - q] - c [a.ncol]) < tol) |
| 771 | q ++; |
| 772 | /* |
| 773 | Step 2: x = U'F'y |
| 774 | */ |
| 775 | autoVEC ftphi = mul_VEC (a.transpose(), y); |
| 776 | autoVEC x = mul_VEC (u.transpose(), ftphi.get()); |
| 777 | /* |
| 778 | Step 3: |
| 779 | */ |
| 780 | struct nr2_struct me; |
| 781 | me.numberOfTerms = a.ncol; |
| 782 | me.delta = delta; |
| 783 | me.alpha = alpha; |
| 784 | me.x = x.get(); |
| 785 | me.c = c.get(); |
| 786 | |
| 787 | const double xqsq = NUMsum2 (x.part (a.ncol - q + 1, a.ncol)); // = NUMinner (xq,xq) |
| 788 | integer r = a.ncol; |
| 789 | if (xqsq < tol) { // Case3.b page 608 |
| 790 | r = a.ncol - q; |
| 791 | me.numberOfTerms = r; |
| 792 | const double fm = bolzanoFunction (c [a.ncol], & me); |
| 793 | if (fm >= 0.0) { // step 3.b1 |
| 794 | /* |
| 795 | Get w0 by overwriting vector x. |
| 796 | */ |
| 797 | x [r + 1] = sqrt (fm); |
| 798 | for (integer j = 1; j <= r; j ++) |
| 799 | x [j] /= c [j] - c [a.ncol]; // eq. 10 |
| 800 | if (q > 1) |
| 801 | x.part (r + 2, a.ncol) <<= 0.0; |
| 802 | autoVEC result = mul_VEC (u, x.all()); |
| 803 | return result; |
| 804 | } |
| 805 | // else continue with r = m - q |
| 806 | } |
| 807 | /* |
| 808 | Step 3a & 3b2, determine interval lower bound for root finder |
| 809 | */ |
| 810 | longdouble xCx = 0.0; |
| 811 | for (integer j = 1; j <= r; j ++) |
| 812 | xCx += x [j] * x [j] / c [j]; |
| 813 | |
| 814 | const double bmin = ( delta > 0.0 ? - xCx / delta : -2.0 * sqrt (alpha * xCx) ); |
| 815 | //const double eps = (c [a.ncol] - bmin) * tol; |
| 816 | /* |
| 817 | Find the root of d(psi(b)/db in interval (bmin, c [m]) |
| 818 | */ |
| 819 | const double b0 = NUMbolzanoSearch (bolzanoFunction, bmin, c [a.ncol], & me); |
| 820 | /* |
| 821 | Get w0 by overwriting vector x. |
| 822 | */ |
| 823 | for (integer j = 1; j <= r; j ++) |
| 824 | x [j] /= c [j] - b0; // eq. 7 |
| 825 | if (q > 1) |
| 826 | x.part (r + 1, a.ncol) <<= 0.0; |
| 827 | autoVEC result = mul_VEC (u, x.all()); |
| 828 | return result; |
| 829 | } |
| 830 | |
| 831 | |
| 832 | void NUMprocrustes (constMATVU const& x, constMATVU const& y, autoMAT *out_rotation, autoVEC *out_translation, double *out_scale) { |
| 833 | Melder_assert (x.nrow == y.nrow && x.ncol == y.ncol); |
| 834 | Melder_assert (x.nrow >= x.ncol); |
| 835 | const bool orthogonal = ! out_translation || ! out_scale; // else similarity transform |
| 836 | /* |
| 837 | Reference: Borg & Groenen (1997), Modern multidimensional scaling, |
| 838 | Springer |
| 839 | 1. Calculate C = X'JY (page 346) for similarity transform |
| 840 | else X'Y for othogonal (page 341) |
| 841 | JY amounts to centering the columns of Y. |
| 842 | */ |
| 843 | autoMAT yc = copy_MAT (y); |
| 844 | if (! orthogonal) |
| 845 | centreEachColumn_MAT_inout (yc.get()); |
| 846 | autoMAT c = mul_MAT (x.transpose(), yc.get()); // X'(JY) |
| 847 | /* |
| 848 | 2. Decompose C by SVD: C = UDV' (our SVD has eigenvectors stored row-wise V!) |
| 849 | */ |
| 850 | autoSVD svd = SVD_createFromGeneralMatrix (c.get()); |
| 851 | const double trace = NUMsum (svd -> d.all()); |
| 852 | Melder_require (trace > 0.0, |
| 853 | U"NUMprocrustes: degenerate configuration(s)."); |
| 854 | /* |
| 855 | 3. T = VU' |
| 856 | */ |
| 857 | autoMAT rotation = mul_MAT (svd->v.all(), svd->u.transpose()); |
| 858 | |
| 859 | if (! orthogonal) { |
| 860 | /* |
| 861 | 4. Dilation factor s = (tr X'JYT) / (tr Y'JY) |
| 862 | First we need YT. |
| 863 | */ |
| 864 | autoMAT yt = mul_MAT (y, rotation.get()); |
| 865 | /* |
| 866 | X'J = (JX)' centering the columns of X |
| 867 | */ |
| 868 | autoMAT xc = copy_MAT (x); |
| 869 | centreEachColumn_MAT_inout (xc.get()); |
| 870 | /* |
| 871 | tr X'J YT == tr xc' yt |
| 872 | */ |
| 873 | const double traceXtJYT = NUMtrace2 (xc.transpose(), yt.get()); // trace (Xc'.(YT)) |
| 874 | const double traceYtJY = NUMtrace2 (y.transpose(), yc.get()); // trace (Y'.Yc) |
| 875 | const longdouble scale = traceXtJYT / traceYtJY; |
| 876 | /* |
| 877 | 5. Translation vector tr = (X - sYT)'1 / x.nrow |
| 878 | */ |
| 879 | if (out_translation) { |
| 880 | autoVEC translation = zero_VEC (x.ncol); |
| 881 | for (integer i = 1; i <= x.ncol; i ++) { |
| 882 | longdouble productsum = 0.0; |
| 883 | for (integer j = 1; j <= x.nrow; j ++) |
| 884 | productsum += x [j] [i] - scale * yt [j] [i]; |
| 885 | translation [i] = double (productsum / x.nrow); |
| 886 | } |
| 887 | *out_translation = translation.move(); |
| 888 | } |
| 889 | if (out_scale) |
| 890 | *out_scale = (double) scale; |
| 891 | } |
| 892 | if (out_rotation) |
| 893 | *out_rotation = rotation.move(); |
| 894 | } |
| 895 | |
| 896 | double NUMmspline (constVEC const & knot, integer order, integer i, double x) { |
| 897 | const integer nSplines = knot.size - order; |
| 898 | |
| 899 | Melder_require (nSplines > 0, |
| 900 | U"No splines."); |
| 901 | Melder_require (order > 0 && i <= nSplines, |
| 902 | U"Combination of order and index not correct."); |
| 903 | /* |
| 904 | Find the interval where x is located. |
| 905 | M-splines of order k have degree k-1. |
| 906 | M-splines are zero outside interval [ knot [i], knot [i+order] ). |
| 907 | First and last 'order' knots are equal, i.e., |
| 908 | knot [1] = ... = knot [order] && knot [knot.size-order+1] = ... knot [knot.size]. |
| 909 | */ |
| 910 | integer jj; |
| 911 | for (jj = order; jj <= knot.size - order + 1; jj ++) |
| 912 | if (x < knot [jj]) |
| 913 | break; |
| 914 | |
| 915 | if (jj < i || (jj > i + order) || jj == order || jj > (knot.size - order + 1)) |
| 916 | return 0.0; |
| 917 | /* |
| 918 | Calculate M [i](x|1,t) according to eq.2. |
| 919 | */ |
| 920 | const integer ito = i + order - 1; |
| 921 | autoVEC m = zero_VEC (order); |
| 922 | for (integer j = i; j <= ito; j ++) |
| 923 | if (x >= knot [j] && x < knot [j + 1]) |
| 924 | m [j - i + 1] = 1 / (knot [j + 1] - knot [j]); |
| 925 | /* |
| 926 | Iterate to get M [i](x|k,t) |
| 927 | */ |
| 928 | for (integer k = 2; k <= order; k ++) { |
| 929 | for (integer j = i; j <= i + order - k; j ++) { |
| 930 | const double kj = knot [j], kjpk = knot [j + k]; |
| 931 | if (kjpk > kj) |
| 932 | m [j - i + 1] = k * ((x - kj) * m [j - i + 1] + (kjpk - x) * m [j - i + 1 + 1]) / ((k - 1) * (kjpk - kj)); |
| 933 | } |
| 934 | } |
| 935 | return m [1]; |
| 936 | } |
| 937 | |
| 938 | double NUMispline (constVEC const & aknot, integer order, integer i, double x) { |
| 939 | const integer orderp1 = order + 1; |
| 940 | integer j; |
| 941 | for (j = orderp1; j <= aknot.size - order; j ++) |
| 942 | if (x < aknot [j]) |
| 943 | break; |
| 944 | |
| 945 | if (-- j < i) |
| 946 | return 0.0; |
| 947 | |
| 948 | if (j > i + order || (j == aknot.size - order && x == aknot [j])) |
| 949 | return 1.0; |
| 950 | |
| 951 | /* |
| 952 | Equation 5 in Ramsay's article contains some errors!!! |
| 953 | 1. the interval selection should be 'j-k <= i <= j' instead of |
| 954 | j-k+1 <= i <= j' |
| 955 | 2. the summation index m starts at 'i+1' instead of 'i' |
| 956 | */ |
| 957 | double y = 0.0; |
| 958 | for (integer m = i + 1; m <= j; m ++) { |
| 959 | const double r = NUMmspline (aknot, orderp1, m, x); |
| 960 | y += (aknot [m + orderp1] - aknot [m]) * r; |
| 961 | } |
| 962 | y /= orderp1; |
| 963 | return y; |
| 964 | } |
| 965 | |
| 966 | double NUMwilksLambda (constVEC const& lambda, integer from, integer to) { |
| 967 | Melder_assert (from > 0 && to <= lambda.size && from <= to); |
| 968 | longdouble result = 1.0; |
| 969 | for (integer i = from; i <= to; i ++) |
| 970 | result *= 1.0 / (1.0 + lambda [i]); |
| 971 | return (double) result; |
| 972 | } |
| 973 | |
| 974 | double NUMfactln (integer n) { |
| 975 | static double table [101]; |
| 976 | if (n < 0) |
| 977 | return undefined; |
| 978 | if (n <= 1) |
| 979 | return 0.0; |
| 980 | return n > 100 ? NUMlnGamma (n + 1.0) : table [n] != 0.0 ? table [n] : (table [n] = NUMlnGamma (n + 1.0)); |
| 981 | } |
| 982 | |
| 983 | double NUMnrbis (double (*f) (double x, double *dfx, void *closure), double xmin, double xmax, void *closure) { |
| 984 | double df, tmp, xh, xl, tol; |
| 985 | const integer itermax = 80; |
| 986 | double fl = (*f) (xmin, & df, closure); |
| 987 | if (fl == 0.0) |
| 988 | return xmin;; |
| 989 | |
| 990 | double fh = (*f) (xmax, & df, closure); |
| 991 | if (fh == 0.0) |
| 992 | return xmax; |
| 993 | |
| 994 | if ((fl > 0.0 && fh > 0.0) || (fl < 0.0 && fh < 0.0)) |
| 995 | return undefined; |
| 996 | |
| 997 | if (fl < 0.0) { |
| 998 | xl = xmin; |
| 999 | xh = xmax; |
| 1000 | } else { |
| 1001 | xh = xmin; |
| 1002 | xl = xmax; |
| 1003 | } |
| 1004 | |
| 1005 | double dxold = fabs (xmax - xmin); |
| 1006 | double dx = dxold; |
| 1007 | double root = 0.5 * (xmin + xmax); |
| 1008 | double fx = (*f) (root, & df, closure); |
| 1009 | |
| 1010 | for (integer iter = 1; iter <= itermax; iter ++) { |
| 1011 | if ((((root - xh) * df - fx) * ((root - xl) * df - fx) >= 0.0) || (fabs (2.0 * fx) > fabs (dxold * df))) { |
| 1012 | dxold = dx; |
| 1013 | dx = 0.5 * (xh - xl); |
| 1014 | root = xl + dx; |
| 1015 | if (xl == root) |
| 1016 | return root; |
| 1017 | } else { |
| 1018 | dxold = dx; |
| 1019 | dx = fx / df; |
| 1020 | tmp = root; |
| 1021 | root -= dx; |
| 1022 | if (tmp == root) |
| 1023 | return root; |
| 1024 | } |
| 1025 | tol = NUMfpp -> eps * (root == 0.0 ? 1.0 : fabs (root)); |
| 1026 | if (fabs (dx) < tol) |
| 1027 | return root; |
| 1028 | |
| 1029 | fx = (*f) (root, & df, closure); |
| 1030 | |
| 1031 | if (fx < 0.0) |
| 1032 | xl = root; |
| 1033 | else |
| 1034 | xh = root; |
| 1035 | } |
| 1036 | Melder_warning (U"NUMnrbis: maximum number of iterations (", itermax, U") exceeded."); |
| 1037 | return root; |
| 1038 | } |
| 1039 | |
| 1040 | double NUMridders (double (*f) (double x, void *closure), double x1, double x2, void *closure) { |
| 1041 | /* There is still a problem with this implementation: |
| 1042 | tol may be zero; |
| 1043 | */ |
| 1044 | double d, root = undefined, tol; |
| 1045 | const integer itermax = 100; |
| 1046 | |
| 1047 | double f1 = f (x1, closure); |
| 1048 | if (f1 == 0.0) |
| 1049 | return x1; |
| 1050 | if (isundef (f1)) |
| 1051 | return undefined; |
| 1052 | |
| 1053 | double f2 = f (x2, closure); |
| 1054 | if (f2 == 0.0) |
| 1055 | return x2; |
| 1056 | if (isundef (f2)) |
| 1057 | return undefined; |
| 1058 | if ((f1 < 0.0 && f2 < 0.0) || (f1 > 0.0 && f2 > 0.0)) |
| 1059 | return undefined; |
| 1060 | |
| 1061 | for (integer iter = 1; iter <= itermax; iter ++) { |
| 1062 | const double x3 = 0.5 * (x1 + x2); |
| 1063 | const double f3 = f (x3, closure); |
| 1064 | if (f3 == 0.0) |
| 1065 | return x3; |
| 1066 | if (isundef (f3)) |
| 1067 | return undefined; |
| 1068 | |
| 1069 | // New guess: x4 = x3 + (x3 - x1) * sign(f1 - f2) * f3 / sqrt(f3^2 - f1*f2) |
| 1070 | |
| 1071 | d = f3 * f3 - f1 * f2; |
| 1072 | if (d < 0.0) { |
| 1073 | Melder_warning (U"d < 0 in ridders (iter = ", iter, U")."); |
| 1074 | return undefined; |
| 1075 | } |
| 1076 | |
| 1077 | if (d == 0.0) { |
| 1078 | // pb test added because f1 f2 f3 may be 1e-170 or so |
| 1079 | tol = NUMfpp -> eps * (x3 == 0.0 ? 1.0 : fabs (x3)); |
| 1080 | if (iter > 1 && fabs (x3 - root) < tol) |
| 1081 | return root; |
| 1082 | root = x3; |
| 1083 | |
| 1084 | // Perform bisection. |
| 1085 | |
| 1086 | if (f1 > 0.0) { |
| 1087 | // falling curve: f1 > 0, f2 < 0 |
| 1088 | if (f3 > 0.0) { |
| 1089 | x1 = x3; |
| 1090 | f1 = f3; // retain invariant: f1 > 0, f2 < 0 |
| 1091 | } else { |
| 1092 | // f3 <= 0.0 |
| 1093 | x2 = x3; |
| 1094 | f2 = f3; // retain invariant: f1 > 0, f2 < 0 |
| 1095 | } |
| 1096 | } else { |
| 1097 | // rising curve: f1 < 0, f2 > 0 |
| 1098 | if (f3 > 0.0) { |
| 1099 | x2 = x3; |
| 1100 | f2 = f3; // retain invariant: f1 < 0, f2 > 0 |
| 1101 | } else { |
| 1102 | // f3 < 0.0 |
| 1103 | x1 = x3; |
| 1104 | f1 = f3; // retain invariant: f1 < 0, f2 > 0 |
| 1105 | } |
| 1106 | } |
| 1107 | } else { |
| 1108 | d = sqrt (d); |
| 1109 | if (isnan (d)) { |
| 1110 | // pb: square root of denormalized small number fails on some computers |
| 1111 | tol = NUMfpp -> eps * (x3 == 0.0 ? 1.0 : fabs (x3)); |
| 1112 | if (iter > 1 && fabs (x3 - root) < tol) |
| 1113 | return root; |
| 1114 | root = x3; |
| 1115 | |
| 1116 | // Perform bisection. |
| 1117 | |
| 1118 | if (f1 > 0.0) { |
| 1119 | // falling curve: f1 > 0, f2 < 0 |
| 1120 | if (f3 > 0.0) { |
| 1121 | x1 = x3; |
| 1122 | f1 = f3; // retain invariant: f1 > 0, f2 < 0 |
| 1123 | } else { |
| 1124 | // f3 <= 0.0 |
| 1125 | x2 = x3; |
| 1126 | f2 = f3; // retain invariant: f1 > 0, f2 < 0 |
| 1127 | } |
| 1128 | } else { |
| 1129 | // rising curve: f1 < 0, f2 > 0 |
| 1130 | if (f3 > 0.0) { |
| 1131 | x2 = x3; |
| 1132 | f2 = f3; // retain invariant: f1 < 0, f2 > 0 |
| 1133 | } else { |
| 1134 | // f3 < 0.0 |
| 1135 | x1 = x3; |
| 1136 | f1 = f3; // retain invariant: f1 < 0, f2 > 0 */ |
| 1137 | } |
| 1138 | } |
| 1139 | } else { |
| 1140 | d = (x3 - x1) * f3 / d; |
| 1141 | const double x4 = f1 - f2 < 0 ? x3 - d : x3 + d; |
| 1142 | tol = NUMfpp -> eps * (x4 == 0.0 ? 1.0 : fabs (x4)); |
| 1143 | if (iter > 1 && fabs (x4 - root) < tol) |
| 1144 | return root; |
| 1145 | root = x4; |
| 1146 | const double f4 = f (x4, closure); |
| 1147 | if (f4 == 0.0) |
| 1148 | return root; |
| 1149 | if (isundef (f4)) |
| 1150 | return undefined; |
| 1151 | if ((f1 > f2) == (d > 0.0)) { // pb: instead of x3 < x4 |
| 1152 | if (SIGN (f3, f4) != f3) { |
| 1153 | x1 = x3; |
| 1154 | f1 = f3; |
| 1155 | x2 = x4; |
| 1156 | f2 = f4; |
| 1157 | } else { |
| 1158 | x1 = x4; |
| 1159 | f1 = f4; |
| 1160 | } |
| 1161 | } else { |
| 1162 | if (SIGN (f3, f4) != f3) { |
| 1163 | x1 = x4; |
| 1164 | f1 = f4; |
| 1165 | x2 = x3; |
| 1166 | f2 = f3; |
| 1167 | } else { |
| 1168 | x2 = x4; |
| 1169 | f2 = f4; |
| 1170 | } |
| 1171 | } |
| 1172 | } |
| 1173 | } |
| 1174 | if (fabs (x1 - x2) < tol) |
| 1175 | return root; |
| 1176 | } |
| 1177 | |
| 1178 | { |
| 1179 | static integer nwarnings = 0; |
| 1180 | nwarnings ++; |
| 1181 | Melder_warning (U"NUMridders: maximum number of iterations (", itermax, U") exceeded."); |
| 1182 | } |
| 1183 | return root; |
| 1184 | } |
| 1185 | |
| 1186 | double NUMlogNormalP (double x, double zeta, double sigma) { |
| 1187 | return gsl_cdf_lognormal_P (x, zeta, sigma); |
| 1188 | } |
| 1189 | |
| 1190 | double NUMlogNormalQ (double x, double zeta, double sigma) { |
| 1191 | return gsl_cdf_lognormal_Q (x, zeta, sigma); |
| 1192 | } |
| 1193 | |
| 1194 | double NUMstudentP (double t, double df) { |
| 1195 | if (df < 1.0) return undefined; |
| 1196 | const double ib = NUMincompleteBeta (0.5 * df, 0.5, df / (df + t * t)); |
| 1197 | if (isundef (ib)) |
| 1198 | return undefined; |
| 1199 | return t < 0.0 ? 0.5 * ib : 1.0 - 0.5 * ib; |
| 1200 | } |
| 1201 | |
| 1202 | double NUMstudentQ (double t, double df) { |
| 1203 | if (df < 1) |
| 1204 | return undefined; |
| 1205 | const double ib = NUMincompleteBeta (0.5 * df, 0.5, df / (df + t * t)); |
| 1206 | if (isundef (ib)) |
| 1207 | return undefined; |
| 1208 | return t > 0.0 ? 0.5 * ib : 1.0 - 0.5 * ib; |
| 1209 | } |
| 1210 | |
| 1211 | double NUMfisherP (double f, double df1, double df2) { |
| 1212 | if (f < 0.0 || df1 < 1.0 || df2 < 1.0) |
| 1213 | return undefined; |
| 1214 | const double ib = NUMincompleteBeta (0.5 * df2, 0.5 * df1, df2 / (df2 + f * df1)); |
| 1215 | if (isundef (ib)) |
| 1216 | return undefined; |
| 1217 | return 1.0 - ib; |
| 1218 | } |
| 1219 | |
| 1220 | double NUMfisherQ (double f, double df1, double df2) { |
| 1221 | if (f < 0.0 || df1 < 1.0 || df2 < 1.0) |
| 1222 | return undefined; |
| 1223 | if (Melder_debug == 28) { |
| 1224 | return NUMincompleteBeta (0.5 * df2, 0.5 * df1, df2 / (df2 + f * df1)); |
| 1225 | } else { |
| 1226 | const double result = gsl_cdf_fdist_Q (f, df1, df2); |
| 1227 | if (isnan (result)) |
| 1228 | return undefined; |
| 1229 | return result; |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | double NUMinvGaussQ (double p) { |
| 1234 | return gsl_cdf_ugaussian_Qinv (p); |
| 1235 | } |
| 1236 | |
| 1237 | static double studentQ_func (double x, void *voidParams) { |
| 1238 | const struct pdf1_struct *params = (struct pdf1_struct *) voidParams; |
| 1239 | const double q = NUMstudentQ (x, params -> df); |
| 1240 | return isundef (q) ? undefined : q - params -> p; |
| 1241 | } |
| 1242 | |
| 1243 | double NUMinvStudentQ (double p, double df) { |
| 1244 | struct pdf1_struct params; |
| 1245 | const double pc = ( p > 0.5 ? 1.0 - p : p ); |
| 1246 | |
| 1247 | if (p < 0.0 || p >= 1.0) |
| 1248 | return undefined; |
| 1249 | /* |
| 1250 | Bracket the function f(x) = NUMstudentQ (x, df) - p. |
| 1251 | */ |
| 1252 | double xmax = 1.0; |
| 1253 | for (;;) { |
| 1254 | const double q = NUMstudentQ (xmax, df); |
| 1255 | if (isundef (q)) |
| 1256 | return undefined; |
| 1257 | if (q < pc) |
| 1258 | break; |
| 1259 | xmax *= 2.0; |
| 1260 | } |
| 1261 | |
| 1262 | const double xmin = ( xmax > 1.0 ? xmax / 2.0 : 0.0 ); |
| 1263 | /* |
| 1264 | Find zero of f(x) with Ridders' method. |
| 1265 | */ |
| 1266 | params. df = df; |
| 1267 | params. p = pc; |
| 1268 | const double x = NUMridders (studentQ_func, xmin, xmax, & params); |
| 1269 | if (isundef (x)) |
| 1270 | return undefined; |
| 1271 | return p > 0.5 ? -x : x; |
| 1272 | } |
| 1273 | |
| 1274 | static double chiSquareQ_func (double x, void *voidParams) { |
| 1275 | const struct pdf1_struct *params = (struct pdf1_struct *) voidParams; |
| 1276 | const double q = NUMchiSquareQ (x, params -> df); |
| 1277 | return isundef (q) ? undefined : q - params -> p; |
| 1278 | } |
| 1279 | |
| 1280 | double NUMinvChiSquareQ (double p, double df) { |
| 1281 | struct pdf1_struct params; |
| 1282 | |
| 1283 | if (p < 0.0 || p >= 1.0) |
| 1284 | return undefined; |
| 1285 | /* |
| 1286 | Bracket the function f(x) = NUMchiSquareQ (x, df) - p. |
| 1287 | */ |
| 1288 | double xmax = 1.0; |
| 1289 | for (;;) { |
| 1290 | const double q = NUMchiSquareQ (xmax, df); |
| 1291 | if (isundef (q)) |
| 1292 | return undefined; |
| 1293 | if (q < p) |
| 1294 | break; |
| 1295 | xmax *= 2.0; |
| 1296 | } |
| 1297 | const double xmin = ( xmax > 1.0 ? xmax / 2.0 : 0.0 ); |
| 1298 | /* |
| 1299 | Find zero of f(x) with Ridders' method. |
| 1300 | */ |
| 1301 | params. df = df; |
| 1302 | params. p = p; |
| 1303 | return NUMridders (chiSquareQ_func, xmin, xmax, & params); |
| 1304 | } |
| 1305 | |
| 1306 | static double fisherQ_func (double x, void *voidParams) { |
| 1307 | struct pdf2_struct *params = (struct pdf2_struct *) voidParams; |
| 1308 | const double q = NUMfisherQ (x, params -> df1, params -> df2); |
| 1309 | return ( isundef (q) ? undefined : q - params -> p ); |
| 1310 | } |
| 1311 | |
| 1312 | double NUMinvFisherQ (double p, double df1, double df2) { |
| 1313 | if (p <= 0.0 || p > 1.0 || df1 < 1.0 || df2 < 1.0) |
| 1314 | return undefined; |
| 1315 | if (Melder_debug == 29) { |
| 1316 | //if (p == 1.0) return 0.0; |
| 1317 | return gsl_cdf_fdist_Qinv (p, df1, df2); |
| 1318 | } else { |
| 1319 | struct pdf2_struct params; |
| 1320 | if (p == 1.0) |
| 1321 | return 0.0; |
| 1322 | params. p = p; |
| 1323 | params. df1 = df1; |
| 1324 | params. df2 = df2; |
| 1325 | double top = 1000.0; |
| 1326 | for (;;) { |
| 1327 | const double q = NUMfisherQ (top, df1, df2); |
| 1328 | if (isundef (q)) |
| 1329 | return undefined; |
| 1330 | if (q < p) |
| 1331 | break; |
| 1332 | if (top > 0.9e300) |
| 1333 | return undefined; |
| 1334 | top *= 1e9; |
| 1335 | } |
| 1336 | return NUMridders (fisherQ_func, 0.0, p > 0.5 ? 2.2 : top, & params); |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | double NUMbeta2 (double z, double w) { |
| 1341 | gsl_sf_result result; |
| 1342 | const integer status = gsl_sf_beta_e (z, w, &result); |
| 1343 | return status == GSL_SUCCESS ? result.val : undefined; |
| 1344 | } |
| 1345 | |
| 1346 | double NUMlnBeta (double a, double b) { |
| 1347 | gsl_sf_result result; |
| 1348 | const integer status = gsl_sf_lnbeta_e (a, b, & result); |
| 1349 | return status == GSL_SUCCESS ? result.val : undefined; |
| 1350 | } |
| 1351 | |
| 1352 | /*************** Hz <--> other freq reps *********************/ |
| 1353 | |
| 1354 | double NUMmelToHertz3 (double mel) { |
| 1355 | if (mel < 0.0) |
| 1356 | return undefined; |
| 1357 | return mel < 1000.0 ? mel : 1000.0 * (exp (mel * log10 (2.0) / 1000.0) - 1.0); |
| 1358 | } |
| 1359 | |
| 1360 | double NUMhertzToMel3 (double hz) { |
| 1361 | if (hz < 0.0) |
| 1362 | return undefined; |
| 1363 | return hz < 1000.0 ? hz : 1000.0 * log10 (1.0 + hz / 1000.0) / log10 (2.0); |
| 1364 | } |
| 1365 | |
| 1366 | double NUMmelToHertz2 (double mel) { |
| 1367 | if (mel < 0.0) |
| 1368 | return undefined; |
| 1369 | return 700.0 * (pow (10.0, mel / 2595.0) - 1.0); |
| 1370 | } |
| 1371 | |
| 1372 | double NUMhertzToMel2 (double hz) { |
| 1373 | if (hz < 0.0) |
| 1374 | return undefined; |
| 1375 | return 2595.0 * log10 (1.0 + hz / 700.0); |
| 1376 | } |
| 1377 | |
| 1378 | double NUMhertzToBark_traunmueller (double hz) { |
| 1379 | if (hz < 0.0) |
| 1380 | return undefined; |
| 1381 | return 26.81 * hz / (1960.0 + hz) - 0.53; |
| 1382 | } |
| 1383 | |
| 1384 | double NUMbarkToHertz_traunmueller (double bark) { |
| 1385 | if (bark < 0.0 || bark > 26.28) |
| 1386 | return undefined; |
| 1387 | return 1960.0 * (bark + 0.53) / (26.28 - bark); |
| 1388 | } |
| 1389 | |
| 1390 | |
| 1391 | double NUMbarkToHertz_zwickerterhardt (double hz) { |
| 1392 | if (hz < 0.0) |
| 1393 | return undefined; |
| 1394 | return 13.0 * atan (0.00076 * hz) + 3.5 * atan (hz / 7500.0); |
| 1395 | } |
| 1396 | |
| 1397 | double NUMbladonlindblomfilter_amplitude (double zc, double z) { |
| 1398 | const double dz = zc - z + 0.474; |
| 1399 | return pow (10.0, 1.581 + 0.75 * dz - 1.75 * sqrt (1.0 + dz * dz)); |
| 1400 | } |
| 1401 | |
| 1402 | double NUMsekeyhansonfilter_amplitude (double zc, double z) { |
| 1403 | const double dz = zc - z - 0.215; |
| 1404 | return pow (10.0, 0.7 - 0.75 * dz - 1.75 * sqrt (0.196 + dz * dz)); |
| 1405 | } |
| 1406 | |
| 1407 | double NUMtriangularfilter_amplitude (double fl, double fc, double fh, double f) { |
| 1408 | double a = 0.0; |
| 1409 | if (f > fl && f < fh) { |
| 1410 | a = f < fc ? (f - fl) / (fc - fl) : (fh - f) / (fh - fc); |
| 1411 | |
| 1412 | /* Normalize such that area under the filter is always 1. ??? |
| 1413 | |
| 1414 | a /= 2 * (fh - fl);*/ |
| 1415 | } |
| 1416 | return a; |
| 1417 | } |
| 1418 | |
| 1419 | double NUMformantfilter_amplitude (double fc, double bw, double f) { |
| 1420 | const double dq = (fc * fc - f * f) / (bw * f); |
| 1421 | return 1.0 / (dq * dq + 1.0); |
| 1422 | } |
| 1423 | |
| 1424 | /* Childers (1978), Modern Spectrum analysis, IEEE Press, 252-255) */ |
| 1425 | /* work [1..n+n+n]; |
| 1426 | b1 = & work [1]; |
| 1427 | b2 = & work [n+1]; |
| 1428 | aa = & work [n+n+1]; |
| 1429 | for (i=1; i<=n+n+n; i ++) work [i]=0; |
| 1430 | */ |
| 1431 | double VECburg (VEC const& a, constVEC const& x) { |
| 1432 | const integer n = x.size, m = a.size; |
| 1433 | for (integer j = 1; j <= m; j ++) |
| 1434 | a [j] = 0.0; |
| 1435 | if (n <= 2) { |
| 1436 | a [1] = -1.0; |
| 1437 | return ( n == 2 ? 0.5 * (x [1] * x [1] + x [2] * x [2]) : x [1] * x [1] ); |
| 1438 | } |
| 1439 | |
| 1440 | autoVEC b1 = zero_VEC (n), b2 = zero_VEC (n), aa = zero_VEC (m); |
| 1441 | |
| 1442 | // (3) |
| 1443 | |
| 1444 | longdouble p = 0.0; |
| 1445 | for (integer j = 1; j <= n; j ++) |
| 1446 | p += x [j] * x [j]; |
| 1447 | |
| 1448 | longdouble xms = p / n; |
| 1449 | if (xms <= 0.0) |
| 1450 | return xms; // warning empty |
| 1451 | |
| 1452 | // (9) |
| 1453 | |
| 1454 | b1 [1] = x [1]; |
| 1455 | if (n < 2) |
| 1456 | return (double) xms; |
| 1457 | b2 [n - 1] = x [n]; |
| 1458 | for (integer j = 2; j <= n - 1; j ++) |
| 1459 | b1 [j] = b2 [j - 1] = x [j]; |
| 1460 | |
| 1461 | for (integer i = 1; i <= m; i ++) { |
| 1462 | // (7) |
| 1463 | |
| 1464 | longdouble num = 0.0, denum = 0.0; |
| 1465 | for (integer j = 1; j <= n - i; j ++) { |
| 1466 | num += b1 [j] * b2 [j]; |
| 1467 | denum += b1 [j] * b1 [j] + b2 [j] * b2 [j]; |
| 1468 | } |
| 1469 | |
| 1470 | if (denum <= 0.0) |
| 1471 | return 0.0; // warning ill-conditioned |
| 1472 | |
| 1473 | a [i] = 2.0 * num / denum; |
| 1474 | |
| 1475 | // (10) |
| 1476 | |
| 1477 | xms *= 1.0 - a [i] * a [i]; |
| 1478 | |
| 1479 | // (5) |
| 1480 | |
| 1481 | for (integer j = 1; j <= i - 1; j ++) |
| 1482 | a [j] = aa [j] - a [i] * aa [i - j]; |
| 1483 | |
| 1484 | if (i < m) { |
| 1485 | |
| 1486 | // (8) Watch out: i -> i+1 |
| 1487 | |
| 1488 | for (integer j = 1; j <= i; j ++) |
| 1489 | aa [j] = a [j]; |
| 1490 | for (integer j = 1; j <= n - i - 1; j ++) { |
| 1491 | b1 [j] -= aa [i] * b2 [j]; |
| 1492 | b2 [j] = b2 [j + 1] - aa [i] * b1 [j + 1]; |
| 1493 | } |
| 1494 | } |
| 1495 | } |
| 1496 | return xms; |
| 1497 | } |
| 1498 | |
| 1499 | autoVEC newVECburg (constVEC const& x, integer numberOfPredictionCoefficients, double *out_xms) { |
| 1500 | autoVEC a = raw_VEC (numberOfPredictionCoefficients); |
| 1501 | const double xms = VECburg (a.get(), x); |
| 1502 | if (out_xms) |
| 1503 | *out_xms = xms; |
| 1504 | return a; |
| 1505 | } |
| 1506 | |
| 1507 | void VECfilterInverse_inplace (VEC const& s, constVEC const& filter, VEC const& filterMemory) { |
| 1508 | Melder_assert (filterMemory.size >= filter.size); |
| 1509 | filterMemory.part (1, filter.size) <<= 0.0; |
| 1510 | for (integer i = 1; i <= s.size; i ++) { |
| 1511 | const double y0 = s [i]; |
| 1512 | for (integer j = 1; j <= filter.size; j ++) |
| 1513 | s [i] += filter [j] * filterMemory [j]; |
| 1514 | for (integer j = filter.size; j > 1; j --) |
| 1515 | filterMemory [j] = filterMemory [j - 1]; |
| 1516 | filterMemory [1] = y0; |
| 1517 | } |
| 1518 | } |
| 1519 | |
| 1520 | void NUMdmatrix_to_dBs (MAT const& m, double ref, double factor, double floor) { |
| 1521 | const double factor10 = factor * 10.0; |
| 1522 | MelderExtremaWithInit extrema; |
| 1523 | |
| 1524 | Melder_assert (ref > 0 && factor > 0); |
| 1525 | |
| 1526 | for (integer irow = 1; irow <= m.nrow; irow ++) |
| 1527 | for (integer icol = 1; icol <= m.ncol; icol ++) |
| 1528 | extrema.update (m [irow] [icol]); |
| 1529 | |
| 1530 | |
| 1531 | Melder_require (extrema.min >= 0.0 && extrema.max >= 0.0, |
| 1532 | U"All matrix elements should be positive."); |
| 1533 | |
| 1534 | const double ref_db = factor10 * log10 (ref); |
| 1535 | |
| 1536 | for (integer irow = 1; irow <= m.nrow; irow ++) { |
| 1537 | for (integer icol = 1; icol <= m.ncol; icol ++) { |
| 1538 | double mij = floor; |
| 1539 | if (m [irow] [icol] > 0.0) { |
| 1540 | mij = factor10 * log10 (m [irow] [icol]) - ref_db; |
| 1541 | if (mij < floor) |
| 1542 | mij = floor; |
| 1543 | } |
| 1544 | m [irow] [icol] = mij; |
| 1545 | } |
| 1546 | } |
| 1547 | } |
| 1548 | |
| 1549 | autoMAT MATcosinesTable (integer n) { |
| 1550 | autoMAT result = raw_MAT (n, n); |
| 1551 | for (integer irow = 1; irow <= n; irow ++) |
| 1552 | for (integer icol = 1; icol <= n; icol ++) |
| 1553 | result [irow] [icol] = cos (NUMpi * (irow - 1) * (icol - 0.5) / n); |
| 1554 | return result; |
| 1555 | } |
| 1556 | |
| 1557 | void VECcosineTransform_preallocated (VEC const& target, constVEC const& x, constMAT const& cosinesTable) { |
| 1558 | Melder_assert (cosinesTable.nrow == cosinesTable.ncol); |
| 1559 | Melder_assert (x.size == target.size && x.size == cosinesTable.nrow); |
| 1560 | for (integer k = 1; k <= target.size; k ++) |
| 1561 | target [k] = NUMinner (x, cosinesTable.row (k)); |
| 1562 | } |
| 1563 | |
| 1564 | void VECinverseCosineTransform_preallocated (VEC const& target, constVEC const& x, constMAT const& cosinesTable) { |
| 1565 | Melder_assert (cosinesTable.nrow == cosinesTable.ncol); |
| 1566 | Melder_assert (x.size == target.size && x.size == cosinesTable.nrow); |
| 1567 | for (integer j = 1; j <= target.size; j ++) { |
| 1568 | target [j] = 0.5 * x [1] * cosinesTable [1] [j]; |
| 1569 | for (integer k = 2; k <= target.size; k ++) |
| 1570 | target [j] += x [k] * cosinesTable [k] [j]; |
| 1571 | target [j] *= 2.0 / target.size; |
| 1572 | } |
| 1573 | } |
| 1574 | |
| 1575 | void NUMcubicSplineInterpolation_getSecondDerivatives (VEC const& out_y, constVEC const& x, constVEC const& y, double yp1, double ypn) { |
| 1576 | Melder_assert (x.size == y.size && out_y.size == y.size); |
| 1577 | |
| 1578 | autoVEC u = raw_VEC (x.size - 1); |
| 1579 | |
| 1580 | if (yp1 > 0.99e30) |
| 1581 | out_y [1] = u [1] = 0.0; |
| 1582 | else { |
| 1583 | out_y [1] = -0.5; |
| 1584 | u [1] = (3.0 / (x [2] - x [1])) * ( (y [2] - y [1]) / (x [2] - x [1]) - yp1); |
| 1585 | } |
| 1586 | |
| 1587 | for (integer i = 2; i <= x.size - 1; i ++) { |
| 1588 | const double sig = (x [i] - x [i - 1]) / (x [i + 1] - x [i - 1]); |
| 1589 | const double p = sig * out_y [i - 1] + 2.0; |
| 1590 | out_y [i] = (sig - 1.0) / p; |
| 1591 | u [i] = (y [i + 1] - y [i]) / (x [i + 1] - x [i]) - (y [i] - y [i - 1]) / (x [i] - x [i - 1]); |
| 1592 | u [i] = (6.0 * u [i] / (x [i + 1] - x [i - 1]) - sig * u [i - 1]) / p; |
| 1593 | } |
| 1594 | |
| 1595 | double qn, un; |
| 1596 | if (ypn > 0.99e30) |
| 1597 | qn = un = 0.0; |
| 1598 | else { |
| 1599 | qn = 0.5; |
| 1600 | un = (3.0 / (x [x.size] - x [x.size - 1])) * (ypn - (y [x.size] - y [x.size - 1]) / (x [x.size] - x [x.size - 1])); |
| 1601 | } |
| 1602 | |
| 1603 | out_y [x.size] = (un - qn * u [x.size - 1]) / (qn * out_y [x.size - 1] + 1.0); |
| 1604 | for (integer k = x.size - 1; k >= 1; k--) |
| 1605 | out_y [k] = out_y [k] * out_y [k + 1] + u [k]; |
| 1606 | } |
| 1607 | |
| 1608 | double NUMcubicSplineInterpolation (constVEC const& x, constVEC const& y, constVEC const& y2, double xin) { |
| 1609 | Melder_assert (x.size == y.size && x.size == y2.size); |
| 1610 | integer klo = 1, khi = x.size; |
| 1611 | while (khi - klo > 1) { |
| 1612 | integer k = (khi + klo) >> 1; |
| 1613 | if (x [k] > xin) |
| 1614 | khi = k; |
| 1615 | else |
| 1616 | klo = k; |
| 1617 | } |
| 1618 | const double h = x [khi] - x [klo]; |
| 1619 | Melder_require (h != 0.0, |
| 1620 | U"NUMcubicSplineInterpolation: bad input value."); |
| 1621 | |
| 1622 | const double a = (x [khi] - xin) / h; |
| 1623 | const double b = (xin - x [klo]) / h; |
| 1624 | const double yint = a * y [klo] + b * y [khi] + ((a * a * a - a) * y2 [klo] + (b * b * b - b) * y2 [khi]) * (h * h) / 6.0; |
| 1625 | return yint; |
| 1626 | } |
| 1627 | |
| 1628 | double NUMsinc (const double x) { |
| 1629 | struct gsl_sf_result_struct result; |
| 1630 | const integer status = gsl_sf_sinc_e (x / NUMpi, &result); |
| 1631 | return status == GSL_SUCCESS ? result. val : undefined; |
| 1632 | } |
| 1633 | |
| 1634 | double NUMsincpi (const double x) { |
| 1635 | struct gsl_sf_result_struct result; |
| 1636 | const integer status = gsl_sf_sinc_e (x, &result); |
| 1637 | return status == GSL_SUCCESS ? result. val : undefined; |
| 1638 | } |
| 1639 | |
| 1640 | /* Does the line segment from (x1,y1) to (x2,y2) intersect with the line segment from (x3,y3) to (x4,y4)? */ |
| 1641 | bool NUMdoLineSegmentsIntersect (double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { |
| 1642 | const integer o11 = NUMgetOrientationOfPoints (x1, y1, x2, y2, x3, y3); |
| 1643 | const integer o12 = NUMgetOrientationOfPoints (x1, y1, x2, y2, x4, y4); |
| 1644 | const integer o21 = NUMgetOrientationOfPoints (x3, y3, x4, y4, x1, y1); |
| 1645 | const integer o22 = NUMgetOrientationOfPoints (x3, y3, x4, y4, x2, y2); |
| 1646 | return ((o11 * o12 < 0) && (o21 * o22 < 0)) || (o11 *o12 *o21 *o22 == 0); |
| 1647 | } |
| 1648 | |
| 1649 | integer NUMgetOrientationOfPoints (double x1, double y1, double x2, double y2, double x3, double y3) { |
| 1650 | integer orientation; |
| 1651 | const longdouble dx2 = x2 - x1, dy2 = y2 - y1; |
| 1652 | const longdouble dx3 = x3 - x1, dy3 = y3 - y1; |
| 1653 | if (dx2 * dy3 > dy2 * dx3) |
| 1654 | orientation = -1; |
| 1655 | else if (dx2 * dy3 < dy2 * dx3) |
| 1656 | orientation = 1; |
| 1657 | else { |
| 1658 | if ((dx2 * dx3 < 0) || (dy2 * dy3 < 0)) |
| 1659 | orientation = -1; |
| 1660 | else if ((dx2 * dx2 + dy2 * dy2) >= (dx3 * dx3 + dy3 * dy3)) |
| 1661 | orientation = 0; |
| 1662 | else |
| 1663 | orientation = 1; |
| 1664 | } |
| 1665 | return orientation; |
| 1666 | } |
| 1667 | |
| 1668 | integer NUMgetIntersectionsWithRectangle (double x1, double y1, double x2, double y2, double xmin, double ymin, double xmax, double ymax, double *xi, double *yi) { |
| 1669 | double x [6], y [6]; |
| 1670 | integer ni = 0; |
| 1671 | |
| 1672 | x [1] = x [4] = x [5] = xmin; |
| 1673 | x [2] = x [3] = xmax; |
| 1674 | y [1] = y [2] = y [5] = ymin; |
| 1675 | y [3] = y [4] = ymax; |
| 1676 | /* |
| 1677 | Calculate intersection of line segment through p1=(x1,y1) to p2(x2,y2) with line segment |
| 1678 | through p3=(x3,y3) to p4=(x4,y4). |
| 1679 | Parametrisation of the lines: |
| 1680 | l1 = p1 + s (p2 - p1), s in (-inf,+inf) |
| 1681 | l2 = p3 + t (p4 - p3), t in (-inf,+inf). |
| 1682 | When s and t are in [0, 1] we have line segments between the points. |
| 1683 | At the intersection l1 == l2. We get for the x and y coordinates: |
| 1684 | x1 + s (x2 - x1) = x3 + t (x4 - x3).............(1) |
| 1685 | y1 + s (y2 - y1) = y3 + t (y4 - y3).............(2) |
| 1686 | Multiply (1)*(y2 - y1) and (2)*(x2 - x1): |
| 1687 | x1 (y2 - y1) + s (x2 - x1)(y2 - y1) = x3 (y2 - y1) + t (x4 - x3)(y2 - y1).......(3) |
| 1688 | y1 (x2 - x1) + s (y2 - y1)(x2 - x1) = y3 (x2 - x1) + t (y4 - y3)(x2 - x1).......(4) |
| 1689 | (3)-(4) with y21 = y2 -y1, x21 = x2 - x1, x43 = x4 - x3, ... |
| 1690 | x1 y21 - y1 x21 = x3 y21 - y3 x21 +t (x43 y21 - y43 x21) |
| 1691 | Combining: |
| 1692 | y31 x21 - x31 y21 = t (x43 y21 - y43 x21) |
| 1693 | Therefore at the intersection we have: |
| 1694 | |
| 1695 | t = (y31 x21 - x31 y21) / (x43 y21 - y43 x21) |
| 1696 | |
| 1697 | If (x43 y21 - y43 x21) == 0 |
| 1698 | There is no intersection. |
| 1699 | If (t < 0 || t >= 1) |
| 1700 | No intersection in the segment l2 |
| 1701 | To count intersections in a corner only once we have t < 0 instead of t <= 0! |
| 1702 | */ |
| 1703 | |
| 1704 | for (integer i = 1; i <= 4; i ++) { |
| 1705 | const double denom = (x [i + 1] - x [i]) * (y2 - y1) - (y [i + 1] - y [i]) * (x2 - x1); |
| 1706 | if (denom == 0.0) |
| 1707 | continue; |
| 1708 | |
| 1709 | // We have an intersection. |
| 1710 | |
| 1711 | const double t = ((y [i] - y1) * (x2 - x1) - (x [i] - x1) * (y2 - y1)) / denom; |
| 1712 | if (t < 0.0 || t >= 1.0) |
| 1713 | continue; |
| 1714 | |
| 1715 | // Intersection is within rectangle side. |
| 1716 | |
| 1717 | const double x3 = x [i] + t * (x [i + 1] - x [i]); |
| 1718 | const double y3 = y [i] + t * (y [i + 1] - y [i]); |
| 1719 | |
| 1720 | // s must also be valid |
| 1721 | |
| 1722 | const double s = ( x1 != x2 ? (x3 - x1) / (x2 - x1) : (y3 - y1) / (y2 - y1) ); |
| 1723 | if (s < 0.0 || s >= 1.0) |
| 1724 | continue; |
| 1725 | |
| 1726 | ni ++; |
| 1727 | Melder_require (ni <= 3, |
| 1728 | U"Too many intersections."); |
| 1729 | |
| 1730 | xi [ni] = x3; |
| 1731 | yi [ni] = y3; |
| 1732 | } |
| 1733 | return ni; |
| 1734 | } |
| 1735 | |
| 1736 | bool NUMclipLineWithinRectangle (double line_x1, double line_y1, double line_x2, double line_y2, double rect_x1, double rect_y1, double rect_x2, double rect_y2, double *out_line_x1, double *out_line_y1, double *out_line_x2, double *out_line_y2) { |
| 1737 | integer numberOfRectangleCrossings = 0; |
| 1738 | double x, y, a, b; |
| 1739 | double crossing_x [5], crossing_y [5], xmin, xmax, ymin, ymax; |
| 1740 | double segment_x1 = line_x1, segment_y1 = line_y1, segment_x2 = line_x2, segment_y2 = line_y2; |
| 1741 | /* |
| 1742 | This test first because we expect the majority of the tested segments to be within the rectangle |
| 1743 | */ |
| 1744 | if (line_x1 >= rect_x1 && line_x1 <= rect_x2 && line_y1 >= rect_y1 && line_y1 <= rect_y2 && |
| 1745 | line_x2 >= rect_x1 && line_x2 <= rect_x2 && line_y2 >= rect_y1 && line_y2 <= rect_y2) |
| 1746 | goto end; |
| 1747 | /* |
| 1748 | All lines that are completely outside the rectangle |
| 1749 | */ |
| 1750 | if ( (line_x1 <= rect_x1 && line_x2 <= rect_x1) || (line_x1 >= rect_x2 && line_x2 >= rect_x2) || |
| 1751 | (line_y1 <= rect_y1 && line_y2 <= rect_y1) || (line_y1 >= rect_y2 && line_y2 >= rect_y2)) |
| 1752 | return false; |
| 1753 | /* |
| 1754 | At least line spans (part of) the rectangle. |
| 1755 | Get extremes in x and y of the line for easy testing further on. |
| 1756 | */ |
| 1757 | bool xswap, yswap; |
| 1758 | if (line_x1 < line_x2) { |
| 1759 | xmin = line_x1; |
| 1760 | xmax = line_x2; |
| 1761 | xswap = false; |
| 1762 | } else { |
| 1763 | xmin = line_x2; |
| 1764 | xmax = line_x1; |
| 1765 | xswap = true; |
| 1766 | } |
| 1767 | if (line_y1 < line_y2) { |
| 1768 | ymin = line_y1; |
| 1769 | ymax = line_y2; |
| 1770 | yswap = false; |
| 1771 | } else { |
| 1772 | ymin = line_y2; |
| 1773 | ymax = line_y1; |
| 1774 | yswap = true; |
| 1775 | } |
| 1776 | |
| 1777 | if (line_y1 == line_y2) { |
| 1778 | if (xmin < rect_x1) |
| 1779 | segment_x1 = rect_x1; |
| 1780 | if (xmax > rect_x2) |
| 1781 | segment_x2 = rect_x2; |
| 1782 | if (xswap) |
| 1783 | std::swap (segment_x1, segment_x2); |
| 1784 | goto end; |
| 1785 | } |
| 1786 | if (line_x1 == line_x2) { |
| 1787 | if (ymin < rect_y1) |
| 1788 | segment_y1 = rect_y1; |
| 1789 | if (ymax > rect_y2) |
| 1790 | segment_y2 = rect_y2; |
| 1791 | if (yswap) |
| 1792 | std::swap (segment_y1, segment_y2); |
| 1793 | goto end; |
| 1794 | } |
| 1795 | /* |
| 1796 | Now we know that the line from (line_x1,line_y1) to (line_x2,line_y2) is neither horizontal nor vertical. |
| 1797 | We can parametrize it as y = ax + b |
| 1798 | */ |
| 1799 | a = (line_y1 - line_y2) / (line_x1 - line_x2); |
| 1800 | b = line_y1 - a * line_x1; |
| 1801 | |
| 1802 | /* |
| 1803 | To determine the crossings we have to avoid counting the crossings in a corner twice. |
| 1804 | Therefore we test the corners inclusive (..<=..<=..) on the vertical borders of the rectangle |
| 1805 | and exclusive (..<..<) at the horizontal borders. |
| 1806 | */ |
| 1807 | |
| 1808 | y = a * rect_x1 + b; // Crossing at y with left border: x = rect_x1 |
| 1809 | |
| 1810 | if (y >= rect_y1 && y <= rect_y2 && xmin < rect_x1) { // Within vertical range? |
| 1811 | crossing_x [++ numberOfRectangleCrossings] = rect_x1; |
| 1812 | crossing_y [numberOfRectangleCrossings] = y; |
| 1813 | crossing_x [2] = xmax; |
| 1814 | crossing_y [2] = line_x1 > line_x2 ? line_y1 : line_y2; |
| 1815 | } |
| 1816 | |
| 1817 | x = (rect_y2 - b) / a; // Crossing at x with top border: y = rect_y2 |
| 1818 | |
| 1819 | if (x > rect_x1 && x < rect_x2 && ymax > rect_y2) { // Within horizontal range? |
| 1820 | crossing_x [++ numberOfRectangleCrossings] = x; |
| 1821 | crossing_y [numberOfRectangleCrossings] = rect_y2; |
| 1822 | if (numberOfRectangleCrossings == 1) { |
| 1823 | crossing_y [2] = ymin; |
| 1824 | crossing_x [2] = line_y1 < line_y2 ? line_x1 : line_x2; |
| 1825 | } |
| 1826 | } |
| 1827 | |
| 1828 | y = a * rect_x2 + b; // Crossing at y with right border: x = rect_x2 |
| 1829 | |
| 1830 | if (y >= rect_y1 && y <= rect_y2 && xmax > rect_x2) { // Within vertical range? |
| 1831 | crossing_x [++ numberOfRectangleCrossings] = rect_x2; |
| 1832 | crossing_y [numberOfRectangleCrossings] = y; |
| 1833 | if (numberOfRectangleCrossings == 1) { |
| 1834 | crossing_x [2] = xmin; |
| 1835 | crossing_y [2] = line_x1 < line_x2 ? line_y1 : line_y2; |
| 1836 | } |
| 1837 | } |
| 1838 | |
| 1839 | x = (rect_y1 - b) / a; // Crossing at x with bottom border: y = rect_y1 |
| 1840 | |
| 1841 | if (x > rect_x1 && x < rect_x2 && ymin < rect_y1) { |
| 1842 | crossing_x [++ numberOfRectangleCrossings] = x; |
| 1843 | crossing_y [numberOfRectangleCrossings] = rect_y1; |
| 1844 | if (numberOfRectangleCrossings == 1) { |
| 1845 | crossing_y [2] = ymax; |
| 1846 | crossing_x [2] = line_y1 > line_y2 ? line_x1 : line_x2; |
| 1847 | } |
| 1848 | } |
| 1849 | if (numberOfRectangleCrossings == 0) |
| 1850 | return false; |
| 1851 | Melder_require (numberOfRectangleCrossings <= 2, |
| 1852 | U"Too many crossings found."); |
| 1853 | |
| 1854 | /* |
| 1855 | If start and endpoint of line are outside rectangle and numberOfRectangleCrossings == 1, than the line only touches. |
| 1856 | */ |
| 1857 | |
| 1858 | if (numberOfRectangleCrossings == 1 && (line_x1 < rect_x1 || line_x1 > rect_x2 || line_y1 < rect_y1 || line_y1 > rect_y2) && |
| 1859 | (line_x2 < rect_x1 || line_x2 > rect_x2 || line_y2 < rect_y1 || line_y2 > rect_y2)) |
| 1860 | goto end; |
| 1861 | |
| 1862 | if ((crossing_x [1] > crossing_x [2] && ! xswap) || (crossing_x [1] < crossing_x [2] && xswap)) { |
| 1863 | std::swap (crossing_x [1], crossing_x [2]); |
| 1864 | std::swap (crossing_y [1], crossing_y [2]); |
| 1865 | } |
| 1866 | segment_x1 = crossing_x [1]; |
| 1867 | segment_y1 = crossing_y [1]; |
| 1868 | segment_x2 = crossing_x [2]; |
| 1869 | segment_y2 = crossing_y [2]; |
| 1870 | |
| 1871 | end: |
| 1872 | |
| 1873 | if (out_line_x1) |
| 1874 | *out_line_x1 = segment_x1; |
| 1875 | if (out_line_y1) |
| 1876 | *out_line_y1 = segment_y1; |
| 1877 | if (out_line_x2) |
| 1878 | *out_line_x2 = segment_x2; |
| 1879 | if (out_line_y2) |
| 1880 | *out_line_y2 = segment_y2; |
| 1881 | return true; |
| 1882 | } |
| 1883 | |
| 1884 | void NUMgetEllipseBoundingBox (double a, double b, double cospsi, double *out_width, double *out_height) { |
| 1885 | Melder_require (cospsi >= -1.0 && cospsi <= 1.0, |
| 1886 | U"NUMgetEllipseBoundingBox: abs (cospi) should not exceed 1.", cospsi); |
| 1887 | double width, height; |
| 1888 | if (cospsi == 1.0) { // a-axis along x-axis |
| 1889 | width = a; |
| 1890 | height = b; |
| 1891 | } else if (cospsi == 0.0) { // a-axis along y-axis |
| 1892 | width = b; |
| 1893 | height = a; |
| 1894 | } else { |
| 1895 | const double psi = acos (cospsi), sinpsi = sin (psi); |
| 1896 | double phi = atan2 (-b * sinpsi, a * cospsi); |
| 1897 | width = fabs (a * cospsi * cos (phi) - b * sinpsi * sin (phi)); |
| 1898 | phi = atan2 (b * cospsi, a * sinpsi); |
| 1899 | height = fabs (a * sinpsi * cos (phi) + b * cospsi * sin (phi)); |
| 1900 | } |
| 1901 | if (out_width) |
| 1902 | *out_width = width; |
| 1903 | if (out_height) |
| 1904 | *out_height = height; |
| 1905 | } |
| 1906 | |
| 1907 | /* |
| 1908 | Closely modeled after the netlib code by Oleg Keselyov. |
| 1909 | */ |
| 1910 | double NUMminimize_brent (double (*f) (double x, void *closure), double a, double b, void *closure, double tol, double *fx) { |
| 1911 | double x, v, fv, w, fw; |
| 1912 | const double golden = 1 - NUM_goldenSection; |
| 1913 | const double sqrt_epsilon = sqrt (NUMfpp -> eps); |
| 1914 | const integer itermax = 60; |
| 1915 | |
| 1916 | Melder_assert (tol > 0 && a < b); |
| 1917 | |
| 1918 | /* |
| 1919 | First step - golden section |
| 1920 | */ |
| 1921 | v = a + golden * (b - a); |
| 1922 | fv = (*f) (v, closure); |
| 1923 | x = v; |
| 1924 | w = v; |
| 1925 | *fx = fv; |
| 1926 | fw = fv; |
| 1927 | |
| 1928 | for (integer iter = 1; iter <= itermax; iter ++) { |
| 1929 | const double middle_range = (a + b) / 2.0; |
| 1930 | const double tol_act = sqrt_epsilon * fabs (x) + tol / 3.0; |
| 1931 | double range = b - a; |
| 1932 | if (fabs (x - middle_range) + range / 2.0 <= 2.0 * tol_act) |
| 1933 | return x; |
| 1934 | |
| 1935 | // Obtain the golden section step |
| 1936 | |
| 1937 | double new_step = golden * (x < middle_range ? b - x : a - x); |
| 1938 | |
| 1939 | // Decide if the parabolic interpolation can be tried |
| 1940 | |
| 1941 | if (fabs (x - w) >= tol_act) { |
| 1942 | /* |
| 1943 | Interpolation step is calculated as p/q; |
| 1944 | division operation is delayed until last moment. |
| 1945 | */ |
| 1946 | |
| 1947 | const double t = (x - w) * (*fx - fv); |
| 1948 | double q = (x - v) * (*fx - fw); |
| 1949 | double p = (x - v) * q - (x - w) * t; |
| 1950 | q = 2.0 * (q - t); |
| 1951 | |
| 1952 | if (q > 0.0) |
| 1953 | p = -p; |
| 1954 | else |
| 1955 | q = -q; |
| 1956 | |
| 1957 | /* |
| 1958 | If x+p/q falls in [a,b], not too close to a and b, |
| 1959 | and isn't too large, it is accepted. |
| 1960 | If p/q is too large then the golden section procedure can |
| 1961 | reduce [a,b] range. |
| 1962 | */ |
| 1963 | |
| 1964 | if (fabs (p) < fabs (new_step * q) && |
| 1965 | p > q * (a - x + 2.0 * tol_act) && |
| 1966 | p < q * (b - x - 2.0 * tol_act)) { |
| 1967 | new_step = p / q; |
| 1968 | } |
| 1969 | } |
| 1970 | |
| 1971 | // Adjust the step to be not less than tolerance. |
| 1972 | |
| 1973 | if (fabs (new_step) < tol_act) |
| 1974 | new_step = new_step > 0.0 ? tol_act : - tol_act; |
| 1975 | |
| 1976 | // Obtain the next approximation to min and reduce the enveloping range |
| 1977 | |
| 1978 | { |
| 1979 | const double t = x + new_step; // Tentative point for the min |
| 1980 | const double ft = (*f) (t, closure); |
| 1981 | |
| 1982 | /* |
| 1983 | If t is a better approximation, reduce the range so that |
| 1984 | t would fall within it. If x remains the best, reduce the range |
| 1985 | so that x falls within it. |
| 1986 | */ |
| 1987 | |
| 1988 | if (ft <= *fx) { |
| 1989 | if (t < x) |
| 1990 | b = x; |
| 1991 | else |
| 1992 | a = x; |
| 1993 | |
| 1994 | v = w; |
| 1995 | w = x; |
| 1996 | x = t; |
| 1997 | fv = fw; |
| 1998 | fw = *fx; |
| 1999 | *fx = ft; |
| 2000 | } else { |
| 2001 | if (t < x) |
| 2002 | a = t; |
| 2003 | else |
| 2004 | b = t; |
| 2005 | |
| 2006 | if (ft <= fw || w == x) { |
| 2007 | v = w; |
| 2008 | w = t; |
| 2009 | fv = fw; |
| 2010 | fw = ft; |
| 2011 | } else if (ft <= fv || v == x || v == w) { |
| 2012 | v = t; |
| 2013 | fv = ft; |
| 2014 | } |
| 2015 | } |
| 2016 | } |
| 2017 | } |
| 2018 | Melder_warning (U"NUMminimize_brent: maximum number of iterations (", itermax, U") exceeded."); |
| 2019 | return x; |
| 2020 | } |
| 2021 | |
| 2022 | /* |
| 2023 | probs is probability vector, i.e. all 0 <= probs [i] <= 1 and sum(i=1...probs.size, probs [i])= 1 |
| 2024 | */ |
| 2025 | integer NUMgetIndexFromProbability (constVEC probs, double p) { |
| 2026 | integer index = 1; |
| 2027 | double psum = probs [index]; |
| 2028 | while (p > psum && index < probs.size) |
| 2029 | psum += probs [++ index]; |
| 2030 | return index; |
| 2031 | } |
| 2032 | |
| 2033 | // straight line fitting |
| 2034 | |
| 2035 | void NUMfitLine_theil (constVEC const& x, constVEC const& y, double *out_m, double *out_intercept, bool completeMethod) { |
| 2036 | try { |
| 2037 | Melder_require (x.size == y.size, |
| 2038 | U"NUMfitLine_theil: the sizes of the two vectors should be equal."); |
| 2039 | /* |
| 2040 | Theil's incomplete method: |
| 2041 | Split (x [i],y [i]) as |
| 2042 | (x [i],y [i]), (x [N+i],y [N+i], i=1..numberOfPoints/2 |
| 2043 | m [i] = (y [N+i]-y [i])/(x [N+i]-x [i]) |
| 2044 | m = median (m [i]) |
| 2045 | b = median(y [i]-m*x [i]) |
| 2046 | */ |
| 2047 | autoVEC lineParameters = raw_VEC (6); |
| 2048 | NUMfitLine_theil_preallocated (lineParameters.get(), x, y, out_intercept, 0.025, completeMethod); |
| 2049 | |
| 2050 | if (out_m) |
| 2051 | *out_m = lineParameters [1]; |
| 2052 | if (out_intercept) |
| 2053 | *out_intercept = lineParameters [4]; |
| 2054 | } catch (MelderError) { |
| 2055 | Melder_throw (U"No line fit (Theil's method)."); |
| 2056 | } |
| 2057 | } |
| 2058 | |
| 2059 | void NUMfitLine_theil_preallocated (VEC const& out_lineParameters, constVEC const& x, constVEC const& y, bool wantIntercept, double oneTailedUnconfidence, bool completeMethod) { |
| 2060 | try { |
| 2061 | Melder_require (x.size == y.size, |
| 2062 | U"NUMfitLine_theil: the sizes of the two vectors should be equal."); |
| 2063 | Melder_require (out_lineParameters.size == 6, |
| 2064 | U"The line parameters vector should have size 6."); |
| 2065 | /* |
| 2066 | Theil's incomplete method: |
| 2067 | Split (x [i],y [i]) as |
| 2068 | (x [i],y [i]), (x [N+i],y [N+i], i=1..numberOfPoints/2 |
| 2069 | m [i] = (y [N+i]-y [i])/(x [N+i]-x [i]) |
| 2070 | m = median (m [i]) |
| 2071 | b = median(y [i]-m*x [i]) |
| 2072 | */ |
| 2073 | out_lineParameters <<= undefined; |
| 2074 | if (x.size == 1) { |
| 2075 | out_lineParameters [1] = 0.0; // m |
| 2076 | out_lineParameters [4] = y [1]; // intercept |
| 2077 | } else if (x.size == 2) { |
| 2078 | const double m = out_lineParameters [1] = (y [2] - y [1]) / (x [2] - x [1]); |
| 2079 | out_lineParameters [4] = y [1] - m * x [1]; |
| 2080 | } else { |
| 2081 | integer numberOfCombinations; |
| 2082 | autoVEC mbs; |
| 2083 | if (! completeMethod) { |
| 2084 | numberOfCombinations = x.size / 2; |
| 2085 | mbs = zero_VEC (x.size); // allocate for the intercept calculation too |
| 2086 | integer n2 = x.size % 2 == 1 ? numberOfCombinations + 1 : numberOfCombinations; |
| 2087 | for (integer i = 1; i <= numberOfCombinations; i ++) |
| 2088 | mbs [i] = (y [n2 + i] - y [i]) / (x [n2 + i] - x [i]); |
| 2089 | } else { // use all combinations |
| 2090 | numberOfCombinations = (x.size - 1) * x.size / 2; |
| 2091 | mbs = zero_VEC (numberOfCombinations); |
| 2092 | integer index = 0; |
| 2093 | for (integer i = 1; i < x.size; i ++) |
| 2094 | for (integer j = i + 1; j <= x.size; j ++) |
| 2095 | mbs [++ index] = (y [j] - y [i]) / (x [j] - x [i]); |
| 2096 | Melder_assert (index == numberOfCombinations); |
| 2097 | } |
| 2098 | /* |
| 2099 | Get slope as the median of all slopes |
| 2100 | */ |
| 2101 | VEC mbsPart = mbs.part (1, numberOfCombinations); |
| 2102 | sort_e_VEC_inout (mbsPart); |
| 2103 | out_lineParameters [1] = NUMquantile (mbsPart, 0.5); |
| 2104 | out_lineParameters [2] = NUMquantile (mbsPart, oneTailedUnconfidence); |
| 2105 | out_lineParameters [3] = NUMquantile (mbsPart, 1.0 - oneTailedUnconfidence); |
| 2106 | /* |
| 2107 | Reuse array for intercept |
| 2108 | */ |
| 2109 | if (wantIntercept) { |
| 2110 | for (integer i = 1; i <= x.size; i ++) |
| 2111 | mbs [i] = y [i] - out_lineParameters [1] * x [i]; |
| 2112 | mbsPart = mbs.part (1, x.size); |
| 2113 | sort_e_VEC_inout (mbsPart); |
| 2114 | out_lineParameters [4] = NUMquantile (mbsPart, 0.5); |
| 2115 | out_lineParameters [5] = NUMquantile (mbsPart, oneTailedUnconfidence); |
| 2116 | out_lineParameters [6] = NUMquantile (mbsPart, 1.0 - oneTailedUnconfidence); |
| 2117 | } |
| 2118 | } |
| 2119 | } catch (MelderError) { |
| 2120 | Melder_throw (U"No line fit (Theil's method)."); |
| 2121 | } |
| 2122 | } |
| 2123 | |
| 2124 | void NUMfitLine_LS (constVEC const& x, constVEC const& y, double *out_m, double *out_intercept) { |
| 2125 | Melder_require (x.size == y.size, |
| 2126 | U"NUMfitLine_LS: the sizes of the two vectors should be equal."); |
| 2127 | const double xsum = NUMsum (x); |
| 2128 | const double xmean = xsum / x.size; |
| 2129 | longdouble variance = 0.0, m = 0.0; |
| 2130 | for (integer i = 1; i <= x.size; i ++) { |
| 2131 | const double t = x [i] - xmean; |
| 2132 | variance += t * t; |
| 2133 | m += t * y [i]; |
| 2134 | } |
| 2135 | // y = m*x + b |
| 2136 | m /= variance; |
| 2137 | if (out_intercept) { |
| 2138 | const double ysum = NUMsum (y); |
| 2139 | *out_intercept = (ysum - m * xsum) / x.size; |
| 2140 | } |
| 2141 | if (out_m) |
| 2142 | *out_m = m; |
| 2143 | } |
| 2144 | |
| 2145 | void NUMlineFit (constVEC x, constVEC y, double *out_m, double *out_intercept, integer method) { |
| 2146 | if (method == 1) |
| 2147 | NUMfitLine_LS (x, y, out_m, out_intercept); |
| 2148 | else if (method == 3) |
| 2149 | NUMfitLine_theil (x, y, out_m, out_intercept, true); |
| 2150 | else |
| 2151 | NUMfitLine_theil (x, y, out_m, out_intercept, false); |
| 2152 | } |
| 2153 | |
| 2154 | // IEEE: Programs for digital signal processing section 4.3 LPTRN |
| 2155 | // lpc [1..n] to rc [1..n] |
| 2156 | |
| 2157 | void VECrc_from_lpc (VEC rc, constVEC lpc) { |
| 2158 | Melder_assert (rc.size == lpc.size); |
| 2159 | autoVEC b = raw_VEC (lpc.size); |
| 2160 | autoVEC a = raw_VEC (lpc.size); |
| 2161 | a.all() <<= lpc; |
| 2162 | for (integer m = lpc.size; m > 0; m--) { |
| 2163 | rc [m] = a [m]; |
| 2164 | Melder_require (fabs (rc [m]) <= 1.0, |
| 2165 | U"Relection coefficient [", m, U"] larger than 1."); |
| 2166 | b.part (1, m) <<= a.part (1, m); |
| 2167 | for (integer i = 1; i < m; i ++) |
| 2168 | a [i] = (b [i] - rc [m] * b [m - i]) / (1.0 - rc [m] * rc [m]); |
| 2169 | } |
| 2170 | } |
| 2171 | |
| 2172 | static void VEClpc_from_rc (VEC lpc, constVEC rc) { |
| 2173 | Melder_assert (lpc.size == rc.size); |
| 2174 | lpc <<= rc; |
| 2175 | for (integer j = 2; j <= lpc.size; j ++) { |
| 2176 | for (integer k = 1; k <= j / 2; k ++) { |
| 2177 | double at = lpc [k] + rc [j] * lpc [j - k]; |
| 2178 | lpc [j - k] += rc [j] * lpc [k]; |
| 2179 | lpc [k] = at; |
| 2180 | } |
| 2181 | } |
| 2182 | } |
| 2183 | |
| 2184 | void VECarea_from_rc (VEC area, constVEC rc) { |
| 2185 | Melder_assert (area.size == rc.size); |
| 2186 | longdouble s = 0.0001; // 1.0 cm^2 at glottis |
| 2187 | for (integer i = area.size; i > 0; i --) { |
| 2188 | s *= (1.0 + rc [i]) / (1.0 - rc [i]); |
| 2189 | area [i] = s; |
| 2190 | } |
| 2191 | } |
| 2192 | |
| 2193 | void VECrc_from_area (VEC rc, constVEC area) { |
| 2194 | Melder_assert (rc.size == area.size); |
| 2195 | double ar; |
| 2196 | for (integer j = 1; j <= rc.size - 1; j ++) { |
| 2197 | ar = area [j + 1] / area [j]; |
| 2198 | rc [j] = (1.0 - ar) / (1.0 + ar); |
| 2199 | } |
| 2200 | ar = 0.0001 / area [rc.size]; // 1.0 cm^2 at glottis |
| 2201 | rc [rc.size] = (1.0 - ar) / (1.0 + ar); |
| 2202 | } |
| 2203 | |
| 2204 | void VEClpc_from_area (VEC lpc, constVEC area) { |
| 2205 | Melder_assert (lpc.size == area.size); |
| 2206 | autoVEC rc = zero_VEC (lpc.size); |
| 2207 | VECrc_from_area (rc.get(), area); |
| 2208 | VEClpc_from_rc (lpc, rc.get()); |
| 2209 | } |
| 2210 | |
| 2211 | void VECarea_from_lpc (VEC area, constVEC lpc) { |
| 2212 | Melder_assert (area.size == lpc.size); |
| 2213 | autoVEC rc = raw_VEC (lpc.size); |
| 2214 | VECrc_from_lpc (rc.get(), lpc); |
| 2215 | VECarea_from_rc (area, rc.get()); |
| 2216 | } |
| 2217 | |
| 2218 | #if 0 |
| 2219 | /*********** Begin deprecated LPC routines ***********************************/ |
| 2220 | void NUMlpc_lpc_to_rc (double *lpc, integer p, double *rc) { |
| 2221 | autoVEC b = zero_VEC (p); |
| 2222 | autoVEC a <<= VEC (lpc, p); |
| 2223 | for (integer m = p; m > 0; m--) { |
| 2224 | rc [m] = a [m]; |
| 2225 | Melder_require (fabs (rc [m]) <= 1.0, |
| 2226 | U"Relection coefficient [", m, U"] larger than 1."); |
| 2227 | for (integer i = 1; i < m; i ++) { |
| 2228 | b [i] = a [i]; |
| 2229 | } |
| 2230 | for (integer i = 1; i < m; i ++) { |
| 2231 | a [i] = (b [i] - rc [m] * b [m - i]) / (1.0 - rc [m] * rc [m]); |
| 2232 | } |
| 2233 | } |
| 2234 | } |
| 2235 | |
| 2236 | void NUMlpc_rc_to_area2 (double *rc, integer n, double *area); |
| 2237 | void NUMlpc_rc_to_area2 (double *rc, integer n, double *area) { |
| 2238 | double s = 0.0001; /* 1.0 cm^2 at glottis */ |
| 2239 | for (integer i = n; i > 0; i--) { |
| 2240 | s *= (1.0 + rc [i]) / (1.0 - rc [i]); |
| 2241 | area [i] = s; |
| 2242 | } |
| 2243 | } |
| 2244 | |
| 2245 | void NUMlpc_area_to_lpc2 (double *area, integer n, double *lpc); |
| 2246 | void NUMlpc_area_to_lpc2 (double *area, integer n, double *lpc) { |
| 2247 | // from area to reflection coefficients |
| 2248 | autoVEC rc =raw_VEC (n); |
| 2249 | // normalisation: area [n+1] = 0.0001 |
| 2250 | for (integer j = n; j > 0; j--) { |
| 2251 | double ar = area [j+1] / area [j]; |
| 2252 | rc [j] = (1 - ar) / (1 + ar); |
| 2253 | } |
| 2254 | // LPTRAN works from mouth to lips: |
| 2255 | for (integer j = 1; j <= n; j ++) { |
| 2256 | lpc [j] = rc [n - j + 1]; |
| 2257 | } |
| 2258 | for (integer j = 2; j <= n; j ++) { |
| 2259 | integer nh = j / 2; |
| 2260 | double q = rc [j]; |
| 2261 | for (integer k = 1; k <= nh; k ++) { |
| 2262 | double at = lpc [k] + q * lpc [j - k]; |
| 2263 | lpc [j - k] += q * lpc [k]; |
| 2264 | lpc [k] = at; |
| 2265 | } |
| 2266 | } |
| 2267 | } |
| 2268 | |
| 2269 | void NUMlpc_lpc_to_rc2 (double *lpc, integer m, double *rc); |
| 2270 | void NUMlpc_lpc_to_rc2 (double *lpc, integer m, double *rc) { // klopt nog niet |
| 2271 | rc.part (1, m) <<= lpc.part (1, m) |
| 2272 | for (integer j = 2; j <= m; j ++) { |
| 2273 | integer jb = m + 1 - j; |
| 2274 | integer mh = (jb + 1) / 2; |
| 2275 | double rct = rc [jb+1]; |
| 2276 | double d = 1.0 - rct * rct; |
| 2277 | for (integer k = 1; k <= mh; k ++) { |
| 2278 | rc [k] *= (1 - rct) / d; |
| 2279 | } |
| 2280 | } |
| 2281 | } |
| 2282 | // area [1] at lips generates n+1 areas from n rc's |
| 2283 | void NUMlpc_rc_to_area (double *rc, integer m, double *area) { |
| 2284 | area [m+1] = 0.0001; /* 1.0 cm^2 */ |
| 2285 | for (integer j = 1; j <= m; j ++) { |
| 2286 | double ar = (1.0 - rc [m+1-j]) / (1.0 + rc [m+1-j]); |
| 2287 | area [m+1-j] = area [m+2-j] / ar; |
| 2288 | } |
| 2289 | } |
| 2290 | |
| 2291 | // returns m-1 reflection coefficients from m areas |
| 2292 | void NUMlpc_area_to_rc (double *area, integer m, double *rc) { |
| 2293 | for (integer j = 1; j <= m - 1; j ++) { |
| 2294 | double ar = area [j+1] / area [j]; |
| 2295 | rc [j] = (1.0 - ar) / (1.0 + ar); |
| 2296 | } |
| 2297 | } |
| 2298 | |
| 2299 | void NUMlpc_rc_to_lpc (double *rc, integer m, double *lpc); |
| 2300 | void NUMlpc_rc_to_lpc (double *rc, integer m, double *lpc) { |
| 2301 | lpc.part (1, m) <<= rc.part (1, m) |
| 2302 | for (integer j = 2; j <= m; j ++) { |
| 2303 | for (integer k = 1; k <= j / 2; k ++) { |
| 2304 | double at = lpc [k] + rc [j] * lpc [j - k]; |
| 2305 | lpc [j - k] += rc [j] * lpc [k]; |
| 2306 | lpc [k] = at; |
| 2307 | } |
| 2308 | } |
| 2309 | } |
| 2310 | |
| 2311 | void NUMlpc_area_to_lpc (double *area, integer m, double *lpc) { |
| 2312 | // from area to reflection coefficients |
| 2313 | autoVEC rc = zero_VEC (m); |
| 2314 | // normalisation: area [n+1] = 0.0001 |
| 2315 | NUMlpc_area_to_rc (area, m, rc.peek()); |
| 2316 | NUMlpc_rc_to_lpc (rc.peek(), m - 1, lpc); // m-1 ??? |
| 2317 | } |
| 2318 | |
| 2319 | void NUMlpc_lpc_to_area (double *lpc, integer m, double *area) { |
| 2320 | autoVEC rc = zero_VEC (m); |
| 2321 | NUMlpc_lpc_to_rc (lpc, m, rc.peek()); |
| 2322 | NUMlpc_rc_to_area (rc.peek(), m, area); |
| 2323 | |
| 2324 | } |
| 2325 | /*********** End deprecated LPC routines ***********************************/ |
| 2326 | #endif |
| 2327 | |
| 2328 | #undef SIGN |
| 2329 | |
| 2330 | /* Start of GSL based routines: |
| 2331 | The following random number generating routines are based on the GSL library |
| 2332 | Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough |
| 2333 | |
| 2334 | */ |
| 2335 | |
| 2336 | #define SMALL_MEAN 14 |
| 2337 | /* If n*p < SMALL_MEAN then use BINV algorithm. The ranlib implementation used cutoff=30; |
| 2338 | * but on my (Brian Gough) computer 14 works better |
| 2339 | */ |
| 2340 | |
| 2341 | #define BINV_CUTOFF 110 |
| 2342 | /* In BINV, do not permit ix too large */ |
| 2343 | |
| 2344 | #define FAR_FROM_MEAN 20 |
| 2345 | /* If ix-n*p is larger than this, then use the "squeeze" algorithm. |
| 2346 | * Ranlib used 20, and this seems to be the best choice on my (Brian Gough) machine as well. |
| 2347 | */ |
| 2348 | |
| 2349 | #define LNFACT(x) gsl_sf_lnfact(x) |
| 2350 | |
| 2351 | inline static double Stirling (double y1) |
| 2352 | { |
| 2353 | const double y2 = y1 * y1; |
| 2354 | const double s = (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / y2) / y2) / y2) / y2) / y1 / 166320.0; |
| 2355 | return s; |
| 2356 | } |
| 2357 | |
| 2358 | /* |
| 2359 | This implementation of NUMrandomBinomial is by James Theiler, April 2003, |
| 2360 | djmw 20121211 replaced calls to gsl_rng_uniform with NUMrandomUniform (0,1) |
| 2361 | */ |
| 2362 | integer NUMrandomBinomial (double p, integer n) { |
| 2363 | if (p < 0.0 || p > 1.0 || n < 0) { |
| 2364 | return -100000000; |
| 2365 | } |
| 2366 | integer ix; // return value |
| 2367 | bool flipped = false; |
| 2368 | |
| 2369 | if (n == 0) |
| 2370 | return 0; |
| 2371 | if (p > 0.5) { |
| 2372 | p = 1.0 - p; // work with small p |
| 2373 | flipped = true; |
| 2374 | } |
| 2375 | |
| 2376 | const double q = 1.0 - p; |
| 2377 | const double s = p / q; |
| 2378 | const double np = n * p; |
| 2379 | |
| 2380 | /* |
| 2381 | Inverse cdf logic for small mean (BINV in K+S) |
| 2382 | */ |
| 2383 | |
| 2384 | if (np < SMALL_MEAN) { |
| 2385 | const double f0 = pow (q, n); // djmw gsl_pow_int (q, n); f(x), starting with x=0 |
| 2386 | |
| 2387 | while (1) { |
| 2388 | /* |
| 2389 | This while(1) loop will almost certainly only loop once; but |
| 2390 | if u=1 to within a few epsilons of machine precision, then it |
| 2391 | is possible for roundoff to prevent the main loop over ix to |
| 2392 | achieve its proper value. Following the ranlib implementation, |
| 2393 | we introduce a check for that situation, and when it occurs, |
| 2394 | we just try again. |
| 2395 | */ |
| 2396 | |
| 2397 | double f = f0; |
| 2398 | double u = NUMrandomUniform (0.0, 1.0); // djmw gsl_rng_uniform (rng); |
| 2399 | |
| 2400 | for (ix = 0; ix <= BINV_CUTOFF; ++ ix) { |
| 2401 | if (u < f) |
| 2402 | goto Finish; |
| 2403 | u -= f; |
| 2404 | // Use recursion f(x+1) = f(x)* [(n-x)/(x+1)]* [p/(1-p)] |
| 2405 | f *= s * (n - ix) / (ix + 1.0); |
| 2406 | } |
| 2407 | |
| 2408 | /* |
| 2409 | It should be the case that the 'goto Finish' was encountered |
| 2410 | before this point was ever reached. But if we have reached |
| 2411 | this point, then roundoff has prevented u from decreasing |
| 2412 | all the way to zero. This can happen only if the initial u |
| 2413 | was very nearly equal to 1, which is a rare situation. In |
| 2414 | that rare situation, we just try again. |
| 2415 | |
| 2416 | Note, following the ranlib implementation, we loop ix only to |
| 2417 | a hardcoded value of SMALL_MEAN_LARGE_N=110; we could have |
| 2418 | looped to n, and 99.99...% of the time it won't matter. This |
| 2419 | choice, I think is a little more robust against the rare |
| 2420 | roundoff error. If n>LARGE_N, then it is technically |
| 2421 | possible for ix>LARGE_N, but it is astronomically rare, and |
| 2422 | if ix is that large, it is more likely due to roundoff than |
| 2423 | probability, so better to nip it at LARGE_N than to take a |
| 2424 | chance that roundoff will somehow conspire to produce an even |
| 2425 | larger (and more improbable) ix. If n<LARGE_N, then once |
| 2426 | ix=n, f=0, and the loop will continue until ix=LARGE_N. |
| 2427 | */ |
| 2428 | } |
| 2429 | } else { |
| 2430 | |
| 2431 | /* |
| 2432 | For n >= SMALL_MEAN, we invoke the BTPE algorithm |
| 2433 | */ |
| 2434 | |
| 2435 | const double ffm = np + p; // ffm = n*p+p |
| 2436 | const integer m = (integer) ffm; // m = int floor [n*p+p] |
| 2437 | const double fm = m; // fm = double m |
| 2438 | const double xm = fm + 0.5; // xm = half integer mean (tip of triangle) |
| 2439 | const double npq = np * q; // npq = n*p*q |
| 2440 | |
| 2441 | /* |
| 2442 | Compute cumulative area of tri, para, exp tails |
| 2443 | |
| 2444 | p1: radius of triangle region; since height=1, also: area of region |
| 2445 | p2: p1 + area of parallelogram region |
| 2446 | p3: p2 + area of left tail |
| 2447 | p4: p3 + area of right tail |
| 2448 | pi/p4: probability of i'th area (i=1,2,3,4) |
| 2449 | |
| 2450 | Note: magic numbers 2.195, 4.6, 0.134, 20.5, 15.3 |
| 2451 | These magic numbers are not adjustable...at least not easily! |
| 2452 | */ |
| 2453 | |
| 2454 | const double p1 = Melder_roundDown (2.195 * sqrt (npq) - 4.6 * q) + 0.5; |
| 2455 | |
| 2456 | // xl, xr: left and right edges of triangle |
| 2457 | const double xl = xm - p1; |
| 2458 | const double xr = xm + p1; |
| 2459 | |
| 2460 | /* |
| 2461 | Parameter of exponential tails |
| 2462 | Left tail: t(x) = c*exp(-lambda_l* [xl - (x+0.5)]) |
| 2463 | Right tail: t(x) = c*exp(-lambda_r* [(x+0.5) - xr]) |
| 2464 | */ |
| 2465 | |
| 2466 | const double c = 0.134 + 20.5 / (15.3 + fm); |
| 2467 | const double p2 = p1 * (1.0 + c + c); |
| 2468 | const double al = (ffm - xl) / (ffm - xl * p); |
| 2469 | const double lambda_l = al * (1.0 + 0.5 * al); |
| 2470 | const double ar = (xr - ffm) / (xr * q); |
| 2471 | const double lambda_r = ar * (1.0 + 0.5 * ar); |
| 2472 | const double p3 = p2 + c / lambda_l; |
| 2473 | const double p4 = p3 + c / lambda_r; |
| 2474 | double var, accept; |
| 2475 | |
| 2476 | TryAgain: |
| 2477 | |
| 2478 | /* |
| 2479 | Generate random variates, u specifies which region: Tri, Par, Tail |
| 2480 | */ |
| 2481 | |
| 2482 | const double u = p4 * NUMrandomUniform (0.0, 1.0); // djmw gsl_rng_uniform (rng) * p4; |
| 2483 | double v = NUMrandomUniform (0.0, 1.0); // djmw gsl_rng_uniform (rng); |
| 2484 | |
| 2485 | if (u <= p1) { |
| 2486 | // Triangular region |
| 2487 | ix = (integer) (xm - p1 * v + u); |
| 2488 | goto Finish; |
| 2489 | } else if (u <= p2) { |
| 2490 | // Parallelogram region |
| 2491 | const double x = xl + (u - p1) / c; |
| 2492 | v = v * c + 1.0 - fabs (x - xm) / p1; |
| 2493 | if (v > 1.0 || v <= 0.0) |
| 2494 | goto TryAgain; |
| 2495 | ix = (integer) x; |
| 2496 | } else if (u <= p3) { |
| 2497 | // Left tail |
| 2498 | ix = (integer) (xl + log (v) / lambda_l); |
| 2499 | if (ix < 0) |
| 2500 | goto TryAgain; |
| 2501 | v *= ((u - p2) * lambda_l); |
| 2502 | } else { |
| 2503 | // Right tail |
| 2504 | ix = (integer) (xr - log (v) / lambda_r); |
| 2505 | if (ix > (double) n) |
| 2506 | goto TryAgain; |
| 2507 | v *= ((u - p3) * lambda_r); |
| 2508 | } |
| 2509 | |
| 2510 | /* |
| 2511 | At this point, the goal is to test whether v <= f(x)/f(m) |
| 2512 | v <= f(x)/f(m) = (m!(n-m)! / (x!(n-x)!)) * (p/q)^{x-m} |
| 2513 | |
| 2514 | Here is a direct test using logarithms. It is a little |
| 2515 | slower than the various "squeezing" computations below, but |
| 2516 | if things are working, it should give exactly the same answer |
| 2517 | (given the same random number seed). |
| 2518 | */ |
| 2519 | |
| 2520 | #ifdef DIRECT |
| 2521 | var = log (v); |
| 2522 | |
| 2523 | accept = LNFACT (m) + LNFACT (n - m) - LNFACT (ix) - LNFACT (n - ix) + (ix - m) * log (p / q); |
| 2524 | |
| 2525 | #else // SQUEEZE METHOD |
| 2526 | |
| 2527 | /* |
| 2528 | More efficient determination of whether v < f(x)/f(M) |
| 2529 | */ |
| 2530 | |
| 2531 | const integer k = integer_abs (ix - m); |
| 2532 | |
| 2533 | if (k <= FAR_FROM_MEAN) { |
| 2534 | /* |
| 2535 | If ix near m (ie, |ix-m|<FAR_FROM_MEAN), then do |
| 2536 | explicit evaluation using recursion relation for f(x) |
| 2537 | */ |
| 2538 | const double g = (n + 1) * s; |
| 2539 | double f = 1.0; |
| 2540 | |
| 2541 | var = v; |
| 2542 | |
| 2543 | if (m < ix) { |
| 2544 | for (integer i = m + 1; i <= ix; i ++) |
| 2545 | f *= (g / i - s); |
| 2546 | } else if (m > ix) { |
| 2547 | for (integer i = ix + 1; i <= m; i ++) |
| 2548 | f /= (g / i - s); |
| 2549 | } |
| 2550 | |
| 2551 | accept = f; |
| 2552 | } else { |
| 2553 | // If ix is far from the mean m: k=ABS(ix-m) large |
| 2554 | |
| 2555 | var = log (v); |
| 2556 | |
| 2557 | if (k < npq / 2 - 1) { |
| 2558 | /* |
| 2559 | "Squeeze" using upper and lower bounds on |
| 2560 | log(f(x)) The squeeze condition was derived |
| 2561 | under the condition k < npq/2-1 |
| 2562 | */ |
| 2563 | const double amaxp = k / npq * ((k * (k / 3.0 + 0.625) + (1.0 / 6.0)) / npq + 0.5); |
| 2564 | const double ynorm = -(k * k / (2.0 * npq)); |
| 2565 | if (var < ynorm - amaxp) |
| 2566 | goto Finish; |
| 2567 | if (var > ynorm + amaxp) |
| 2568 | goto TryAgain; |
| 2569 | } |
| 2570 | |
| 2571 | /* |
| 2572 | Now, again: do the test log(v) vs. log f(x)/f(M) |
| 2573 | */ |
| 2574 | |
| 2575 | #if USE_EXACT |
| 2576 | /* |
| 2577 | This is equivalent to the above, but is a little (~20%) slower |
| 2578 | There are five log's vs three above, maybe that's it? |
| 2579 | */ |
| 2580 | |
| 2581 | accept = LNFACT (m) + LNFACT (n - m) - LNFACT (ix) - LNFACT (n - ix) + (ix - m) * log (p / q); |
| 2582 | |
| 2583 | #else |
| 2584 | /* USE STIRLING: |
| 2585 | The "#define Stirling" above corresponds to the first five |
| 2586 | terms in asymptotic formula for |
| 2587 | log Gamma (y) - (y-0.5)log(y) + y - 0.5 log(2*pi); |
| 2588 | See Abramowitz and Stegun, eq 6.1.40 |
| 2589 | |
| 2590 | |
| 2591 | Note below: two Stirling's are added, and two are |
| 2592 | subtracted. In both K+S, and in the ranlib |
| 2593 | implementation, all four are added. I (jt) believe that |
| 2594 | is a mistake -- this has been confirmed by personal |
| 2595 | correspondence w/ Dr. Kachitvichyanukul. Note, however, |
| 2596 | the corrections are so small, that I couldn't find an |
| 2597 | example where it made a difference that could be |
| 2598 | observed, let alone tested. In fact, define'ing Stirling |
| 2599 | to be zero gave identical results!! In practice, alv is |
| 2600 | O(1), ranging 0 to -10 or so, while the Stirling |
| 2601 | correction is typically O(10^{-5}) ...setting the |
| 2602 | correction to zero gives about a 2% performance boost; |
| 2603 | might as well keep it just to be pedantic. |
| 2604 | */ |
| 2605 | |
| 2606 | { |
| 2607 | const double x1 = ix + 1.0; |
| 2608 | const double w1 = n - ix + 1.0; |
| 2609 | const double f1 = fm + 1.0; |
| 2610 | const double z1 = n + 1.0 - fm; |
| 2611 | |
| 2612 | accept = xm * log (f1 / x1) + (n - m + 0.5) * log (z1 / w1) + (ix - m) * log (w1 * p / (x1 * q)) |
| 2613 | + Stirling (f1) + Stirling (z1) - Stirling (x1) - Stirling (w1); |
| 2614 | } |
| 2615 | #endif |
| 2616 | #endif |
| 2617 | } |
| 2618 | |
| 2619 | |
| 2620 | if (var <= accept) |
| 2621 | goto Finish; |
| 2622 | else |
| 2623 | goto TryAgain; |
| 2624 | } |
| 2625 | |
| 2626 | Finish: |
| 2627 | |
| 2628 | return flipped ? (n - ix) : ix; |
| 2629 | } |
| 2630 | |
| 2631 | double NUMrandomBinomial_real (double p, integer n) { |
| 2632 | if (p < 0.0 || p > 1.0 || n < 0) |
| 2633 | return undefined; |
| 2634 | else |
| 2635 | return (double) NUMrandomBinomial (p, n); |
| 2636 | } |
| 2637 | |
| 2638 | /* |
| 2639 | From gsl_ran_weibull.c |
| 2640 | */ |
| 2641 | double NUMrandomWeibull (double scale_lambda, double shape_k) { |
| 2642 | Melder_require (scale_lambda > 0.0 && shape_k > 0.0, |
| 2643 | U"NUMrandomWeibull: both arguments should be positive."); |
| 2644 | const double u = NUMrandomUniform (0, 1); |
| 2645 | return scale_lambda * pow (- log (u), 1.0 / shape_k); |
| 2646 | } |
| 2647 | |
| 2648 | /* |
| 2649 | Notice in GSL gsl_randist_gamma: |
| 2650 | Version based on Marsaglia and Tsang, "A Simple Method for generating gamma variables", |
| 2651 | ACM Transactions on Mathematical Software, Vol 26, No 3 (2000), p363-372. |
| 2652 | |
| 2653 | Implemented by [email protected], minor modifications for GSL by Brian Gough |
| 2654 | */ |
| 2655 | double NUMrandomGamma (const double alpha, const double beta) { |
| 2656 | Melder_require (alpha > 0 && beta > 0, |
| 2657 | U"NUMrandomGamma: both arguments should be positive."); |
| 2658 | double result; |
| 2659 | if (alpha >= 1.0) { |
| 2660 | double x, v, d = alpha - 1.0 / 3.0; |
| 2661 | double c = (1.0 / 3.0) / sqrt (d); |
| 2662 | while (1) { |
| 2663 | do { |
| 2664 | x = NUMrandomGauss (0.0, 1.0); |
| 2665 | v = 1.0 + c * x; |
| 2666 | } while (v <= 0.0); |
| 2667 | v = v * v * v; |
| 2668 | double u = NUMrandomUniform (0.0, 1.0); |
| 2669 | if (u < 1.0 - 0.0331 * (x * x) * (x * x)) |
| 2670 | break; |
| 2671 | if (log(u) < 0.5 * x * x + d * (1.0 - v + log(v))) |
| 2672 | break; |
| 2673 | } |
| 2674 | result = d * v / beta; |
| 2675 | } else { |
| 2676 | double u = NUMrandomUniform (0.0, 1.0); |
| 2677 | result = NUMrandomGamma (alpha + 1.0, beta) * pow (u, 1.0 / alpha); |
| 2678 | } |
| 2679 | return result; |
| 2680 | } |
| 2681 | |
| 2682 | void NUMlngamma_complex (double zr, double zi, double *out_lnr, double *out_arg) { |
| 2683 | double ln_re = undefined, ln_arg = undefined; |
| 2684 | gsl_sf_result gsl_lnr, gsl_arg; |
| 2685 | if (gsl_sf_lngamma_complex_e (zr, zi, & gsl_lnr, & gsl_arg)) { |
| 2686 | ln_re = gsl_lnr.val; |
| 2687 | ln_arg = gsl_arg.val; |
| 2688 | } |
| 2689 | if (out_lnr) |
| 2690 | *out_lnr = ln_re; |
| 2691 | if (out_arg) |
| 2692 | *out_arg = ln_arg; |
| 2693 | } |
| 2694 | |
| 2695 | /* End of GSL based routines */ |
| 2696 | |
| 2697 | autoVEC newVECbiharmonic2DSplineInterpolation_getWeights (constVECVU const& x, constVECVU const& y, constVECVU const& z) { |
| 2698 | Melder_assert (x.size == y.size && x.size == z.size); |
| 2699 | autoMAT g = raw_MAT (x.size, x.size); |
| 2700 | /* |
| 2701 | 1. Calculate the Green matrix G = |point [i]-point [j]|^2 (ln (|point [i]-point [j]|) - 1.0) |
| 2702 | 2. Solve z = G.w for w |
| 2703 | */ |
| 2704 | for (integer i = 1; i <= x.size; i ++) { |
| 2705 | for (integer j = i + 1; j <= x.size; j ++) { |
| 2706 | double dx = x [i] - x [j], dy = y [i] - y [j]; |
| 2707 | double distanceSquared = dx * dx + dy * dy; |
| 2708 | g [i] [j] = g [j] [i] = distanceSquared * (0.5 * log (distanceSquared) - 1.0); // Green's function |
| 2709 | } |
| 2710 | g [i] [i] = 0.0; |
| 2711 | } |
| 2712 | autoVEC w = solve_VEC (g.get(), z, 0.0); |
| 2713 | return w; |
| 2714 | } |
| 2715 | |
| 2716 | double NUMbiharmonic2DSplineInterpolation (constVECVU const& x, constVECVU const& y, constVECVU const& w, double xp, double yp) { |
| 2717 | Melder_assert (x.size == y.size && x.size == w.size); |
| 2718 | longdouble result = 0.0; |
| 2719 | for (integer i = 1; i <= x.size; i ++) { |
| 2720 | const double dx = xp - x [i], dy = yp - y [i]; |
| 2721 | const double d = dx * dx + dy * dy; |
| 2722 | result += w [i] * d * (0.5 * log (d) - 1.0); |
| 2723 | } |
| 2724 | return (double) result; |
| 2725 | } |
| 2726 | |
| 2727 | void NUMfixIndicesInRange (integer lowerLimit, integer upperLimit, integer *lowIndex, integer *highIndex) { |
| 2728 | Melder_require (lowerLimit <= upperLimit, U"The lower limit should not exceed the upper limit."); |
| 2729 | if (*highIndex < *lowIndex) { |
| 2730 | *lowIndex = lowerLimit; *highIndex = upperLimit; |
| 2731 | } else if (*highIndex == *lowIndex) { |
| 2732 | Melder_require (*lowIndex >= lowerLimit && *highIndex <= upperLimit, |
| 2733 | U"Both lower and upper indices are out of range."); |
| 2734 | } else { // low < high |
| 2735 | Melder_require (*lowIndex < upperLimit && *highIndex > lowerLimit, |
| 2736 | U"Both lower and upper indices are out of range."); |
| 2737 | if (*lowIndex < lowerLimit) |
| 2738 | *lowIndex = lowerLimit; |
| 2739 | if (*highIndex > upperLimit) |
| 2740 | *highIndex = upperLimit; |
| 2741 | } |
| 2742 | } |
| 2743 | |
| 2744 | void NUMgetEntropies (constMATVU const& m, double *out_h, double *out_hx, double *out_hy, double *out_hygx, double *out_hxgy, double *out_uygx, double *out_uxgy, double *out_uxy) { |
| 2745 | |
| 2746 | double h = undefined, hx = undefined, hy = undefined; |
| 2747 | double hxgy = undefined, hygx = undefined, uygx = undefined, uxgy = undefined, uxy = undefined; |
| 2748 | |
| 2749 | // Get total sum and check if all elements are not negative. |
| 2750 | |
| 2751 | longdouble totalSum = 0.0; |
| 2752 | for (integer i = 1; i <= m.nrow; i ++) { |
| 2753 | for (integer j = 1; j <= m.ncol; j++) { |
| 2754 | Melder_require (m [i] [j] >= 0.0, |
| 2755 | U"Matrix elements should not be negative."); |
| 2756 | totalSum += m [i] [j]; |
| 2757 | } |
| 2758 | } |
| 2759 | |
| 2760 | if (totalSum > 0.0) { |
| 2761 | longdouble hy_t = 0.0; |
| 2762 | for (integer i = 1; i <= m.nrow; i ++) { |
| 2763 | const double rowsum = NUMsum (m.row (i)); |
| 2764 | if (rowsum > 0.0) { |
| 2765 | const double p = rowsum / double (totalSum); |
| 2766 | hy_t -= p * NUMlog2 (p); |
| 2767 | } |
| 2768 | } |
| 2769 | hy = (double) hy_t; |
| 2770 | |
| 2771 | longdouble hx_t = 0.0; |
| 2772 | for (integer j = 1; j <= m.ncol; j ++) { |
| 2773 | const double colsum = NUMsum (m.column (j)); |
| 2774 | if (colsum > 0.0) { |
| 2775 | const double p = colsum / double (totalSum); |
| 2776 | hx_t -= p * NUMlog2 (p); |
| 2777 | } |
| 2778 | } |
| 2779 | hx = (double) hx_t; |
| 2780 | |
| 2781 | // Total entropy |
| 2782 | longdouble h_t = 0.0; |
| 2783 | for (integer i = 1; i <= m.nrow; i ++) { |
| 2784 | for (integer j = 1; j <= m.ncol; j ++) { |
| 2785 | if (m [i] [j] > 0.0) { |
| 2786 | const double p = m [i] [j] / double (totalSum); |
| 2787 | h_t -= p * NUMlog2 (p); |
| 2788 | } |
| 2789 | } |
| 2790 | } |
| 2791 | h = (double) h_t; |
| 2792 | hygx = h - hx; |
| 2793 | hxgy = h - hy; |
| 2794 | uygx = (hy - hygx) / hy; |
| 2795 | uxgy = (hx - hxgy) / hx; |
| 2796 | uxy = 2.0 * (hx + hy - h) / (hx + hy); |
| 2797 | } |
| 2798 | if (out_h) |
| 2799 | *out_h = h; |
| 2800 | if (out_hx) |
| 2801 | *out_hx = hx; |
| 2802 | if (out_hy) |
| 2803 | *out_hy = hy; |
| 2804 | // Conditional entropies |
| 2805 | if (out_hygx) |
| 2806 | *out_hygx = hygx; |
| 2807 | if (out_hxgy) |
| 2808 | *out_hxgy = hxgy; |
| 2809 | if (out_uygx) |
| 2810 | *out_uygx = uygx; |
| 2811 | if (out_uxgy) |
| 2812 | *out_uxgy = uxgy; |
| 2813 | if (out_uxy) |
| 2814 | *out_uxy = uxy; |
| 2815 | } |
| 2816 | #undef TINY |
| 2817 | |
| 2818 | double NUMtrace (constMATVU const& a) { |
| 2819 | Melder_assert (a.nrow == a.ncol); |
| 2820 | longdouble trace = 0.0; |
| 2821 | for (integer i = 1; i <= a.nrow; i ++) |
| 2822 | trace += a [i] [i]; |
| 2823 | return (double) trace; |
| 2824 | } |
| 2825 | |
| 2826 | double NUMtrace2 (constMATVU const& x, constMATVU const& y) { |
| 2827 | Melder_assert (x.ncol == y.nrow && x.nrow == y.ncol); |
| 2828 | longdouble trace = 0.0; |
| 2829 | for (integer irow = 1; irow <= x.nrow; irow ++) |
| 2830 | for (integer k = 1; k <= x.ncol; k ++) |
| 2831 | trace += x [irow] [k] * y [k] [irow]; |
| 2832 | return (double) trace; |
| 2833 | } |
| 2834 | |
| 2835 | void NUMeigencmp22 (double a, double b, double c, double *out_rt1, double *out_rt2, double *out_cs1, double *out_sn1) { |
| 2836 | const longdouble sm = a + c, df = a - c, adf = fabs (df); |
| 2837 | const longdouble tb = b + b, ab = fabs (tb); |
| 2838 | longdouble acmx = c, acmn = a; |
| 2839 | if (fabs (a) > fabs (c)) { |
| 2840 | acmx = a; |
| 2841 | acmn = c; |
| 2842 | } |
| 2843 | longdouble rt, tn; |
| 2844 | if (adf > ab) { |
| 2845 | tn = ab / adf; |
| 2846 | rt = adf * sqrt (1.0 + tn * tn); |
| 2847 | } else if (adf < ab) { |
| 2848 | tn = adf / ab; |
| 2849 | rt = ab * sqrt (1.0 + tn * tn); |
| 2850 | } else |
| 2851 | rt = ab * sqrt (2.0); |
| 2852 | |
| 2853 | longdouble rt1, rt2; |
| 2854 | integer sgn1, sgn2; |
| 2855 | if (sm < 0.0) { |
| 2856 | rt1 = 0.5 * (sm - rt); |
| 2857 | sgn1 = -1; |
| 2858 | /* |
| 2859 | Order of execution important. |
| 2860 | To get fully accurate smaller eigenvalue, |
| 2861 | next line needs to be executed in higher precision. |
| 2862 | */ |
| 2863 | rt2 = (acmx / rt1) * acmn - (b / rt1) * b; |
| 2864 | } else if (sm > 0.0) { |
| 2865 | rt1 = 0.5 * (sm + rt); |
| 2866 | sgn1 = 1; |
| 2867 | /* |
| 2868 | Order of execution important. |
| 2869 | To get fully accurate smaller eigenvalue, |
| 2870 | next line needs to be executed in higher precision. |
| 2871 | */ |
| 2872 | rt2 = (acmx / rt1) * acmn - (b / rt1) * b; |
| 2873 | } else { |
| 2874 | rt1 = 0.5 * rt; |
| 2875 | rt2 = -0.5 * rt; |
| 2876 | sgn1 = 1; |
| 2877 | } |
| 2878 | |
| 2879 | // Compute the eigenvector |
| 2880 | |
| 2881 | longdouble cs; |
| 2882 | if (df >= 0.0) { |
| 2883 | cs = df + rt; |
| 2884 | sgn2 = 1; |
| 2885 | } else { |
| 2886 | cs = df - rt; |
| 2887 | sgn2 = -1; |
| 2888 | } |
| 2889 | const longdouble acs = fabs (cs); |
| 2890 | longdouble cs1, sn1; |
| 2891 | if (acs > ab) { |
| 2892 | const longdouble ct = -tb / cs; |
| 2893 | sn1 = 1.0 / sqrt (1.0 + ct * ct); |
| 2894 | cs1 = ct * sn1; |
| 2895 | } else { |
| 2896 | if (ab == 0.0) { |
| 2897 | cs1 = 1.0; |
| 2898 | sn1 = 0.0; |
| 2899 | } else { |
| 2900 | tn = -cs / tb; |
| 2901 | cs1 = 1.0 / sqrt (1.0 + tn * tn); |
| 2902 | sn1 = tn * cs1; |
| 2903 | } |
| 2904 | } |
| 2905 | if (sgn1 == sgn2) { |
| 2906 | tn = cs1; |
| 2907 | cs1 = -sn1; |
| 2908 | sn1 = tn; |
| 2909 | } |
| 2910 | if (fabs (cs1) > 1.0) |
| 2911 | cs1 = copysign (1.0, cs1); |
| 2912 | if (fabs (sn1) > 1.0) |
| 2913 | sn1 = copysign (1.0, sn1); |
| 2914 | if (out_rt1) |
| 2915 | *out_rt1 = (double) rt1; |
| 2916 | if (out_rt2) |
| 2917 | *out_rt2 = (double) rt2; |
| 2918 | if (out_cs1) |
| 2919 | *out_cs1 = (double) cs1; |
| 2920 | if (out_sn1) |
| 2921 | *out_sn1 = (double) sn1; |
| 2922 | } |
| 2923 | |
| 2924 | void MATmul3_XYXt (MATVU const& target, constMATVU const& x, constMATVU const& y) { // X.Y.X' |
| 2925 | Melder_assert (x.ncol == y.nrow && y.ncol == x.ncol); |
| 2926 | Melder_assert (target.nrow == target.ncol && target.nrow == x.nrow); |
| 2927 | for (integer irow = 1; irow <= target.nrow; irow ++) |
| 2928 | for (integer icol = 1; icol <= target.ncol; icol ++) { |
| 2929 | longdouble sum = 0.0; |
| 2930 | for (integer k = 1; k <= x.ncol; k ++) |
| 2931 | sum += x [irow] [k] * NUMinner (y.row (k), x.row (icol)); |
| 2932 | target [irow] [icol] = double (sum); |
| 2933 | } |
| 2934 | } |
| 2935 | |
| 2936 | void MATmul3_XYsXt (MATVU const& target, constMATVU const& x, constMATVU const& y) { // X.Y.X' |
| 2937 | Melder_assert (x.ncol == y.nrow && y.ncol == x.ncol); |
| 2938 | Melder_assert (target.nrow == target.ncol && target.nrow == x.nrow); |
| 2939 | for (integer irow = 1; irow <= target.nrow; irow ++) |
| 2940 | for (integer icol = irow; icol <= target.ncol; icol ++) { |
| 2941 | longdouble sum = 0.0; |
| 2942 | for (integer k = 1; k <= x.ncol; k ++) |
| 2943 | sum += x [irow] [k] * NUMinner (y.row (k), x.row (icol)); |
| 2944 | target [irow] [icol] = double (sum); |
| 2945 | } |
| 2946 | for (integer irow = 1; irow <= target.nrow; irow ++) |
| 2947 | for (integer icol = irow + 1; icol <= target.ncol; icol ++) |
| 2948 | target [icol] [irow] = target [irow] [icol]; |
| 2949 | } |
| 2950 | |
| 2951 | /* |
| 2952 | 1. Take absolute value of v. |
| 2953 | 2. Sort abs(v) and its index together. |
| 2954 | 3. Make all elements of v zero, except the numberOfNonZeros largest elements. |
| 2955 | 4. Set the support of these largest elements to 1 and the rest to zero. |
| 2956 | */ |
| 2957 | static void VECupdateDataAndSupport_inplace (VECVU const& v, BOOLVECVU const& support, integer numberOfNonZeros) { |
| 2958 | Melder_assert (v.size == support.size); |
| 2959 | autoVEC abs = abs_VEC (v); |
| 2960 | autoINTVEC index = to_INTVEC (v.size); |
| 2961 | NUMsortTogether (abs.get(), index.get()); // sort is always increasing |
| 2962 | for (integer i = 1; i <= v.size - numberOfNonZeros; i ++) { |
| 2963 | v [index [i]] = 0.0; |
| 2964 | support [index [i]] = false; |
| 2965 | } |
| 2966 | for (integer i = v.size - numberOfNonZeros + 1; i <= v.size; i ++) |
| 2967 | support [index [i]] = true; |
| 2968 | } |
| 2969 | |
| 2970 | static double update (VEC const& x_new, VEC const& y_new, BOOLVECVU const& support_new, constVECVU const& xn, double stepSize, constVEC const& gradient, constMATVU const& dictionary, constVEC const& yn, integer numberOfNonZeros, VEC buffer) { |
| 2971 | Melder_assert (x_new.size == xn.size && buffer.size == x_new.size); |
| 2972 | Melder_assert (gradient.size == support_new.size && gradient.size == x_new.size); |
| 2973 | Melder_assert (y_new.size == yn.size); |
| 2974 | Melder_assert (dictionary.nrow == yn.size && dictionary.ncol == xn.size); |
| 2975 | |
| 2976 | buffer <<= stepSize * gradient; |
| 2977 | x_new <<= xn + buffer; // x(n) + stepSize * gradient |
| 2978 | VECupdateDataAndSupport_inplace (x_new, support_new, numberOfNonZeros); |
| 2979 | buffer <<= x_new - xn; // x(n+1) - x (n) |
| 2980 | const double xdifsq = NUMsum2 (buffer); // ||x(n+1) - x (n)||^2 |
| 2981 | |
| 2982 | mul_VEC_out (y_new, dictionary, x_new); // y(n+1) = D. x(n+1) |
| 2983 | buffer.part (1, yn.size) <<= y_new - yn; // y(n+1) - y(n) = D.(x(n+1) - x(n)) |
| 2984 | const double ydifsq = NUMsum2 (buffer.part (1, yn.size)); // ||y(n+1) - y(n)||^2 |
| 2985 | return xdifsq / ydifsq; |
| 2986 | } |
| 2987 | |
| 2988 | autoVEC solveSparse_IHT_VEC (constMATVU const& dictionary, constVECVU const& y, integer numberOfNonZeros, integer maximumNumberOfIterations, double tolerance, integer infoLevel) { |
| 2989 | try { |
| 2990 | Melder_assert (dictionary.ncol > dictionary.nrow); // must be underdetermined system |
| 2991 | Melder_assert (dictionary.nrow == y.size); // y = D.x + e |
| 2992 | autoVEC result = zero_VEC (dictionary.ncol); |
| 2993 | VECsolveSparse_IHT (result.get(), dictionary, y, numberOfNonZeros, maximumNumberOfIterations, tolerance, infoLevel); |
| 2994 | return result; |
| 2995 | } catch (MelderError) { |
| 2996 | Melder_throw (U"Solution of sparse problem not found."); |
| 2997 | } |
| 2998 | } |
| 2999 | |
| 3000 | void VECsolveSparse_IHT (VECVU const& x, constMATVU const& dictionary, constVECVU const& y, integer numberOfNonZeros, integer maximumNumberOfIterations, double tolerance, integer infoLevel) { |
| 3001 | try { |
| 3002 | Melder_assert (dictionary.ncol > dictionary.nrow); // must be underdetermined system |
| 3003 | Melder_assert (dictionary.ncol == x.size); // we calculate D.x |
| 3004 | Melder_assert (dictionary.nrow == y.size); // y = D.x + e |
| 3005 | |
| 3006 | autoVEC gradient = raw_VEC (x.size); |
| 3007 | autoVEC x_new = raw_VEC (x.size); // x(n+1), x == x(n) |
| 3008 | autoVEC yfromx = raw_VEC (y.size); // D.x(n) |
| 3009 | autoVEC yfromx_new = raw_VEC (y.size); // D.x(n+1) |
| 3010 | autoVEC ydif = raw_VEC (y.size); // y - D.x(n) |
| 3011 | autoVEC buffer = raw_VEC (x.size); |
| 3012 | autoBOOLVEC support = raw_BOOLVEC (x.size); |
| 3013 | autoBOOLVEC support_new = raw_BOOLVEC (x.size); |
| 3014 | |
| 3015 | const double xnormSq = NUMsum2 (x); |
| 3016 | const double rms_y = NUMsum2 (y) / y.size; |
| 3017 | double rms = rms_y; |
| 3018 | |
| 3019 | if (xnormSq == 0.0) { |
| 3020 | /* |
| 3021 | Start with x == 0. |
| 3022 | Get initial support supp (Hard_K (D'y)) |
| 3023 | Hard_K (v) is a hard thresholder which only keeps the largest K elements from the vector v |
| 3024 | */ |
| 3025 | mul_VEC_out (buffer.get(), dictionary.transpose(), y); |
| 3026 | VECupdateDataAndSupport_inplace (buffer.get(), support.get(), numberOfNonZeros); |
| 3027 | yfromx.all() <<= 0.0; |
| 3028 | ydif.all() <<= y; // ydif = y - D.x(1) = y - D.0 = y |
| 3029 | } else { |
| 3030 | /* |
| 3031 | We improve a current solution x |
| 3032 | */ |
| 3033 | VECupdateDataAndSupport_inplace (x, support.get(), numberOfNonZeros); |
| 3034 | mul_VEC_out (yfromx.get(), dictionary, x); // D.x(n) |
| 3035 | ydif.all() <<= y - yfromx.all(); // y - D.x(n) |
| 3036 | rms = NUMsum2 (ydif.get()) / y.size; // ||y - D.x(n)||^2 |
| 3037 | } |
| 3038 | |
| 3039 | bool convergence = false; |
| 3040 | integer iter = 1; |
| 3041 | while (iter <= maximumNumberOfIterations && not convergence) { |
| 3042 | |
| 3043 | mul_VEC_out (gradient.get(), dictionary.transpose(), ydif.get()); // D'.(y - D.x(n)) |
| 3044 | /* |
| 3045 | Calculate stepSize mu according to Eq. (13) |
| 3046 | mu = || g_sparse ||^2 / || D_sparse * g_sparse ||^2 |
| 3047 | where g_sparse only contains the supported elements from the gradient and D_sparse only the supported columns from the dictionary. |
| 3048 | */ |
| 3049 | longdouble normsq_gs = 0.0; // squared norm of the sparse gradient |
| 3050 | for (integer ig = 1; ig <= gradient.size; ig ++) { |
| 3051 | if (support [ig]) |
| 3052 | normsq_gs += gradient [ig] * gradient [ig]; |
| 3053 | } |
| 3054 | longdouble normsq_dgs = 0.0; // squared norm of the transformed sparse gradient |
| 3055 | for (integer irow = 1; irow <= dictionary.nrow; irow ++) { |
| 3056 | longdouble sum = 0.0; |
| 3057 | for (integer icol = 1; icol <= dictionary.ncol; icol ++) |
| 3058 | if (support [icol]) |
| 3059 | sum += dictionary [irow] [icol] * gradient [icol]; |
| 3060 | normsq_dgs += sum * sum; |
| 3061 | } |
| 3062 | |
| 3063 | double stepSize = normsq_gs / normsq_dgs; |
| 3064 | |
| 3065 | double normsq_ratio = update (x_new.get(), yfromx_new.get(), support_new.get(), x, stepSize, gradient.get(), dictionary, yfromx.get(), numberOfNonZeros, buffer.get()); |
| 3066 | |
| 3067 | if (! NUMequal (support.get(), support_new.get())) { |
| 3068 | double omega; |
| 3069 | const double kappa = 2.0, c = 0.0; |
| 3070 | while (stepSize > (omega = (1.0 - c) * normsq_ratio)) { // stepSize > omega, from Eq. 14 |
| 3071 | stepSize *= 1.0 / (kappa * (1.0 - c)); |
| 3072 | normsq_ratio = update (x_new.get(), yfromx_new.get(), support_new.get(), x, stepSize, gradient.get(), dictionary, yfromx.get(), numberOfNonZeros, buffer.get()); |
| 3073 | } |
| 3074 | } |
| 3075 | |
| 3076 | ydif.all() <<= y - yfromx_new.all(); // y - D.x(n+1) |
| 3077 | |
| 3078 | const double rms_new = NUMsum2 (ydif.get()) / y.size; |
| 3079 | const double relativeError = fabs (rms - rms_new) / rms_y; |
| 3080 | convergence = relativeError < tolerance; |
| 3081 | if (infoLevel > 1) |
| 3082 | MelderInfo_writeLine (U"\t\tIteration: ", iter, U", error: ", rms_new, U" relative: ", relativeError, U" stepSize: ", stepSize); |
| 3083 | |
| 3084 | x <<= x_new.all(); |
| 3085 | support.all() <<= support_new.all(); |
| 3086 | yfromx.all() <<= yfromx_new.all(); |
| 3087 | rms = rms_new; |
| 3088 | iter ++; |
| 3089 | } |
| 3090 | iter = std::min (iter, maximumNumberOfIterations); |
| 3091 | if (infoLevel >= 1) |
| 3092 | MelderInfo_writeLine (U"\t\tNumber of iterations: ", iter, U" Difference squared: ", rms); |
| 3093 | if (infoLevel > 0) |
| 3094 | MelderInfo_drain(); |
| 3095 | } catch (MelderError) { |
| 3096 | Melder_throw (U"Solution of sparse problem not found."); |
| 3097 | } |
| 3098 | } |
| 3099 | |
| 3100 | void NUMpolynomial_recurrence (VEC const& pn, double a, double b, double c, constVEC const& pnm1, constVEC const& pnm2) { |
| 3101 | const integer degree = pn.size - 1; |
| 3102 | Melder_assert (degree > 1 && pnm1.size >= pn.size && pnm2.size >= pn.size); |
| 3103 | |
| 3104 | pn [1] = b * pnm1 [1] + c * pnm2 [1]; |
| 3105 | for (integer i = 2; i <= degree - 1; i ++) |
| 3106 | pn [i] = a * pnm1 [i - 1] + b * pnm1 [i] + c * pnm2 [i]; |
| 3107 | pn [degree] = a * pnm1 [degree - 1] + b * pnm1 [degree]; |
| 3108 | pn [degree + 1] = a * pnm1 [degree]; |
| 3109 | } |
| 3110 | |
| 3111 | /* End of file NUM2.cpp */ |