use multishoot::periodic::{sin_cos_grid, spectrum, tail, Parity};
use multishoot::DD;
use multisolver::prec::nan_max;
const PHASES: [(f64, f64); 4] = [
(0.6, 0.8),
(5.0 / 13.0, 12.0 / 13.0),
(8.0 / 17.0, 15.0 / 17.0),
(1.0, 0.0),
];
fn planted(parity: Parity, m: usize) -> Vec<(i64, DD, DD)> {
let n = if parity == Parity::Full { m as i64 } else { 2 * m as i64 };
(0..=n / 2)
.filter(|&k| match parity {
Parity::Full => true,
Parity::Odd => k % 2 == 1,
Parity::Even => k % 2 == 0,
})
.map(|k| {
let amp = DD::from_f64(10f64.powi(-(k as i32)));
let (c, s) = if k == 0 || 2 * k == n {
(1.0, 0.0)
} else {
PHASES[k as usize % 4]
};
(k, amp * DD::from_f64(c), amp * DD::from_f64(s))
})
.collect()
}
fn field(parity: Parity, m: usize, coef: &[(i64, DD, DD)]) -> Vec<DD> {
(0..m)
.map(|j| {
coef.iter().fold(DD::ZERO, |t, &(k, a, b)| {
let (s, c) = sin_cos_grid(parity, m, j, k);
t + a * c + b * s
})
})
.collect()
}
fn coef_err(got: &[(i64, DD, DD)], want: &[(i64, DD, DD)]) -> f64 {
assert_eq!(got.len(), want.len());
got.iter()
.zip(want)
.map(|(g, w)| {
assert_eq!(g.0, w.0);
nan_max((g.1 - w.1).hi.abs(), (g.2 - w.2).hi.abs())
})
.fold(0.0, nan_max)
}
#[test]
fn spectrum_recovers_planted_coefficients() {
for (parity, m) in [(Parity::Full, 16), (Parity::Odd, 8), (Parity::Even, 8)] {
let want = planted(parity, m);
let f = field(parity, m, &want);
let e = coef_err(&spectrum(parity, &f), &want);
let amp: Vec<f64> = want.iter().map(|&(_, a, b)| a.hi.hypot(b.hi)).collect();
let ratio = amp[amp.len() - 2..].iter().copied().fold(0.0, nan_max) / amp.iter().copied().fold(0.0, nan_max);
let t = tail(parity, &f, 2);
let tail_ok = |t: f64| (t / ratio - 1.0).abs() <= 1e-12;
println!("{parity:?} on {m}: coefficients {e:.3e}, tail {t:.6e} (planted {ratio:.6e})");
assert!(e <= 1e-30 && tail_ok(t), "{parity:?}");
assert!(!tail_ok(2.0 * t), "tail control did not fire");
let mut nan = spectrum(parity, &f);
nan[1].2 = DD::from_f64(f64::NAN);
let accurate = |e: f64| e <= 1e-30;
assert!(!accurate(coef_err(&nan, &want)), "NaN control did not fire");
}
let want = planted(Parity::Full, 16);
let mut off = want.clone();
off[3].1 = off[3].1 + DD::from_f64(1e-20);
let e = coef_err(&spectrum(Parity::Full, &field(Parity::Full, 16, &off)), &want);
println!("control, a_3 changed by 1e-20: {e:.3e}");
assert!(e > 1e-25, "control did not fire");
}