Debian Codegraph @

dwsys/NUM2.h

raw symbols SCIP
1 #ifndef _NUM2_h_
2 #define _NUM2_h_
3 /* NUM2.h
4 *
5 * Copyright (C) 1997-2025, 2026 David Weenink
6 *
7 * This code is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or (at
10 * your option) any later version.
11 *
12 * This code is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this work. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "ExtendedReal.h"
22 #include "MAT_numerics.h"
23 #include "NUMsorting.h"
24 #include "NUMFourier.h"
25
26 /*
27 A typical iteration goes like
28 do {
29 previous is ...
30 get value of current
31 while (fabs (current - previous) > fabs (NUMeps * current);
32 Because of floating point arithmetic we have a rounding differences which are large or equal to the
33 machine precision eps = 2.2...e-16. To have an escape if fabs (current - previous) e<= eps we choose
34 NUMeps just a little larger than eps.
35 */
36 #define NUMeps 2.3e-16
37
38 int NUMcompareTwoIntegers (integer& a, integer& b);
39 int NUMcompareTwoDoubles (double& a, double& b);
40 /*
41 return a < b ? -1 : a > b ? 1 : 0;
42 */
43
44 /*
45 only used to append the time info to the name of an object.
46 1.2345678 -> 1_2345678
47 1.2 -> 1_2
48 2 -> 2
49 */
50 char32 * NUMnumber_as_stringWithDotReplacedByUnderscore (double time);
51
52 regexp *NUMregexp_compile (conststring32 regexp);
53 /* Compiles a regular expression to a datastructure used by the regexp engine */
54
55 char32 *strstr_regexp (conststring32 string, conststring32 search_regexp);
56 /*
57 Returns a pointer to the first occurrence in 'string' of the
58 regular expression 'searchRE'. It returns a null pointer if
59 no match is found.
60 */
61
62 inline integer isqrt_roundUp (double number) {
63 return ceil (sqrt (number));
64 }
65
66 autoSTRVEC string32vector_searchAndReplace (constSTRVEC me,
67 conststring32 search, conststring32 replace, integer maximumNumberOfReplaces,
68 integer *nmatches, integer *nstringmatches, bool use_regexp);
69 /*
70 Searches and replaces in string array of strings.
71 If use_regexp != 0, 'search' and 'replace' will be interpreted
72 as regular expressions. Else these strings are taken literally.
73
74 'maximumNumberOfReplaces' is the maximum number of replaces in EACH string
75 in the array of strings (you can replace ALL occurrences by making this
76 number <= 0).
77 The totalnumber of matches found is returned in 'nmatches'.
78 The number of strings with at least one match is returned in
79 'nstringmatches'.
80 */
81
82 void MATprintMatlabForm (constMATVU const& m, conststring32 name);
83 /*
84 Print a matrix in a form that can be used as input for octave/matlab.
85 1 2 3
86 Let A be the matrix: 4 5 6
87 7 8 9
88 The output from MATprintMatlabForm (A, "M") will be
89 M= [1, 2, 3;
90 4, 5, 6;
91 7, 8, 9];
92 */
93
94 inline bool NUMisNonNegative (constVECVU const& vec) {
95 for (integer i = 1; i <= vec.size; i ++)
96 if (vec [i] < 0.0)
97 return false;
98 return true;
99 }
100 inline bool NUMisNonNegative (constMATVU const& mat) {
101 for (integer irow = 1; irow <= mat.nrow; irow ++)
102 for (integer icol = 1; icol <= mat.ncol; icol ++)
103 if (mat [irow] [icol] < 0.0)
104 return false;
105 return true;
106 }
107
108 inline integer NUMmaxPos (constVECVU const& v) {
109 if (NUMisEmpty (v)) return 0;
110 integer index = 1;
111 double maximum = v [1];
112 for (integer i = 2; i <= v.size; i ++) {
113 if (v [i] > maximum) {
114 maximum = v [i];
115 index = i;
116 }
117 }
118 return index;
119 }
120
121 #if 0
122 template <typename T>
123 inline T NUMmaxPos (constvectorview<T> const& v) {
124 if (NUMisEmpty (v)) return 0;
125 integer index = 1;
126 T maximum = v [1];
127 for (integer i = 2; i <= v.size; i ++) {
128 if (v [i] > maximum) {
129 maximum = v [i];
130 index = i;
131 }
132 }
133 return index;
134 }
135 #endif
136
137 inline integer NUMmaxPos (constINTVECVU const& v) {
138 if (NUMisEmpty (v)) return 0;
139 integer index = 1;
140 integer maximum = v [1];
141 for (integer i = 2; i <= v.size; i ++) {
142 if (v [i] > maximum) {
143 maximum = v [i];
144 index = i;
145 }
146 }
147 return index;
148 }
149
150 inline integer NUMminPos (constVECVU const& v) {
151 if (NUMisEmpty (v)) return 0;
152 integer index = 1;
153 double minimum = v [1];
154 for (integer i = 2; i <= v.size; i ++) {
155 if (v [i] < minimum) {
156 minimum = v [i];
157 index = i;
158 }
159 }
160 return index;
161 }
162
163 inline integer NUMminPos (constINTVECVU const& v) {
164 if (NUMisEmpty (v))
165 return 0;
166 integer index = 1;
167 integer minimum = v [1];
168 for (integer i = 2; i <= v.size; i ++) {
169 if (v [i] < minimum) {
170 minimum = v [i];
171 index = i;
172 }
173 }
174 return index;
175 }
176
177 inline void NUMextrema_e (constVECVU const& x, double *out_minimum, double *out_maximum) {
178 if (out_minimum)
179 *out_minimum = NUMmin_e (x);
180 if (out_maximum)
181 *out_maximum = NUMmax_e (x);
182 }
183
184 inline void NUMextrema_u (constVECVU const& x, double *out_minimum, double *out_maximum) {
185 if (out_minimum)
186 *out_minimum = NUMmin_u (x);
187 if (out_maximum)
188 *out_maximum = NUMmax_u (x);
189 }
190
191 /*
192 Clip array values.
193 c [i] = c [i] < min ? min : (c [i] > max ? max : c [i])
194 */
195 inline void VECclip_inplace (double min, VECVU const& x, double max) {
196 for (integer i = 1; i <= x.size; i ++)
197 Melder_clip (min, & x [i], max);
198 }
199
200 inline bool NUMhasZeroElement (constMATVU const m) {
201 for (integer irow = 1; irow <= m.nrow; irow ++)
202 for (integer icol = 1; icol <= m.ncol; icol++)
203 if (m [irow] [icol] == 0.0)
204 return true;
205 return false;
206 }
207
208 inline integer NUMcountNumberOfNonZeroElements (constVECVU const& v) {
209 integer count = 0;
210 for (integer i = 1; i <= v.size; i ++)
211 if (v [i] != 0.0)
212 ++ count;
213 return count;
214 }
215
216 inline double NUMmul (constVECVU const& x, constMATVU const& m, constVECVU const& y) { // x'. M . y
217 Melder_assert (x.size == m.nrow);
218 Melder_assert (y.size == m.ncol);
219 longdouble result = 0.0;
220 for (integer k = 1; k <= x.size; k ++)
221 result += x [k] * NUMinner (m.row (k), y);
222 return (double) result;
223 }
224
225 inline autoVEC VECnorm_rows (constMATVU const& x, double power) {
226 autoVEC norm = raw_VEC (x.nrow);
227 for (integer irow = 1; irow <= norm.size; irow ++)
228 norm [irow] = NUMnorm (x.row (irow), power);
229 return norm;
230 }
231
232 inline void VECnormalize_inplace (VECVU const& vec, double power, double newNorm) {
233 Melder_assert (newNorm > 0.0);
234 double oldnorm = NUMnorm (vec, power);
235 if (oldnorm > 0.0)
236 vec *= newNorm / oldnorm;
237 }
238
239 inline void MATnormalize_inplace (MATVU const& mat, double power, double newNorm) {
240 Melder_assert (newNorm > 0.0);
241 double oldnorm = NUMnorm (mat, power);
242 if (oldnorm > 0.0)
243 mat *= newNorm / oldnorm;
244 }
245
246 inline void MATnormalizeRows_inplace (MATVU const& a, double power, double norm) {
247 Melder_assert (norm > 0.0);
248 for (integer irow = 1; irow <= a.nrow; irow ++)
249 VECnormalize_inplace (a.row (irow), power, norm);
250 }
251
252 inline void MATnormalizeColumns_inplace (MATVU const& a, double power, double norm) {
253 MATnormalizeRows_inplace (a.transpose(), power, norm);
254 }
255 /*
256 Scale a [.] [j] such that sqrt (Sum(a [i] [j]^2, i=1..nPoints)) = norm.
257 */
258
259 void VECsmoothByMovingAverage_preallocated (VECVU const& out, constVECVU const& in, integer window);
260
261 autoMAT MATcovarianceFromColumnCentredMatrix (constMATVU const& x, integer ndf);
262 /*
263 Calculate covariance matrix(ncols x ncols) from data matrix (nrows x ncols);
264 The matrix x must be column centered.
265 covar [i] [j] = sum (k=1..nrows, x [i] [k] * x [k] [j]) / (nrows - ndf)
266 */
267
268 void MATmtm_weighRows (MATVU const& result, constMATVU const& data, constVECVU const& rowWeights);
269
270 inline autoMAT newMATmtm_weighRows (constMATVU const& data, constVECVU const& rowWeights) {
271 autoMAT result = raw_MAT (data.ncol, data.ncol);
272 MATmtm_weighRows (result.get(), data, rowWeights);
273 return result;
274 }
275
276 double NUMmultivariateKurtosis (constMATVU const& x, integer method);
277 /*
278 calculate multivariate kurtosis.
279 method = 1 : Schott (2001), J. of Statistical planning and Inference 94, 25-36.
280 */
281
282 void NUMmad (constVEC x, double *inout_location, bool wantlocation, double *out_mad, VEC const& workSpace);
283 /*
284 Computes the median absolute deviation, i.e., the median of the
285 absolute deviations from the median, and adjust by a factor for
286 asymptotically normal consistency, i.e. the returned value is 1.4826*mad which
287 makes the returned value "equal" to the standard deviation if the data is normally distributed.
288 You either GIVE the median location (if wantlocation = false) or it
289 will be calculated (if wantlocation = true);
290
291 Precondition: workSpace.size >= x.size
292 */
293
294 void NUMstatistics_huber (constVEC x, double *inout_location, bool wantlocation, double *inout_scale, bool wantscale, double k_stdev, double tol, integer maximumNumberOfiterations, VEC const& workSpace);
295 /*
296 Finds the Huber M-estimator for location with scale specified,
297 scale with location specified, or both if neither is specified.
298 k_stdev Winsorizes at `k_stdev' standard deviations.
299
300 Precondition: workSpace.size >= x.size
301 */
302
303 autoVEC newVECmonotoneRegression (constVEC x);
304 /*
305 Find numbers xs [1..n] that have a monotone relationship with
306 the numbers in x [1..n].
307 The xs [i] will be ascending.
308 */
309
310 autoMAT newMATlowerCholeslyInverse_fromLowerCholesky (constMAT const& m);
311
312 /*
313 Pre: matrices must be square.
314 */
315 autoMAT newMATsymmetricPositiveDefinte_inverse (constMAT m);
316 autoMAT newMATsymmetric_inverse (constMAT m);
317 autoMAT newMATinverse (constMAT m);
318
319 void MATlowerCholesky_inplace (MAT a, double *out_lnd);
320
321 autoMAT newMATlowerCholesky (constMATVU const& a, double *out_lnd);
322
323 void MATlowerCholeskyInverse_inplace (MAT a, double *out_lnd);
324
325 inline autoMAT newMATlowerCholeskyInverse (constMAT const& a) {
326 autoMAT result = copy_MAT (a);
327 MATlowerCholeskyInverse_inplace (result.get(), nullptr);
328 return result;
329 }
330 /*
331 Calculates L^-1, where A = L.L' is a symmetric positive definite matrix
332 and ln(determinant). L^-1 in lower, leave upper part intact.
333 */
334
335 autoMAT newMATinverse_fromLowerCholeskyInverse (constMAT m);
336 /*
337 Return the complete matrix inverse when only the inverse of the lower Cholesky part is given.
338 Input m is a square matrix, in the lower part is the inverse of the lower Cholesky part as calculated by NUMlowerCholeskyInverse.
339 */
340
341 double NUMdeterminant_fromSymmetricMatrix (constMAT m);
342 /*
343 ln(determinant) of a symmetric p.s.d. matrix
344 */
345
346 double NUMmahalanobisDistanceSquared (constMAT lowerInverse, constVEC v, constVEC m);
347 /*
348 Calculates squared Mahalanobis distance: (v-m)'S^-1(v-m).
349 Input matrix is the inverse L^-1 of the Cholesky decomposition S = L.L'
350 as calculated by NUMlowerCholeskyInverse or 1-row for a diagonal matrix (nr =1)
351 Mahalanobis distance calculation. S = L.L' -> S**-1 = L**-1' . L**-1
352 (x-m)'S**-1 (x-m) = (x-m)'L**-1' . L**-1. (x-m) =
353 (L**-1.(x-m))' . (L**-1.(x-m))
354 */
355
356 double NUMtrace (constMATVU const& a);
357 double NUMtrace2 (constMATVU const& x, constMATVU const& y);
358 /*
359 Calculates the trace from a product matrix x*y
360 */
361
362 void MATprojectColumnsOnEigenspace_preallocated (MAT projection, constMATVU const& data, constMATVU const& eigenvectors);
363 /* Input:
364 data [dimension, numberOfColumns]
365 contains the column vectors to be projected on the eigenspace.
366 eigenvectors [numberOfEigenvectors] [dimension]
367 the eigenvectors stored as rowvectors
368 Input/Output
369 projection [numberOfEigenvectors, numberOfColumns]
370 the projected vectors from 'data'
371
372 Project the columnvectors in matrix 'data' along the 'numberOfEigenvectors' eigenvectors into the matrix 'projection'.
373 */
374
375
376 double VECdominantEigenvector_inplace (VEC inout_q, constMAT m, double tolerance);
377 /*
378 Determines the first dominant eigenvector from a square GENERAL matrix m.
379 Besides the matrix m, a first guess for the eigenvector q must
380 be supplied (e.g. 1,0,...,0) and a value for tolerance (iteration
381 stops when fabs(lamda [k] - lambda [k-1]) <= tolerance, where lamda [k] is
382 the eigenvalue at the k-th iteration step.
383 The methos is described in:
384 G. Golub & C. van Loan (1996), Matrix computations, third edition,
385 The Johns Hopkins University Press Ltd.,
386 London, (Par. 7.3.1 The Power Method)
387 */
388
389 integer NUMsolveQuadraticEquation (double a, double b, double c, double *x1, double *x2);
390 /*
391 Finds the real roots of ax^2 + bx + c = 0.
392 The number of real roots is returned and their locations in x1 and x2.
393 If only one root found it is stored in x1.
394 If no roots found then x1 and x2 will not be changed.
395 */
396
397 autoVEC solve_VEC (constMATVU const& a, constVECVU const& b, double tol);
398 /*
399 Solve the equation: A.x = b for x;
400 a [1..nr] [1..nc], b [1..nr] and the unknown x [1..nc]
401 Algorithm: s.v.d.
402 */
403
404 autoMAT solve_MAT (constMATVU const& a, constMATVU const& b, double tol);
405 /*
406 Solve the equations: A.X = B;
407 a [1..nr] [1..nc], b [1..nr] [1..nc2] and the unknown x [1..nc] [1..nc2]
408 Algorithm: s.v.d.
409 */
410
411
412 /*
413 Solve y = D.x + e for x, where x is sparse and e is observation noise.
414 Minimize the 2-norm (y - D.x), where maximally K elements of x may be non-zero, by an iterative hard thresholding algorithm.
415 D is a MxN real matrix with (many) more columns than rows, i.e. N > M. We need to find a vector x
416 with maximally K non-zero elements (sparse).
417 The algorithm is described in T. Blumensath & M.E. Davies (2010): "Normalised iterative hard thresholding;
418 guaranteed stability and performance", IEEE Journal of Selected Topics in Signal Processing #4: 298-309.
419 x in/out: the start value (you typically would start the iteration with all zeros).
420 */
421 void VECsolveSparse_IHT (VECVU const& x, constMATVU const& d, constVECVU const& y, integer numberOfNonZeros, integer maximumNumberOfIterations, double tolerance, integer infoLevel);
422 autoVEC solveSparse_IHT_VEC (constMATVU const& d, constVECVU const& y, integer numberOfNonZeros, integer maximumNumberOfIterations, double tolerance, integer infoLevel);
423
424 void VECsolveNonnegativeLeastSquaresRegression (VECVU const& result, constMATVU const& m, constVECVU const& y, integer itermax, double tol, integer infoLevel);
425
426 inline autoVEC solveNonnegativeLeastSquaresRegression_VEC (constMATVU const& a, constVECVU const& y, integer itermax, double tol, integer infoLevel) {
427 autoVEC result = zero_VEC (a.ncol);
428 VECsolveNonnegativeLeastSquaresRegression (result.get(), a, y, itermax, tol, infoLevel);
429 return result;
430 }
431 /*
432 Solve the equation: A.x = y for x under the constraint: all x [i] >= 0;
433 a [1..nr][1..nc], y [1..nr] and x [1..nc].
434 Algorithm: Alternating least squares.
435 Borg & Groenen (1997), Modern multidimensional scaling, Springer, page 180.
436 */
437
438 void NUMsolveConstrainedLSQuadraticRegression (constMAT const& x, constVEC const& y, double *out_alpha, double *out_gamma);
439 /*
440 Solve y [i] = alpha + beta * x [i] + gamma * x [i]^2, with i = 1..n,
441 subject to the constraint beta^2 = 4 * alpha * gamma, for alpha and
442 gamma (Least Squares).
443 The input Vandermonde-matrix o [1..n,1..3] has columns with 1, x [i] and
444 x [i]^2, respectively.
445 The algorithm is according to:
446 Jos M.F. Ten Berge (1983), A generalization of Verhelst's solution for
447 a constrained regression problem in ALSCAL and related MDS-algorithms,
448 Psychometrika 48, 631-638.
449 */
450
451 autoVEC solveWeaklyConstrainedLinearRegression_VEC (constMAT const& a, constVEC const& y, double alpha, double delta);
452 /*
453 Solve g(x) = ||A*x - y||^2 + alpha (x'*x - delta)^2 for x [1..m],
454 where A [1..n] [1..m] is a matrix, y [1..n] a given vector, and alpha
455 and delta are fixed numbers.
456 This class of functions is composed of a linear regression function and
457 a penalty function for the sum of squared regression weights. It is weakly
458 constrained because the penalty function prohibits a relatively large
459 departure of x'x from delta.
460 The solution is due to:
461 Jos M.F. ten Berge (1991), A general solution for a class of weakly
462 constrained linear regression problems, Psychometrika 56, 601-609.
463 Preconditions:
464 a.nrow >= a.ncol
465 alpha >= 0
466 */
467
468 void NUMprocrustes (constMATVU const& x, constMATVU const& y, autoMAT *out_rotation, autoVEC *out_translation, double *out_scale);
469 /*
470 Given two configurations x and y (nPoints x nDimensions), find the
471 the Procrustes rotation/reflection matrix T, the translation vector v and the scaling
472 factor s such that Y = sXT+1v' (1 is the nPoints vector with ones).
473 Solution: see Borg and Groenen (1997), Modern Multidimensional Scaling, pp 340-346.
474 When out_translation == nullptr or out_scale == nullptr, only the matrix T will be solved for:
475 the orthogonal Procrustes transform.
476 */
477
478 double NUMnrbis (double (*f)(double x, double *dfx, void *closure), double xmin, double xmax, void *closure);
479 /*
480 Find the root of a function between xmin and xmax.
481 Method: Newton-Raphson with bisection (i.e., derivative is known!).
482 Error condition:
483 return undefined if root not bracketed.
484 */
485
486 double NUMridders (double (*f) (double x, void *closure), double xmin, double xmax, void *closure);
487 /*
488 Return the root of a function f bracketed in [xmin, xmax].
489 Error condition:
490 root not bracketed.
491 */
492
493 double NUMmspline (constVEC const & knot, integer order, integer i, double x);
494 /*
495 Calculates an M-spline for a knot sequence.
496 After Ramsay (1988), Monotone splines in action, Statistical Science 4.
497
498 M-splines of order k have degree k-1.
499 M-splines are zero outside interval [ knot [i], knot [i+order] ).
500 First and last 'order' knots are equal, i.e.,
501 knot [1] = ... = knot [order] && knot [nKnots-order+1] = ... knot [nKnots].
502 Error condition: no memory.
503 */
504
505 double NUMispline (constVEC const & aknot, integer order, integer i, double x);
506 /*
507 Calculates an I-spline for simple knot sequences: only one knot at each
508 interior boundary.
509 After Ramsay (1988), Monotone splines in action, Statistical Science 4.
510
511 I-splines of order k have degree k (because they Integrate an M-spline
512 of degree k-1).
513 In the calculation of the integral of M(x|k,t), M-splines are used that
514 have two more knots, i.e., M(x|k+1,t). For reasons of efficiency we
515 demand that these extra knots are given, i.e., the 'aknot []' argument
516 contains the knot positions as if the spline to be integrated were an
517 M(x|k+1,t) spline.
518 knot [1] = ... = knot [order+1] && knot [nKnots-order] = ... knot [nKnots]
519 Error condition: no memory.
520 */
521
522 double NUMwilksLambda (constVEC const& lambda, integer from, integer to);
523 /*
524 Calculate: Product (i=from..to; 1/(1+lambda [i]))
525 Preconditions: to >= from
526 */
527
528 double NUMlnBeta (double a, double b);
529 /*
530 Computes the logarithm of the beta function log(B(a,b) subject to
531 a and b not being negative integers.
532 */
533
534 double NUMbeta2 (double z, double w);//temporarily
535
536 double NUMbetaContinuedFraction(double a, double b, double x);
537
538 double NUMfactln (integer n);
539 /* Returns ln (n!) */
540
541 void NUMlngamma_complex (double zr, double zi, double *out_lnr, double *out_arg);
542 /* Log [Gamma(z)] for z complex, z not a negative integer
543 * Uses complex Lanczos method. Note that the phase part (arg)
544 * is not well-determined when |z| is very large, due
545 * to inevitable roundoff in restricting to (-pi, pi].
546 * The absolute value part (lnr), however, never suffers.
547 *
548 * Calculates:
549 * lnr = log|Gamma(z)|
550 * arg = arg(Gamma(z)) in (-Pi, Pi]
551 */
552
553 /***** STATISTICS: PROBABILITY DENSITY FUNCTIONS ********************/
554
555 double NUMlogNormalP (double x, double zeta, double sigma);
556 /* Area under log normal from 0 to x */
557
558 double NUMlogNormalQ (double x, double zeta, double sigma);
559 /* Area under log normal from x to +infinity */
560
561 double NUMstudentP (double t, double df);
562 /*
563 The area under the student T-distribution from -infinity to t.
564 Precondition: df > 0
565 */
566
567 double NUMstudentQ (double t, double df);
568 /*
569 The area under the student T distribution from t to +infinity.
570 Precondition: df > 0
571 */
572
573 double NUMfisherP (double f, double df1, double df2);
574 /*
575 The area under Fisher's F-distribution from 0 to f
576 Preconditions: f >= 0, df1 > 0, df2 > 0
577 */
578
579 double NUMfisherQ (double f, double df1, double df2);
580 /*
581 The area under Fisher's F-distribution from f to +infinity
582 Preconditions: f >= 0, df1 > 0, df2 > 0
583 */
584
585 double NUMinvGaussQ (double p);
586 /*
587 Solves NUMgaussQ (x) == p for x, given p.
588 Precondition: 0 < p < 1
589 Method: Abramovitz & Stegun 26.2.23
590 Precision: |eps(p)| < 4.5 10^-4
591 */
592
593 double NUMinvChiSquareQ (double p, double df);
594 /*
595 Solves NUMchiSquareQ (chiSquare, df) == p for chiSquare, given p, df.
596 Preconditions: 0 < p < 1, df > 0
597 */
598
599 double NUMinvStudentQ (double p, double df);
600 /*
601 Solves NUMstudentQ (t, df) == p for t, given p, df.
602 Preconditions: 0 < p < 1, df > 0
603 */
604
605 double NUMinvFisherQ (double p, double df1, double df2);
606 /*
607 Solves NUMfisherQ (f, df1, df2) == p for f, given p, df1, df2
608 Precondition: 0 < p < 1
609 */
610
611 double NUMtukeyQ (double q, double cc, double df, double rr);
612 /* Computes the probability that the maximum of rr studentized
613 * ranges, each based on cc means and with df degrees of freedom
614 * for the standard error, is larger than q.
615 */
616
617 double NUMinvTukeyQ (double p, double cc, double df, double rr);
618 /* Solves NUMtukeyQ (q, rr, cc, df) == p for q given p, rr, cc and df.
619 * Computes the quantiles of the maximum of rr studentized
620 * ranges, each based on cc means and with df degrees of freedom
621 * for the standard error, is larger than q.
622 * p = probability (alpha)
623 * rr = no. of rows or groups
624 * cc = no. of columns or treatments
625 * df = degrees of freedom of error term
626 */
627
628
629 /****** Frequency in Hz to other frequency reps ****/
630
631 double NUMmelToHertz2 (double mel);
632 /*
633 Return 700 * (pow (10.0, mel / 2595.0) - 1)
634 */
635
636 double NUMhertzToMel2 (double f);
637 /*
638 Return 2595 * log10 (1 + f/700)
639 */
640
641 double NUMmelToHertz3 (double mel);
642 /*
643 Return mel < 1000 ? mel : 1000 * (exp (mel * log10(2) / 1000) - 1)
644 */
645
646 double NUMhertzToMel3 (double hz);
647 /*
648 Return hz < 1000 ? hz : 1000 * log10 (1 + hz / 1000) / log10 (2)
649 */
650
651 double NUMbarkToHertz2 (double bark);
652 /*
653 Return 650 * sinh (bark / 7)
654 */
655
656 double NUMhertzToBark2 (double hz);
657 /*
658 Return 7 * ln (hz / 650 + sqrt(1 + (hz / 650)^2))
659 */
660
661 double NUMhertzToBark_traunmueller (double hz);
662 /*
663 return 26.81 * hz /(1960 + hz) -0.53;
664 */
665
666 double NUMbarkToHertz_traunmueller (double bark);
667 /*
668 return 1960* (bark + 0.53) / (26.28 - bark);
669 */
670
671 double NUMbarkToHertz_zwickerterhardt (double hz);
672 /*
673 return 13 * atan (0.00076 * hz) + 3.5 * atan (hz / 7500);
674 */
675
676 double NUMbladonlindblomfilter_amplitude (double zc, double z);
677 /*
678 Amplitude of filter at dz (barks) from centre frequency.
679 dz may be positive and negative.
680
681 The bladonlindblomfilter function is:
682
683 z' = zc - z + 0.474
684 10 log10 F(z') = 15.81 + 7.5 z' - 17.5 sqrt( 1 + z'^2 )
685
686 Reference: Bladon, R.A.W & Lindblom, B., (1980),
687 "Modeling the judgment of vowel quality differences", JASA 69, 1414-1422.
688 The filter has a bandwidth of 1.43 Bark, the maximum occurs at z = zc,
689 and the slopes are -10 dB/Bark and +25 dB/Bark.
690 */
691
692 double NUMsekeyhansonfilter_amplitude (double zc, double z);
693 /*
694 Amplitude of filter at dz (barks) from centre frequency.
695 dz may be positive and negative.
696
697 The sekeyhansonfilter function is:
698 z' = zc - z - 0.215
699 10 log10 F(z') = 7 - 7.5 * z' - 17.5 * sqrt( 0.196 + z'^2 )
700
701 Reference: Sekey, A. & Hanson, B.A. (1984),
702 "Improved 1-Bark bandwidth auditory filter", JASA 75, 1902-1904.
703 The filter function has a bandwidth of 1 Bark, the maximum response
704 occurs at z=zc, and the slopes are +10 dB/Bark and -25 dB/Bark.
705 It is an improved version of bladonlindblomfilter.
706 */
707
708 double NUMtriangularfilter_amplitude (double fl, double fc, double fh,
709 double f);
710 /*
711 Filterfunction that intermediates in Mel frequency cepstral coefficients
712 calculation.
713 The filter function is
714
715 (f-fl)/(fc-fl) fl < f < fc
716 H(z) = (fh-f)/(fh-fc) fc < f < fh
717 0 otherwise
718 Preconditions:
719 0 < fl < fh
720 */
721
722 double NUMformantfilter_amplitude (double fc, double bw, double f);
723 /*
724 Filterfunction with a formant-like shape on a linear freq. scale.
725
726 H(f) = 1.0 / (dq * dq + 1.0), where
727 dq = (fc * fc - f * f) / (bw * f)
728 Preconditions: f > 0 && bw > 0
729 */
730
731 double VECburg (VEC const& a, constVEC const& x);
732 /*
733 Calculates linear prediction coefficients according to the algorithm
734 from J.P. Burg as described by N.Anderson in Childers, D. (ed), Modern
735 Spectrum Analysis, IEEE Press, 1978, 252-255.
736 Returns the sum of squared sample values or 0.0 if failure
737 */
738
739 autoVEC newVECburg (constVEC const& x, integer numberOfPredictionCoefficients, double *out_xms);
740
741 /*
742 assertion: filtermemory.size >= filter.size
743 */
744 void VECfilterInverse_inplace (VEC const& s, constVEC const& filter, VEC const& filterMemory);
745
746 void NUMdmatrix_to_dBs (MAT const& m, double ref, double factor, double floor);
747 /*
748 Transforms the values in the matrix m [rb..re] [cb..ce] to dB's
749
750 m [i] [j] = factor * 10 * log10 (m [i] [j] / ref)
751 if (m [i] [j] < floor) m [i] [j] = floor;
752
753 Preconditions:
754 rb <= re
755 cb <= ce
756 ref > 0
757 factor > 0
758 Errors:
759 Matrix elements < 0;
760 */
761
762 autoMAT MATcosinesTable (integer n);
763 /*
764 Generate table with cosines.
765
766 result [i] [j] = cos (i * pi * (j - 1/2) / npoints)
767 */
768 void VECcosineTransform_preallocated (VEC const& target, constVEC const& x, constMAT const& cosinesTable);
769 void VECinverseCosineTransform_preallocated (VEC const& target, constVEC const& x, constMAT const& cosinesTable);
770
771 /****** Interpolation ****/
772
773 void NUMcubicSplineInterpolation_getSecondDerivatives (VEC const& out_y, constVEC const& x, constVEC const& y, double yp1, double ypn);
774 /*
775 Given arrays x [1..n] and y [1..n] containing a tabulated function, i.e.,
776 y [i] = f(x [i]), with x [1] < x [2] < ... < x [n], and given values yp1 and
777 ypn for the first derivative of the interpolating function at point
778 1 and n, respectively, this routine returns an array out_y [1..n] that
779 contains the second derivative of the interpolating function at the
780 tabulated point x.
781 If yp1 and/or ypn are >= 10^30, the routine is signaled to
782 set the corresponding boundary condition for a natural spline, with
783 zero second derivative on that boundary.
784 */
785
786 double NUMcubicSplineInterpolation (constVEC const& xa, constVEC const& ya, constVEC const& y2a, double x);
787 /*
788 Given arrays xa [1..n] and ya [1..n] containing a tabulated function,
789 i.e., y [i] = f(x [i]), with x [1] < x [2] < ... < x [n], and given the
790 array y2a [1..n] which is the output of NUMcubicSplineInterpolation_getSecondDerivatives above, and given
791 a value of x, this routine returns an interpolated value y.
792 */
793
794 autoVEC newVECbiharmonic2DSplineInterpolation_getWeights (constVECVU const& x, constVECVU const& y, constVECVU const& w);
795 /*
796 Input: x [1..numberOfPoints], y [1..numberOfPoints], (xp,yp)
797 Output: interpolated result
798 */
799
800 double NUMbiharmonic2DSplineInterpolation (constVECVU const& x, constVECVU const& y, constVECVU const& w, double xp, double yp);
801 /* Biharmonic spline interpolation based on Green's function.
802 . Given z [i] values at points (x [i],y [i]) for i=1..n,
803 Get value at new point (px,py).
804 1. Calculate weights w once: newVECbiharmonic2DSplineInterpolation_getWeights
805 2. Interpolate at (xp,yp): NUMbiharmonic2DSplineInterpolation
806 Input: x [1..numberOfPoints], y [1..numberOfPoints], z [1..numberOfPoints], weights [1..numberOfPoints]
807 Output: weights [1..numberOfPoints]
808
809 Preconditions: all x [i] are different and all y [i] are different.
810
811 This routine inializes the numberOfPoints weigts by inverting a numberOfPoints x numberOfPoints matrix.
812 D. Sandwell (1987), Biharmonic spline interpolation of GEOS-3 and SEASAT altimetr data, Geophysical Research Letters 14, 139--142
813 X. Deng & Z. Tang (2011), Moving surface spline interpolation based on Green's function, Math. Geosci 43: 663--680
814 */
815
816
817 double NUMsincpi (const double x);
818 /* Calculates sin(pi*x)/(pi*x) */
819 double NUMsinc (const double x);
820 /* Calculates sin(x)/(x) */
821
822 /*********************** Geometry *************************************/
823
824 integer NUMgetOrientationOfPoints (double x1, double y1, double x2, double y2, double x3, double y3);
825 /* Traverse points 1, 2 and 3. If we travel counter-clockwise the result will be 1,
826 if we travel clockwise the result will be -1 and the result will be 0 if 3 is on the line segment between 1 and 2.
827 J. O'Rourke: Computational Geometry, 2nd Edition, Code 1.5
828 */
829
830 bool NUMdoLineSegmentsIntersect (double x1, double y1, double x2, double y2, double x3, double y3,
831 double x4, double y4);
832 /* Does the line segment from (x1,y1) to (x2,y2) intersect with the line segment from (x3,y3) to (x4,y4)? */
833
834 integer NUMgetIntersectionsWithRectangle (double x1, double y1, double x2, double y2,
835 double xmin, double ymin, double xmax, double ymax, double *xi, double *yi);
836 /* Get the intersection points of the line through the points (x1,y1) and (x2,y2) with the
837 rectangle with corners (xmin, ymin) and (xmax,ymax).
838 The returned value is the number of intersections found and is either 0 or 1 or 2.
839 */
840
841 bool NUMclipLineWithinRectangle (double line_x1, double line_y1, double line_x2, double line_y2, double rect_x1, double rect_y1, double rect_x2, double rect_y2, double *out_line_x1, double *out_line_y1, double *out_line_x2, double *out_line_y2);
842 /*
843 If true, then returns in (out_line_x1, out_line_y1) and (out_line_x2, out_line_y2) the coordinates of start and end points of the line (line_x1, line_y1)..(line_x2, line_y2) that can be drawn within the rectangle with lowerleft corner (rect_x1, rect_y1) and upperright (rect_x2, rect_y2).
844 Returns false if there is nothing to be drawn inside.
845 */
846
847 void NUMgetEllipseBoundingBox (double a, double b, double cospsi,
848 double *out_width, double *out_height);
849 /*
850 Get the width and the height of the bonding box around an ellipse.
851 a and b are the lengths of the long axes.
852 cospsi is the cosine of the angle between the a-axis and the horizontal
853 x-axis (cs == 0 when a-axis and x-axis are perpendicular).
854
855 Parametrisation of the ellipse:
856 x(phi) = a cos(psi) cos(phi) - b sin (psi) sin(phi)
857 y(phi) = a sin(psi) cos(phi) + b cos(psi) sin(phi) 0 <= phi <= 2 pi
858 Extrema:
859 d x(phi) / dphi == 0 and d y(phi) / dphi == 0
860 Solution:
861 x(phi1) = a cos(psi) cos(phi1) - b sin (psi) sin(phi1)
862 y(phi2) = a sin(psi) cos(phi2) + b cos(psi) sin(phi2),
863 where
864 phi1 = arctg ( -b/a tg(psi))
865 phi2 = arctg ( b/a cotg(psi))
866 Special cases are psi = 0 and pi /2
867 */
868
869 double NUMminimize_brent (double (*f) (double x, void *closure), double a, double b,
870 void *closure, double tol, double *fx);
871 /*
872 The function returns an estimate for the minimum location with accuracy
873 3 * SQRT_EPSILON * abs(x) + tol.
874 The function always obtains a local minimum which coincides with
875 the global one only if a function under investigation being unimodular.
876 If a function being examined possesses no local minimum within
877 the given range, the function returns 'a' (if f(a) < f(b)), otherwise
878 it returns the right range boundary value b.
879
880 Algorithm
881
882 The function makes use of the golden section procedure combined with
883 parabolic interpolation.
884 At every step, the program operates at three abscissae - x, v, and w.
885 x - the last and the best approximation to the minimum location,
886 i.e. f(x) <= f(a) or/and f(x) <= f(b)
887 (if the function f has a local minimum in (a,b), then both
888 conditions are fulfiled after one or two steps).
889 v, w are previous approximations to the minimum location. They may
890 coincide with a, b, or x (although the algorithm tries to make all
891 u, v, and w distinct). Points x, v, and w are used to construct
892 interpolating parabola whose minimum will be treated as a new
893 approximation to the minimum location if the former falls within
894 [a,b] and reduces the range enveloping minimum more efficient than
895 the golden section procedure.
896 When f(x) has a second derivative positive at the minimum location
897 (not coinciding with a or b) the procedure converges superlinearly
898 at a rate order about 1.324
899 */
900
901 void VECsmooth_gaussian_inplace (VECVU const& in_out, double sigma);
902 void VECsmooth_gaussian_inplace (VECVU const& in_out, double sigma, NUMFourierTable fftTable);
903 void VECsmooth_gaussian (VECVU const& out, constVECVU const& in, double sigma, NUMFourierTable fftTable);
904 /*
905 Smooth the vector 'in/in_out' by convolving with a Gaussian, i.e. convolve with gaussian by
906 using the Fourier Transform. Normally an FFT is used unless otherwise specified in 'fftTable"
907 If fftTable == nullptr the FFT of size 2^k is used, where 2^(k-1) < n <= 2^k.
908 For a given fftTable we require that fftTable->n >= n.
909 */
910
911 integer NUMgetIndexFromProbability (constVEC probs, double p); //TODO HMM zero start matrices
912 integer NUMgetIndexFromProbability (double *probs, integer nprobs, double p);
913
914 // Fit the line y= ax+b
915 void NUMlineFit (constVEC x, constVEC y, double *out_m, double *out_intercept, integer method);
916 /* method
917 * 1 least squares
918 * 2 rubust incomplete Theil O(N/2)
919 * 3 robust complete Theil (very slow for large N, O(N^2))
920 */
921
922 void NUMfitLine_theil_preallocated (VEC const& out_lineParameters, constVEC const& x, constVEC const& y, bool wantIntercept, double oneTailedUnconfidence, bool completeMethod);
923
924 void NUMfitLine_theil (constVEC const& x, constVEC const& y, double *out_m, double *out_intercept, bool completeMethod);
925 /*
926 * Preconditions:
927 * all x [i] should be different, i.e. x [i] != x [j] for all i = 1..(numberOfPoints - 1), j = (i+1) ..numberOfPoints
928 * Algorithm:
929 * Theils robust line fit method:
930 * 1. Use all combination of pairs (x [i],y [i]), (x [j],y [j]) to calculate an intercept m [k] as
931 * m [k] = (y [j] - y [i]) / (x [j] - x [i]).
932 * There will be (numberOfPoints - 1) * numberOfPoints / 2 numbers m [k].
933 * 2. Take the median value m of all the m [k].
934 * 3. Calculate the numberOfPoints intercepts b [i] as b [i] = y [i] - m * x [i]
935 * 4. Take the median value b of all the b [i] values
936 *
937 * If incompleteMethod we use Theil's incomplete method to reduce the number of combinations.
938 * I.e. split the data in two equal parts at n2 = numberOfPoints / 2 and then calculate the numberOfPoints/2 intercepts m [i] as
939 * m [i] = (y [n2+i] - y [i]) / (x [n2 + i] - x [i]).
940 * The rest proceeds as outlined above
941 */
942
943
944 void NUMfitLine_LS (constVEC const& x, constVEC const& y, double *out_m, double *out_intercept);
945
946 /*
947 scale_lambda, shape_k > 0
948 */
949 double NUMrandomWeibull (double scale_lambda, double shape_k);
950
951 /* The binomial distribution has the form,
952
953 f(x) = n!/(x!(n-x)!) * p^x (1-p)^(n-x) for integer 0 <= x <= n
954 = 0 otherwise
955
956 This implementation follows the public domain ranlib function
957 "ignbin", the bulk of which is the BTPE (Binomial Triangle
958 Parallelogram Exponential) algorithm introduced in
959 Kachitvichyanukul and Schmeiser [1]. It has been translated to use
960 modern C coding standards.
961
962 If n is small and/or p is near 0 or near 1 (specifically, if
963 n*min(p,1-p) < SMALL_MEAN), then a different algorithm, called
964 BINV, is used which has an average runtime that scales linearly
965 with n*min(p,1-p).
966
967 But for larger problems, the BTPE algorithm takes the form of two
968 functions b(x) and t(x) -- "bottom" and "top" -- for which b(x) <
969 f(x)/f(M) < t(x), with M = floor(n*p+p). b(x) defines a triangular
970 region, and t(x) includes a parallelogram and two tails. Details
971 (including a nice drawing) are in the paper.
972
973 [1] Kachitvichyanukul, V. and Schmeiser, B. W. Binomial Random
974 Variate Generation. Communications of the ACM, 31, 2 (February,
975 1988) 216.
976
977 Note, Bruce Schmeiser (personal communication) points out that if
978 you want very fast binomial deviates, and you are happy with
979 approximate results, and/or n and n*p are both large, then you can
980 just use gaussian estimates: mean=n*p, variance=n*p*(1-p).
981
982 This implementation by James Theiler, April 2003, after obtaining
983 permission -- and some good advice -- from Drs. Kachitvichyanukul
984 and Schmeiser to use their code as a starting point, and then doing
985 a little bit of tweaking.
986
987 Additional polishing for GSL coding standards by Brian Gough.
988 */
989 integer NUMrandomBinomial (double p, integer n);
990 double NUMrandomBinomial_real (double p, integer n);
991
992 /*
993 Generates random numbers according to a Gamma distribution with shape parameter "alpha"
994 and rate parameter "beta".
995
996 The Gamma distribution of order (shape) parameter alpha and rate (beta) is defined as:
997
998 f(x; alpha, beta) = (1 / Gamma (alpha)) beta^alpha x^(alpha-1) e^(-beta.x),
999 for x > 0, alpha > 0 && beta > 0.
1000
1001 The method is described in
1002 G. Marsaglia & W. Tsang (2000): A simple method for generating gamma variables. ACM Transactions on Mathematical Software, 26(3):363-372.
1003 Preconditions: alpha > 0 && beta > 0.
1004 */
1005 double NUMrandomGamma (const double alpha, const double beta);
1006
1007 // IEEE: Programs for digital signal processing section 4.3 LPTRN (modfied)
1008 // lpc [1..n] to rc [1..n]
1009 void VECrc_from_lpc (VEC rc, constVEC lpc);
1010
1011 // rc [1..n] to area [1..n], implicit: area [n+1] = 0.0001; (1 cm^2)
1012 void VECarea_from_rc (VEC area, constVEC rc);
1013
1014 // area [1..n] to rc [1..n-1] (modification: LPTRN assumes area [n+1])
1015 void VECrc_from_area (VEC rc, constVEC area);
1016
1017 // area [1..n] to lpc [1..n-1]! (modification: lptrn gives lpc [1] = 1 we don't)
1018 void VEClpc_from_area (VEC lpc, constVEC area);
1019
1020 // lpc [1..n] to area [1..n+1], area [m+1] = 0.0001; (1 cm^2)
1021 void VECarea_from_lpc (VEC area, constVEC lpc);
1022 /*
1023 Fix indices to be in the range [lowerLimit, upperLimit].
1024 */
1025 void NUMfixIndicesInRange (integer lowerLimit, integer upperLimit, integer *lowIndex, integer *highIndex);
1026
1027 void NUMgetEntropies (constMATVU const& m, double *out_h, double *out_hx,
1028 double *out_hy, double *out_hygx, double *out_hxgy, double *out_uygx, double *out_uxgy, double *out_uxy);
1029
1030 inline double NUMmean_weighted (constVEC x, constVEC w) {
1031 Melder_assert (x.size == w.size);
1032 double inproduct = NUMinner (x, w);
1033 double wsum = NUMsum (w);
1034 return inproduct / wsum;
1035 }
1036
1037 inline void VECchainRows_preallocated (VECVU const& v, constMATVU const& m) {
1038 Melder_assert (m.nrow * m.ncol == v.size);
1039 integer k = 1;
1040 for (integer irow = 1; irow <= m.nrow; irow ++)
1041 for (integer icol = 1; icol <= m.ncol; icol ++)
1042 v [k ++] = m [irow] [icol];
1043 }
1044
1045 inline autoVEC VECchainRows (constMATVU const& m) {
1046 autoVEC result = raw_VEC (m.nrow * m.ncol);
1047 VECchainRows_preallocated (result.get(), m);
1048 return result;
1049 }
1050
1051 inline void VECchainColumns_preallocated (VEC const& v, constMATVU const& m) {
1052 Melder_assert (m.nrow * m.ncol == v.size);
1053 integer k = 1;
1054 for (integer icol = 1; icol <= m.ncol; icol ++)
1055 for (integer irow = 1; irow <= m.nrow; irow ++)
1056 v [k ++] = m [irow] [icol];
1057 }
1058
1059 inline autoVEC VECchainColumns (constMATVU const& m) {
1060 autoVEC result = raw_VEC (m.nrow * m.ncol);
1061 VECchainColumns_preallocated (result.get(), m);
1062 return result;
1063 }
1064
1065 /* R = X.Y.Z */
1066 void MATmul3 (MATVU const & target, constMATVU const& X, constMATVU const& Y, constMATVU const& Z);
1067
1068 /* Z = X.Y.X' */
1069 void MATmul3_XYXt (MATVU const& target, constMATVU const& X, constMATVU const& Y);
1070
1071 /* Z = X.Y.X where Y is a symmetric matrix */
1072 void MATmul3_XYsXt (MATVU const& target, constMATVU const& X, constMATVU const& Y);
1073
1074 /*
1075 First row (n elements) is at v [1]..v [n],
1076 second row (n-1 elements) is at v [n+1],..,v [n+n-1],
1077 third row (n-2 elements) is at v [n+n],..,v [n+n+n-2]
1078 last row (1 element) is at v [n(n+1)/2].
1079 */
1080 inline void MATfromUpperTriangularVector_preallocated (MAT m, constVEC v) {
1081 Melder_assert (v.size == m.ncol * (m.ncol + 1) / 2);
1082 integer irow = 1;
1083 for (integer inum = 1; inum <= v.size; inum ++) {
1084 integer nskipped = (irow - 1) * irow / 2;
1085 integer inumc = inum + nskipped;
1086 irow = (inumc - 1) / m.ncol + 1;
1087 integer icol = ( (inumc - 1) % m.ncol) + 1;
1088 m [irow] [icol] = m [icol] [irow] = v [inum];
1089 if (icol == m.ncol) irow ++;
1090 }
1091 }
1092
1093 void NUMeigencmp22 (double a, double b, double c, double *out_rt1, double *out_rt2, double *out_cs1, double *out_sn1 );
1094 /*
1095 This routine is copied from LAPACK.
1096 Computes the eigendecomposition of a 2-by-2 symmetric matrix
1097 [ a b ]
1098 [ b c ].
1099 on return, rt1 is the eigenvalue of larger absolute value, rt2 is the
1100 eigenvalue of smaller absolute value, and (cs1,sn1) is the unit right
1101 eigenvector for rt1, giving the decomposition
1102
1103 [ cs1 sn1 ] [ a b ] [ cs1 -sn1 ] = [ rt1 0 ]
1104 [-sn1 cs1 ] [ b c ] [ sn1 cs1 ] [ 0 rt2 ].
1105
1106
1107
1108 rt1 is accurate to a few ulps barring over/underflow.
1109
1110 rt2 may be inaccurate if there is massive cancellation in the
1111 determinant a*c-b*b; higher precision or correctly rounded or
1112 correctly truncated arithmetic would be needed to compute rt2
1113 accurately in all cases.
1114
1115 cs1 and sn1 are accurate to a few ulps barring over/underflow.
1116
1117 overflow is possible only if rt1 is within a factor of 5 of overflow.
1118 underflow is harmless if the input data is 0 or exceeds
1119 underflow_threshold / macheps.
1120 */
1121
1122 void NUMpolynomial_recurrence (VEC const& pn, double a, double b, double c, constVEC const& pnm1, constVEC const& pnm2);
1123
1124 #endif // !_NUM2_h_