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