1use super::*;
4
5pub(in crate::coating) fn wave_segment(
7 wls: &[f64],
8 wl: f64,
9 kinks: &[f64],
10) -> Option<(usize, usize)> {
11 const EPS: f64 = 1e-9;
12 let n = wls.len();
13 if n == 0 || !(wls[0] - EPS <= wl && wl <= wls[n - 1] + EPS) {
14 return None;
15 }
16 let lo = kinks
18 .iter()
19 .copied()
20 .filter(|&k| k <= wl + EPS)
21 .fold(f64::NEG_INFINITY, f64::max);
22 let hi = kinks
23 .iter()
24 .copied()
25 .filter(|&k| k > wl + EPS)
26 .fold(f64::INFINITY, f64::min);
27 let s = wls.partition_point(|&w| w < lo - EPS);
28 let e = wls.partition_point(|&w| w <= hi + EPS);
29 let n = e - s;
30 if n == 0 || (n < 2 && n < wls.len()) {
32 return None;
33 }
34 Some((s, e))
35}
36
37pub(in crate::coating) fn wave_weights(
40 wls: &[f64],
41 wl: f64,
42 kinks: &[f64],
43 p: usize,
44) -> Option<(usize, Vec<f64>)> {
45 let (s, e) = wave_segment(wls, wl, kinks)?;
46 let seg = &wls[s..e];
47 let n = seg.len();
48 let m = n.min(p);
49 let i = seg
50 .partition_point(|&w| w < wl)
51 .saturating_sub(m / 2)
52 .min(n - m);
53 let x: Vec<f64> = seg[i..i + m].iter().map(|w| 1.0 / w).collect();
54 Some((s + i, lagrange_weights(&x, 1.0 / wl)))
55}
56
57pub(in crate::coating) fn lagrange_weights(x: &[f64], q: f64) -> Vec<f64> {
59 let m = x.len();
60 (0..m)
61 .map(|a| {
62 (0..m)
63 .filter(|&b| b != a)
64 .map(|b| (q - x[b]) / (x[a] - x[b]))
65 .product()
66 })
67 .collect()
68}
69
70pub(in crate::coating) fn local_weights(
72 xs: &[f64],
73 n: usize,
74 p: usize,
75 q: f64,
76) -> (usize, Vec<f64>) {
77 let m = n.min(p);
78 let i = xs[..n]
79 .partition_point(|&x| x < q)
80 .saturating_sub(m / 2)
81 .min(n - m);
82 (i, lagrange_weights(&xs[i..i + m], q))
83}
84
85#[derive(Debug, Clone, Copy, PartialEq)]
87pub(crate) struct MirrorBranch {
88 pub(in crate::coating) xb: f64,
90 pub(in crate::coating) k: usize,
92 pub(in crate::coating) on_grid: bool,
94}
95
96pub(in crate::coating) const MIRROR_BRANCH_MIN_DEV: f64 = 1e-5;
100
101pub const MIRROR_TIR_TOL: f64 = 1e-8;
105
106pub(in crate::coating) const MIRROR_BRANCH_SNAP: f64 = 1e-6;
110
111pub(in crate::coating) const RATIONAL_N: usize = 8;
113
114pub(in crate::coating) fn rational_at(
118 xs: &[f64],
119 s: usize,
120 e: usize,
121 q: f64,
122 f: &dyn Fn(usize) -> C64,
123) -> C64 {
124 let n = e - s;
125 let start = |m: usize| {
126 s + xs[s..e]
127 .partition_point(|&x| x < q)
128 .saturating_sub(m / 2)
129 .min(n - m)
130 };
131 let mut m = RATIONAL_N.min(n - n % 2);
132 while m >= 4 {
133 if let Some(v) = rational_solve(xs, start(m), m, q, f) {
134 return v;
135 }
136 m -= 2;
137 }
138 let m = n.min(4);
139 let i = start(m);
140 (i..i + m)
141 .map(|a| {
142 let w: f64 = (i..i + m)
143 .filter(|&b| b != a)
144 .map(|b| (q - xs[b]) / (xs[a] - xs[b]))
145 .product();
146 f(a) * w
147 })
148 .sum::<C64>()
149}
150
151pub(in crate::coating) fn rational_solve(
153 xs: &[f64],
154 i: usize,
155 m: usize,
156 q: f64,
157 f: &dyn Fn(usize) -> C64,
158) -> Option<C64> {
159 let t: Vec<f64> = (i..i + m).map(|j| xs[j] - q).collect();
160 let h = t.iter().fold(0.0f64, |a, b| a.max(b.abs())).max(1e-300);
161 let (np, nq) = (m / 2, m - m / 2);
163 let mut a = vec![vec![C64::new(0.0, 0.0); m + 1]; m];
164 for (r, row) in a.iter_mut().enumerate() {
165 let u = t[r] / h;
166 let fv = f(i + r);
167 for (k, v) in row.iter_mut().enumerate().take(np) {
168 *v = C64::new(u.powi(k as i32), 0.0);
169 }
170 for k in 1..=nq {
171 row[np + k - 1] = -fv * u.powi(k as i32);
172 }
173 row[m] = fv;
174 }
175 let scale = a
176 .iter()
177 .flat_map(|r| r[..m].iter().map(|v| v.norm()))
178 .fold(0.0, f64::max);
179 for c in 0..m {
180 let p = (c..m).max_by(|&x, &y| a[x][c].norm().total_cmp(&a[y][c].norm()))?;
181 if a[p][c].norm() <= 1e-11 * scale {
182 return None;
183 }
184 a.swap(c, p);
185 for r in 0..m {
186 if r != c {
187 let g = a[r][c] / a[c][c];
188 for k in c..=m {
189 let v = a[c][k];
190 a[r][k] -= g * v;
191 }
192 }
193 }
194 }
195 let v = a[0][m] / a[0][0];
196 (v.re.is_finite() && v.im.is_finite()).then_some(v)
197}
198
199pub(in crate::coating) fn mirror_branch(b2: &[f64], r: &[[C64; 2]]) -> Option<MirrorBranch> {
207 let dev = |j: usize| {
208 r[j].iter()
209 .map(|v| (v.norm() - 1.0).abs())
210 .fold(0.0, f64::max)
211 };
212 let n = b2.len();
213 let k = (0..n).rev().find(|&j| !(dev(j) < MIRROR_TIR_TOL))? + 1;
214 if k < 4 || n - k < 4 || dev(k - 1).max(dev(k - 2)) < MIRROR_BRANCH_MIN_DEV {
217 return None;
218 }
219 let m = RATIONAL_N.min(k).min(n - k);
220 let gap = |xb: f64| -> f64 {
222 let tl: Vec<f64> = (0..m)
223 .map(|i| (xb - b2[k - 1 - i]).max(0.0).sqrt())
224 .collect();
225 let th: Vec<f64> = (0..m).map(|i| (b2[k + i] - xb).max(0.0).sqrt()).collect();
226 (0..2)
227 .map(|pol| {
228 let lo = rational_at(&tl, 0, m, 0.0, &|i| r[k - 1 - i][pol]);
229 let hi = rational_at(&th, 0, m, 0.0, &|i| r[k + i][pol]);
230 (lo - hi).norm()
231 })
232 .sum::<f64>()
233 };
234 let (a0, c0) = (b2[k - 1], b2[k]);
235 const N: usize = 200;
236 let grid = |i: usize| a0 + (c0 - a0) * i as f64 / N as f64;
237 let j = (0..=N)
238 .min_by(|&p, &q| gap(grid(p)).total_cmp(&gap(grid(q))))
239 .unwrap_or(0);
240 let (mut a, mut c) = (grid(j.saturating_sub(1)), grid((j + 1).min(N)));
241 for _ in 0..60 {
243 let (p, q) = (a + (c - a) * 0.381_966, a + (c - a) * 0.618_034);
244 if gap(p) < gap(q) {
245 c = q;
246 } else {
247 a = p;
248 }
249 }
250 let xb = 0.5 * (a + c);
251 let xb = if gap(xb) <= gap(grid(j)) { xb } else { grid(j) };
253 let tol = MIRROR_BRANCH_SNAP * (c0 - a0);
255 let (xb, on_grid) = if xb - a0 <= tol {
256 (a0, true)
257 } else if c0 - xb <= tol {
258 (c0, true)
259 } else {
260 (xb, false)
261 };
262 Some(MirrorBranch { xb, k, on_grid })
263}
264
265pub(in crate::coating) fn out_of_waves(wls: &[f64], wl: f64) -> String {
267 match (wls.first(), wls.last()) {
268 (Some(&a), Some(&b)) if a - 1e-9 <= wl && wl <= b + 1e-9 => {
269 "has fewer than 2 measured wavelengths between the kinks (KINKS) around it".to_string()
270 }
271 (Some(&a), Some(&b)) => format!("is outside the range ({a} to {b} µm)"),
272 _ => "has no wavelength data".to_string(),
273 }
274}
275
276pub(in crate::coating) fn beta_spline(name: &str, b2: &[f64], ys: &[f64]) -> Result<Spline> {
278 match Spline::not_a_knot(b2, ys) {
279 Some(s) => Ok(s),
280 None => invalid!("coating model {name}: β can't be interpolated"),
281 }
282}
283
284pub(in crate::coating) fn unwrap_deg(v: &mut [f64]) {
287 for i in 1..v.len() {
288 let d = v[i] - v[i - 1];
289 v[i] -= 360.0 * (d / 360.0).round();
290 }
291}
292
293pub fn interp(x: f64, xs: &[f64], ys: &[f64]) -> f64 {
294 let n = xs.len();
295 if x.is_nan() {
296 return f64::NAN;
297 }
298 if n == 1 || x <= xs[0] {
299 return ys[0];
300 }
301 if x >= xs[n - 1] {
302 return ys[n - 1];
303 }
304 let i = xs.partition_point(|&v| v <= x) - 1;
305 let t = (x - xs[i]) / (xs[i + 1] - xs[i]);
306 ys[i] + t * (ys[i + 1] - ys[i])
307}
308
309#[derive(Debug, Clone)]
312pub(in crate::coating) struct Branch {
313 pub(in crate::coating) xb: f64,
314 pub(in crate::coating) lo_end: usize,
316 pub(in crate::coating) t_lo: Vec<f64>,
317 pub(in crate::coating) hi_start: usize,
319 pub(in crate::coating) t_hi: Vec<f64>,
320}
321
322impl Branch {
323 pub(in crate::coating) fn new(b2: &[f64], xb: f64) -> Branch {
324 let lo_end = b2.partition_point(|&v| v <= xb + 1e-12);
326 let hi_start = b2.partition_point(|&v| v < xb - 1e-12);
327 Branch {
328 xb,
329 lo_end,
330 t_lo: (0..lo_end)
331 .rev()
332 .map(|j| (xb - b2[j]).max(0.0).sqrt())
333 .collect(),
334 hi_start,
335 t_hi: (hi_start..b2.len())
336 .map(|j| (b2[j] - xb).max(0.0).sqrt())
337 .collect(),
338 }
339 }
340
341 pub(in crate::coating) fn eval(&self, x: f64, f: &dyn Fn(usize) -> C64) -> C64 {
343 if x <= self.xb {
344 let q = (self.xb - x).sqrt();
345 rational_at(&self.t_lo, 0, self.t_lo.len(), q, &|i| {
346 f(self.lo_end - 1 - i)
347 })
348 } else {
349 let q = (x - self.xb).sqrt();
350 rational_at(&self.t_hi, 0, self.t_hi.len(), q, &|i| f(self.hi_start + i))
351 }
352 }
353}