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