main
John Lauer Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulat… c0c5c9b
// SPDX-License-Identifier: MIT
//! Offline accuracy evaluation: run the simulator and the detector together and
//! compare the counted displacement with the simulator's ground truth.

use crate::dsp::{DetectParams, Detector};
use crate::sim::{Profile, SimParams, Simulator, FS};
use serde::Serialize;

#[derive(Serialize, Clone)]
pub struct EvalRow {
    pub case: String,
    pub seconds: f64,
    pub c: f64,
    pub speed_note: String,
    pub lp_hz: f64,
    pub multimode: bool,
    pub noise: f64,
    /// Fringe boundaries the target actually crossed (sum of |d floor(L / (lambda/2))|).
    pub true_fringes: u64,
    pub detected: u64,
    /// Detected fringes whose direction disagreed with the true velocity.
    pub dir_errors: u64,
    pub final_err_nm: f64,
    pub rms_err_nm: f64,
    pub max_err_nm: f64,
    pub travel_um: f64,
}

pub fn run_case(name: &str, p: SimParams, d: DetectParams, seconds: f64) -> EvalRow {
    let half = p.wavelength_nm / 2.0;
    let mut sim = Simulator::new(p.clone());
    let mut det = Detector::new(DetectParams { wavelength_nm: p.wavelength_nm, ..d.clone() }, FS);
    let total = (seconds * FS) as usize;
    let chunk = 25_000;
    let mut done = 0usize;
    let mut truth: Vec<f64> = Vec::with_capacity(total);
    let mut events: Vec<(u64, i8)> = vec![];
    let (mut se, mut mx, mut ns) = (0.0f64, 0.0f64, 0u64);
    while done < total {
        let n = chunk.min(total - done);
        let ch = sim.generate(n);
        for i in 0..n {
            let pair = (done + i) as u64;
            if let Some(f) = det.push(ch.ch1[i], pair) {
                events.push((f.pair, f.dir));
            }
            if pair % 250 == 0 {
                let e = det.displacement_nm() - ch.truth_nm[i];
                se += e * e;
                mx = mx.max(e.abs());
                ns += 1;
            }
        }
        truth.extend_from_slice(&ch.truth_nm);
        done += n;
    }
    let mut true_fr = 0u64;
    let mut travel = 0.0;
    for w in truth.windows(2) {
        let a = (w[0] / half).floor() as i64;
        let b = (w[1] / half).floor() as i64;
        true_fr += (b - a).unsigned_abs();
        travel += (w[1] - w[0]).abs();
    }
    // Direction check against the true velocity over +-0.5 ms around each event.
    let mut dir_err = 0u64;
    for &(pair, dir) in &events {
        let i = pair as usize;
        let a = i.saturating_sub(125);
        let b = (i + 125).min(truth.len() - 1);
        let dv = truth[b] - truth[a];
        if dv.abs() > half * 0.25 && (dv > 0.0) != (dir > 0) {
            dir_err += 1;
        }
    }
    let speed_note = match p.profile {
        Profile::Constant => format!("{} um/s", p.speed_um_s),
        Profile::Sine => format!("{} um at {} Hz", p.amp_um, p.freq_hz),
        Profile::Step => format!("{} um steps", p.step_um),
        Profile::Hand => format!("{} um wander", p.jitter_um),
        Profile::Hold => "still".into(),
        Profile::Stage => "test stage".into(),
    };
    EvalRow {
        case: name.into(),
        seconds,
        c: p.c,
        speed_note,
        lp_hz: d.lp_hz,
        multimode: p.multimode,
        noise: p.noise,
        true_fringes: true_fr,
        detected: events.len() as u64,
        dir_errors: dir_err,
        final_err_nm: det.displacement_nm() - truth.last().copied().unwrap_or(0.0),
        rms_err_nm: if ns > 0 { (se / ns as f64).sqrt() } else { 0.0 },
        max_err_nm: mx,
        travel_um: travel / 1000.0,
    }
}

pub fn suite() -> Vec<EvalRow> {
    let base = SimParams::default();
    let d = DetectParams::default();
    let fast = DetectParams { lp_hz: 60_000.0, ..d.clone() };
    let cases: Vec<(&str, SimParams, DetectParams)> = vec![
        ("constant 1 mm/s", SimParams { profile: Profile::Constant, speed_um_s: 1000.0, range_um: 400.0, ..base.clone() }, d.clone()),
        ("constant 5 mm/s, 10 kHz LP", SimParams { profile: Profile::Constant, speed_um_s: 5000.0, range_um: 2000.0, ..base.clone() }, d.clone()),
        ("constant 5 mm/s, 60 kHz LP", SimParams { profile: Profile::Constant, speed_um_s: 5000.0, range_um: 2000.0, ..base.clone() }, fast.clone()),
        ("constant 10 mm/s, 60 kHz LP", SimParams { profile: Profile::Constant, speed_um_s: 10_000.0, range_um: 4000.0, ..base.clone() }, fast.clone()),
        ("sine 5 um, 2 Hz", SimParams { profile: Profile::Sine, amp_um: 5.0, freq_hz: 2.0, ..base.clone() }, d.clone()),
        ("sine 50 um, 5 Hz", SimParams { profile: Profile::Sine, amp_um: 50.0, freq_hz: 5.0, ..base.clone() }, d.clone()),
        ("step 10 um and return", SimParams { profile: Profile::Step, step_um: 10.0, ..base.clone() }, d.clone()),
        ("hand jitter", SimParams { profile: Profile::Hand, ..base.clone() }, d.clone()),
        ("very weak feedback C 0.1", SimParams { profile: Profile::Constant, c: 0.1, ..base.clone() }, d.clone()),
        ("weak feedback C 0.5", SimParams { profile: Profile::Constant, c: 0.5, ..base.clone() }, d.clone()),
        ("C 1.2", SimParams { profile: Profile::Constant, c: 1.2, ..base.clone() }, d.clone()),
        ("C 6", SimParams { profile: Profile::Constant, c: 6.0, ..base.clone() }, d.clone()),
        ("noise x10", SimParams { profile: Profile::Constant, noise: 10.0, ..base.clone() }, d.clone()),
        ("single mode, 2 mm/s over 3 mm", SimParams { profile: Profile::Constant, speed_um_s: 2000.0, range_um: 3000.0, ..base.clone() }, d.clone()),
        ("multimode, 2 mm/s over 3 mm", SimParams { profile: Profile::Constant, speed_um_s: 2000.0, range_um: 3000.0, multimode: true, ..base.clone() }, d.clone()),
    ];
    cases.into_iter().map(|(n, p, d)| run_case(n, p, d, 1.5)).collect()
}

pub fn markdown(rows: &[EvalRow]) -> String {
    let mut s = String::from("| Case | C | Motion | LP | True fringes | Detected | Direction errors | Final error | RMS error | Max error |\n|---|---|---|---|---|---|---|---|---|---|\n");
    for r in rows {
        s += &format!(
            "| {} | {} | {} | {:.0} kHz | {} | {} | {} | {:.0} nm | {:.0} nm | {:.0} nm |\n",
            r.case, r.c, r.speed_note, r.lp_hz / 1000.0, r.true_fringes, r.detected, r.dir_errors, r.final_err_nm, r.rms_err_nm, r.max_err_nm
        );
    }
    s
}

// ------------------------------------------------------------ board v1.2 --

/// One steady-state case through the simulated v1.2 board: laser at `i_ma`,
/// channel 1 second stage at `gain`, both offsets centred the way
/// `smi-dash offset auto` does it, then counting error against truth.
#[derive(Serialize, Clone)]
pub struct BoardRow {
    pub current_ma: f64,
    pub gain: f64,
    pub speed_um_s: f64,
    pub swing_codes: f64,
    pub noise_codes: f64,
    pub score: f64,
    pub true_fringes: u64,
    pub detected: u64,
    pub final_err_nm: f64,
    pub rms_err_nm: f64,
}

pub fn board_case(i_ma: f64, gain: f64, speed: f64, seconds: f64) -> BoardRow {
    use crate::controls::{cmd_laser, cmd_set, SimBoard, OP_HEARTBEAT};
    let p = SimParams { profile: Profile::Constant, speed_um_s: speed, range_um: 400.0, board: true, ..SimParams::default() };
    let half = p.wavelength_nm / 2.0;
    let mut sim = Simulator::new(p);
    let mut b = SimBoard::new(0);
    let map = b.map.clone();
    let li = map.laser();
    let gi = map.find("gain", Some(1), Some("amp")).unwrap();
    let oi = [map.find("offset", Some(1), None).unwrap(), map.find("offset", Some(2), None).unwrap()];
    let gi2 = map.find("gain", Some(2), Some("amp")).unwrap();
    let mut t = 0u64;
    let mut seq = 0u16;
    let mut run = |b: &mut SimBoard, sim: &mut Simulator, pairs: usize, t: &mut u64| {
        let mut out = crate::sim::Chunk::default();
        let mut done = 0;
        while done < pairs {
            let n = 1000.min(pairs - done);
            *t += n as u64 * 4;
            let a = b.advance(*t, n as u64 * 4);
            let c = sim.generate_with(n, Some(&a));
            out.ch1.extend_from_slice(&c.ch1);
            out.ch2.extend_from_slice(&c.ch2);
            out.truth_nm.extend_from_slice(&c.truth_nm);
            done += n;
            seq = seq.wrapping_add(1);
            b.command(&[OP_HEARTBEAT], seq, *t);
        }
        out
    };
    run(&mut b, &mut sim, 375_000, &mut t); // 1.5 s: current-readback zero check
    // Board rule: selectors and offsets are written with the laser off.
    b.command(&cmd_set(gi, 0, gain as f32), 2, t);
    b.command(&cmd_laser(true), 1, t);
    let ack = crate::controls::Ack::parse(&b.command(&cmd_set(li, 0, i_ma as f32), 3, t)).unwrap();
    assert!(ack.ok(), "the firmware refused {i_ma} mA (status {})", ack.status);
    while b.state(t).ramping {
        run(&mut b, &mut sim, 25_000, &mut t);
    }
    run(&mut b, &mut sim, 50_000, &mut t);
    // Centre both channels: Vstage = (1 + K) Voffset - K Vbuffer. Measure with
    // the laser on, then (board rule) turn it off to write the offsets, back on
    // at the same set-point, and let the head's soft-start settle.
    let lsb = 3.3 / 4096.0;
    for _ in 0..5 {
        let c = run(&mut b, &mut sim, 5_000, &mut t);
        let st = b.state(t);
        b.command(&cmd_laser(false), 9, t);
        for (k, ch) in [&c.ch1, &c.ch2].into_iter().enumerate() {
            let mean = ch.iter().map(|&v| v as f64).sum::<f64>() / ch.len() as f64;
            let kk = 1.0 + st.targets[if k == 0 { gi } else { gi2 }].abs() as f64;
            let cur = st.targets[oi[k]] as f64;
            let want = (cur - (mean - 2048.0) * lsb / kk).clamp(0.0, map.controls[oi[k]].max);
            let ack = crate::controls::Ack::parse(&b.command(&cmd_set(oi[k], 0, want as f32), 10, t)).unwrap();
            assert!(ack.ok(), "offset write refused (status {})", ack.status);
        }
        b.command(&cmd_laser(true), 11, t);
        run(&mut b, &mut sim, 75_000, &mut t); // 0.3 s: write, soft-start, settle
    }
    run(&mut b, &mut sim, 25_000, &mut t);
    let mut det = Detector::new(DetectParams::default(), FS);
    let c = run(&mut b, &mut sim, (seconds * FS) as usize, &mut t);
    let t0 = c.truth_nm[0];
    let (mut se, mut ns, mut events) = (0.0, 0u64, 0u64);
    for (i, &v) in c.ch1.iter().enumerate() {
        if det.push(v, i as u64).is_some() {
            events += 1;
        }
        if i % 250 == 0 && i > 2500 {
            let e = det.displacement_nm() - (c.truth_nm[i] - t0);
            se += e * e;
            ns += 1;
        }
    }
    let mut true_fr = 0u64;
    for w in c.truth_nm.windows(2) {
        true_fr += (((w[1] - t0) / half).floor() as i64 - ((w[0] - t0) / half).floor() as i64).unsigned_abs();
    }
    // Swing and noise as the tuner measures them (last 0.4 s).
    let tail: Vec<u16> = c.ch1[c.ch1.len().saturating_sub(100_000)..].to_vec();
    let k = 16;
    let mut avg = vec![];
    let mut res = vec![];
    for i in k..tail.len() {
        let a = tail[i - k..i].iter().map(|&v| v as f64).sum::<f64>() / k as f64;
        avg.push(a);
        res.push((tail[i - k / 2] as f64 - a).abs());
    }
    avg.sort_by(|a, b| a.partial_cmp(b).unwrap());
    res.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let swing = avg[avg.len() * 99 / 100] - avg[avg.len() / 100];
    let noise = res[res.len() / 2] * 1.4826;
    BoardRow {
        current_ma: i_ma,
        gain,
        speed_um_s: speed,
        swing_codes: swing,
        noise_codes: noise,
        score: swing / noise.max(0.5),
        true_fringes: true_fr,
        detected: events,
        final_err_nm: det.displacement_nm() - (c.truth_nm.last().unwrap() - t0),
        rms_err_nm: if ns > 0 { (se / ns as f64).sqrt() } else { 0.0 },
    }
}

/// Laser current x channel 1 second-stage gain, 400 um/s, 2 s each, in parallel.
/// A set-point the firmware refuses would leave the laser at 0, so the case
/// panics rather than report a meaningless row.
pub fn board_suite() -> Vec<BoardRow> {
    let mut hs = vec![];
    // Currents across the map's range, from just above threshold to the limit.
    let map = crate::controls::ControlMap::load();
    let lim = map.controls[map.laser()].limit();
    let currents = [65.0, 80.0, 95.0, (lim - 5.0).floor(), (lim * 10.0).floor() / 10.0];
    for &i in &currents {
        for &g in &[-5.0, -20.0] {
            hs.push(std::thread::spawn(move || board_case(i, g, 400.0, 2.0)));
        }
    }
    hs.into_iter().map(|h| h.join().unwrap()).collect()
}

pub fn board_markdown(rows: &[BoardRow]) -> String {
    let mut s = String::from("| Laser current | Stage 2 gain | Fringe swing | Noise | Score | True fringes | Detected | Final error | RMS error |\n|---|---|---|---|---|---|---|---|---|\n");
    for r in rows {
        s += &format!(
            "| {:.0} mA | {} V/V | {:.0} codes | {:.2} codes | {:.0} | {} | {} | {:.0} nm | {:.0} nm |\n",
            r.current_ma, r.gain, r.swing_codes, r.noise_codes, r.score, r.true_fringes, r.detected, r.final_err_nm, r.rms_err_nm
        );
    }
    s
}