NUM2.h 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. #ifndef _NUM2_h_
  2. #define _NUM2_h_
  3. /* NUM2.h
  4. *
  5. * Copyright (C) 1997-2018 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 2 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. djmw 20020815 GPL header
  22. djmw 20121024 Latest modification.
  23. */
  24. #include <limits.h>
  25. #include "../melder/melder.h"
  26. #include "MAT_numerics.h"
  27. /* machine precision */
  28. #define NUMeps 2.2e-16
  29. autoVEC VEC_createFromString (conststring32 s);
  30. /* return array with the numbers found */
  31. /*
  32. * Acceptable ranges e.g. "1 4 2 3:7 4:3 3:5:2" -->
  33. * 1, 4, 2, 3, 4, 5, 6, 7, 4, 3, 3, 4, 5, 4, 3, 2
  34. * Overlap is allowed. Ranges can go up and down.
  35. */
  36. autoINTVEC NUMstring_getElementsOfRanges (conststring32 ranges, integer maximumElement, conststring32 elementType, bool sortedUniques);
  37. char32 * NUMstring_timeNoDot (double time);
  38. regexp *NUMregexp_compile (conststring32 regexp);
  39. /* Compiles a regular expression to a datastructure used by the regexp engine */
  40. char32 *strstr_regexp (conststring32 string, conststring32 search_regexp);
  41. /*
  42. Returns a pointer to the first occurrence in 'string' of the
  43. regular expression 'searchRE'. It returns a null pointer if
  44. no match is found.
  45. */
  46. autostring32vector string32vector_searchAndReplace (string32vector me,
  47. conststring32 search, conststring32 replace, int maximumNumberOfReplaces,
  48. integer *nmatches, integer *nstringmatches, bool use_regexp);
  49. /*
  50. Searches and replaces in string array of strings.
  51. If use_regexp != 0, 'search' and 'replace' will be interpreted
  52. as regular expressions. Else these strings are taken literally.
  53. 'maximumNumberOfReplaces' is the maximum number of replaces in EACH string
  54. in the array of strings (you can replace ALL occurrences by making this
  55. number <= 0).
  56. The totalnumber of matches found is returned in 'nmatches'.
  57. The number of strings with at least one match is returned in
  58. 'nstringmatches'.
  59. */
  60. void MATprintMatlabForm (constMAT m, conststring32 name);
  61. /*
  62. Print a matrix in a form that can be used as input for octave/matlab.
  63. 1 2 3
  64. Let A be the matrix: 4 5 6
  65. 7 8 9
  66. The output from NUMdmatrix_printAsOctaveForm (A, 3, 3, "M") will be
  67. M=[ 1, 2, 3;
  68. 4, 5, 6;
  69. 7, 8, 9 ];
  70. */
  71. void NUMdmatrix_diagnoseCells (double **m, integer rb, integer re, integer cb, integer ce, integer maximumNumberOfPositionsToReport);
  72. /* which cells are not finite? */
  73. /* NUMvector_extrema
  74. * Function:
  75. * compute minimum and maximum values of array v[lo..hi].
  76. * Precondition:
  77. * lo and hi should be valid indices in the array.
  78. */
  79. template <class T>
  80. void NUMvector_extrema (const T *v, integer lo, integer hi, double *p_min, double *p_max) {
  81. double min = v [lo];
  82. double max = min;
  83. for (integer i = lo + 1; i <= hi; i++)
  84. {
  85. if (v [i] < min) min = v [i];
  86. else if (v [i] > max) max = v [i];
  87. }
  88. if (p_min) *p_min = min;
  89. if (p_max) *p_max = max;
  90. }
  91. template <class T>
  92. void NUMmatrix_extrema (const T * const *x, integer rb, integer re, integer cb, integer ce, double *p_min, double *p_max) {
  93. T min = x[rb][cb], max = min;
  94. for (integer i = rb; i <= re; i++) {
  95. for (integer j = cb; j <= ce; j++) {
  96. T t = x[i] [j];
  97. if (t < min) min = t;
  98. else if (t > max) max = t;
  99. }
  100. }
  101. if (p_min) {
  102. *p_min = min;
  103. }
  104. if (p_max) {
  105. *p_max = max;
  106. }
  107. }
  108. template <class T>
  109. double NUMmatrix_extremum (const T * const *x, integer rb, integer re, integer cb, integer ce) {
  110. double min, max;
  111. NUMmatrix_extrema (x, rb, re, cb, ce, & min, & max);
  112. return fabs (max) > fabs (min) ? max : min;
  113. }
  114. /* NUMvector_clip
  115. Clip array values.
  116. c[i] = c[i] < min ? min : (c[i] > max ? max : c[i])
  117. */
  118. template <class T>
  119. void NUMvector_clip (T *v, integer lo, integer hi, double min, double max) {
  120. for (integer i = lo; i <= hi; i++)
  121. {
  122. if (v[i] < min) v[i] = min;
  123. else if (v[i] > max) v[i] = max;
  124. }
  125. }
  126. inline void VEC_normalize_inplace (VEC v, double power, double norm) {
  127. Melder_assert (norm > 0.0);
  128. double oldnorm = NUMnorm (v, power);
  129. if (oldnorm > 0.0)
  130. VECmultiply_inplace (v, norm / oldnorm);
  131. }
  132. inline void MATnormalizeRows_inplace (MAT a, double power, double norm) {
  133. Melder_assert (norm > 0);
  134. for (integer irow = 1; irow <= a.nrow; irow ++)
  135. VEC_normalize_inplace (a.row (irow), power, norm);
  136. }
  137. inline void MATnormalize_inplace (MAT a, double power, double norm) {
  138. Melder_assert (norm > 0);
  139. return VEC_normalize_inplace (asvector (a), power, norm);
  140. }
  141. void MATnormalizeColumns_inplace (MAT a, double power, double norm);
  142. /*
  143. Scale a[.][j] such that sqrt (Sum(a[i][j]^2, i=1..nPoints)) = norm.
  144. */
  145. void NUMaverageColumns (double **a, integer rb, integer re, integer cb, integer ce);
  146. /* a[i][j] = average[j]) */
  147. void VECsmoothByMovingAverage_preallocated (VEC out, constVEC in, integer window);
  148. autoMAT MATcovarianceFromColumnCentredMatrix (constMAT x, integer ndf);
  149. /*
  150. Calculate covariance matrix(ncols x ncols) from data matrix (nrows x ncols);
  151. The matrix x must be column centered.
  152. covar[i][j] = sum (k=1..nrows, x[i]k]*x[k][j])/(nrows - ndf)
  153. */
  154. double NUMmultivariateKurtosis (constMAT x, int method);
  155. /*
  156. calculate multivariate kurtosis.
  157. method = 1 : Schott (2001), J. of Statistical planning and Inference 94, 25-36.
  158. */
  159. void NUMmad (constVEC x, double *inout_location, bool wantlocation, double *out_mad, VEC *work);
  160. /*
  161. Computes the median absolute deviation, i.e., the median of the
  162. absolute deviations from the median, and adjust by a factor for
  163. asymptotically normal consistency, i.e. the returned value is 1.4826*mad which
  164. makes the returned value "equal" to the standard deviation if the data is normally distributed.
  165. You either GIVE the median location (if wantlocation = 0) or it
  166. will be calculated (if wantlocation = 1);
  167. work is a working array (1..n) that can be used for efficiency reasons.
  168. If work == NULL, the routine allocates (and destroys) its own memory.
  169. */
  170. void NUMstatistics_huber (constVEC x, double *inout_location, bool wantlocation,
  171. double *inout_scale, bool wantscale, double k_stdev, double tol, VEC *work);
  172. /*
  173. Finds the Huber M-estimator for location with scale specified,
  174. scale with location specified, or both if neither is specified.
  175. k Winsorizes at `k' standard deviations.
  176. work is a working array (1..n) that can be used for efficiency reasons.
  177. If work == NULL, the routine allocates (and destroys) its own memory.
  178. */
  179. autoVEC VECmonotoneRegression (constVEC x);
  180. /*
  181. Find numbers xs[1..n] that have a monotone relationship with
  182. the numbers in x[1..n].
  183. The xs[i] will be ascending.
  184. */
  185. /* NUMsort2:
  186. NUMsort2 uses heapsort to sort the second array in parallel with the first one.
  187. Algorithm follows p. 145 and 642 in:
  188. Donald E. Knuth (1998): The art of computer programming. Third edition. Vol. 3: sorting and searching.
  189. Boston: Addison-Wesley, printed may 2002.
  190. Modification: there is no distinction between record and key and
  191. Floyd's optimization (page 642) is used.
  192. Sorts (inplace) an array a[1..n] into ascending order using the Heapsort algorithm,
  193. while making the corresponding rearrangement of the companion
  194. array b[1..n]. A characteristic of heapsort is that it does not conserve
  195. the order of equals: e.g., the array 3,1,1,2 will be sorted as 1,1,2,3.
  196. It may occur that a_sorted[1] = a_presorted[2] and a_sorted[2] = a_presorted[1]
  197. */
  198. template<class T1, class T2>
  199. void NUMsort2 (integer n, T1 *a, T2 *b) {
  200. integer l, r, j, i, imin;
  201. T1 k, min;
  202. T2 kb, min2;
  203. if (n < 2) {
  204. return; /* Already sorted. */
  205. }
  206. if (n == 2) {
  207. if (a [1] > a [2]) {
  208. min = a [2]; a [2] = a [1]; a [1] = min;
  209. min2 = b [2]; b [2] = b [1]; b [1] = min2;
  210. }
  211. return;
  212. }
  213. if (n <= 12) {
  214. for (i = 1; i < n; i ++) {
  215. min = a [i];
  216. imin = i;
  217. for (j = i + 1; j <= n; j ++) {
  218. if (a [j] < min) {
  219. min = a [j];
  220. imin = j;
  221. }
  222. }
  223. a [imin] = a [i]; a [i] = min;
  224. min2 = b [imin]; b [imin] = b [i]; b [i] = min2;
  225. }
  226. return;
  227. }
  228. /* H1 */
  229. l = (n >> 1) + 1;
  230. r = n;
  231. for (;;) {
  232. if (l > 1) {
  233. l --;
  234. k = a [l]; kb = b [l];
  235. } else /* l == 1 */ {
  236. k = a [r]; kb = b [r];
  237. a [r] = a [1]; b [r] = b [1];
  238. r --;
  239. if (r == 1) {
  240. a [1] = k; b [1] = kb; return;
  241. }
  242. }
  243. /* H3 */
  244. j = l;
  245. for (;;) { /* H4 */
  246. i = j;
  247. j = j << 1;
  248. if (j > r) break;
  249. if (j < r && a [j] < a [j + 1]) j ++; /* H5 */
  250. /* if (k >= a[j]) break; H6 */
  251. a [i] = a [j]; b [i] = b [j]; /* H7 */
  252. }
  253. /* a[i] = k; b[i] = kb; H8 */
  254. for (;;) { /*H8' */
  255. j = i;
  256. i = j >> 1;
  257. /* H9' */
  258. if (j == l || k <= a [i]) {
  259. a [j] = k; b [j] = kb; break;
  260. }
  261. a [j] = a [i]; b [j] = b [i];
  262. }
  263. }
  264. }
  265. void NUMsort3 (VEC a, INTVEC iv1, INTVEC iv2, bool descending); // TODO template
  266. /* Sort a together with iv1 and iv2 */
  267. autoINTVEC NUMindexx (constVEC a);
  268. autoINTVEC NUMindexx_s (constSTRVEC a);
  269. void NUMindexx (const double a[], integer n, integer indx[]);
  270. void NUMindexx_s (char32 *a[], integer n, integer indx[]);
  271. /*
  272. Indexes the array a[1..n], i.e., outputs the array indx[1..n] such that
  273. a [indx[i]] is in ascending order for i=1..n;
  274. No preservation of order among equals (see NUMsort2_...)
  275. */
  276. /* NUMrank:
  277. * Replace content of array by rank number, including midranking of ties.
  278. * E.g. The elements {10, 20.1, 20.1, 20.1, 20.1, 30} in array a will be replaced
  279. * by {1, 3.5, 3.5, 3.5, 3.5, 4}, respectively. *
  280. */
  281. template <class T>
  282. void NUMrank (integer n, T *a) {
  283. integer jt, j = 1;
  284. while (j < n) {
  285. for (jt = j + 1; jt <= n && a[jt] == a[j]; jt++) {}
  286. T rank = (j + jt - 1) * 0.5;
  287. for (integer i = j; i <= jt - 1; i++) {
  288. a[i] = rank;
  289. }
  290. j = jt;
  291. }
  292. if (j == n) a[n] = n;
  293. }
  294. void NUMrankColumns (double **m, integer rb, integer re, integer cb, integer ce);
  295. int NUMjacobi (float **a, integer n, float d[], float **v, integer *nrot);
  296. /*
  297. This version deviates from the NR version.
  298. HERE: v[1..n][1..n] is a matrix whose ROWS
  299. (and not the columns) contain, on output, the normalized eigenvectors
  300. of `a'.
  301. Computes all eigenvalues and eigenvectors of a real symmetric
  302. matrix a[1..n][1..n].
  303. On output, elements of `a' above the diagonal are destroyed.
  304. d[1..n] returns the eigenvalues of `a'.
  305. `nrot' returns the number of Jacobi rotations that were required.
  306. */
  307. void NUMtred2 (double **a, integer n, double d[], double e[]);
  308. /*
  309. Householder reduction of a real, symmetric matrix a[1..n][1..n]. On output,
  310. a is replaced by the orthogonal matrix Q effecting the transformation.
  311. d[1..n] returns the diagonal elements of the tridiagonal matrix, and e[1..n]
  312. the off-diagonal elements, with e[1] = 0.
  313. */
  314. int NUMtqli (double d[], double e[], integer n, double **z);
  315. /*
  316. QL algorithm with implicit shifts, to determine the (sorted) eigenvalues
  317. and eigenvectors of a real, symmetric, tridiagonal matrix, or of a real,
  318. symmetric matrix previously reduced by NUMtred2 .
  319. On input d[1..n] contains the diagonal elements of the tridiagonal matrix.
  320. On output, it returns the eigenvalues.
  321. The vector e[1..n] inputs the subdiagonal elements of the tridiagonal
  322. matrix, with e[1] arbitrary.
  323. On output e is destroyed.
  324. If the eigenvectors of a tridiagonal matrix are desired,
  325. the matrix z[1..n][1..n] is input as the identity matrix.
  326. If the eigenvectors of a matrix that has been reduced by NUMtred2 are
  327. required, then z is input as the matrix output by NUMtred2. The k-th
  328. column of z returns the normalized eigenvector corresponding to d[k].
  329. Returns 0 in case of too many rotations.
  330. */
  331. int NUMgaussj (double **a, integer n, double **b, integer m);
  332. /*
  333. Calculate inverse of square matrix a[1..n][1..n] (in-place).
  334. Method: Gauss-Jordan elimination with full pivoting.
  335. Error message in case of singular matrix.
  336. */
  337. int NUMsvdcmp (double **a, integer m, integer n, double w[], double **v);
  338. /*
  339. Given a matrix a[1..m][1..n], this routine computes its singular
  340. value decomposition, A = U.W.V'. The matrix U replaces a on output.
  341. The diagonal matrix of singular values W is output as vector w[1..n].
  342. The matrix V (not the transpose V') is output as v[1..n][1..n].
  343. Possible errors: no memory or more than 30 iterations.
  344. */
  345. int NUMsvbksb (double **u, double w[], double **v, integer m, integer n, double b[], double x[]);
  346. /*
  347. Solves A.X=B for a vector X, where A is specified by the arrays
  348. u[1..m][1..n], w[1..n], v[1..n][1..n] as returned by NUMsvdcmp.
  349. m and n are the dimensions of a, and will be equal for square
  350. matrices. b[1..m] is the input right-hand side. x[1..n] is the
  351. output solution vector.
  352. Possible errors: no memory.
  353. */
  354. int NUMludcmp (double **a, integer n, integer *indx, double *d);
  355. /* Given a matrix a[1..n][1..n], this routine replaces it by the
  356. LU decomposition of a rowwise permutation of itself.
  357. a : matrix [1..n][1..n]
  358. n : dimension of matrix
  359. indx : output vector[1..n] that records the row permutation effected by
  360. partial pivoting.
  361. d : output +/-1 depending on whether the number of ro interchanges was
  362. even/odd.
  363. */
  364. int NUMcholeskyDecomposition (double **a, integer n, double d[]);
  365. /*
  366. Cholesky decomposition of a symmetric positive definite matrix.
  367. */
  368. void NUMcholeskySolve (double **a, integer n, double d[], double b[], double x[]);
  369. /*
  370. Solves A.x=b for x. A[][] and d[] are output from NUMcholeskyDecomposition.
  371. */
  372. void MATlowerCholeskyInverse_inplace (MAT a, double *out_lnd);
  373. /*
  374. Calculates L^-1, where A = L.L' is a symmetric positive definite matrix
  375. and ln(determinant). L^-1 in lower, leave upper part intact.
  376. */
  377. autoMAT MATinverse_fromLowerCholeskyInverse (constMAT m);
  378. /*
  379. Return the complete matrix inverse when only the inverse of the lower Cholesky part is given.
  380. Input m is a square matrix, in the lower part is the inverse of the lower Cholesky part as calculated by NUMlowerCholeskyInverse.
  381. */
  382. double MATdeterminant_fromSymmetricMatrix (constMAT m);
  383. /*
  384. ln(determinant) of a symmetric p.s.d. matrix
  385. */
  386. double NUMmahalanobisDistance (constMAT lowerInverse, constVEC v, constVEC m);
  387. double NUMmahalanobisDistance_chi (double **l, double *v, double *m, integer nr, integer nc);
  388. /*
  389. Calculates squared Mahalanobis distance: (v-m)'S^-1(v-m).
  390. Input matrix (li) is the inverse L^-1 of the Cholesky decomposition S = L.L'
  391. as calculated by NUMlowerCholeskyInverse or 1-row for a diagonal matrix (nr =1)
  392. Mahalanobis distance calculation. S = L.L' -> S**-1 = L**-1' . L**-1
  393. (x-m)'S**-1 (x-m) = (x-m)'L**-1' . L**-1. (x-m) =
  394. (L**-1.(x-m))' . (L**-1.(x-m))
  395. */
  396. double NUMtrace (constMAT a);
  397. double NUMtrace2_nn (constMAT x, constMAT y);
  398. double NUMtrace2_nt (constMAT x, constMAT y);
  399. double NUMtrace2_tn (constMAT x, constMAT y);
  400. double NUMtrace2_tt (constMAT x, constMAT y);
  401. /*
  402. Calculates the trace from a product matrix
  403. _nn : trace (X.Y)
  404. _nt : trace (X.Y')
  405. _tn : trace (X'.Y) = trace (Y'.X)
  406. _tt : trace (X'.Y') = trace ((Y.X)') = trace (Y.X)
  407. */
  408. void eigenSort (double d[], double **v, integer n, int sort);
  409. void MATprojectRowsOnEigenspace_preallocated (MAT projection, integer toColumn, constMAT data, integer fromColumn, constMAT eigenvectors);
  410. /* Input:
  411. data[numberOfRows, from_col - 1 + my dimension]
  412. contains the 'numberOfRows' vectors to be projected on the eigenspace.
  413. eigenvectors [numberOfEigenvectors][dimension]
  414. the eigenvectors stored as rows
  415. Input/Output
  416. projection [numberOfRows, to_colbegin - 1 + numberOfDimensionsToKeep]
  417. the projected vectors from 'data'
  418. Project (part of) the vectors in matrix 'data' along the 'numberOfEigenvectors' eigenvectors into the matrix 'projection'.
  419. */
  420. void MATprojectColumnsOnEigenspace_preallocated (MAT projection, constMAT data, constMAT eigenvectors);
  421. /* Input:
  422. data[dimension, numberOfColumns]
  423. contains the column vectors to be projected on the eigenspace.
  424. eigenvectors [numberOfEigenvectors][dimension]
  425. the eigenvectors stored as rowvectors
  426. Input/Output
  427. projection [numberOfEigenvectors, numberOfColumns]
  428. the projected vectors from 'data'
  429. Project the columnvectors in matrix 'data' along the 'numberOfEigenvectors' eigenvectors into the matrix 'projection'.
  430. */
  431. void NUMdominantEigenvector (constMAT mns, VEC inout_q, double *out_lambda, double tolerance);
  432. /*
  433. Determines the first dominant eigenvector from a square GENERAL matrix m.
  434. Besides the matrix m, a first guess for the eigenvector q must
  435. be supplied (e.g. 1,0,...,0) and a value for tolerance (iteration
  436. stops when fabs(lamda[k] - lambda[k-1]) <= tolerance, where lamda[k] is
  437. the eigenvalue at the k-th iteration step.
  438. The methos is described in:
  439. G. Golub & C. van Loan (1996), Matrix computations, third edition,
  440. The Johns Hopkins University Press Ltd.,
  441. London, (Par. 7.3.1 The Power Method)
  442. */
  443. void NUMdmatrix_into_principalComponents (double **m, integer nrows, integer ncols,
  444. integer numberOfComponents, double **pc);
  445. /*
  446. Precondition:
  447. numberOfComponents > 0 && numberOfComponents <= ncols
  448. pc[1..nrows][1..numberOfComponents] exists
  449. Function:
  450. Calculates the first 'numberOfComponents' principal components for the
  451. matrix m[1..nrows][1..ncols].
  452. Postcondition:
  453. Matrix pc contains the principal components
  454. Algorithm:
  455. Singular Value Decomposition:
  456. 1. Centre the columns of m, this results in a new matrix mc
  457. 2. SVD the mc matrix -> U.d.V'
  458. (Covariance matrix from mc is mc'.mc = (U.d.V')'.(U.d.V') =
  459. V.d^2.V')
  460. 3. Sort singular values d (descending) and corresponding vectors in V
  461. 4. The principal components are now:
  462. pc[i][j] = sum (k=1..ncols, v[k][j] * m[i][k])
  463. Remark:
  464. The resulting configuration is unique up to reflections along the new
  465. principal directions.
  466. */
  467. void NUMprincipalComponents (double **a, integer n, integer nComponents, double **pc);
  468. /*
  469. Determines the principal components of a real symmetric matrix
  470. a[1..n][1..n] as a pc[1..n][1..nComponents] column matrix.
  471. */
  472. void NUMpseudoInverse (double **y, integer nr, integer nc, double **yinv, double tolerance);
  473. /*
  474. Determines the pseudo-inverse Y^-1 of Y[1..nr][1..nc] via s.v.d.
  475. Alternative notation for pseudo-inverse: (Y'.Y)^-1.Y'
  476. Returns a [1..nc][1..nr] matrix
  477. */
  478. integer NUMsolveQuadraticEquation (double a, double b, double c, double *x1, double *x2);
  479. /*
  480. Finds the real roots of ax^2 + bx + c = 0.
  481. The number of real roots is returned and their locations in x1 and x2.
  482. If only one root found it is stored in x1.
  483. If no roots found then x1 and x2 will not be changed.
  484. */
  485. autoVEC NUMsolveEquation (constMAT a, constVEC b, double tol);
  486. /*
  487. Solve the equation: A.x = b for x;
  488. a[1..nr][1..nc], b[1..nr] and the unknown x[1..nc]
  489. Algorithm: s.v.d.
  490. */
  491. autoMAT NUMsolveEquations (constMAT a, constMAT b, double tol);
  492. /*
  493. Solve the equations: A.X = B;
  494. a[1..nr][1..nc], b[1..nr][1..nc2] and the unknown x[1..nc][1..nc2]
  495. Algorithm: s.v.d.
  496. */
  497. autoVEC NUMsolveNonNegativeLeastSquaresRegression (constMAT m, constVEC d, double tol, integer itermax);
  498. /*
  499. Solve the equation: M.b = d for b under the constraint: all b[i] >= 0;
  500. m[1..nr][1..nc], d[1..nr] and b[1..nc].
  501. Algorithm: Alternating least squares.
  502. Borg & Groenen (1997), Modern multidimensional scaling, Springer, page 180.
  503. */
  504. void NUMsolveConstrainedLSQuadraticRegression (constMAT o, constVEC y,double *out_alpha, double *out_gamma);
  505. /*
  506. Solve y[i] = alpha + beta * x[i] + gamma * x[i]^2, with i = 1..n,
  507. subject to the constraint beta^2 = 4 * alpha * gamma, for alpha and
  508. gamma (Least Squares).
  509. The input Vandermonde-matrix o[1..n,1..3] has columns with 1, x[i] and
  510. x[i]^2, respectively.
  511. The algorithm is according to:
  512. Jos M.F. Ten Berge (1983), A generalization of Verhelst's solution for
  513. a constrained regression problem in ALSCAL and related MDS-algorithms,
  514. Psychometrika 48, 631-638.
  515. */
  516. autoVEC NUMsolveWeaklyConstrainedLinearRegression (constMAT f, constVEC phi, double alpha, double delta);
  517. /*
  518. Solve g(t) = ||Ft - phi||^2 + alpha (t't - delta)^2 for t[1..m],
  519. where F[1..n][1..m] is a matrix, phi[1..n] a given vector, and alpha
  520. and delta are fixed numbers.
  521. This class of functions is composed of a linear regression function and
  522. a penalty function for the sum of squared regression weights. It is weakly
  523. constrained because the penalty function prohibits a relatively large
  524. departure of t't from delta.
  525. The solution is due to:
  526. Jos M.F. ten Berge (1991), A general solution for a class of weakly
  527. constrained linear regression problems, Psychometrika 56, 601-609.
  528. Preconditions:
  529. n >= m
  530. alpha >= 0
  531. */
  532. void NUMprocrustes (constMAT x, constMAT y, autoMAT *out_rotation, autoVEC *out_translation, double *out_scale);
  533. /*
  534. Given two configurations x and y (nPoints x nDimensions), find the
  535. the Procrustes rotation/reflection matrix T, the translation vector v and the scaling
  536. factor s such that Y = sXT+1v' (1 is the nPoints vector with ones).
  537. Solution: see Borg and Groenen (1997), Modern Multidimensional Scaling, pp 340-346.
  538. When on input v == NULL or s == NULL, only the matrix T will be solved for:
  539. the orthogonal Procrustes transform.
  540. */
  541. void NUMnrbis (void (*f)(double x, double *fx, double *dfx, void *closure), double xmin, double xmax, void *closure, double *root);
  542. /*
  543. Find the root of a function between xmin and xmax.
  544. Method: Newton-Raphson with bisection (i.e., derivative is known!).
  545. Error condition:
  546. return undefined if root not bracketed.
  547. */
  548. double NUMridders (double (*f) (double x, void *closure), double xmin, double xmax, void *closure);
  549. /*
  550. Return the root of a function f bracketed in [xmin, xmax].
  551. Error condition:
  552. root not bracketed.
  553. */
  554. double NUMmspline (constVEC knot, integer order, integer i, double x);
  555. /*
  556. Calculates an M-spline for a knot sequence.
  557. After Ramsay (1988), Monotone splines in action, Statistical Science 4.
  558. M-splines of order k have degree k-1.
  559. M-splines are zero outside interval [ knot[i], knot[i+order] ).
  560. First and last 'order' knots are equal, i.e.,
  561. knot[1] = ... = knot[order] && knot[nKnots-order+1] = ... knot[nKnots].
  562. Error condition: no memory.
  563. */
  564. double NUMispline (constVEC aknot, integer order, integer i, double x);
  565. /*
  566. Calculates an I-spline for simple knot sequences: only one knot at each
  567. interior boundary.
  568. After Ramsay (1988), Monotone splines in action, Statistical Science 4.
  569. I-splines of order k have degree k (because they Integrate an M-spline
  570. of degree k-1).
  571. In the calculation of the integral of M(x|k,t), M-splines are used that
  572. have two more knots, i.e., M(x|k+1,t). For reasons of efficiency we
  573. demand that these extra knots are given, i.e., the 'aknot[]' argument
  574. contains the knot positions as if the spline to be integrated were an
  575. M(x|k+1,t) spline.
  576. knot[1] = ... = knot[order+1] && knot[nKnots-order] = ... knot[nKnots]
  577. Error condition: no memory.
  578. */
  579. double NUMwilksLambda (double *lambda, integer from, integer to);
  580. /*
  581. Calculate: Product (i=from..to; 1/(1+lambda[i]))
  582. Preconditions: to >= from
  583. */
  584. double NUMlnBeta (double a, double b);
  585. /*
  586. Computes the logarithm of the beta function log(B(a,b) subject to
  587. a and b not being negative integers.
  588. */
  589. double NUMbeta2 (double z, double w);//temporarily
  590. double NUMbetaContinuedFraction(double a, double b, double x);
  591. double NUMfactln (int n);
  592. /* Returns ln (n!) */
  593. void NUMlngamma_complex (double zr, double zi, double *lnr, double *arg);
  594. /* Log[Gamma(z)] for z complex, z not a negative integer
  595. * Uses complex Lanczos method. Note that the phase part (arg)
  596. * is not well-determined when |z| is very large, due
  597. * to inevitable roundoff in restricting to (-pi, pi].
  598. * The absolute value part (lnr), however, never suffers.
  599. *
  600. * Calculates:
  601. * lnr = log|Gamma(z)|
  602. * arg = arg(Gamma(z)) in (-Pi, Pi]
  603. */
  604. /***** STATISTICS: PROBABILITY DENSITY FUNCTIONS ********************/
  605. double NUMlogNormalP (double x, double zeta, double sigma);
  606. /* Area under log normal from 0 to x */
  607. double NUMlogNormalQ (double x, double zeta, double sigma);
  608. /* Area under log normal from x to +infinity */
  609. double NUMstudentP (double t, double df);
  610. /*
  611. The area under the student T-distribution from -infinity to t.
  612. Precondition: df > 0
  613. */
  614. double NUMstudentQ (double t, double df);
  615. /*
  616. The area under the student T distribution from t to +infinity.
  617. Precondition: df > 0
  618. */
  619. double NUMfisherP (double f, double df1, double df2);
  620. /*
  621. The area under Fisher's F-distribution from 0 to f
  622. Preconditions: f >= 0, df1 > 0, df2 > 0
  623. */
  624. double NUMfisherQ (double f, double df1, double df2);
  625. /*
  626. The area under Fisher's F-distribution from f to +infinity
  627. Preconditions: f >= 0, df1 > 0, df2 > 0
  628. */
  629. double NUMinvGaussQ (double p);
  630. /*
  631. Solves NUMgaussQ (x) == p for x, given p.
  632. Precondition: 0 < p < 1
  633. Method: Abramovitz & Stegun 26.2.23
  634. Precision: |eps(p)| < 4.5 10^-4
  635. */
  636. double NUMinvChiSquareQ (double p, double df);
  637. /*
  638. Solves NUMchiSquareQ (chiSquare, df) == p for chiSquare, given p, df.
  639. Preconditions: 0 < p < 1, df > 0
  640. */
  641. double NUMinvStudentQ (double p, double df);
  642. /*
  643. Solves NUMstudentQ (t, df) == p for t, given p, df.
  644. Preconditions: 0 < p < 1, df > 0
  645. */
  646. double NUMinvFisherQ (double p, double df1, double df2);
  647. /*
  648. Solves NUMfisherQ (f, df1, df2) == p for f, given p, df1, df2
  649. Precondition: 0 < p < 1
  650. */
  651. double NUMtukeyQ (double q, double cc, double df, double rr);
  652. /* Computes the probability that the maximum of rr studentized
  653. * ranges, each based on cc means and with df degrees of freedom
  654. * for the standard error, is larger than q.
  655. */
  656. double NUMinvTukeyQ (double p, double cc, double df, double rr);
  657. /* Solves NUMtukeyQ (q, rr, cc, df) == p for q given p, rr, cc and df.
  658. * Computes the quantiles of the maximum of rr studentized
  659. * ranges, each based on cc means and with df degrees of freedom
  660. * for the standard error, is larger than q.
  661. * p = probability (alpha)
  662. * rr = no. of rows or groups
  663. * cc = no. of columns or treatments
  664. * df = degrees of freedom of error term
  665. */
  666. double NUMnormalityTest_HenzeZirkler (constMAT data, double *beta, double *tnb, double *lnmu, double *lnvar);
  667. /*
  668. Multivariate normality test of nxp data matrix according to the method described in Henze & Wagner (1997).
  669. The test statistic is returned in tnb, together with the lognormal mean 'lnmu' and the lognormal variance 'lnvar'.
  670. */
  671. /****** Frequency in Hz to other frequency reps ****/
  672. double NUMmelToHertz2 (double mel);
  673. /*
  674. Return 700 * (pow (10.0, mel / 2595.0) - 1)
  675. */
  676. double NUMhertzToMel2 (double f);
  677. /*
  678. Return 2595 * log10 (1 + f/700)
  679. */
  680. double NUMmelToHertz3 (double mel);
  681. /*
  682. Return mel < 1000 ? mel : 1000 * (exp (mel * log10(2) / 1000) - 1)
  683. */
  684. double NUMhertzToMel3 (double hz);
  685. /*
  686. Return hz < 1000 ? hz : 1000 * log10 (1 + hz / 1000) / log10 (2)
  687. */
  688. double NUMbarkToHertz2 (double bark);
  689. /*
  690. Return 650 * sinh (bark / 7)
  691. */
  692. double NUMhertzToBark2 (double hz);
  693. /*
  694. Return 7 * ln (hz / 650 + sqrt(1 + (hz / 650)^2))
  695. */
  696. double NUMhertzToBark_traunmueller (double hz);
  697. /*
  698. return 26.81 * hz /(1960 + hz) -0.53;
  699. */
  700. double NUMbarkToHertz_traunmueller (double bark);
  701. /*
  702. return 1960* (bark + 0.53) / (26.28 - bark);
  703. */
  704. double NUMbarkToHertz_schroeder (double bark);
  705. /*
  706. return 650.0 * sinh (bark / 7.0);
  707. */
  708. double NUMbarkToHertz_zwickerterhardt (double hz);
  709. /*
  710. return 13 * atan (0.00076 * hz) + 3.5 * atan (hz / 7500);
  711. */
  712. double NUMhertzToBark_schroeder (double hz);
  713. /*
  714. return 7.0 * log (hz / 650 + sqrt (1 + (hz / 650)^2));
  715. */
  716. double NUMbladonlindblomfilter_amplitude (double zc, double z);
  717. /*
  718. Amplitude of filter at dz (barks) from centre frequency.
  719. dz may be positive and negative.
  720. The bladonlindblomfilter function is:
  721. z' = zc - z + 0.474
  722. 10 log10 F(z') = 15.81 + 7.5 z' - 17.5 sqrt( 1 + z'^2 )
  723. Reference: Bladon, R.A.W & Lindblom, B., (1980),
  724. "Modeling the judgment of vowel quality differences", JASA 69, 1414-1422.
  725. The filter has a bandwidth of 1.43 Bark, the maximum occurs at z = zc,
  726. and the slopes are -10 dB/Bark and +25 dB/Bark.
  727. */
  728. double NUMsekeyhansonfilter_amplitude (double zc, double z);
  729. /*
  730. Amplitude of filter at dz (barks) from centre frequency.
  731. dz may be positive and negative.
  732. The sekeyhansonfilter function is:
  733. z' = zc - z - 0.215
  734. 10 log10 F(z') = 7 - 7.5 * z' - 17.5 * sqrt( 0.196 + z'^2 )
  735. Reference: Sekey, A. & Hanson, B.A. (1984),
  736. "Improved 1-Bark bandwidth auditory filter", JASA 75, 1902-1904.
  737. The filter function has a bandwidth of 1 Bark, the maximum response
  738. occurs at z=zc, and the slopes are +10 dB/Bark and -25 dB/Bark.
  739. It is an improved version of bladonlindblomfilter.
  740. */
  741. double NUMtriangularfilter_amplitude (double fl, double fc, double fh,
  742. double f);
  743. /*
  744. Filterfunction that intermediates in Mel frequency cepstral coefficients
  745. calculation.
  746. The filter function is
  747. (f-fl)/(fc-fl) fl < f < fc
  748. H(z) = (fh-f)/(fh-fc) fc < f < fh
  749. 0 otherwise
  750. Preconditions:
  751. 0 < fl < fh
  752. */
  753. double NUMformantfilter_amplitude (double fc, double bw, double f);
  754. /*
  755. Filterfunction with a formant-like shape on a linear freq. scale.
  756. H(f) = 1.0 / (dq * dq + 1.0), where
  757. dq = (fc * fc - f * f) / (bw * f)
  758. Preconditions: f > 0 && bw > 0
  759. */
  760. double NUMburg_preallocated (VEC a, constVEC x);
  761. /*
  762. Calculates linear prediction coefficients according to the algorithm
  763. from J.P. Burg as described by N.Anderson in Childers, D. (ed), Modern
  764. Spectrum Analysis, IEEE Press, 1978, 252-255.
  765. Returns the sum of squared sample values or 0.0 if failure
  766. */
  767. autoVEC NUMburg (constVEC x, integer numberOfPredictionCoefficients, double *out_xms);
  768. void NUMdmatrix_to_dBs (double **m, integer rb, integer re, integer cb, integer ce,
  769. double ref, double factor, double floor);
  770. /*
  771. Transforms the values in the matrix m[rb..re][cb..ce] to dB's
  772. m[i][j] = factor * 10 * log10 (m[i][j] / ref)
  773. if (m[i][j] < floor) m[i][j] = floor;
  774. Preconditions:
  775. rb <= re
  776. cb <= ce
  777. ref > 0
  778. factor > 0
  779. Errors:
  780. Matrix elements < 0;
  781. */
  782. double **NUMcosinesTable (integer first, integer last, integer npoints);
  783. /*
  784. Generate table with cosines.
  785. result[i][j] = cos (i * pi * (j - 1/2) / npoints)
  786. i=first..last; j=1..npoints
  787. Preconditions:
  788. 1 <= first <= last
  789. npoints > 1
  790. */
  791. /****** Interpolation ****/
  792. void NUMcubicSplineInterpolation_getSecondDerivatives (double x[], double y[], integer n, double yp1, double ypn, double y2[]);
  793. /*
  794. Given arrays a[1..n] and y[1..n] containing a tabulated function, i.e.,
  795. y[i] = f(x[i]), with x[1] < x[2] < ... < x[n], and given values yp1 and
  796. ypn for the first derivative of the interpolating function at point
  797. 1 and n, respectively, this routine returns an array y2[1..n] that
  798. contains the second derivative of the interpolating function at the
  799. tabulated point x.
  800. If yp1 and/or ypn are >= 10^30, the routine is signaled to
  801. set the corresponding boundary condition for a natural spline, with
  802. zero second derivative on that boundary.
  803. */
  804. double NUMcubicSplineInterpolation (double xa[], double ya[], double y2a[], integer n, double x);
  805. /*
  806. Given arrays xa[1..n] and ya[1..n] containing a tabulated function,
  807. i.e., y[i] = f(x[i]), with x[1] < x[2] < ... < x[n], and given the
  808. array y2a[1..n] which is the output of NUMcubicSplineInterpolation_getSecondDerivatives above, and given
  809. a value of x, this routine returns an interpolated value y.
  810. */
  811. autoVEC NUMbiharmonic2DSplineInterpolation_getWeights (constVEC x, constVEC y, constVEC w);
  812. /*
  813. Input: x[1..numberOfPoints], y[1..numberOfPoints], (xp,yp)
  814. Output: interpolated result
  815. */
  816. double NUMbiharmonic2DSplineInterpolation (constVEC x, constVEC y, constVEC w, double xp, double yp);
  817. /* Biharmonic spline interpolation based on Green's function.
  818. . Given z[i] values at points (x[i],y[i]) for i=1..n,
  819. Get value at new point (px,py).
  820. 1. Calculate weights w once: NUMbiharmonic2DSplineInterpolation_getWeights
  821. 2. Interpolate at (xp,yp): NUMbiharmonic2DSplineInterpolation
  822. Input: x[1..numberOfPoints], y[1..numberOfPoints], z[1..numberOfPoints], weights[1..numberOfPoints]
  823. Output: weights[1..numberOfPoints]
  824. Preconditions: all x[i] are different and all y[i] are different.
  825. This routine inializes the numberOfPoints weigts by inverting a numberOfPoints x numberOfPoints matrix.
  826. D. Sandwell (1987), Biharmonic spline interpolation of GEOS-3 and SEASAT altimetr data, Geophysical Research Letters 14, 139--142
  827. X. Deng & Z. Tang (2011), Moving surface spline interpolation based on Green's function, Math. Geosci 43: 663--680
  828. */
  829. double NUMsincpi (const double x);
  830. /* Calculates sin(pi*x)/(pi*x) */
  831. double NUMsinc (const double x);
  832. /* Calculates sin(x)/(x) */
  833. /*********************** Geometry *************************************/
  834. int NUMgetOrientationOfPoints (double x1, double y1, double x2, double y2, double x3, double y3);
  835. /* Traverse points 1, 2 and 3. If we travel counter-clockwise the result will be 1,
  836. 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.
  837. */
  838. int NUMdoLineSegmentsIntersect (double x1, double y1, double x2, double y2, double x3, double y3,
  839. double x4, double y4);
  840. /* Does the line segment from (x1,y1) to (x2,y2) intersect with the line segment from (x3,y3) to (x4,y4)? */
  841. int NUMgetIntersectionsWithRectangle (double x1, double y1, double x2, double y2,
  842. double xmin, double ymin, double xmax, double ymax, double *xi, double *yi);
  843. /* Get the intersection points of the line through the points (x1,y1) and (x2,y2) with the
  844. rectangle with corners (xmin, ymin) and (xmax,ymax).
  845. The returned value is the number of intersections found and is either 0 or 1 or 2.
  846. */
  847. bool NUMclipLineWithinRectangle (double xl1, double yl1, double xl2, double yl2, double xr1, double yr1,
  848. double xr2, double yr2, double *xo1, double *yo1, double *xo2, double *yo2);
  849. /*
  850. If true, then returns in (xo1, yo1) and (xo2, yo2) the coordinates of that piece of the line (xl1, yl1)..(xl2, yl2)
  851. that can be drawn within the rectangle with lowerleft corner (xr1, yr1) and upperright (xr2, yr2).
  852. Returns false if there is nothing to be drawn inside.
  853. */
  854. void NUMgetEllipseBoundingBox (double a, double b, double cospsi,
  855. double *width, double *height);
  856. /*
  857. Get the width and the height of the bonding box around an ellipse.
  858. a and b are the lengths of the long axes.
  859. cospsi is the cosine of the angle between the a-axis and the horizontal
  860. x-axis (cs == 0 when a-axis and x-axis are perpendicular).
  861. Parametrisation of the ellipse:
  862. x(phi) = a cos(psi) cos(phi) - b sin (psi) sin(phi)
  863. y(phi) = a sin(psi) cos(phi) + b cos(psi) sin(phi) 0 <= phi <= 2 pi
  864. Extrema:
  865. d x(phi) / dphi == 0 and d y(phi) / dphi == 0
  866. Solution:
  867. x(phi1) = a cos(psi) cos(phi1) - b sin (psi) sin(phi1)
  868. y(phi2) = a sin(psi) cos(phi2) + b cos(psi) sin(phi2),
  869. where
  870. phi1 = arctg ( -b/a tg(psi))
  871. phi2 = arctg ( b/a cotg(psi))
  872. Special cases are psi = 0 and pi /2
  873. */
  874. double NUMminimize_brent (double (*f) (double x, void *closure), double a, double b,
  875. void *closure, double tol, double *fx);
  876. /*
  877. The function returns an estimate for the minimum location with accuracy
  878. 3 * SQRT_EPSILON * abs(x) + tol.
  879. The function always obtains a local minimum which coincides with
  880. the global one only if a function under investigation being unimodular.
  881. If a function being examined possesses no local minimum within
  882. the given range, the function returns 'a' (if f(a) < f(b)), otherwise
  883. it returns the right range boundary value b.
  884. Algorithm
  885. The function makes use of the golden section procedure combined with
  886. parabolic interpolation.
  887. At every step, the program operates at three abscissae - x, v, and w.
  888. x - the last and the best approximation to the minimum location,
  889. i.e. f(x) <= f(a) or/and f(x) <= f(b)
  890. (if the function f has a local minimum in (a,b), then both
  891. conditions are fulfiled after one or two steps).
  892. v, w are previous approximations to the minimum location. They may
  893. coincide with a, b, or x (although the algorithm tries to make all
  894. u, v, and w distinct). Points x, v, and w are used to construct
  895. interpolating parabola whose minimum will be treated as a new
  896. approximation to the minimum location if the former falls within
  897. [a,b] and reduces the range enveloping minimum more efficient than
  898. the golden section procedure.
  899. When f(x) has a second derivative positive at the minimum location
  900. (not coinciding with a or b) the procedure converges superlinearly
  901. at a rate order about 1.324
  902. */
  903. /********************** fft ******************************************/
  904. struct structNUMfft_Table
  905. {
  906. integer n;
  907. autoVEC trigcache;
  908. autoINTVEC splitcache;
  909. };
  910. typedef struct structNUMfft_Table *NUMfft_Table;
  911. void NUMfft_Table_init (NUMfft_Table table, integer n);
  912. /*
  913. n : data size
  914. */
  915. struct autoNUMfft_Table : public structNUMfft_Table {
  916. autoNUMfft_Table () throw () {
  917. n = 0;
  918. }
  919. ~autoNUMfft_Table () { }
  920. };
  921. void NUMfft_forward (NUMfft_Table table, VEC data);
  922. /*
  923. Function:
  924. Calculates the Fourier Transform of a set of n real-valued data points.
  925. Replaces this data in array data [1...n] by the positive frequency half
  926. of its complex Fourier Transform, with a minus sign in the exponent.
  927. Preconditions:
  928. data != NULL;
  929. table must have been initialised with NUMfft_Table_init_f/d
  930. Postconditions:
  931. data[1] contains real valued first component (Direct Current)
  932. data[2..n-1] even index : real part; odd index: imaginary part of DFT.
  933. data[n] contains real valued last component (Nyquist frequency)
  934. Output parameters:
  935. data r(1) = the sum from i=1 to i=n of r(i)
  936. If l =(int) (n+1)/2
  937. then for k = 2,...,l
  938. r(2*k-2) = the sum from i = 1 to i = n of r(i)*cos((k-1)*(i-1)*2*pi/n)
  939. r(2*k-1) = the sum from i = 1 to i = n of -r(i)*sin((k-1)*(i-1)*2*pi/n)
  940. if n is even
  941. r(n) = the sum from i = 1 to i = n of (-1)**(i-1)*r(i)
  942. i.e., the ordering of the output array will be for n even
  943. r(1),(r(2),i(2)),(r(3),i(3)),...,(r(l-1),i(l-1)),r(l).
  944. Or ...., (r(l),i(l)) for n uneven.
  945. ***** note
  946. this transform is unnormalized since a call of NUMfft_forward
  947. followed by a call of NUMfft_backward will multiply the input sequence by n.
  948. */
  949. void NUMfft_backward (NUMfft_Table table, VEC data);
  950. /*
  951. Function:
  952. Calculates the inverse transform of a complex array if it is the transform of real data.
  953. (Result in this case should be multiplied by 1/n.)
  954. Preconditions:
  955. n is an integer power of 2.
  956. data != NULL;
  957. data [1] contains real valued first component (Direct Current)
  958. data [2..n-1] even index : real part; odd index: imaginary part of DFT.
  959. data [n] contains real valued last component (Nyquist frequency)
  960. table must have been initialised with NUMfft_Table_init_f/d
  961. Output parameters
  962. data for n even and for i = 1,...,n
  963. r(i) = r(1)+(-1)**(i-1)*r(n)
  964. plus the sum from k=2 to k=n/2 of
  965. 2.0*r(2*k-2)*cos((k-1)*(i-1)*2*pi/n) -2.0*r(2*k-1)*sin((k-1)*(i-1)*2*pi/n)
  966. for n odd and for i = 1,...,n
  967. r(i) = r(1) plus the sum from k=2 to k=(n+1)/2 of
  968. 2.0*r(2*k-2)*cos((k-1)*(i-1)*2*pi/n) -2.0*r(2*k-1)*sin((k-1)*(i-1)*2*pi/n)
  969. ***** note
  970. this transform is unnormalized since a call of NUMfft_forward
  971. followed by a call of NUMfft_backward will multiply the input
  972. sequence by n.
  973. */
  974. /**** Compatibility with NR fft's */
  975. void NUMforwardRealFastFourierTransform (VEC data);
  976. /*
  977. Function:
  978. Calculates the Fourier Transform of a set of n real-valued data points.
  979. Replaces this data in array data [1...n] by the positive frequency half
  980. of its complex Fourier Transform, with a minus sign in the exponent.
  981. Preconditions:
  982. n is an integer power of 2.
  983. data != NULL;
  984. Postconditions:
  985. data [1] contains real valued first component (Direct Current)
  986. data [2] contains real valued last component (Nyquist frequency)
  987. data [3..n] odd index : real part; even index: imaginary part of DFT.
  988. */
  989. void NUMreverseRealFastFourierTransform (VEC data);
  990. /*
  991. Function:
  992. Calculates the inverse transform of a complex array if it is the transform of real data.
  993. (Result in this case should be multiplied by 1/n.)
  994. Preconditions:
  995. n is an integer power of 2.
  996. data != NULL;
  997. data [1] contains real valued first component (Direct Current)
  998. data [2] contains real valued last component (Nyquist frequency)
  999. data [3..n] odd index : real part; even index: imaginary part of DFT.
  1000. */
  1001. void NUMrealft (VEC data, int direction);
  1002. integer NUMgetIndexFromProbability (double *probs, integer nprobs, double p);
  1003. // Fit the line y= ax+b
  1004. void NUMlineFit (double *x, double *y, integer numberOfPoints, double *m, double *intercept, int method);
  1005. /* method
  1006. * 1 least squares
  1007. * 2 rubust incomplete Theil O(N/2)
  1008. * 3 robust complete Theil (very slow for large N, O(N^2))
  1009. */
  1010. void NUMlineFit_theil (double *x, double *y, integer numberOfPoints, double *m, double *intercept, bool incompleteMethod);
  1011. /*
  1012. * Preconditions:
  1013. * all x[i] should be different, i.e. x[i] != x[j] for all i = 1..(numberOfPoints - 1), j = (i+1) ..numberOfPoints
  1014. * Algorithm:
  1015. * Theils robust line fit method:
  1016. * 1. Use all combination of pairs (x[i],y[i]), (x[j],y[j]) to calculate an intercept m[k] as
  1017. * m[k] = (y[j] - y[i]) / (x[j] - x[i]).
  1018. * There will be (numberOfPoints - 1) * numberOfPoints / 2 numbers m[k].
  1019. * 2. Take the median value m of all the m[k].
  1020. * 3. Calculate the numberOfPoints intercepts b[i] as b[i] = y[i] - m * x[i]
  1021. * 4. Take the median value b of all the b[i] values
  1022. *
  1023. * If incompleteMethod we use Theil's incomplete method to reduce the number of combinations.
  1024. * I.e. split the data in two equal parts at n2 = numberOfPoints / 2 and then calculate the numberOfPoints/2 intercepts m[i] as
  1025. * m[i] = (y[n2+i] - y[i]) / (x[n2 + i] - x[i]).
  1026. * The rest proceeds as outlined above
  1027. */
  1028. void NUMlineFit_LS (double *x, double *y, integer numberOfPoints, double *m, double *intercept);
  1029. /* The binomial distribution has the form,
  1030. f(x) = n!/(x!(n-x)!) * p^x (1-p)^(n-x) for integer 0 <= x <= n
  1031. = 0 otherwise
  1032. This implementation follows the public domain ranlib function
  1033. "ignbin", the bulk of which is the BTPE (Binomial Triangle
  1034. Parallelogram Exponential) algorithm introduced in
  1035. Kachitvichyanukul and Schmeiser[1]. It has been translated to use
  1036. modern C coding standards.
  1037. If n is small and/or p is near 0 or near 1 (specifically, if
  1038. n*min(p,1-p) < SMALL_MEAN), then a different algorithm, called
  1039. BINV, is used which has an average runtime that scales linearly
  1040. with n*min(p,1-p).
  1041. But for larger problems, the BTPE algorithm takes the form of two
  1042. functions b(x) and t(x) -- "bottom" and "top" -- for which b(x) <
  1043. f(x)/f(M) < t(x), with M = floor(n*p+p). b(x) defines a triangular
  1044. region, and t(x) includes a parallelogram and two tails. Details
  1045. (including a nice drawing) are in the paper.
  1046. [1] Kachitvichyanukul, V. and Schmeiser, B. W. Binomial Random
  1047. Variate Generation. Communications of the ACM, 31, 2 (February,
  1048. 1988) 216.
  1049. Note, Bruce Schmeiser (personal communication) points out that if
  1050. you want very fast binomial deviates, and you are happy with
  1051. approximate results, and/or n and n*p are both large, then you can
  1052. just use gaussian estimates: mean=n*p, variance=n*p*(1-p).
  1053. This implementation by James Theiler, April 2003, after obtaining
  1054. permission -- and some good advice -- from Drs. Kachitvichyanukul
  1055. and Schmeiser to use their code as a starting point, and then doing
  1056. a little bit of tweaking.
  1057. Additional polishing for GSL coding standards by Brian Gough. */
  1058. integer NUMrandomBinomial (double p, integer n);
  1059. double NUMrandomBinomial_real (double p, integer n);
  1060. // IEEE: Programs for digital signal processing section 4.3 LPTRN (modfied)
  1061. // lpc[1..n] to rc[1..n]
  1062. void NUMlpc_lpc_to_rc (double *lpc, integer p, double *rc);
  1063. // rc[1..n] to area[1..n+1], area[m+1] = 0.0001; (1 cm^2)
  1064. void NUMlpc_rc_to_area (double *rc, integer n, double *area);
  1065. // area[1..n] to rc[1..n-1] (modification: LPTRN assumes area[n+1])
  1066. void NUMlpc_area_to_rc (double *area, integer n, double *rc);
  1067. // area[1..n] to lpc[1..n-1]! (modification: lptrn gives lpc[1] = 1 we don't)
  1068. void NUMlpc_area_to_lpc (double *area, integer n, double *lpc);
  1069. // lpc[1..n] to area[1..n+1], area[m+1] = 0.0001; (1 cm^2)
  1070. void NUMlpc_lpc_to_area (double *lpc, integer m, double *area);
  1071. /*
  1072. Fix indices to be in the range [lowerLimit, upperLimit].
  1073. */
  1074. void NUMfixIndicesInRange (integer lowerLimit, integer upperLimit, integer *lowIndex, integer *highIndex);
  1075. void MAT_getEntropies (constMAT m, double *out_h, double *out_hx,
  1076. double *out_hy, double *out_hygx, double *out_hxgy, double *out_uygx, double *out_uxgy, double *out_uxy);
  1077. double NUMfrobeniusnorm (constMAT x);
  1078. /*
  1079. Returns frobenius norm of matrix sqrt (sum (i=1:nrow, j=1:ncol, x[i][j]^2))
  1080. */
  1081. inline autoINTVEC INTVECto (integer to) {
  1082. autoINTVEC result = INTVECraw (to);
  1083. for (integer i = 1; i <= to; i ++)
  1084. result [i] = i;
  1085. return result;
  1086. }
  1087. void NUMeigencmp22 (double a, double b, double c, double *rt1, double *rt2, double *cs1, double *sn1 );
  1088. /*
  1089. This routine is copied from LAPACK.
  1090. Computes the eigendecomposition of a 2-by-2 symmetric matrix
  1091. [ a b ]
  1092. [ b c ].
  1093. on return, rt1 is the eigenvalue of larger absolute value, rt2 is the
  1094. eigenvalue of smaller absolute value, and (cs1,sn1) is the unit right
  1095. eigenvector for rt1, giving the decomposition
  1096. [ cs1 sn1 ] [ a b ] [ cs1 -sn1 ] = [ rt1 0 ]
  1097. [-sn1 cs1 ] [ b c ] [ sn1 cs1 ] [ 0 rt2 ].
  1098. rt1 is accurate to a few ulps barring over/underflow.
  1099. rt2 may be inaccurate if there is massive cancellation in the
  1100. determinant a*c-b*b; higher precision or correctly rounded or
  1101. correctly truncated arithmetic would be needed to compute rt2
  1102. accurately in all cases.
  1103. cs1 and sn1 are accurate to a few ulps barring over/underflow.
  1104. overflow is possible only if rt1 is within a factor of 5 of overflow.
  1105. underflow is harmless if the input data is 0 or exceeds
  1106. underflow_threshold / macheps.
  1107. */
  1108. #endif // _NUM2_h_