stable-flight 0.3.0

no_std autopilot core for Stable Flight: copter, plane, tailsitter, and quadplane guidance and stabilizers, waypoint navigation, failsafe, autotune, mixers, and the per-tick flight loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use assert2::{assert, check};

use super::*;
use crate::tuning::plant::{Plant, PlantParams, gyro_noise};
use crate::tuning::{LoopSignals, Measurement, Probe, ProbeConfig, ProbeStatus};

/// The flight loop's tick: 250 Hz.
const DT: f32 = 0.004;

/// A 0.07 square wave for 3 s, washed out as the copter's, and not extended.
const CONFIG: IdentifyConfig = IdentifyConfig {
    amplitude: 0.07,
    duration_s: 3.0,
    washout_tc_s: 0.2,
    noisy: None,
};

/// [`CONFIG`], a noisy window extended to 8 s at twice the amplitude, as the copter's.
const EXTENDED: IdentifyConfig = IdentifyConfig {
    noisy: Some(IdentifyExtension {
        amplitude: 0.14,
        duration_s: 8.0,
    }),
    ..CONFIG
};

/// Angle P (rate per angle) and rate P (moment per rate) of the loops the tests close around
/// the plant: stable on every row's plant.
const ANGLE_P: f32 = 4.0;
const RATE_P: f32 = 0.3;

/// Runs `probe` on `params`'s axis inside an angle loop and a rate loop, as a copter host
/// flies it: the probe's offset on the angle setpoint, the axis's rate (through `corrupt`,
/// given the tick) and last moment back. Returns the finished probe.
fn identify_with(
    params: PlantParams,
    mut probe: IdentifyProbe,
    corrupt: impl Fn(usize, f32) -> f32,
) -> IdentifyProbe {
    let mut plant = Plant::new(params, DT);
    let (mut angle_rad, mut last_moment) = (0.0f32, 0.0f32);
    let mut tick = 0;
    while matches!(probe.status(), IdentifyStatus::Running { .. }) {
        let rate_radps = plant.measure();
        let offset_rad = probe.step(DT, corrupt(tick, rate_radps), last_moment);
        let rate_setpoint_radps = ANGLE_P * (offset_rad - angle_rad);
        last_moment = (RATE_P * (rate_setpoint_radps - rate_radps)).clamp(-1.0, 1.0);
        plant.step(last_moment);
        angle_rad += plant.output() * DT;
        tick += 1;
    }
    probe
}

/// [`identify_with`] on clean signals: the probe's final status.
fn identify(params: PlantParams, probe: IdentifyProbe) -> IdentifyStatus {
    identify_with(params, probe, |_, rate_radps| rate_radps).status()
}

fn model(status: IdentifyStatus) -> RateModel {
    match status {
        IdentifyStatus::Done(model) => model,
        other => panic!("expected Done, got {other:?}"),
    }
}

/// A plant with one lag: the second sits at 1 ms, under a tick.
fn single_lag(gain: f32, lag_s: f32, delay_s: f32) -> PlantParams {
    PlantParams {
        gain,
        lag1_s: lag_s,
        lag2_s: 0.001,
        delay_s,
        ..PlantParams::rate_axis()
    }
}

/// The fit recovers each plant's lag and delay, and its gain, from 3 s of excitation in closed
/// loop: (gain rad/s² per unit moment, lag s, dead time s) → delay ticks. The plant's moment
/// takes effect the dead time plus 1½ ticks on (the probe's one tick and half of the
/// zero-order hold's), and the fit trades delay against lag between near-tied fits, so it holds
/// what the design's phase reads: the fitted lag plus delay within 10% of the plant's two lags
/// plus that time (measured within 1.8%), the delay within a tick of it, and the gain within
/// 10%.
#[test]
fn recovers_lag_delay_and_gain() {
    let rows = [
        ((20.0, 0.02, 0.0), 1.5),
        ((40.0, 0.03, 0.0), 1.5),
        ((10.0, 0.05, 0.0), 1.5),
        ((5.0, 0.2, 0.0), 1.5),
        ((20.0, 0.03, 0.008), 3.5),
        ((20.0, 0.03, 0.02), 6.5),
    ];
    for ((gain, lag_s, delay_s), delay_ticks) in rows {
        let row = format!("gain {gain}, lag {lag_s} s, delay {delay_s} s");
        let fitted = model(identify(
            single_lag(gain, lag_s, delay_s),
            IdentifyProbe::new(CONFIG),
        ));
        let [now, next, _] = fitted.moment_weights.map(f32::abs);
        let fitted_ticks = fitted.delay_ticks as f32 + next / (now + next);
        check!(
            (fitted_ticks - delay_ticks).abs() <= 1.0,
            "{row}: {fitted:?}"
        );
        let fitted_s = fitted.lag_s().unwrap_or(f32::NAN) + fitted_ticks * DT;
        let plant_s = lag_s + 0.001 + delay_ticks * DT;
        check!(
            (fitted_s - plant_s).abs() <= 0.1 * plant_s,
            "{row}: lag and delay {fitted_s} s against {plant_s} s"
        );
        let accel = fitted.accel_radps2().unwrap_or(f32::NAN);
        check!((accel - gain).abs() <= 0.1 * gain, "{row}: accel {accel}");
        check!((fitted.dt_s - DT).abs() < 1e-6);
    }
}

/// The delay a fit reads in ticks, its half tick included.
fn fitted_ticks(fitted: &RateModel) -> f32 {
    let [now, next, _] = fitted.moment_weights.map(f32::abs);
    fitted.delay_ticks as f32 + next / (now + next)
}

/// Through white gyro noise of about the sim's (0.035 rad/s uniform, 0.02 RMS), the extended
/// window's integrated fit reads each plant's delay within a tick and its lag plus delay within
/// 20%, where the least squares, with the noisy rate among its terms, reads the lag as nothing
/// (#551), and the per-tick fit took the shortest delay (#603): (lag s, dead time s) → delay
/// ticks, as in [`recovers_lag_delay_and_gain`].
#[test]
fn the_integrated_fit_reads_the_delay_through_gyro_noise() {
    let rows = [
        ((0.03, 0.0), 1.5),
        ((0.03, 0.008), 3.5),
        ((0.05, 0.008), 3.5),
        ((0.03, 0.02), 6.5),
    ];
    for ((lag_s, delay_s), delay_ticks) in rows {
        let row = format!("lag {lag_s} s, delay {delay_s} s");
        let params = single_lag(20.0, lag_s, delay_s);
        let probe = identify_with(params, IdentifyProbe::new(EXTENDED), |tick, rate| {
            rate + gyro_noise(tick, 0.035)
        });
        check!(probe.window.len > 1900, "{row}: not extended");
        let fitted = model(probe.status());
        let ticks = fitted_ticks(&fitted);
        check!((ticks - delay_ticks).abs() <= 1.0, "{row}: {fitted:?}");
        let fitted_s = fitted.lag_s().unwrap_or(f32::NAN) + ticks * DT;
        let plant_s = lag_s + 0.001 + delay_ticks * DT;
        check!(
            (fitted_s - plant_s).abs() <= 0.2 * plant_s,
            "{row}: lag and delay {fitted_s} s against {plant_s} s: {fitted:?}"
        );
        let recorded = fit_recorded(&probe.window).expect("recorded fit").model;
        check!(recorded.lag_s() < Some(0.01), "{row}: {recorded:?}");
    }
}

/// A window that reads noisy at `duration_s` goes on to the extension's length at its
/// amplitude; a quiet one, or a config without one, stops: (case, config, gyro noise in rad/s,
/// ticks recorded, largest offset from 0.1 s past `duration_s`).
#[test]
fn a_noisy_window_is_extended() {
    let params = single_lag(20.0, 0.03, 0.0);
    let rows = [
        ("noisy", EXTENDED, 0.06, 2000, 0.14),
        ("quiet", EXTENDED, 0.0, 750, 0.0),
        ("noisy, no extension", CONFIG, 0.06, 750, 0.0),
    ];
    for (case, config, noise, ticks, peak) in rows {
        let probe = identify_with(params, IdentifyProbe::new(config), |tick, rate| {
            rate + gyro_noise(tick, noise)
        });
        let window = &probe.window;
        let after = window.offsets[..window.len].iter().skip(775);
        let largest = after.map(|offset| offset.abs()).fold(0.0f32, f32::max);
        check!(
            probe.window.len.abs_diff(ticks) <= 1,
            "{case}: {} ticks",
            probe.window.len
        );
        check!(
            (largest - peak).abs() <= 0.01,
            "{case}: largest offset {largest}"
        );
    }
}

/// The fit a window takes: by least squares when quiet (stiff and ringing, or saturated,
/// included), integrated when noisy, and none when noisy and saturated, which no fit reads
/// (#551).
#[derive(Clone, Copy, Debug)]
enum Taken {
    LeastSquares,
    Integrated,
    Saturated,
}

/// (case, rate P of the closed loop, gyro noise amplitude in rad/s, the fit taken).
#[test]
fn a_window_takes_the_fit_its_noise_and_saturation_call_for() {
    let params = single_lag(20.0, 0.03, 0.0);
    let rows = [
        ("quiet", RATE_P, 0.0, Taken::LeastSquares),
        ("quiet and stiff", 4.0 * RATE_P, 0.0, Taken::LeastSquares),
        ("quiet and saturated", 40.0, 0.0, Taken::LeastSquares),
        ("noisy", RATE_P, 0.06, Taken::Integrated),
        ("noisy and saturated", 40.0, 0.06, Taken::Saturated),
    ];
    for (case, rate_p, noise, taken) in rows {
        let mut plant = Plant::new(params, DT);
        let (mut angle_rad, mut last_moment) = (0.0f32, 0.0f32);
        let mut probe = IdentifyProbe::new(CONFIG);
        let mut tick = 0;
        while matches!(probe.status(), IdentifyStatus::Running { .. }) {
            let rate_radps = plant.measure() + gyro_noise(tick, noise);
            tick += 1;
            let offset_rad = probe.step(DT, rate_radps, last_moment);
            let rate_setpoint_radps = ANGLE_P * (offset_rad - angle_rad);
            last_moment = (rate_p * (rate_setpoint_radps - rate_radps)).clamp(-1.0, 1.0);
            plant.step(last_moment);
            angle_rad += plant.output() * DT;
        }
        let window = &probe.window;
        let expected = match taken {
            Taken::LeastSquares => fit_recorded(window)
                .map(|fit| fit.model)
                .ok_or(IdentifyAbort::Unexcited),
            Taken::Integrated => fit_integrated(window).ok_or(IdentifyAbort::Unexcited),
            Taken::Saturated => Err(IdentifyAbort::Saturated),
        };
        check!(fit_window(window) == expected, "{case}");
    }
}

/// A window longer than [`WINDOW_CAPACITY`] ticks records its first ones and still fits them.
#[test]
fn a_long_window_fits_its_first_ticks() {
    let config = IdentifyConfig {
        duration_s: 10.0,
        ..CONFIG
    };
    let probe = identify_with(
        single_lag(20.0, 0.03, 0.0),
        IdentifyProbe::new(config),
        |_, rate| rate,
    );
    check!(probe.window.len == WINDOW_CAPACITY);
    check!(
        matches!(probe.status(), IdentifyStatus::Done(_)),
        "{:?}",
        probe.status()
    );
}

/// The square wave's edges fall at PX4's half-periods (1.0, 0.9, 0.8 s, …), and each edge
/// washes out over the time constant: one time constant after the first rising edge, the
/// offset is about `amplitude·e⁻¹`.
#[test]
fn excites_with_a_washed_out_shrinking_square_wave() {
    let config = IdentifyConfig {
        duration_s: 10.0,
        ..CONFIG
    };
    let mut probe = IdentifyProbe::new(config);
    let offsets: Vec<f32> = (0..2500).map(|_| probe.step(DT, 0.0, 0.0)).collect();
    // Edges: where the offset jumps by most of the amplitude in one tick.
    let edges_s: Vec<f32> = offsets
        .windows(2)
        .enumerate()
        .filter(|(_, pair)| (pair[1] - pair[0]).abs() > 0.5 * config.amplitude)
        .map(|(tick, _)| (tick + 1) as f32 * DT)
        .collect();
    for (edge_s, expected_s) in edges_s.iter().zip([1.0, 1.9, 2.7, 3.4, 4.0]) {
        check!((edge_s - expected_s).abs() <= 1.5 * DT, "{edges_s:?}");
    }
    let one_tc = offsets[(config.washout_tc_s / DT) as usize - 1];
    let expected = config.amplitude * (-1.0f32).exp();
    check!(
        (one_tc - expected).abs() <= 0.05 * config.amplitude,
        "{one_tc}"
    );
}

/// A non-finite rate or moment is recorded as the last finite one, and the recorded-moment fit
/// skips it: the fit still finishes and reads the clean fit's delay, and its lag within 1%.
#[test]
fn holds_a_non_finite_tick_at_the_last_value() {
    let params = single_lag(20.0, 0.02, 0.0);
    let clean = model(identify(params, IdentifyProbe::new(CONFIG)));
    let dropped = model(
        identify_with(params, IdentifyProbe::new(CONFIG), |tick, rate| {
            if tick == 300 { f32::NAN } else { rate }
        })
        .status(),
    );
    check!(dropped.delay_ticks == clean.delay_ticks, "{dropped:?}");
    let [dropped_s, clean_s] = [dropped, clean].map(|model| model.lag_s().unwrap_or(f32::NAN));
    check!(
        (dropped_s - clean_s).abs() <= 0.01 * clean_s,
        "{dropped:?} against {clean:?}"
    );
}

/// The delay is the shortest whose residual is within the tie share of the least, so rounding
/// doesn't pick between near-equal delays, and the least alone at a share of 0: (residuals per
/// delay from 1, tie share, delay picked).
#[test]
fn picks_the_shortest_of_near_tied_delays() {
    type Row<'a> = (&'a [Option<f32>], f32, Option<usize>);
    let rows: [Row; 8] = [
        (&[Some(3.0), Some(1.0), Some(2.0)], TIE_SHARE, Some(2)),
        (&[Some(1.005), Some(1.0)], TIE_SHARE, Some(1)),
        (&[Some(1.02), Some(1.0)], TIE_SHARE, Some(2)),
        (&[Some(1.0005), Some(1.0)], 0.0, Some(2)),
        (&[Some(1.0), Some(1.0)], 0.0, Some(1)),
        (&[None, Some(0.0), Some(0.0)], TIE_SHARE, Some(2)),
        (&[None, None], TIE_SHARE, None),
        (&[], TIE_SHARE, None),
    ];
    for (residuals, tie_share, delay) in rows {
        check!(
            shortest_tied(residuals, tie_share) == delay,
            "{residuals:?} at {tie_share}"
        );
    }
}

/// A delay's moment effect and residual, as `delay_to_fit` takes them.
type DelayFit = Option<(f32, f32)>;

/// The fit takes the best of the delays whose moment pushes the axis the way it was pushed, and
/// the best of all only when none does: (each delay's moment effect and residual from 1, delay
/// picked).
#[test]
fn fits_a_delay_whose_moment_pushes_the_right_way() {
    let rows: [(&str, &[DelayFit], Option<usize>); 4] = [
        (
            "all push: least residual",
            &[Some((1.0, 2.0)), Some((1.0, 1.0))],
            Some(2),
        ),
        (
            "the least pushes back: the next",
            &[Some((1.0, 1.5)), Some((-1.0, 1.0))],
            Some(1),
        ),
        (
            "none pushes: least of all",
            &[Some((-1.0, 2.0)), Some((-1.0, 1.0))],
            Some(2),
        ),
        ("none solved", &[None, None], None),
    ];
    for (row, fits, delay) in rows {
        check!(delay_to_fit(fits, TIE_SHARE) == delay, "{row}");
    }
}

/// A fit on recorded flight data skips the delays whose model pushes the axis the wrong way:
/// QuadCopterX's first roll fit in RealFlight run 33 (#518) fitted best at 5 ticks with a
/// negative moment effect (−1 rad/s², #529). Which pushing delay wins isn't pinned: the best
/// is 6 ticks (11 rad/s²), and 4 (40 rad/s²) ties with it at 1% by 0.03%, under `f32`
/// summation order.
#[test]
fn a_recorded_fit_reads_a_positive_acceleration() {
    let mut probe = IdentifyProbe::new(CONFIG);
    for line in include_str!("realflight_roll_fit.csv").lines() {
        if line.starts_with('#') {
            continue;
        }
        let (rate, moment) = line.split_once(',').expect("rate,moment");
        let rate_radps = rate.parse().expect("rate");
        let last_moment = moment.parse().expect("moment");
        probe.step(DT, rate_radps, last_moment);
    }
    let model = model(probe.status());
    check!(model.moment_effect() > 0.0, "{model:?}");
    let accel_radps2 = model.accel_radps2().unwrap_or(f32::NAN);
    check!(accel_radps2 > 0.0, "{model:?}: {accel_radps2} rad/s²");
}

/// The windows of a recorded fixture: per line `window,rate,last moment`, `#` lines skipped.
fn realflight_windows<const N: usize>(fixture: &str) -> [Vec<(f32, f32)>; N] {
    let mut windows: [Vec<(f32, f32)>; N] = core::array::from_fn(|_| Vec::new());
    for line in fixture.lines().filter(|line| !line.starts_with('#')) {
        let fields: Vec<&str> = line.split(',').collect();
        let window: usize = fields[0].parse().expect("window");
        let rate_radps = fields[1].parse().expect("rate");
        let last_moment = fields[2].parse().expect("moment");
        windows[window].push((rate_radps, last_moment));
    }
    windows
}

/// The probe's fit to a recorded window, and the least squares' residual on it, in rad/s.
fn fit_recorded_window(window: &[(f32, f32)]) -> (RateModel, f32) {
    let mut probe = IdentifyProbe::new(crate::tuning::autotune::COPTER_IDENTIFY);
    for &(rate_radps, last_moment) in window {
        probe.step(DT, rate_radps, last_moment);
    }
    let residual_radps = fit_recorded(&probe.window)
        .expect("recorded fit")
        .residual_radps;
    (model(probe.status()), residual_radps)
}

/// Rate P designed from `fitted` at the copter's loop shaping and the 40 Hz gyro filter.
fn designed_p(fitted: &RateModel, start: crate::controllers::Gains) -> Option<f32> {
    use crate::tuning::autotune::COPTER_LOOP_SHAPING;
    crate::tuning::design_rate(
        fitted,
        start,
        crate::controllers::GyroFilters::low_pass(40.0),
        &COPTER_LOOP_SHAPING,
    )
    .ok()
    .map(|gains| gains.p)
}

/// RealFlight's QuadCopterX identify windows (PR #585's flight check) are quiet, so they take
/// the recorded-moment fit, and each designs rate P within the 0.5–1.0 that fit designs on
/// that airframe (#551).
#[test]
fn realflight_quadcopterx_windows_design_rate_p_in_range() {
    let start = crate::controllers::Gains {
        p: 0.5,
        i: 0.1,
        d: 0.004,
    };
    let windows = realflight_windows::<4>(include_str!("realflight_quadcopterx_windows.csv"));
    for (index, window) in windows.iter().enumerate() {
        let (fitted, residual) = fit_recorded_window(window);
        check!(
            residual < NOISY_RESIDUAL_RADPS,
            "window {index}: residual {residual}"
        );
        let p = designed_p(&fitted, start);
        check!(
            p.is_some_and(|p| (0.5..=1.0).contains(&p)),
            "window {index}: P {p:?} from {fitted:?}"
        );
    }
}

/// RealFlight's eXplora roll and pitch rate windows (#539's run 3) are quiet, and design the
/// rate P RealFlight's autotune designed from them, within 5% (the replay reproduced it to two
/// places, #551).
#[test]
fn realflight_explora_windows_design_realflights_rate_p() {
    let start = crate::controllers::Gains {
        p: 0.4,
        i: 0.2,
        d: 0.03,
    };
    // (axis, RealFlight's designed rate P)
    let designs = [("roll", 0.94), ("pitch", 1.69)];
    let windows = realflight_windows::<2>(include_str!("realflight_explora_windows.csv"));
    for ((axis, realflight_p), window) in designs.into_iter().zip(&windows) {
        let (fitted, residual) = fit_recorded_window(window);
        check!(
            residual < NOISY_RESIDUAL_RADPS,
            "{axis}: residual {residual}"
        );
        let p = designed_p(&fitted, start);
        check!(
            p.is_some_and(|p| (p - realflight_p).abs() <= 0.05 * realflight_p),
            "{axis}: P {p:?} against {realflight_p} from {fitted:?}"
        );
    }
}

/// An axis that never moves can't be fitted: no delay's sums solve.
#[test]
fn a_motionless_axis_is_unexcited() {
    let mut probe = IdentifyProbe::new(CONFIG);
    while matches!(probe.status(), IdentifyStatus::Running { .. }) {
        probe.step(DT, 0.0, 0.0);
    }
    check!(probe.status() == IdentifyStatus::Aborted(IdentifyAbort::Unexcited));
}

/// Once finished, the probe offsets nothing and keeps its result.
#[test]
fn a_finished_probe_offsets_nothing() {
    let mut probe = IdentifyProbe::new(CONFIG);
    while matches!(probe.status(), IdentifyStatus::Running { .. }) {
        probe.step(DT, 0.0, 0.0);
    }
    let status = probe.status();
    check!(probe.step(DT, 1.0, 1.0) == 0.0);
    check!(probe.status() == status);
}

/// Through [`Probe`], identification adds its offset to the loop's setpoint and reports a
/// [`Measurement::Identify`] once done.
#[test]
fn probe_injects_the_offset_on_the_setpoint() {
    let mut probe = Probe::new(ProbeConfig::Identify(CONFIG));
    let signals = LoopSignals {
        setpoint: 0.1,
        ..LoopSignals::default()
    };
    let setpoint = probe.step(DT, &signals);
    check!(setpoint > 0.1 && setpoint <= 0.1 + CONFIG.amplitude);

    let fitted = identify(single_lag(20.0, 0.02, 0.0), IdentifyProbe::new(CONFIG));
    let status = ProbeStatus::from(fitted);
    assert!(matches!(
        status,
        ProbeStatus::Done(Measurement::Identify(_))
    ));
}

/// Each field's requirement: (field changed, valid).
#[test]
fn validate_checks_each_field() {
    let rows = [
        (CONFIG, true),
        (
            IdentifyConfig {
                amplitude: 0.0,
                ..CONFIG
            },
            false,
        ),
        (
            IdentifyConfig {
                amplitude: -0.07,
                ..CONFIG
            },
            true,
        ),
        (
            IdentifyConfig {
                amplitude: f32::NAN,
                ..CONFIG
            },
            false,
        ),
        (
            IdentifyConfig {
                duration_s: 0.0,
                ..CONFIG
            },
            false,
        ),
        (
            IdentifyConfig {
                duration_s: f32::INFINITY,
                ..CONFIG
            },
            false,
        ),
        (
            IdentifyConfig {
                washout_tc_s: 0.0,
                ..CONFIG
            },
            false,
        ),
        (EXTENDED, true),
        (extended(-0.14, 8.0), true),
        (extended(0.0, 8.0), false),
        (extended(f32::NAN, 8.0), false),
        (extended(0.14, 3.0), true),
        (extended(0.14, 2.9), false),
        (extended(0.14, f32::INFINITY), false),
    ];
    for (config, valid) in rows {
        check!(config.validate().is_ok() == valid, "{config:?}");
    }
}

/// [`CONFIG`] extended to `duration_s` at `amplitude`.
fn extended(amplitude: f32, duration_s: f32) -> IdentifyConfig {
    IdentifyConfig {
        noisy: Some(IdentifyExtension {
            amplitude,
            duration_s,
        }),
        ..CONFIG
    }
}

/// A pole in (0, 1) is a lag; one at or below 0 a lag under a tick, so 0 (#563); one at or
/// past 1 none: (pole, lag).
#[test]
fn lag_needs_a_pole_below_one() {
    let rows = [
        (0.9, Some(-DT / 0.9f32.ln())),
        (0.0, Some(0.0)),
        (-0.2, Some(0.0)),
        (1.0, None),
        (1.2, None),
    ];
    for (pole, lag_s) in rows {
        let model = RateModel {
            rate_weights: [1.0 + pole, -pole],
            moment_weights: [0.1, 0.0, 0.0],
            delay_ticks: 1,
            dt_s: DT,
        };
        check!(model.lag_s() == lag_s, "pole {pole}");
        // 0.1 of moment per tick, over (1 − p)·dt with a pole at or below 0 taken as 0.
        let accel = lag_s.map(|_| 0.1 / ((1.0 - pole.max(0.0)) * DT));
        check!(model.accel_radps2() == accel, "pole {pole}");
    }
}