Skip to main content

mathverse_complex/
analysis.rs

1//! Complex analysis: residues, contour integration, analytic continuation.
2
3use crate::Complex;
4
5/// Complex analysis operations.
6pub struct ComplexAnalysis;
7
8impl ComplexAnalysis {
9    /// Compute residue of f(z) at z0 using Laurent series approximation.
10    /// For simple pole: lim_{z->z0} (z - z0) * f(z)
11    pub fn residue_simple_pole(f: &dyn Fn(Complex) -> Complex, z0: Complex, h: f64) -> Complex {
12        let z = z0 + Complex::new(h, 0.0);
13        (z - z0) * f(z)
14    }
15
16    /// Compute residue using derivative formula for higher order poles.
17    /// For pole of order n: (1/(n-1)!) * lim_{z->z0} d^{n-1}/dz^{n-1} [(z-z0)^n * f(z)]
18    pub fn residue_pole_order_n(
19        f: &dyn Fn(Complex) -> Complex,
20        z0: Complex,
21        order: usize,
22        h: f64,
23    ) -> Complex {
24        if order == 1 {
25            return Self::residue_simple_pole(f, z0, h);
26        }
27
28        let g = |z: Complex| (z - z0).powf(order as f64) * f(z);
29        let derivative = Self::nth_derivative(&g, z0, order - 1, h);
30
31        // Divide by factorial
32        let factorial: f64 = (1..=order - 1).map(|x| x as f64).product();
33        derivative / Complex::real(factorial)
34    }
35
36    /// Numerical derivative of complex function (central difference on the
37    /// real axis).
38    pub fn derivative(f: &dyn Fn(Complex) -> Complex, z: Complex, h: f64) -> Complex {
39        let z_plus = z + Complex::new(h, 0.0);
40        let z_minus = z - Complex::new(h, 0.0);
41        (f(z_plus) - f(z_minus)) / Complex::new(2.0 * h, 0.0)
42    }
43
44    /// Complex derivative via the complex-step method.
45    ///
46    /// For analytic `f`, `f'(z) = (f(z + ih) − f(z − ih)) / (2ih)` with
47    /// error `O(h²)`. Stepping along the imaginary axis exercises the
48    /// derivative in the complex plane (not just along the real axis) and
49    /// avoids the cancellation that limits real finite differences.
50    pub fn derivative_complex_step(f: &dyn Fn(Complex) -> Complex, z: Complex, h: f64) -> Complex {
51        let ih = Complex::new(0.0, h);
52        (f(z + ih) - f(z - ih)) / (ih * Complex::real(2.0))
53    }
54
55    /// Full complex derivative via the Cauchy integral formula:
56    /// `f'(z) = (1/(2πi)) ∮ f(w)/(w − z)² dw` around a circle of `radius`
57    /// sampled at `n` points. Robust for analytic `f` (no finite-difference
58    /// step-size tuning needed).
59    pub fn derivative_cauchy(
60        f: &dyn Fn(Complex) -> Complex,
61        z: Complex,
62        radius: f64,
63        n: usize,
64    ) -> Complex {
65        let integrand = |w: Complex| f(w) / (w - z).powf(2.0);
66        let integral = Self::contour_integral_circle(&integrand, z, radius, n);
67        integral / Complex::new(0.0, 2.0 * std::f64::consts::PI)
68    }
69
70    /// Nth derivative of complex function.
71    pub fn nth_derivative(f: &dyn Fn(Complex) -> Complex, z: Complex, n: usize, h: f64) -> Complex {
72        if n == 0 {
73            return f(z);
74        }
75        if n == 1 {
76            return Self::derivative(f, z, h);
77        }
78
79        // Use finite differences for higher derivatives
80        let mut result = Complex::zero();
81
82        for k in 0..=n {
83            let coeff = Self::binomial_coefficient(n, k) as f64;
84            let sign: f64 = if (n - k) % 2 == 0 { 1.0 } else { -1.0 };
85            let z_k = z + Complex::new((k as f64 - n as f64 / 2.0) * h, 0.0);
86            let term = f(z_k) * Complex::real(coeff * sign);
87            result = result + term;
88        }
89
90        result / Complex::new(h.powi(n as i32), 0.0)
91    }
92
93    fn binomial_coefficient(n: usize, k: usize) -> usize {
94        if k > n {
95            return 0;
96        }
97        if k == 0 || k == n {
98            return 1;
99        }
100
101        let mut result = 1;
102        for i in 0..k.min(n - k) {
103            result = result * (n - i) / (i + 1);
104        }
105        result
106    }
107
108    /// Contour integral using trapezoidal rule on a circle.
109    /// ∮_C f(z) dz where C is circle centered at z0 with radius r.
110    pub fn contour_integral_circle(
111        f: &dyn Fn(Complex) -> Complex,
112        z0: Complex,
113        radius: f64,
114        n: usize,
115    ) -> Complex {
116        let mut result = Complex::zero();
117        let h = 2.0 * std::f64::consts::PI / n as f64;
118
119        for k in 0..n {
120            let theta = k as f64 * h;
121            let z = z0 + Complex::polar(radius, theta);
122            // dz = i·r·e^(iθ)·dθ, i.e. angle is θ + π/2 (same θ as z)
123            let dz = Complex::polar(radius * h, theta + std::f64::consts::FRAC_PI_2);
124            result = result + f(z) * dz;
125        }
126
127        result
128    }
129
130    /// Cauchy integral formula: f(z0) = (1/(2πi)) ∮_C f(z)/(z-z0) dz
131    pub fn cauchy_integral_formula(
132        f: &dyn Fn(Complex) -> Complex,
133        z0: Complex,
134        radius: f64,
135        n: usize,
136    ) -> Complex {
137        let integrand = |z: Complex| f(z) / (z - z0);
138        let integral = Self::contour_integral_circle(&integrand, z0, radius, n);
139        integral / Complex::new(0.0, 2.0 * std::f64::consts::PI)
140    }
141
142    /// Cauchy's derivative formula: f^(n)(z0) = (n!/(2πi)) ∮_C f(z)/(z-z0)^(n+1) dz
143    pub fn cauchy_derivative_formula(
144        f: &dyn Fn(Complex) -> Complex,
145        z0: Complex,
146        n: usize,
147        radius: f64,
148        contour_n: usize,
149    ) -> Complex {
150        let integrand = |z: Complex| f(z) / (z - z0).powf((n + 1) as f64);
151        let integral = Self::contour_integral_circle(&integrand, z0, radius, contour_n);
152
153        let factorial: f64 = (1..=n).map(|x| x as f64).product();
154        integral * Complex::real(factorial) / Complex::new(0.0, 2.0 * std::f64::consts::PI)
155    }
156
157    /// Check if function is analytic at point (using Cauchy-Riemann equations).
158    pub fn is_analytic(f: &dyn Fn(Complex) -> Complex, z: Complex, h: f64) -> bool {
159        let z_plus = z + Complex::new(h, 0.0);
160        let z_minus = z - Complex::new(h, 0.0);
161        let z_i_plus = z + Complex::new(0.0, h);
162        let z_i_minus = z - Complex::new(0.0, h);
163
164        let f_z_plus = f(z_plus);
165        let f_z_minus = f(z_minus);
166        let f_z_i_plus = f(z_i_plus);
167        let f_z_i_minus = f(z_i_minus);
168
169        // Partial derivatives
170        let u_x = (f_z_plus.re - f_z_minus.re) / (2.0 * h);
171        let u_y = (f_z_i_plus.re - f_z_i_minus.re) / (2.0 * h);
172        let v_x = (f_z_plus.im - f_z_minus.im) / (2.0 * h);
173        let v_y = (f_z_i_plus.im - f_z_i_minus.im) / (2.0 * h);
174
175        // Cauchy-Riemann equations: u_x = v_y and u_y = -v_x
176        let cr1 = (u_x - v_y).abs() < 1e-6;
177        let cr2 = (u_y + v_x).abs() < 1e-6;
178
179        cr1 && cr2
180    }
181
182    /// Compute Laurent series coefficients around z0.
183    /// Returns (a_n for n >= 0, a_n for n < 0)
184    pub fn laurent_series_coefficients(
185        f: &dyn Fn(Complex) -> Complex,
186        z0: Complex,
187        max_positive: usize,
188        max_negative: usize,
189        radius: f64,
190        n_points: usize,
191    ) -> (Vec<Complex>, Vec<Complex>) {
192        let mut positive = Vec::new();
193        let mut negative = Vec::new();
194
195        // Positive coefficients using Cauchy integral formula
196        for n in 0..=max_positive {
197            let coeff = Self::cauchy_derivative_formula(f, z0, n, radius, n_points);
198            positive.push(coeff);
199        }
200
201        // Negative coefficients using residue formula
202        for n in 1..=max_negative {
203            let integrand = |z: Complex| f(z) * (z - z0).powf(n as f64 - 1.0);
204            let integral = Self::contour_integral_circle(&integrand, z0, radius, n_points);
205            let coeff = integral / Complex::new(0.0, 2.0 * std::f64::consts::PI);
206            negative.push(coeff);
207        }
208
209        (positive, negative)
210    }
211
212    /// Conformal mapping: Möbius transformation.
213    /// f(z) = (az + b) / (cz + d)
214    pub fn mobius_transform(z: Complex, a: Complex, b: Complex, c: Complex, d: Complex) -> Complex {
215        (a * z + b) / (c * z + d)
216    }
217
218    /// Inverse Möbius transformation.
219    pub fn mobius_inverse(w: Complex, a: Complex, b: Complex, c: Complex, d: Complex) -> Complex {
220        (d * w - b) / (a - c * w)
221    }
222
223    /// Schwarz-Christoffel mapping (simplified for polygon).
224    /// Maps upper half-plane to polygon interior.
225    pub fn schwarz_christoffel(
226        z: Complex,
227        vertices: &[Complex],
228        angles: &[f64],
229        pre_factor: Complex,
230    ) -> Complex {
231        let mut integral = Complex::zero();
232        let n = vertices.len();
233
234        for i in 0..n {
235            let alpha = angles[i];
236            let vertex = vertices[i];
237            let term = (z - vertex).powf(alpha - 1.0);
238            integral = integral + term;
239        }
240
241        pre_factor * integral
242    }
243
244    /// Argument principle: (1/(2πi)) ∮ f'(z)/f(z) dz = Z - P
245    /// where Z is number of zeros and P is number of poles inside contour.
246    pub fn argument_principle(
247        f: &dyn Fn(Complex) -> Complex,
248        z0: Complex,
249        radius: f64,
250        n: usize,
251    ) -> f64 {
252        let f_prime = |z: Complex| Self::derivative(f, z, 1e-6);
253        let integrand = |z: Complex| f_prime(z) / f(z);
254        let integral = Self::contour_integral_circle(&integrand, z0, radius, n);
255        (integral.im / (2.0 * std::f64::consts::PI)).round()
256    }
257
258    /// Rouché's theorem test: if |f(z)| > |g(z)| for every z on contour C,
259    /// then f and f+g have same number of zeros inside C.
260    pub fn rouches_theorem(
261        f: &dyn Fn(Complex) -> Complex,
262        g: &dyn Fn(Complex) -> Complex,
263        z0: Complex,
264        radius: f64,
265        n: usize,
266    ) -> bool {
267        // Sufficient sampled check: min |f| > max |g| on the contour
268        let mut min_f: f64 = f64::INFINITY;
269        let mut max_g: f64 = 0.0;
270
271        for k in 0..n {
272            let theta = 2.0 * std::f64::consts::PI * k as f64 / n as f64;
273            let z = z0 + Complex::polar(radius, theta);
274
275            let f_val = f(z).norm();
276            let g_val = g(z).norm();
277
278            min_f = min_f.min(f_val);
279            max_g = max_g.max(g_val);
280        }
281
282        min_f > max_g
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn test_residue_simple_pole() {
292        // f(z) = 1/(z-1), residue at z=1 should be 1
293        let f = |z: Complex| Complex::one() / (z - Complex::real(1.0));
294        let residue = ComplexAnalysis::residue_simple_pole(&f, Complex::real(1.0), 0.001);
295
296        assert!((residue.re - 1.0).abs() < 0.1);
297        assert!(residue.im.abs() < 0.1);
298    }
299
300    #[test]
301    fn test_derivative() {
302        let f = |z: Complex| z * z;
303        let z = Complex::new(2.0, 0.0);
304        let deriv = ComplexAnalysis::derivative(&f, z, 1e-6);
305
306        // derivative of z^2 is 2z = 4
307        assert!((deriv.re - 4.0).abs() < 0.01);
308    }
309
310    #[test]
311    fn test_mobius_transform() {
312        let z = Complex::real(1.0);
313        let a = Complex::real(1.0);
314        let b = Complex::zero();
315        let c = Complex::zero();
316        let d = Complex::real(1.0);
317
318        let result = ComplexAnalysis::mobius_transform(z, a, b, c, d);
319        assert_eq!(result, z);
320    }
321
322    #[test]
323    fn test_cauchy_integral_formula() {
324        // f(z) = z, evaluate at z0 = 1
325        let f = |z: Complex| z;
326        let z0 = Complex::real(1.0);
327        let result = ComplexAnalysis::cauchy_integral_formula(&f, z0, 0.5, 100);
328
329        assert!((result.re - 1.0).abs() < 0.1);
330        assert!(result.im.abs() < 0.1);
331    }
332
333    #[test]
334    fn test_is_analytic() {
335        // f(z) = z^2 is analytic everywhere
336        let f = |z: Complex| z * z;
337        let z = Complex::new(1.0, 1.0);
338
339        assert!(ComplexAnalysis::is_analytic(&f, z, 1e-6));
340    }
341
342    #[test]
343    fn test_contour_integral_z_dz_is_zero() {
344        // ∮ z dz around unit circle = 0 (regression: dz was missing the i·e^(iθ) factor)
345        let f = |z: Complex| z;
346        let result = ComplexAnalysis::contour_integral_circle(&f, Complex::zero(), 1.0, 1000);
347        assert!(result.norm() < 1e-10);
348    }
349
350    #[test]
351    fn test_contour_integral_1_over_z() {
352        // ∮ 1/z dz around unit circle = 2πi
353        let f = |z: Complex| Complex::one() / z;
354        let result = ComplexAnalysis::contour_integral_circle(&f, Complex::zero(), 1.0, 1000);
355        let expected = Complex::new(0.0, 2.0 * std::f64::consts::PI);
356        assert!((result - expected).norm() < 1e-8);
357    }
358
359    #[test]
360    fn test_cauchy_integral_formula_quadratic() {
361        // f(z) = z² at z0 = 1 should give 1
362        let f = |z: Complex| z * z;
363        let result = ComplexAnalysis::cauchy_integral_formula(&f, Complex::real(1.0), 0.5, 200);
364        assert!((result.re - 1.0).abs() < 1e-6);
365        assert!(result.im.abs() < 1e-6);
366    }
367
368    #[test]
369    fn test_nth_derivative_second() {
370        // d²/dz² z³ = 6z; at z=1 that's 6 (regression: term signs were wrong)
371        let f = |z: Complex| z * z * z;
372        let deriv = ComplexAnalysis::nth_derivative(&f, Complex::real(1.0), 2, 0.01);
373        assert!((deriv.re - 6.0).abs() < 1e-6);
374        assert!(deriv.im.abs() < 1e-6);
375    }
376
377    #[test]
378    fn test_mobius_inverse_round_trip() {
379        // Non-unit determinant: (2z+1)/(3z+5), det = 2·5 - 1·3 = 7
380        let a = Complex::real(2.0);
381        let b = Complex::real(1.0);
382        let c = Complex::real(3.0);
383        let d = Complex::real(5.0);
384
385        let z = Complex::new(1.0, 1.0);
386        let w = ComplexAnalysis::mobius_transform(z, a, b, c, d);
387        let back = ComplexAnalysis::mobius_inverse(w, a, b, c, d);
388        assert!((back - z).norm() < 1e-12);
389    }
390
391    #[test]
392    fn test_derivative_complex_step() {
393        // f(z) = z² at z = 2 → 4; off the real axis too
394        let f = |z: Complex| z * z;
395        let d1 = ComplexAnalysis::derivative_complex_step(&f, Complex::new(2.0, 0.0), 1e-6);
396        assert!((d1.re - 4.0).abs() < 1e-4);
397        assert!(d1.im.abs() < 1e-4);
398        let d2 = ComplexAnalysis::derivative_complex_step(&f, Complex::new(1.0, 1.0), 1e-6);
399        // d/dz z² = 2z = 2 + 2i
400        assert!((d2 - Complex::new(2.0, 2.0)).norm() < 1e-4);
401        // f(z) = sin(z): f'(0) = 1, f'(1) = cos(1)
402        let g = |z: Complex| z.sin();
403        let d3 = ComplexAnalysis::derivative_complex_step(&g, Complex::new(1.0, 0.0), 1e-6);
404        assert!((d3.re - 1.0f64.cos()).abs() < 1e-4);
405    }
406
407    #[test]
408    fn test_derivative_cauchy() {
409        // f(z) = z² at z0 = 1 → 2; f(z) = z³ at z0 = i → 3i²·... = -3i
410        let f = |z: Complex| z * z;
411        let d1 = ComplexAnalysis::derivative_cauchy(&f, Complex::one(), 0.5, 200);
412        assert!((d1.re - 2.0).abs() < 1e-6);
413        assert!(d1.im.abs() < 1e-6);
414
415        let g = |z: Complex| z * z * z;
416        let d2 = ComplexAnalysis::derivative_cauchy(&g, Complex::i(), 0.5, 200);
417        // d/dz z³ = 3z² = 3i² = -3
418        assert!((d2.re + 3.0).abs() < 1e-6);
419        assert!(d2.im.abs() < 1e-6);
420    }
421
422    #[test]
423    fn test_rouches_theorem() {
424        // |z| > 0.5 on unit circle: true
425        let f = |z: Complex| z;
426        let g = |_z: Complex| Complex::real(0.5);
427        assert!(ComplexAnalysis::rouches_theorem(
428            &f,
429            &g,
430            Complex::zero(),
431            1.0,
432            100
433        ));
434
435        // |z| < 2 on unit circle: false (regression: max-vs-max check gave a false positive)
436        let h = |_z: Complex| Complex::real(2.0);
437        assert!(!ComplexAnalysis::rouches_theorem(
438            &f,
439            &h,
440            Complex::zero(),
441            1.0,
442            100
443        ));
444    }
445}