1use crate::adaptive_gl7k15_integration_engine::{GAUSS_LEGENDRE_WEIGHTS_7, KRONROD_NODES_15, KRONROD_WEIGHTS_15};
14use lib_jsl_core::ErrorsJSL;
15use num_complex::Complex;
16use std::f64::consts::TAU;
17use std::fmt;
18use std::rc::Rc;
19
20pub type C64 = Complex<f64>;
22
23#[derive(Clone)]
25pub enum PathSegment {
26 Line { from: C64, to: C64 },
28 Arc { centre: C64, radius: f64, start_angle: f64, end_angle: f64 },
31 Curve { z: Rc<dyn Fn(f64) -> C64>, dz: Rc<dyn Fn(f64) -> C64>, t0: f64, t1: f64 },
33}
34
35impl fmt::Debug for PathSegment {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 match self {
38 PathSegment::Line { from, to } => write!(f, "Line({from} -> {to})"),
39 PathSegment::Arc { centre, radius, start_angle, end_angle } => write!(f, "Arc(centre {centre}, r {radius}, {start_angle}..{end_angle})"),
40 PathSegment::Curve { t0, t1, .. } => write!(f, "Curve(t {t0}..{t1})"),
41 }
42 }
43}
44
45impl PathSegment {
46 pub fn line(from: C64, to: C64) -> Self {
48 PathSegment::Line { from, to }
49 }
50
51 pub fn circle(centre: C64, radius: f64) -> Self {
53 PathSegment::Arc { centre, radius, start_angle: 0.0, end_angle: TAU }
54 }
55
56 pub fn arc(centre: C64, radius: f64, start_angle: f64, end_angle: f64) -> Self {
58 PathSegment::Arc { centre, radius, start_angle, end_angle }
59 }
60
61 pub fn curve(z: impl Fn(f64) -> C64 + 'static, dz: impl Fn(f64) -> C64 + 'static, t0: f64, t1: f64) -> Self {
63 PathSegment::Curve { z: Rc::new(z), dz: Rc::new(dz), t0, t1 }
64 }
65
66 fn interval(&self) -> (f64, f64) {
68 match self {
69 PathSegment::Line { .. } => (0.0, 1.0),
70 PathSegment::Arc { start_angle, end_angle, .. } => (*start_angle, *end_angle),
71 PathSegment::Curve { t0, t1, .. } => (*t0, *t1),
72 }
73 }
74
75 fn eval(&self, t: f64) -> (C64, C64) {
77 match self {
78 PathSegment::Line { from, to } => (from + (to - from) * t, to - from),
79 PathSegment::Arc { centre, radius, .. } => {
80 let e = C64::from_polar(1.0, t);
81 (centre + e * *radius, C64::new(0.0, 1.0) * e * *radius)
82 }
83 PathSegment::Curve { z, dz, .. } => (z(t), dz(t)),
84 }
85 }
86
87 pub fn start(&self) -> C64 {
89 self.eval(self.interval().0).0
90 }
91
92 pub fn end(&self) -> C64 {
94 self.eval(self.interval().1).0
95 }
96
97 pub fn point_at(&self, s: f64) -> C64 {
99 let (a, b) = self.interval();
100 self.eval(a + s * (b - a)).0
101 }
102}
103
104#[derive(Debug, Clone, Default)]
106pub struct Contour {
107 pub segments: Vec<PathSegment>,
108}
109
110impl Contour {
111 pub fn new(segments: Vec<PathSegment>) -> Self {
113 Contour { segments }
114 }
115
116 pub fn polyline(vertices: &[C64], closed: bool) -> Self {
118 let n = vertices.len();
119 let count = if closed { n } else { n.saturating_sub(1) };
120 Contour { segments: (0..count).map(|i| PathSegment::line(vertices[i], vertices[(i + 1) % n])).collect() }
121 }
122
123 pub fn circle(centre: C64, radius: f64) -> Self {
125 Contour { segments: vec![PathSegment::circle(centre, radius)] }
126 }
127
128 pub fn rectangle(lower_left: C64, upper_right: C64) -> Self {
131 let (a, c) = (lower_left, upper_right);
132 Self::polyline(&[a, C64::new(c.re, a.im), c, C64::new(a.re, c.im)], true)
133 }
134
135 pub fn then(mut self, other: Contour) -> Self {
137 self.segments.extend(other.segments);
138 self
139 }
140
141 pub fn is_connected(&self, tol: f64) -> bool {
143 self.segments.windows(2).all(|w| (w[0].end() - w[1].start()).norm() <= tol)
144 }
145
146 pub fn is_closed(&self, tol: f64) -> bool {
148 match (self.segments.first(), self.segments.last()) {
149 (Some(first), Some(last)) => self.is_connected(tol) && (last.end() - first.start()).norm() <= tol,
150 _ => false,
151 }
152 }
153
154 pub fn length(&self) -> f64 {
156 self.segments.iter().map(|s| integrate_segment(&|_, dz| C64::new(dz.norm(), 0.0), s, 1e-12, true).0.re).sum()
157 }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq)]
162pub struct PathIntegral {
163 pub value: C64,
164 pub error: f64,
166 pub nfev: usize,
168}
169
170fn gk15(f: &mut impl FnMut(f64) -> C64, a: f64, b: f64) -> (C64, C64, f64) {
173 let (centre, half) = (0.5 * (a + b), 0.5 * (b - a));
174 let mut kronrod = C64::new(0.0, 0.0);
175 let mut gauss = C64::new(0.0, 0.0);
176 let mut absolute = 0.0;
177 for (i, (&x, &wk)) in KRONROD_NODES_15.iter().zip(&KRONROD_WEIGHTS_15).enumerate() {
178 let (sample, magnitude) = if i == 0 {
179 let v = f(centre);
180 (v, v.norm())
181 } else {
182 let (lo, hi) = (f(centre - half * x), f(centre + half * x));
183 (lo + hi, lo.norm() + hi.norm())
184 };
185 kronrod += sample * wk;
186 absolute += magnitude * wk;
187 if i % 2 == 0 {
189 gauss += sample * GAUSS_LEGENDRE_WEIGHTS_7[i / 2];
190 }
191 }
192 (gauss * half, kronrod * half, absolute * half.abs())
193}
194
195fn integrate_segment(weight: &dyn Fn(C64, C64) -> C64, seg: &PathSegment, tol: f64, absolute: bool) -> (C64, f64, usize, bool) {
201 let (a, b) = seg.interval();
202 let evals = std::cell::Cell::new(0usize);
203 let mut integrand = |t: f64| {
204 evals.set(evals.get() + 1);
205 let (z, dz) = seg.eval(t);
206 weight(z, dz)
207 };
208 let total_width = (b - a).abs();
213 const INITIAL_PANELS: usize = 4;
214 let mut stack: Vec<(f64, f64, usize)> = (0..INITIAL_PANELS)
215 .map(|i| (a + (b - a) * i as f64 / INITIAL_PANELS as f64, a + (b - a) * (i + 1) as f64 / INITIAL_PANELS as f64, 0))
216 .collect();
217 let (mut value, mut error) = (C64::new(0.0, 0.0), 0.0);
218 let mut forced = false;
219 let mut magnitude = 0.0;
222 for &(lo, hi, _) in &stack {
223 let (_, k, m) = gk15(&mut integrand, lo, hi);
224 if !k.re.is_finite() || !k.im.is_finite() {
225 return (C64::new(f64::NAN, f64::NAN), f64::NAN, evals.get(), false);
227 }
228 magnitude += m;
229 }
230 let scale = if absolute { 1.0 } else { magnitude.max(1e-300) };
231 const MAX_EVALUATIONS: usize = 2_000_000;
232 while let Some((lo, hi, depth)) = stack.pop() {
233 let (g, k, _) = gk15(&mut integrand, lo, hi);
234 let err = (k - g).norm();
235 let allowed = tol * scale * if total_width > 0.0 { (hi - lo).abs() / total_width } else { 1.0 };
236 if err <= allowed || depth >= 40 || evals.get() > MAX_EVALUATIONS || !err.is_finite() {
239 forced |= err > allowed || !err.is_finite();
240 value += k;
241 error += err;
242 } else {
243 let mid = 0.5 * (lo + hi);
244 stack.push((lo, mid, depth + 1));
245 stack.push((mid, hi, depth + 1));
246 }
247 }
248 let converged = !forced || error <= 10.0 * tol * scale;
249 (value, error, evals.get(), converged)
250}
251
252pub fn contour_integral(f: impl Fn(C64) -> C64, contour: &Contour, tol: f64) -> Result<PathIntegral, ErrorsJSL> {
256 if contour.segments.is_empty() {
257 return Err(ErrorsJSL::InvalidInputRange("The contour has no segments."));
258 }
259 if tol.is_nan() || tol <= 0.0 {
260 return Err(ErrorsJSL::InvalidInputRange("The tolerance must be positive."));
261 }
262 let mut total = PathIntegral { value: C64::new(0.0, 0.0), error: 0.0, nfev: 0 };
263 for seg in &contour.segments {
264 let (v, e, n, converged) = integrate_segment(&|z, dz| f(z) * dz, seg, tol, false);
265 if !converged {
266 return Err(ErrorsJSL::RuntimeError("The integral did not converge (the path may pass through or very near a singularity)."));
267 }
268 total.value += v;
269 total.error += e;
270 total.nfev += n;
271 }
272 if !total.value.re.is_finite() || !total.value.im.is_finite() {
273 return Err(ErrorsJSL::RuntimeError("The integral is not finite (the path may pass through a singularity)."));
274 }
275 Ok(total)
276}
277
278pub fn polyline_integral(f: impl Fn(C64) -> C64, vertices: &[C64], tol: f64) -> Result<PathIntegral, ErrorsJSL> {
280 contour_integral(f, &Contour::polyline(vertices, false), tol)
281}
282
283pub fn residue(f: impl Fn(C64) -> C64, z0: C64, radius: f64, tol: f64) -> Result<C64, ErrorsJSL> {
286 if radius.is_nan() || radius <= 0.0 {
287 return Err(ErrorsJSL::InvalidInputRange("The radius must be positive."));
288 }
289 let r = contour_integral(f, &Contour::circle(z0, radius), tol)?;
290 Ok(r.value / C64::new(0.0, TAU))
291}
292
293pub fn cauchy_derivative(f: impl Fn(C64) -> C64, z0: C64, n: u32, radius: f64, tol: f64) -> Result<C64, ErrorsJSL> {
297 if radius.is_nan() || radius <= 0.0 {
298 return Err(ErrorsJSL::InvalidInputRange("The radius must be positive."));
299 }
300 let r = contour_integral(|z| f(z) / (z - z0).powi(n as i32 + 1), &Contour::circle(z0, radius), tol)?;
301 let factorial: f64 = (1..=n).map(f64::from).product();
302 Ok(r.value * factorial / C64::new(0.0, TAU))
303}
304
305pub fn winding_number(vertices: &[C64], point: C64) -> Option<i32> {
309 let n = vertices.len();
310 if n < 3 {
311 return Some(0);
312 }
313 let mut total = 0.0;
314 for i in 0..n {
315 let (a, b) = (vertices[i] - point, vertices[(i + 1) % n] - point);
316 if a.norm() == 0.0 || b.norm() == 0.0 || (a.re * b.im - a.im * b.re).abs() <= 1e-14 * a.norm() * b.norm() && a.re * b.re + a.im * b.im < 0.0 {
317 return None; }
319 total += (a.re * b.im - a.im * b.re).atan2(a.re * b.re + a.im * b.im);
320 }
321 Some((total / TAU).round() as i32)
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use std::f64::consts::PI;
328
329 fn close(a: C64, b: C64, tol: f64) -> bool {
330 (a - b).norm() < tol
331 }
332
333 #[test]
334 fn integral_of_one_over_z_around_the_unit_circle() {
335 let r = contour_integral(|z| z.inv(), &Contour::circle(C64::new(0.0, 0.0), 1.0), 1e-12).unwrap();
336 assert!(close(r.value, C64::new(0.0, TAU), 1e-10), "{:?}", r);
337 assert!(r.error < 1e-9);
338 let enclosing = contour_integral(|z| z.inv(), &Contour::circle(C64::new(0.5, 0.0), 1.0), 1e-12).unwrap();
340 assert!(close(enclosing.value, C64::new(0.0, TAU), 1e-9));
341 let outside = contour_integral(|z| z.inv(), &Contour::circle(C64::new(3.0, 0.0), 1.0), 1e-12).unwrap();
342 assert!(outside.value.norm() < 1e-10);
343 }
344
345 #[test]
346 fn analytic_functions_are_path_independent() {
347 let f = |z: C64| z * z + z.exp();
348 let antiderivative = |z: C64| z * z * z / 3.0 + z.exp();
349 let (a, b) = (C64::new(0.0, 0.0), C64::new(1.0, 2.0));
350 let want = antiderivative(b) - antiderivative(a);
351 let straight = contour_integral(f, &Contour::new(vec![PathSegment::line(a, b)]), 1e-12).unwrap();
352 let dog_leg = polyline_integral(f, &[a, C64::new(2.0, -1.0), b], 1e-12).unwrap();
353 let arc = Contour::new(vec![PathSegment::line(a, C64::new(0.0, 2.0)), PathSegment::line(C64::new(0.0, 2.0), b)]);
354 let via_arc = contour_integral(f, &arc, 1e-12).unwrap();
355 for r in [straight, dog_leg, via_arc] {
356 assert!(close(r.value, want, 1e-9), "{:?} vs {want}", r.value);
357 }
358 let closed = contour_integral(f, &Contour::rectangle(C64::new(-1.0, -1.0), C64::new(2.0, 1.5)), 1e-12).unwrap();
360 assert!(closed.value.norm() < 1e-9);
361 }
362
363 #[test]
364 fn powers_around_a_circle_and_curves() {
365 for n in [-3, -2, 0, 1, 4] {
367 let r = contour_integral(|z| z.powi(n), &Contour::circle(C64::new(0.0, 0.0), 2.0), 1e-12).unwrap();
368 assert!(r.value.norm() < 1e-9, "n={n}");
369 }
370 let curve = PathSegment::curve(|t| C64::from_polar(2.0, t), |t| C64::new(0.0, 1.0) * C64::from_polar(2.0, t), 0.0, TAU);
372 let r = contour_integral(|z| z.inv(), &Contour::new(vec![curve]), 1e-12).unwrap();
373 assert!(close(r.value, C64::new(0.0, TAU), 1e-10));
374 assert!((Contour::circle(C64::new(1.0, 1.0), 3.0).length() - 6.0 * PI).abs() < 1e-9);
376 assert!((Contour::polyline(&[C64::new(0.0, 0.0), C64::new(3.0, 4.0)], false).length() - 5.0).abs() < 1e-10);
377 }
378
379 #[test]
380 fn residues_and_the_residue_theorem() {
381 let f = |z: C64| (z * z + 1.0).inv();
383 let at_i = residue(f, C64::new(0.0, 1.0), 0.5, 1e-12).unwrap();
384 assert!(close(at_i, C64::new(0.0, -0.5), 1e-10));
385 let at_minus_i = residue(f, C64::new(0.0, -1.0), 0.5, 1e-12).unwrap();
386 assert!(close(at_minus_i, C64::new(0.0, 0.5), 1e-10));
387 let both = contour_integral(f, &Contour::rectangle(C64::new(-2.0, -2.0), C64::new(2.0, 2.0)), 1e-12).unwrap();
389 assert!(both.value.norm() < 1e-9);
390 assert!(close(residue(|z| z.exp() / (z * z), C64::new(0.0, 0.0), 1.0, 1e-12).unwrap(), C64::new(1.0, 0.0), 1e-10));
392 assert!(close(residue(|z| z.exp() / (z * z * z), C64::new(0.0, 0.0), 1.0, 1e-12).unwrap(), C64::new(0.5, 0.0), 1e-10));
393 assert!(residue(f, C64::new(0.0, 1.0), -1.0, 1e-9).is_err());
394 }
395
396 #[test]
397 fn cauchy_formula_for_derivatives() {
398 let z0 = C64::new(0.3, -0.2);
399 for n in 0..5 {
400 let d = cauchy_derivative(|z| z.exp(), z0, n, 1.0, 1e-12).unwrap();
401 assert!(close(d, z0.exp(), 1e-9), "n={n}");
402 }
403 for r in [3.0, 6.0, 10.0] {
407 let d = cauchy_derivative(|z| z.exp(), C64::new(0.0, 0.0), 12, r, 1e-14).unwrap();
408 assert!(close(d, C64::new(1.0, 0.0), 1e-9), "r={r}: {d}");
409 }
410 assert!(close(cauchy_derivative(|z| z.powi(5), C64::new(2.0, 0.0), 2, 0.5, 1e-12).unwrap(), C64::new(160.0, 0.0), 1e-8));
412 }
413
414 #[test]
415 fn winding_numbers_and_contour_properties() {
416 let square = [C64::new(-1.0, -1.0), C64::new(1.0, -1.0), C64::new(1.0, 1.0), C64::new(-1.0, 1.0)];
417 assert_eq!(winding_number(&square, C64::new(0.0, 0.0)), Some(1));
418 assert_eq!(winding_number(&square, C64::new(3.0, 0.0)), Some(0));
419 let reversed: Vec<C64> = square.iter().rev().copied().collect();
420 assert_eq!(winding_number(&reversed, C64::new(0.2, 0.1)), Some(-1));
421 assert_eq!(winding_number(&square, C64::new(1.0, 0.0)), None); assert_eq!(winding_number(&square, C64::new(1.0, 1.0)), None); let twice: Vec<C64> = (0..16).map(|k| C64::from_polar(1.0, TAU * 2.0 * k as f64 / 16.0)).collect();
425 assert_eq!(winding_number(&twice, C64::new(0.0, 0.0)), Some(2));
426 let c = Contour::rectangle(C64::new(0.0, 0.0), C64::new(1.0, 1.0));
427 assert!(c.is_closed(1e-12) && Contour::polyline(&square, false).is_connected(1e-12) && !Contour::polyline(&square, false).is_closed(1e-12));
428 assert!(Contour::default().segments.is_empty() && !Contour::default().is_closed(1e-12));
429 }
430
431 #[test]
432 fn error_handling() {
433 assert!(contour_integral(|z| z, &Contour::default(), 1e-9).is_err());
434 assert!(contour_integral(|z| z, &Contour::circle(C64::new(0.0, 0.0), 1.0), 0.0).is_err());
435 let through_pole = Contour::new(vec![PathSegment::line(C64::new(-1.0, 0.0), C64::new(1.0, 0.0))]);
437 assert!(contour_integral(|z| z.inv(), &through_pole, 1e-9).is_err());
438 let arc = Contour::new(vec![PathSegment::arc(C64::new(0.0, 0.0), 1.0, 0.0, PI)]);
439 let half = contour_integral(|z| z.inv(), &arc, 1e-12).unwrap();
440 assert!(close(half.value, C64::new(0.0, PI), 1e-10));
441 }
442}