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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
// SPDX-License-Identifier: MIT
//! Physical simulator of the self-mixing interferometer and the board's analog chain.
//!
//! Optics: the Lang-Kobayashi steady-state excess-phase equation
//!     phi_F = phi_0 - C sin(phi_F + atan(alpha)),   phi_0 = 4 pi L / lambda
//! solved on its stable branch with hysteresis, so C < 1 gives a near-sinusoid,
//! C > 1 gives the leaning sawtooth whose lean follows the direction of motion.
//! Power P = P0 (1 + m cos phi_F). An optional second longitudinal mode, spaced so
//! the two fringe patterns beat with nulls every 1.46 mm of travel, shows the
//! fading problem a single-longitudinal-mode laser removes.
//!
//! Electronics, per channel, from the board netlist: photodiode current into a
//! TIA (Rf), a 1:2 divider, an inverting x20 summing amplifier with the offset
//! trim (net gain -10), a 3.9 k / 1 n pole (40.8 kHz), a Sallen-Key stage
//! (44.4 kHz, Q 0.98), then the RP2040 ADC: 12-bit, 3.3 V reference, about
//! 1.3 LSB rms noise and the wide codes at 512, 1536, 2560 and 3584.
//!
//! Board v1.2 (`generate_with` and a BoardAnalog): the laser current from the
//! simulated DAC sets the optical power, the modulation depth, the wavelength
//! (current tuning makes fringes even with the target still) and mode hops;
//! each channel follows the board map's stage equation with its TIA gain,
//! second-stage gain, DAC offset and the monitor bias (see `laser`).
//!
//! The ADC alternates ADC0/ADC1 every 2 us (500 ksps total), so the simulator
//! runs at 500 kHz and samples ch1 on even ticks and ch2 on odd ticks, exactly
//! as the firmware's round robin does.

use rand::rngs::SmallRng;
use rand::SeedableRng;
use rand_distr::{Distribution, Normal};
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;

pub const TICK_HZ: f64 = 500_000.0;
pub const FS: f64 = 250_000.0;
pub const VREF: f64 = 3.3;
/// Two equal modes beat with nulls every `BEAT_MM` of target travel when
/// their spacing is lambda^2 / (2 * BEAT_MM).
pub const BEAT_MM: f64 = 1.46;

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Profile {
    Constant,
    Sine,
    Step,
    Hand,
    Hold,
    /// The target is the test stage's mirror (board 1.3.1 STAGE connector),
    /// driven by the simulated stage running the firmware's stage core.
    Stage,
}

impl Profile {
    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "constant" => Self::Constant,
            "sine" => Self::Sine,
            "step" => Self::Step,
            "hand" => Self::Hand,
            "hold" => Self::Hold,
            "stage" => Self::Stage,
            _ => return None,
        })
    }
    pub const ALL: [&'static str; 6] = ["constant", "sine", "step", "hand", "hold", "stage"];
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct SimParams {
    pub profile: Profile,
    /// Constant profile: speed in um/s; travel then reverses every `range_um`.
    pub speed_um_s: f64,
    pub range_um: f64,
    /// Sine profile: amplitude (um, zero to peak) and frequency.
    pub amp_um: f64,
    pub freq_hz: f64,
    /// Step profile: step size (um), move time (s) and dwell time (s).
    pub step_um: f64,
    pub move_s: f64,
    pub dwell_s: f64,
    /// Hand jitter: rms wander (um) and tremor amplitude (um).
    pub jitter_um: f64,
    pub tremor_um: f64,
    /// Optical feedback parameter C and linewidth enhancement factor alpha.
    pub c: f64,
    pub alpha: f64,
    /// Modulation depth of the laser power by the returning light.
    pub m: f64,
    pub wavelength_nm: f64,
    pub multimode: bool,
    /// Simulate board v1.2: the laser current, gains, offsets and bias come from
    /// the simulated DAC and switches (Controls panel). Off: the v1.1 fixed chain.
    pub board: bool,
    /// Excess intensity noise multiplier (1 = clean bench, 10 = vibration, speckle).
    pub noise: f64,
    /// Offset trim error at the ADC, volts.
    pub offset_v: f64,
    /// Monitor TIA feedback resistor (1000 or 4700 on the board).
    pub rf1_ohm: f64,
    pub idc1_ua: f64,
    /// External photodiode TIA feedback resistor (47 k or 150 k) and DC current.
    pub rf2_ohm: f64,
    pub idc2_ua: f64,
    pub seed: u64,
}

impl Default for SimParams {
    fn default() -> Self {
        Self {
            profile: Profile::Constant,
            speed_um_s: 1000.0,
            range_um: 400.0,
            amp_um: 5.0,
            freq_hz: 1.0,
            step_um: 10.0,
            move_s: 0.15,
            dwell_s: 0.6,
            jitter_um: 1.5,
            tremor_um: 0.3,
            c: 3.0,
            alpha: 4.0,
            m: 0.12,
            wavelength_nm: 658.0,
            multimode: false,
            board: true,
            noise: 1.0,
            offset_v: 0.02,
            rf1_ohm: 4700.0,
            idc1_ua: 35.0,
            rf2_ohm: 47000.0,
            idc2_ua: 8.0,
            seed: 1,
        }
    }
}

/// Bilinear-transform first-order low-pass.
#[derive(Clone, Default)]
struct Pole1 {
    b: f64,
    a: f64,
    x1: f64,
    y1: f64,
}
impl Pole1 {
    fn new(fc: f64, fs: f64) -> Self {
        let k = (PI * fc / fs).tan();
        Self { b: k / (1.0 + k), a: (k - 1.0) / (k + 1.0), x1: 0.0, y1: 0.0 }
    }
    fn reset(&mut self, v: f64) {
        self.x1 = v;
        self.y1 = v;
    }
    fn run(&mut self, x: f64) -> f64 {
        let y = self.b * (x + self.x1) - self.a * self.y1;
        self.x1 = x;
        self.y1 = y;
        y
    }
}

/// Bilinear-transform second-order low-pass (Direct Form I), prewarped at fc.
#[derive(Clone, Default)]
pub struct Biquad {
    b0: f64,
    b1: f64,
    b2: f64,
    a1: f64,
    a2: f64,
    x1: f64,
    x2: f64,
    y1: f64,
    y2: f64,
}
impl Biquad {
    pub fn lowpass(fc: f64, q: f64, fs: f64) -> Self {
        let k = (PI * fc / fs).tan();
        let n = 1.0 / (1.0 + k / q + k * k);
        let b0 = k * k * n;
        Self {
            b0,
            b1: 2.0 * b0,
            b2: b0,
            a1: 2.0 * (k * k - 1.0) * n,
            a2: (1.0 - k / q + k * k) * n,
            ..Default::default()
        }
    }
    pub fn reset(&mut self, v: f64) {
        self.x1 = v;
        self.x2 = v;
        self.y1 = v;
        self.y2 = v;
    }
    #[inline]
    pub fn run(&mut self, x: f64) -> f64 {
        let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2 - self.a1 * self.y1 - self.a2 * self.y2;
        self.x2 = self.x1;
        self.x1 = x;
        self.y2 = self.y1;
        self.y1 = y;
        y
    }
}

/// One longitudinal mode's self-mixing phase, tracked on its stable branch.
#[derive(Clone)]
struct Mode {
    /// 2 pi / lambda for this mode, rad per metre (round trip is 2x).
    k: f64,
    weight: f64,
    phi_f: f64,
    phi0_prev: f64,
    init: bool,
}

impl Mode {
    fn set_lambda(&mut self, lambda_m: f64) {
        self.k = 2.0 * PI / lambda_m;
    }
    fn new(lambda_m: f64, weight: f64) -> Self {
        Self { k: 2.0 * PI / lambda_m, weight, phi_f: 0.0, phi0_prev: 0.0, init: false }
    }

    /// Solve x - phi0 + C sin(x + th) = 0 on the branch continuing from the last
    /// solution. When the branch folds (C > 1) the scan carries the solution to
    /// the next stable branch: that jump is the sawtooth's sharp edge.
    fn step(&mut self, l_m: f64, c: f64, th: f64) -> f64 {
        let phi0 = 2.0 * self.k * l_m;
        if !self.init || c <= 0.0 {
            self.init = true;
            self.phi0_prev = phi0;
            self.phi_f = if c <= 0.0 { phi0 } else { solve_scan(phi0 - 3.0 * PI, phi0, c, th, 1.0) };
            return self.phi_f.cos();
        }
        let d = phi0 - self.phi0_prev;
        self.phi0_prev = phi0;
        // Fast path: Newton from the predicted point on the current branch. Valid
        // while the branch's slope 1 + C cos(x + th) stays well positive; near
        // the fold (the sawtooth edge) fall back to the bracketed scan.
        let x0 = self.phi_f;
        let s0 = 1.0 + c * (x0 + th).cos();
        if s0 > 0.2 {
            let mut x = x0 + d / s0;
            let mut ok = false;
            for _ in 0..4 {
                let (sn, cs) = (x + th).sin_cos();
                let fx = x - phi0 + c * sn;
                let dfx = 1.0 + c * cs;
                if dfx < 0.1 {
                    break;
                }
                let dx = fx / dfx;
                x -= dx;
                if dx.abs() < 1e-10 {
                    ok = 1.0 + c * (x + th).cos() > 0.1 && (x - x0).abs() < 0.3;
                    break;
                }
            }
            if ok {
                self.phi_f = x;
                return x.cos();
            }
        }
        let dir = if d >= 0.0 { 1.0 } else { -1.0 };
        self.phi_f = solve_scan(self.phi_f, phi0, c, th, dir);
        self.phi_f.cos()
    }
}

#[inline]
fn f_eval(x: f64, phi0: f64, c: f64, th: f64) -> f64 {
    x - phi0 + c * (x + th).sin()
}

/// Scan from `x` in direction `dir` until f changes sign the way a stable root
/// does (upward along the scan), then refine by bisection plus Newton.
fn solve_scan(x: f64, phi0: f64, c: f64, th: f64, dir: f64) -> f64 {
    let f0 = f_eval(x, phi0, c, th);
    if f0 == 0.0 {
        return x;
    }
    // If f has the "wrong" sign for the scan direction the root lies behind us
    // (tiny reversal inside one sample); scan the other way.
    let dir = if dir * f0 > 0.0 { -dir } else { dir };
    let step = 0.05 * dir;
    let mut a = x;
    let mut fa = f0;
    let mut b = x;
    let mut fb;
    let mut found = false;
    for _ in 0..800 {
        b = a + step;
        fb = f_eval(b, phi0, c, th);
        if fa.signum() != fb.signum() {
            found = true;
            break;
        }
        a = b;
        fa = fb;
    }
    if !found {
        return phi0;
    }
    let (mut lo, mut hi) = if fa < 0.0 { (a, b) } else { (b, a) };
    let mut r = 0.5 * (lo + hi);
    for _ in 0..40 {
        let fr = f_eval(r, phi0, c, th);
        if fr.abs() < 1e-12 {
            break;
        }
        if fr < 0.0 { lo = r } else { hi = r }
        let dfr = 1.0 + c * (r + th).cos();
        let nr = r - fr / dfr;
        let (mn, mx) = if lo < hi { (lo, hi) } else { (hi, lo) };
        r = if dfr > 1e-9 && nr > mn && nr < mx { nr } else { 0.5 * (lo + hi) };
        if (hi - lo).abs() < 1e-13 {
            break;
        }
    }
    r
}

/// Everything the simulator produces for one chunk.
#[derive(Default)]
pub struct Chunk {
    pub ch1: Vec<u16>,
    pub ch2: Vec<u16>,
    /// Ground-truth target displacement from the start, nm, one per pair.
    pub truth_nm: Vec<f64>,
    /// SYNC edges: (pair index, level).
    pub sync: Vec<(u64, u8)>,
}

pub struct Simulator {
    pub p: SimParams,
    rng: SmallRng,
    modes: Vec<Mode>,
    aa1: [Pole1; 2],
    aa2: [Biquad; 2],
    pub tick: u64,
    t: f64,
    /// Target position relative to its starting point, metres.
    pos: f64,
    /// Hand-jitter state.
    ou: f64,
    drift: f64,
    tremor_phase: f64,
    seg_prev: i64,
    sync_high_until: Option<u64>,
    base_l: f64,
    rebuild: bool,
    t_profile_origin: f64,
    pos_origin: f64,
    /// Board mode: longitudinal modes keyed by (mode number * 2 + beat partner).
    bmodes: Vec<(i64, Mode)>,
    /// Stage profile: the mirror trajectory for the current chunk (nm, one per
    /// `stage_dt_us`), the time the chunk started, and the mirror position when
    /// the profile started (so switching to it never jumps the target).
    stage_traj: Vec<f64>,
    stage_dt_us: f64,
    stage_t0: f64,
    stage_ref: Option<f64>,
}

/// Laser model for board v1.2 (a 658 nm Fabry-Perot diode such as the HL6501MG).
/// Model values, not datasheet figures: threshold 60 mA, 0.45 mW/mA above it,
/// thermal tuning 0.006 nm/mA, a mode hop every 18 mA (at 70, 88 and 106 mA)
/// with two-mode competition within 2 mA of each hop, 0.2 nm mode spacing.
pub mod laser {
    pub const ITH_MA: f64 = 60.0;
    pub const SLOPE_MW_PER_MA: f64 = 0.45;
    /// Reference current: the monitor and external photocurrents and the
    /// modulation depth m in SimParams are given at this current.
    pub const IREF_MA: f64 = 110.0;
    pub const TUNE_NM_PER_MA: f64 = 0.006;
    pub const HOP_FIRST_MA: f64 = 70.0;
    pub const HOP_EVERY_MA: f64 = 18.0;
    pub const HOP_HALF_WIDTH_MA: f64 = 2.0;
    pub const MODE_SPACING_NM: f64 = 0.2;
    /// Photocurrents at IREF: monitor photodiode and the external detector.
    pub const IMON_UA: f64 = 35.0;
    pub const IEXT_UA: f64 = 3.5;
    /// The external TIA's reference is not in the board map: assumed 0.25 V.
    pub const EXT_VREF: f64 = 0.25;

    pub fn power_mw(i: f64) -> f64 {
        if i > ITH_MA { SLOPE_MW_PER_MA * (i - ITH_MA) + 0.4 } else { 0.4 * (i / ITH_MA).max(0.0) }
    }
    /// Self-mixing modulation depth relative to m at IREF: large just above
    /// threshold, falling as the laser is driven harder; zero below threshold.
    pub fn m_scale(i: f64) -> f64 {
        if i <= ITH_MA {
            return 0.0;
        }
        let on = ((i - ITH_MA) / 2.0).min(1.0);
        (((IREF_MA - ITH_MA) / (i - ITH_MA)).powf(0.6)).min(3.0) * on
    }
    fn hop_n(i: f64) -> i64 {
        if i < HOP_FIRST_MA { 0 } else { ((i - HOP_FIRST_MA) / HOP_EVERY_MA).floor() as i64 + 1 }
    }
    /// Active modes at current i: (mode number, weight), one or two of them.
    pub fn modes(i: f64) -> Vec<(i64, f64)> {
        let n = hop_n(i);
        // Distance to the nearest hop centre.
        let k = ((i - HOP_FIRST_MA) / HOP_EVERY_MA).round();
        let h = HOP_FIRST_MA + k * HOP_EVERY_MA;
        let d = i - h;
        if k >= 0.0 && d.abs() < HOP_HALF_WIDTH_MA {
            let x = (d + HOP_HALF_WIDTH_MA) / (2.0 * HOP_HALF_WIDTH_MA);
            let w = x * x * (3.0 - 2.0 * x); // weight of the mode above the hop
            let hi = k as i64 + 1;
            vec![(hi - 1, 1.0 - w), (hi, w)]
        } else {
            vec![(n, 1.0)]
        }
    }
    pub fn lambda_nm(base: f64, i: f64, n: i64) -> f64 {
        base + TUNE_NM_PER_MA * (i - IREF_MA) + MODE_SPACING_NM * (n - hop_n(IREF_MA)) as f64
    }
}

impl Simulator {
    pub fn new(p: SimParams) -> Self {
        let rng = SmallRng::seed_from_u64(p.seed);
        let mut s = Self {
            p,
            rng,
            modes: vec![],
            aa1: [Pole1::new(40_809.0, TICK_HZ), Pole1::new(40_809.0, TICK_HZ)],
            aa2: [Biquad::lowpass(44_368.0, 0.978, TICK_HZ), Biquad::lowpass(44_368.0, 0.978, TICK_HZ)],
            tick: 0,
            t: 0.0,
            pos: 0.0,
            ou: 0.0,
            drift: 0.0,
            tremor_phase: 0.0,
            seg_prev: -1,
            sync_high_until: None,
            // Target 100 mm from the laser, placed 0.18 mm before a beat
            // maximum so multimode runs start bright and fade as they travel.
            base_l: (0.1 / (BEAT_MM * 1e-3)).round() * BEAT_MM * 1e-3 - 0.18e-3,
            rebuild: true,
            t_profile_origin: 0.0,
            pos_origin: 0.0,
            bmodes: vec![],
            stage_traj: vec![],
            stage_dt_us: 50.0,
            stage_t0: 0.0,
            stage_ref: None,
        };
        s.build_modes();
        for i in 0..2 {
            s.aa1[i].reset(1.65);
            s.aa2[i].reset(1.65);
        }
        s
    }

    fn build_modes(&mut self) {
        let lam = self.p.wavelength_nm * 1e-9;
        self.modes = if self.p.multimode {
            let dl = lam * lam / (2.0 * BEAT_MM * 1e-3);
            vec![Mode::new(lam - dl / 2.0, 0.5), Mode::new(lam + dl / 2.0, 0.5)]
        } else {
            vec![Mode::new(lam, 1.0)]
        };
        self.rebuild = false;
    }

    /// Apply new parameters. Changing the wavelength or mode count re-seeds the
    /// optical phase; the motion state carries on.
    pub fn set_params(&mut self, p: SimParams) {
        let rebuild = p.multimode != self.p.multimode || p.wavelength_nm != self.p.wavelength_nm;
        // Any change to the motion restarts it from where the target is now, so
        // the target never jumps (a jump would be an instant multi-fringe move).
        let motion = |q: &SimParams| (q.profile, q.speed_um_s, q.range_um, q.amp_um, q.freq_hz, q.step_um, q.move_s, q.dwell_s);
        let profile_changed = motion(&p) != motion(&self.p);
        self.p = p;
        if rebuild {
            self.build_modes();
        }
        if profile_changed {
            // Start the new motion from where the target is now.
            self.seg_prev = -1;
            self.t_profile_origin = self.t;
            self.pos_origin = self.pos;
            self.ou = 0.0;
            self.drift = 0.0;
            self.stage_ref = None;
        }
    }

    /// The stage mirror's positions over the next chunk (Stage profile).
    pub fn set_stage(&mut self, nm: Vec<f64>, dt_us: f64) {
        self.stage_traj = nm;
        self.stage_dt_us = dt_us;
        self.stage_t0 = self.t;
    }

    fn stage_nm_now(&self) -> Option<f64> {
        let n = self.stage_traj.len();
        if n == 0 {
            return None;
        }
        let x = (self.t - self.stage_t0) * 1e6 / self.stage_dt_us - 1.0;
        if x <= 0.0 {
            return Some(self.stage_traj[0]);
        }
        let i = x.floor() as usize;
        if i + 1 >= n {
            return Some(self.stage_traj[n - 1]);
        }
        let f = x - i as f64;
        Some(self.stage_traj[i] * (1.0 - f) + self.stage_traj[i + 1] * f)
    }
}

impl Simulator {
    /// Advance the motion by one tick. Returns a SYNC edge if a segment starts.
    fn motion(&mut self, dt: f64) -> Option<u8> {
        let tp = self.t - self.t_profile_origin;
        let p = &self.p;
        let um = 1e-6;
        let (target, seg): (f64, i64) = match p.profile {
            Profile::Hold => (self.pos_origin, 0),
            Profile::Stage => match self.stage_nm_now() {
                Some(nm) => {
                    let r = *self.stage_ref.get_or_insert(nm);
                    (self.pos_origin + (nm - r) * 1e-9, 0)
                }
                None => (self.pos, 0),
            },
            Profile::Constant => {
                let range = p.range_um.max(1.0) * um;
                let v = p.speed_um_s.abs().max(0.0) * um;
                if v <= 0.0 {
                    (self.pos, 0)
                } else {
                    let period = 2.0 * range / v;
                    let ph = (tp / period).fract() * period * v; // 0..2*range
                    let rel = if ph < range { ph } else { 2.0 * range - ph };
                    let seg = (tp / (period / 2.0)).floor() as i64;
                    (self.pos_origin + rel, seg)
                }
            }
            Profile::Sine => {
                let w = 2.0 * PI * p.freq_hz;
                let seg = (tp * p.freq_hz).floor() as i64;
                (self.pos_origin + p.amp_um * um * (w * tp).sin(), seg)
            }
            Profile::Step => {
                // Move out, dwell, move back, dwell. Raised-cosine moves.
                let mv = p.move_s.max(0.005);
                let dw = p.dwell_s.max(0.0);
                let period = 2.0 * (mv + dw);
                let ph = tp % period;
                let seg = (tp / (mv + dw)).floor() as i64;
                let s = p.step_um * um;
                let shape = |x: f64| 0.5 - 0.5 * (PI * x.clamp(0.0, 1.0)).cos();
                let rel = if ph < mv {
                    s * shape(ph / mv)
                } else if ph < mv + dw {
                    s
                } else if ph < 2.0 * mv + dw {
                    s * (1.0 - shape((ph - mv - dw) / mv))
                } else {
                    0.0
                };
                (self.pos_origin + rel, seg)
            }
            Profile::Hand => {
                // A hand-held target: smooth wander (velocity is an
                // Ornstein-Uhlenbeck process, position mean-reverts over 1 s)
                // plus a 9 Hz physiological tremor with drifting phase.
                let tau_v: f64 = 0.08;
                let tau_x: f64 = 1.0;
                let sigma_x = p.jitter_um * um;
                let sigma_v = sigma_x / (tau_v * tau_x).sqrt();
                let n: f64 = Normal::new(0.0, 1.0).unwrap().sample(&mut self.rng);
                self.drift += -self.drift / tau_v * dt + sigma_v * (2.0 * dt / tau_v).sqrt() * n;
                self.ou += (self.drift - self.ou / tau_x) * dt;
                let n2: f64 = Normal::new(0.0, 1.0).unwrap().sample(&mut self.rng);
                self.tremor_phase += 2.0 * PI * 9.0 * dt + 0.6 * dt.sqrt() * n2;
                (self.pos_origin + self.ou + p.tremor_um * um * self.tremor_phase.sin(), 0)
            }
        };
        self.pos = target;
        if seg != self.seg_prev {
            let first = self.seg_prev == -1;
            self.seg_prev = seg;
            if !first {
                return Some(1);
            }
        }
        None
    }

    /// Generate `pairs` ADC sample pairs with the v1.1 fixed analog chain.
    pub fn generate(&mut self, pairs: usize) -> Chunk {
        self.generate_with(pairs, None)
    }

    /// Generate `pairs` ADC sample pairs; with `board`, the v1.2 board's laser
    /// current, gains, offsets and bias drive the optics and the analog chain.
    pub fn generate_with(&mut self, pairs: usize, board: Option<&crate::controls::BoardAnalog>) -> Chunk {
        let mut out = Chunk {
            ch1: Vec::with_capacity(pairs),
            ch2: Vec::with_capacity(pairs),
            truth_nm: Vec::with_capacity(pairs),
            sync: vec![],
        };
        if self.rebuild {
            self.build_modes();
        }
        let dt = 1.0 / TICK_HZ;
        let th = self.p.alpha.atan();
        let normal = Normal::new(0.0, 1.0).unwrap();
        let rin = 4e-5 * self.p.noise; // relative intensity noise per tick
        let lsb = VREF / 4096.0;
        let g = 10.0; // divider 1:2 then inverting x20
        let a1 = self.p.rf1_ohm * self.p.idc1_ua * 1e-6 * g;
        let a2 = self.p.rf2_ohm * self.p.idc2_ua * 1e-6 * g;
        // Mechanical noise term: sub-nm white displacement jitter scaled by noise.
        let mech = 0.3e-9 * self.p.noise;
        for _ in 0..pairs {
            let mut pair = [0u16; 2];
            for sub in 0..2 {
                if sub == 0 {
                    if let Some(lv) = self.motion(dt * 2.0) {
                        let pair_idx = self.tick / 2;
                        out.sync.push((pair_idx, lv));
                        self.sync_high_until = Some(pair_idx + 250); // 1 ms pulse
                    }
                    if let Some(until) = self.sync_high_until {
                        if self.tick / 2 >= until {
                            out.sync.push((self.tick / 2, 0));
                            self.sync_high_until = None;
                        }
                    }
                }
                let l = self.base_l + self.pos + mech * normal.sample(&mut self.rng);
                let (v1, v2) = if let Some(b) = board {
                    let i = b.i0_ma + (b.i1_ma - b.i0_ma) * (out.ch1.len() as f64 + 0.5 * sub as f64) / pairs as f64;
                    let act = laser::modes(i);
                    let beat_dl = if self.p.multimode { let lam = self.p.wavelength_nm; lam * lam / (2.0 * BEAT_MM * 1e6) } else { 0.0 };
                    let mut fr = 0.0;
                    let mut keys = [i64::MIN; 4];
                    let mut nk = 0;
                    for &(n, w) in &act {
                        let parts: &[(i64, f64, f64)] = if self.p.multimode { &[(0, 0.5, -0.5), (1, 0.5, 0.5)] } else { &[(0, 1.0, 0.0)] };
                        for &(pi, pw_, off) in parts {
                            let key = n * 2 + pi;
                            let lam = (laser::lambda_nm(self.p.wavelength_nm, i, n) + off * beat_dl) * 1e-9;
                            let m = match self.bmodes.iter_mut().find(|(k, _)| *k == key) {
                                Some((_, m)) => m,
                                None => {
                                    self.bmodes.push((key, Mode::new(lam, 1.0)));
                                    &mut self.bmodes.last_mut().unwrap().1
                                }
                            };
                            m.set_lambda(lam);
                            fr += w * pw_ * m.step(l, self.p.c, th);
                            keys[nk] = key;
                            nk += 1;
                        }
                    }
                    self.bmodes.retain(|(k, _)| keys[..nk].contains(k));
                    // Mode competition near a hop adds partition noise.
                    let wmix = if act.len() == 2 { act[0].1 * act[1].1 } else { 0.0 };
                    let prel = laser::power_mw(i) / laser::power_mw(laser::IREF_MA);
                    let m = self.p.m * laser::m_scale(i);
                    let pw = 1.0 + m * fr + rin * (1.0 + 120.0 * wmix) * normal.sample(&mut self.rng);
                    let i1 = laser::IMON_UA * 1e-6 * prel * pw;
                    let i2 = laser::IEXT_UA * 1e-6 * prel * pw;
                    // Vbuffer = Vref + I * Rf (rail-limited), Vstage = (1 + K) Voff - K Vbuffer.
                    let vb1: f64 = (b.bias_v + i1 * b.rf1).min(5.2);
                    let vb2: f64 = (laser::EXT_VREF + i2 * b.rf2).min(5.2);
                    let s1: f64 = ((1.0_f64 + b.k1) * b.off1_v - b.k1 * vb1).clamp(0.02, 5.25);
                    let s2: f64 = ((1.0_f64 + b.k2) * b.off2_v - b.k2 * vb2).clamp(0.02, 5.25) + 0.002 * (2.0 * PI * 100.0 * self.t).sin();
                    (s1, s2)
                } else {
                    let mut fr = 0.0;
                    for m in self.modes.iter_mut() {
                        fr += m.weight * m.step(l, self.p.c, th);
                    }
                    let pw = 1.0 + self.p.m * fr + rin * normal.sample(&mut self.rng);
                    // Both channels see the same optical power fluctuation (rear monitor
                    // and front pickoff), each through its own TIA and the inverting chain.
                    (1.65 + self.p.offset_v - a1 * (pw - 1.0), 1.65 - 0.6 * self.p.offset_v - a2 * (pw - 1.0) + 0.002 * (2.0 * PI * 100.0 * self.t).sin())
                };
                let y1 = self.aa2[0].run(self.aa1[0].run(v1));
                let y2 = self.aa2[1].run(self.aa1[1].run(v2));
                let y = if sub == 0 { y1 } else { y2 };
                let code = adc_code(y + 1.3 * lsb * normal.sample(&mut self.rng), lsb);
                pair[sub] = code;
                self.t += dt;
                self.tick += 1;
            }
            out.ch1.push(pair[0]);
            out.ch2.push(pair[1]);
            out.truth_nm.push(self.pos * 1e9);
        }
        out
    }
}

/// RP2040 ADC transfer: 12-bit, clipped to the rails, with the documented wide
/// codes (differential non-linearity) at 512, 1536, 2560 and 3584.
fn adc_code(v: f64, lsb: f64) -> u16 {
    let x = (v / lsb).clamp(0.0, 4095.0);
    let mut c = x.floor() as i32;
    let r = c % 1024;
    if (508..512).contains(&r) {
        c = c - r + 512;
    } else if (512..516).contains(&r) {
        c = c - r + 512;
    }
    c.clamp(0, 4095) as u16
}