main
John Lauer software/: Pico firmware (500 ksps two-channel ADC over DMA, SYNC on GPIO15, framed delta-packed USB stream), smi-dash… e09b832
// SPDX-License-Identifier: MIT
//! Classical fringe detection for self-mixing signals.
//!
//! 1. Low-pass (2nd-order Butterworth, default 10 kHz) to suppress ADC noise.
//! 2. Track the fringe envelope: decaying running max and min give the
//!    peak-to-peak amplitude and midline.
//! 3. Edge detection: a D-sample difference y[n] - y[n-D] with D matched to the
//!    filter's rise time. The sawtooth's sharp jump gives a large difference;
//!    the slow ramp between jumps gives a small one.
//! 4. A jump counts as one fringe (lambda / 2 of travel) when its size exceeds
//!    `threshold` x the envelope's peak-to-peak and the envelope is clear of
//!    the noise floor. The jump's sign gives the direction.
//!
//! Limits, stated plainly: with weak feedback (C below about 1) the signal is a
//! near-sinusoid with no sharp edge, so this detector stops counting; the
//! fringe rate must stay well below the low-pass corner (about fc / 1.5) or the
//! ramp itself crosses the threshold; and when the envelope fades (multimode
//! beating) fringes are missed.

use crate::sim::Biquad;
use rustfft::{num_complex::Complex, FftPlanner};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct DetectParams {
    pub lp_hz: f64,
    /// Jump size as a fraction of the envelope's peak-to-peak.
    pub threshold: f64,
    /// Minimum envelope, in ADC codes, before anything is counted.
    pub min_pp_codes: f64,
    /// Flip the sign convention (depends on the photodiode jumpers and TIA polarity).
    pub invert: bool,
    pub wavelength_nm: f64,
}

impl Default for DetectParams {
    fn default() -> Self {
        Self { lp_hz: 10_000.0, threshold: 0.35, min_pp_codes: 24.0, invert: false, wavelength_nm: 658.0 }
    }
}

#[derive(Clone, Copy, Debug, Serialize)]
pub struct Fringe {
    pub pair: u64,
    /// +1 = target moving away from the laser, -1 = towards it.
    pub dir: i8,
}

pub struct Detector {
    pub p: DetectParams,
    fs: f64,
    lp: Biquad,
    hist: Vec<f64>,
    hpos: usize,
    d: usize,
    env_max: f64,
    env_min: f64,
    decay: f64,
    in_edge: bool,
    edge_best: f64,
    edge_pair: u64,
    refractory: u64,
    last_edge: u64,
    primed: u64,
    /// Signed, squared size of recent edge candidates (exponential average).
    /// Jumps are larger than any ramp segment that crosses the threshold, so
    /// its sign is the jump direction.
    pub jump_sign: f64,
    pub count: i64,
    pub filtered_last: f64,
}

impl Detector {
    pub fn new(p: DetectParams, fs: f64) -> Self {
        let mut d = Self {
            lp: Biquad::lowpass(p.lp_hz, std::f64::consts::FRAC_1_SQRT_2, fs),
            p,
            fs,
            hist: vec![],
            hpos: 0,
            d: 1,
            env_max: f64::MIN,
            env_min: f64::MAX,
            decay: 0.0,
            in_edge: false,
            edge_best: 0.0,
            edge_pair: 0,
            refractory: 0,
            last_edge: 0,
            primed: 0,
            jump_sign: 0.0,
            count: 0,
            filtered_last: 0.0,
        };
        d.configure();
        d
    }

    fn configure(&mut self) {
        let fc = self.p.lp_hz.clamp(500.0, 0.45 * self.fs);
        self.lp = Biquad::lowpass(fc, std::f64::consts::FRAC_1_SQRT_2, self.fs);
        // Difference span: about the filter's 10-90 % rise time (0.35 / fc).
        // Never shorter than the board's own anti-alias rise time (about 2 samples).
        self.d = ((0.35 / fc) * self.fs).round().max(2.0) as usize;
        self.hist = vec![0.0; self.d + 1];
        self.hpos = 0;
        self.refractory = (self.d as u64) * 2;
        // Envelope decays toward the midline with a 30 ms time constant.
        self.decay = 1.0 / (0.03 * self.fs);
        self.primed = 0;
    }

    pub fn set_params(&mut self, p: DetectParams) {
        let refilter = p.lp_hz != self.p.lp_hz;
        self.p = p;
        if refilter {
            self.configure();
        }
    }

    pub fn half_wave_nm(&self) -> f64 {
        self.p.wavelength_nm / 2.0
    }

    pub fn displacement_nm(&self) -> f64 {
        self.count as f64 * self.half_wave_nm()
    }

    pub fn zero(&mut self) {
        self.count = 0;
    }

    /// Process one sample (ADC code) at absolute pair index `pair`.
    /// Returns a fringe when an edge completes.
    #[inline]
    pub fn push(&mut self, code: u16, pair: u64) -> Option<Fringe> {
        let x = code as f64;
        if self.primed == 0 {
            self.lp.reset(x);
            for h in self.hist.iter_mut() {
                *h = x;
            }
            self.env_max = x;
            self.env_min = x;
        }
        self.primed += 1;
        let y = self.lp.run(x);
        self.filtered_last = y;
        // Envelope: jump to new extremes, relax toward each other otherwise.
        if y > self.env_max { self.env_max = y } else { self.env_max -= (self.env_max - y) * self.decay }
        if y < self.env_min { self.env_min = y } else { self.env_min += (y - self.env_min) * self.decay }
        let pp = self.env_max - self.env_min;

        let old = self.hist[self.hpos];
        self.hist[self.hpos] = y;
        self.hpos = (self.hpos + 1) % self.hist.len();
        if self.primed < (self.fs * 0.0005) as u64 {
            return None; // let the filter and envelope settle
        }
        let diff = y - old;
        let thr = self.p.threshold * pp;
        let armed = pp >= self.p.min_pp_codes;
        let mut out = None;
        if armed && diff.abs() > thr && (self.in_edge || pair.saturating_sub(self.last_edge) > self.refractory) {
            if !self.in_edge || diff.abs() > self.edge_best.abs() {
                self.edge_best = diff;
                self.edge_pair = pair;
            }
            self.in_edge = true;
        } else if self.in_edge {
            // A run above threshold ended: it is a candidate edge. At high fringe
            // rates the ramp between jumps also crosses the threshold, with the
            // opposite sign and a smaller size, so weigh candidates by size
            // squared and count only those that agree with the running sign.
            self.in_edge = false;
            self.last_edge = self.edge_pair;
            let rel = self.edge_best / pp.max(1.0);
            let w = rel * rel * rel.signum();
            self.jump_sign = if self.jump_sign == 0.0 { w } else { 0.4 * self.jump_sign + 0.6 * w };
            if self.edge_best.signum() == self.jump_sign.signum() {
                // The board's chain is inverting; a rising jump at the ADC means
                // the power fell sharply, which for this geometry is motion away.
                let mut dir: i8 = if self.edge_best < 0.0 { -1 } else { 1 };
                if self.p.invert {
                    dir = -dir;
                }
                self.count += dir as i64;
                out = Some(Fringe { pair: self.edge_pair, dir });
            }
        }
        out
    }
}

/// Hann-windowed magnitude spectrum in dBFS, max-pooled into `bins` bins.
pub fn spectrum(samples: &[u16], bins: usize, planner: &mut FftPlanner<f64>) -> Vec<f32> {
    let n = samples.len();
    if n < 64 {
        return vec![];
    }
    let mean = samples.iter().map(|&v| v as f64).sum::<f64>() / n as f64;
    let mut buf: Vec<Complex<f64>> = samples
        .iter()
        .enumerate()
        .map(|(i, &v)| {
            let w = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / (n as f64 - 1.0)).cos();
            Complex::new((v as f64 - mean) * w, 0.0)
        })
        .collect();
    planner.plan_fft_forward(n).process(&mut buf);
    let half = n / 2;
    // Full-scale sine (2048 codes amplitude) with a Hann window peaks at 2048 * n / 4.
    let fs_ref = 2048.0 * n as f64 / 4.0;
    let mut out = vec![-140.0f32; bins];
    for (k, c) in buf.iter().take(half).enumerate().skip(1) {
        let b = k * bins / half;
        let db = 20.0 * (c.norm() / fs_ref + 1e-12).log10();
        if (db as f32) > out[b] {
            out[b] = db as f32;
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sim::{Profile, SimParams, Simulator};

    fn run(p: SimParams, seconds: f64) -> (f64, f64, usize) {
        let mut sim = Simulator::new(p.clone());
        let mut det = Detector::new(DetectParams::default(), 250_000.0);
        let n = (seconds * 250_000.0) as usize;
        let ch = sim.generate(n);
        let mut events = 0;
        for (i, &c) in ch.ch1.iter().enumerate() {
            if det.push(c, i as u64).is_some() {
                events += 1;
            }
        }
        (det.displacement_nm(), *ch.truth_nm.last().unwrap(), events)
    }

    #[test]
    fn constant_velocity_counts_and_sign() {
        // 1 mm/s away for 0.2 s over a 400 um range: 200 um, ~608 fringes.
        let p = SimParams { profile: Profile::Constant, speed_um_s: 1000.0, range_um: 400.0, ..Default::default() };
        let (meas, truth, ev) = run(p, 0.2);
        assert!(truth > 190_000.0, "truth {truth}");
        let err = (meas - truth).abs();
        assert!(err < 2.0 * 329.0, "meas {meas} truth {truth} events {ev}");
    }

    #[test]
    fn sine_returns_to_zero() {
        let p = SimParams { profile: Profile::Sine, amp_um: 5.0, freq_hz: 2.0, ..Default::default() };
        let (meas, truth, _) = run(p, 1.0);
        assert!((meas - truth).abs() < 2.0 * 329.0, "meas {meas} truth {truth}");
    }
}