Debian Codegraph @

dwsys/NUMcomplex.cpp

raw
1 /* NUMcomplex.cpp
2 *
3 * Copyright (C) 2017-2020, 2026 David Weenink
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <cmath>
20 #include "NUMcomplex.h"
21
22 void NUMextrema (constCOMPVEC const& v, double *min_re, double *max_re, double *min_im, double *max_im) {
23 integer ndiv2 = v.size / 2;
24 const integer start = v.size & 1 ? 2 : 1; // even or odd?
25 if (min_re || max_re) {
26 double max = v [1].real(), min = max;
27 for (integer i = start; i <= ndiv2; i ++) {
28 const integer i2 = 2 * i, i1 = i2 - 1;
29 if (v [11].real() >= v [i2].real())
30 if (v [i1].real() > max)
31 max = v [i1].real();
32 if (v [11].real() <= v [i2].real())
33 if (v [i1].real() < min)
34 min = v [i1].real();
35 }
36 if (min_re)
37 *min_re = min;
38 if (max_re)
39 *max_re = max;
40 }
41 if (min_im || max_im) {
42 double max = v [1].imag(), min = max;
43 for (integer i = start; i <= ndiv2; i ++) {
44 const integer i2 = 2 * i, i1 = i2 - 1;
45 if (v [11].imag() >= v [i2].imag())
46 if (v [i1].imag() > max)
47 max = v [i1].imag();
48 if (v [11].imag() <= v [i2].imag())
49 if (v [i1].imag() < min)
50 min = v [i1].imag();
51 }
52 if (min_im)
53 *min_im = min;
54 if (max_im)
55 *max_im = max;
56 }
57 }
58
59 /*
60 The code to calculate the complex incomplete gamma function was translated from fortran code into c++ by David Weenink.
61 The fortran code is from the following article:
62 Eric Kostlan & Dmitry Gokhman, A program for calculating the incomplete gamma function.
63 Technical report, Dept. of Mathematics, Univ. of California, Berkeley, 1987.
64
65 Their algorithm calcutes the complex incomplete gamma function Γ(α,x) by using the following formula:
66 (1) Γ(α,x)= exp(-x)x^α / h(α,x),
67 where h(α,x) is a continued fraction:
68 (2) h(α,x)=x+(1-α)
69 -----
70 1+1
71 -------
72 x+(2-α)
73 ------
74 1+2
75 ------
76 x+(3-α)
77 -------
78 1+...
79 Efficient calculation of h(α,x) is possible because consecutive terms of a continued fraction can be computed by means of
80 a two term linear recursion relation.
81 If for the sequences {p [k]} and {q [k]}, k=0,1,2,... the following difference equations hold
82 (3) y [k+2]=x*y [k+1]+((k+2)/2)* y [k] for k even
83 =y [k+1]((k+3)/2-α)*y [k] for k is odd
84 and initial conditions p [0]=x, p [1]=x+1-α, q [0]=1, q [1]=1, then p [k]/q [k] is the k-th term
85 in the continued fraction for h(α,x).
86
87 The value of h(α+1,x) can be reduced to h(α,x)
88 (4) x/h(α+1,x) = α/h(α,x)+1 by using the following relation between gamma functions:
89 Γ(α+1,x)=αΓ(α,x)+x^α exp(-x).
90 If x is near the negative real axis then x can be moved to some new value y:
91 (5) Γ(α,y)-Γ(α,x)=sum(n=0,Infinity,(-1)^n(x^(α+n)-y^(α+n))/(n!(α+n)),
92 where in the code below a valye of y=1 is used to facilitate the computation.
93
94 Numerical considerations:
95 1. In formula (5) Kostlan & Gokhman use y=1 to facilitate the computation
96 2. If (α,x) is near (−n ,0), where n is a non-negative integer, but x is not equal to zero,
97 the n-th term in (5) can turn out to be 0.0/0.0. They replace this term with -log(x)-(α+n)log(x)²/2.
98 Essentially they are helping the computer to calculate (1-x^(α+n))/(α+n).
99
100 Problems:
101 Kostlan & Gokhman notice three intrinsic problems that any algorithm for calculating Γ(α,x) must face:
102 1. For x=0 and α a nonpositive integer Γ(α,x)=∞.
103 2. If α is not an integer Γ(α,x) is a multi-valued function with a branch point at x=0
104 3. As we approach ∞ along certain directions computation of Γ(α,x) is limited because of the inability to compute x^α accurately.
105
106 */
107
108 static double norm1 (const dcomplex *x) {
109 return fabs (real (*x)) + fabs (imag (*x));
110 }
111
112 static void xShiftTerm (const dcomplex *alpha, const dcomplex *x, integer i, dcomplex *p, dcomplex *q) {
113 // Calculate p*q = (-1)^i (1-x^(alpha+i))/(alpha+i)i!
114 constexpr dcomplex zero = 0.0;
115 constexpr double tol = 3e-7, xlim = 39.0;
116 const double di = i;
117
118 if (i == 0)
119 *q = 1.0;
120 const dcomplex alphai = *alpha + di;
121 if (*x == zero) {
122 *p = 1.0 / alphai;
123 if (i != 0)
124 *q /= -di;
125 return;
126 }
127 const dcomplex cdlx = log (*x);
128 /*
129 If (1-x**alphai) = -x**alphai,
130 then change the inductive scheme to avoid overflow.
131 */
132 if (real (alphai * cdlx) > xlim && i != 0) {
133 *p *= (alphai - 1.0) / alphai;
134 *q *= - *x / di;
135 return;
136 }
137 if (norm1 (& alphai) > tol)
138 *p = (1.0 - std::pow (*x, alphai)) / alphai;
139 else
140 *p = -cdlx * (1.0 + cdlx * alphai * 0.5);
141 if (i == 0)
142 *q /= - di;
143 }
144
145 static void continuedFractionExpansion (const dcomplex *alpha, const dcomplex *x, dcomplex *result) {
146 constexpr double tol1 = 1e10, tol2 = 1e-10, error = 1e-18;
147 constexpr dcomplex zero (0.0,0.0);
148 dcomplex q0 = 1.0, q1 = 1.0, p0 = *x;
149 dcomplex p1 = *x + 1.0 - *alpha, r0;
150 for (integer i = 1; i <= 100000; i++) {
151 const double di = i;
152 if (p0 != zero && q0 != zero && q1 != zero) {
153 r0 = p0 / q0;
154 *result = p1 / q1;
155 const dcomplex r0mr1 = r0 - *result;
156 if (norm1 (& r0mr1) < norm1 (result) * error)
157 return;
158 /*
159 Renormalize to avoid underflow or overflow
160 */
161 if (norm1 (& p0) > tol1 || norm1 (& p0) < tol2 || norm1 (& q0) > tol1 || norm1 (& q0) < tol2) {
162 const dcomplex factor = p0 * q0;
163 p0 /= factor;
164 q0 /= factor;
165 p1 /= factor;
166 q1 /= factor;
167 }
168 p0 = *x * p1 + di * p0; // y [k+2] = x * y [k+1] + (k+2)/2 * y [k] with k even
169 q0 = *x * q1 + di * q0;
170 p1 = p0 + (di + 1.0 - *alpha) * p1; // y [k+2] = y [k+1] + ((k+3)/2 - alpha) * y [k] with k odd
171 q1 = q0 + (di + 1.0 - *alpha) * q1;
172 } else {
173 // We should not come here at all!
174 *result = 0.5 * (r0 + *result);
175 return;
176 }
177 }
178 // We should not come here at all!
179 *result = 0.5 * (r0 + *result);
180 }
181
182 static void shiftAlphaByOne (const dcomplex *alpha, const dcomplex *x, dcomplex *result) {
183 constexpr dcomplex one (1.0, 0.0);
184 const integer n = (integer) (real (*alpha) - real (*x));
185 if (n > 0) {
186 dcomplex cn = n + 1;
187 dcomplex term = one / *x;
188 dcomplex sum = term;
189 const dcomplex alpha1 = *alpha - cn;
190 for (integer i = 1; i <= n; i ++) {
191 cn = n - i + 1;
192 term *= (alpha1 + cn) / *x;
193 sum += term;
194 }
195 continuedFractionExpansion (& alpha1, x, result);
196 sum += term * alpha1 / *result;
197 *result = one / sum;
198 } else {
199 continuedFractionExpansion (alpha, x, result);
200 }
201 }
202
203 // Gamma [alpha,x] = integral{x, infty, t^(alpha-1)exp(-t)dt}, Gamma [alpha]= Gamma [alpha,0]
204 dcomplex NUMincompleteGammaFunction (const dcomplex alpha, const dcomplex x) {
205 dcomplex result;
206 constexpr double xlim = 1.0;
207 constexpr integer ibuf = 34;
208 constexpr dcomplex re = 0.36787944117144232, one = 1.0;
209 dcomplex p, q, r;
210 if (norm1 (& x) < xlim || (real (x) < 0.0 && fabs (imag (x)) < xlim)) {
211 shiftAlphaByOne (& alpha, & one, & r);
212 result = re / r;
213 const integer ilim = (integer) real (x / re);
214 for (integer i = 0; i <= ibuf - ilim; i++) {
215 xShiftTerm (& alpha, & x, i, & p, & q);
216 result += p * q;
217 }
218 } else {
219 shiftAlphaByOne (& alpha, & x, & r);
220 result = exp (-x + alpha * log (x)) / r;
221 }
222 return { real (result), imag (result) };
223 }
224
225 // End of translated fortran code
226
227 /*
228 * We have to scale the amplitude "a" of the gammatone such that the response is 0 dB at the peak (w=w0);
229 *
230 * To calculate the spectrum of the truncated gammatone
231 * g(t) = t^(n-1)*exp(-b*t)cos(w0*t+phi) for 0 < t <= T
232 * g(t) = 0 for t > T
233 * we can write
234 * g(t)= t^(n-1)*exp(-b*t)(exp(I*(w0*t+phi))+exp(-I*(w0*t+phi)))/2
235 * = (gp(t)+gm(t))/2, where
236 * gp(t) = t^(n-1)*exp(-b*t + I*(w0*t+phi))
237 * gm(t) = t^(n-1)*exp(-b*t - I*(w0*t+phi))
238 *
239 * Laplace [g(t)]= Laplace [g(t)]-Laplace [g(t+T)],where
240 * g(t+T) = g2(t) = (t+T)^(n-1)*exp(-b*(t+T))cos(w0*(t+T)+phi) for t>0
241 *
242 * g2(t) = (t+T)^(n-1)*(exp(-b*(t+T)+I(w0*(t+T)+phi) + exp(-b*(t+T)-I(w0*(t+T)+phi)))/2
243 * = (exp(-b*T+I*w0*T+I*phi)(t+T)^(n-1)exp(-b*t+I*w0*t) + exp(-b*T-I*w0*T-I*phi)(t+T)^(n-1)exp(-b*t-I*w0*t))/2
244 * = (gpT(t)+gmT(t))/2, where
245 * gpT(t)= exp(-b*T+I*w0*T+I*phi) (t+T)^(n-1) exp(-b*t+I*w0*t)
246 * gmT(t)= exp(-b*T-I*w0*T-I*phi) (t+T)^(n-1) exp(-b*t-I*w0*t)
247 *
248 * Fp(w) = Laplace [gp(t), s=Iw] = exp( I*phi) (b+I(w-w0))^-n Gamma [n]
249 * Fm(w) = Laplace [gm(t), s=Iw] = exp(-I*phi) (b+I(w+w0))^-n Gamma [n]
250 * FpT(w) = Laplace [gpT(t),s=Iw] = exp( I*phi) exp(I*w*T) (b+I(w-w0))^-n Gamma [n, b*T+I(w-w0)*T]
251 * FmT(w) = Laplace [gmT(t),s=Iw] = exp(-I*phi) exp(I*w*T) (b+I(w+w0))^-n Gamma [n, b*T+I(w+w0)*T]
252 * F(g(t)) = (Fp(w) + Fm(w) - FpT(w) - FmT(w)) / 2
253 *
254 * At resonance w=w0:
255 * F(w0) = (Fp(w0) + Fm(w0) - FpT(w0) - FmT(w0)) / 2 =
256 * = (exp(I*phi) (b)^-n Gamma [n] + exp(-I*phi) (b+I*2*w0)^-n Gamma [n] -
257 * exp(I*phi) exp(I*w0*T) (b)^-n Gamma [n, b*T] -
258 * exp(-I*phi) exp(I*w0*T) (b+I*2*w0)^-n Gamma [n, b*T+I*2*w0)]) / 2
259 * = b^-n(exp(I*phi) Gamma [n] + exp(-I*phi) (1+I*2*w0/b)^-n Gamma [n] -
260 * exp(I*phi) exp(I*w0*T) Gamma [n, b*T0] - exp(-I*phi) exp(I*w0*T) (1+I*2*w0/b)^-n Gamma [n, b*T+I*2*w0*T)]) / 2
261 *
262 * (x+I*y)^-n = (r*exp(I theta))^-n, where r = sqrt(x^2+y^2) and theta = ArcTan (y/x)
263 * (1+I*a)^-n = (1+a^2)^(-n/2) exp(-I*n*theta)
264 */
265 dcomplex gammaToneFilterResponseAtCentreFrequency (double centre_frequency, double bandwidth, double gamma, double initialPhase, double truncationTime) {
266 const double b = NUM2pi * bandwidth, w0 = NUM2pi * centre_frequency, theta = atan (2.0 * centre_frequency / bandwidth);
267 const double gamma_n = exp (NUMlnGamma (gamma)), bpow = pow (b, -gamma);
268 const dcomplex expiphi (cos (initialPhase), sin (initialPhase)), expmiphi = conj (expiphi);
269 const dcomplex expnitheta (cos (gamma * theta), - sin (gamma * theta));
270 const dcomplex expiw0T (cos (w0 * truncationTime), sin (w0 * truncationTime));
271 const dcomplex peak = expnitheta * pow (1.0 + 4.0 * (w0 / b) * (w0 / b), - 0.5 * gamma);
272 const dcomplex r1 = NUMincompleteGammaFunction (dcomplex {gamma, 0.0},dcomplex { b * truncationTime, 0.0});
273 const dcomplex r2 = NUMincompleteGammaFunction (dcomplex {gamma, 0.0}, dcomplex {b * truncationTime, 2.0 * w0 * truncationTime});
274 const dcomplex response = 0.5 * bpow * ((expiphi + expmiphi * peak) * gamma_n -
275 expiw0T * (expiphi * r1 + expmiphi * peak * r2));
276 return response;
277 }
278
279 /* End of file NUMcomplex.cpp */