use super::side::Decide;
use super::{AutotuneAbort, Method, Outcome, PlaneMethod, StepTestPlan};
use crate::controllers::{Gains, GyroFilters};
use crate::stabilizers::plane::PlaneAxisGains;
use crate::tuning::{Measurement, ProbeAbort, ProbeConfig, StepMetrics, StepSummary};
use design::Design;
#[cfg(test)]
pub(super) use design::SATURATED_FACTOR;
use plane_design::PlaneDesign;
use search::Search;
mod design;
mod plane_design;
mod search;
#[cfg(test)]
mod tests;
const MAX_MEASURE_STOPS: usize = 3;
const MAX_START_LOWERINGS: usize = 8;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Input {
Start {
gains: Gains,
inner: Option<Gains>,
run_start: Gains,
gyro: GyroFilters,
},
Measured {
measurement: Measurement,
gains: Gains,
stalled: bool,
},
Stalled { gains: Gains },
Aborted { abort: ProbeAbort, gains: Gains },
Breached { reason: AutotuneAbort, gains: Gains },
Held { settled: bool, gains: Gains },
Unsettled { gains: Gains },
}
impl Input {
fn split(self) -> (Decide, Gains) {
match self {
Self::Start { gains, .. } => (Decide::Start, gains),
Self::Measured {
measurement,
gains,
stalled,
} => (
Decide::Measured {
measurement,
stalled,
},
gains,
),
Self::Stalled { gains } => (Decide::Stalled, gains),
Self::Aborted { abort, gains } => (Decide::Aborted { abort }, gains),
Self::Breached { reason, gains } => (Decide::Breached { reason }, gains),
Self::Held { settled, gains } => (Decide::Held { settled }, gains),
Self::Unsettled { gains } => (Decide::Unsettled, gains),
}
}
}
#[cfg(test)]
use crate::stabilizers::copter::DEFAULT_GYRO_CUTOFF_HZ;
#[cfg(test)]
impl Input {
fn start(gains: Gains) -> Self {
Self::Start {
gains,
inner: None,
run_start: gains,
gyro: GyroFilters::low_pass(DEFAULT_GYRO_CUTOFF_HZ),
}
}
}
#[expect(
clippy::large_enum_variant,
reason = "returned once per decision, between ticks; the core has no allocator to box with"
)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Action<G = Gains> {
Probe {
probe: ProbeConfig,
gains: Option<G>,
commit: Option<G>,
wait_for_settle: bool,
},
Finish {
gains: G,
outcome: Outcome,
steps: Option<StepSummary>,
baseline: Option<StepSummary>,
},
Hold { gains: G },
Compute,
Fail(AutotuneAbort),
}
impl<G> Action<G> {
pub(super) fn probe(probe: ProbeConfig) -> Self {
Self::Probe {
probe,
gains: None,
commit: None,
wait_for_settle: true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Verdict<G = Gains> {
pub(super) gains: G,
pub(super) passed: bool,
pub(super) steps: StepSummary,
}
#[expect(
clippy::large_enum_variant,
reason = "one per run, replaced between stages; the core has no allocator to box with"
)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Procedure {
StepTest(Pairs),
Search(Search),
Design(Design),
}
impl Procedure {
pub(super) fn new(method: Method) -> Self {
match method {
Method::StepTest(plan) => Self::StepTest(Pairs::new(plan, plan.pairs)),
Method::Search(plan) => Self::Search(Search::new(plan)),
Method::Design(plan) => Self::Design(Design::new(plan)),
}
}
pub(super) fn next(&mut self, input: Input) -> Action {
match self {
Self::StepTest(pairs) => {
let (on, gains) = input.split();
pairs.step_test(on, gains)
}
Self::Search(search) => search.next(input),
Self::Design(design) => design.next(input),
}
}
pub(super) fn take_verdict(&mut self) -> Option<Verdict> {
match self {
Self::Search(search) => search.take_verdict(),
Self::StepTest(_) | Self::Design(_) => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlaneProcedure(PlaneSteps);
#[derive(Clone, Copy, Debug, PartialEq)]
enum PlaneSteps {
StepTest(Pairs),
Design(PlaneDesign),
}
impl PlaneProcedure {
pub(super) fn new(method: PlaneMethod) -> Self {
match method {
PlaneMethod::StepTest(plan) => Self(PlaneSteps::StepTest(Pairs::new(plan, plan.pairs))),
PlaneMethod::Design(plan) => Self(PlaneSteps::Design(PlaneDesign::new(plan))),
}
}
pub(super) fn next(&mut self, on: Decide, gains: PlaneAxisGains) -> Action<PlaneAxisGains> {
match &mut self.0 {
PlaneSteps::StepTest(pairs) => pairs.step_test(on, gains),
PlaneSteps::Design(design) => design.next(on),
}
}
}
fn measure_again(stops: &mut usize, probe: ProbeConfig) -> Action {
*stops += 1;
if *stops >= MAX_MEASURE_STOPS {
Action::Fail(AutotuneAbort::Stalled)
} else {
Action::probe(probe)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Pairs {
plan: StepTestPlan,
pairs: usize,
invalid: usize,
stalled: usize,
summary: StepSummary,
}
impl Pairs {
fn new(plan: StepTestPlan, pairs: usize) -> Self {
Self {
plan,
pairs,
invalid: 0,
stalled: 0,
summary: StepSummary::default(),
}
}
fn restart(&mut self, pairs: usize) {
*self = Self::new(self.plan, pairs);
}
fn probe(&self) -> ProbeConfig {
let step = if self.summary.count().is_multiple_of(2) {
self.plan.step
} else {
self.plan.step.reversed()
};
ProbeConfig::Step(step)
}
fn record(&mut self, metrics: &StepMetrics, stalled: bool) -> Result<(), AutotuneAbort> {
if stalled {
return self.stall();
}
self.stalled = 0;
if metrics.saturated_s > self.plan.max_saturated_s {
self.invalid += 1;
if self.invalid >= self.plan.max_invalid {
return Err(AutotuneAbort::Invalid);
}
return Ok(());
}
self.invalid = 0;
self.summary.add(metrics);
Ok(())
}
fn stall(&mut self) -> Result<(), AutotuneAbort> {
self.stalled += 1;
if self.stalled >= self.plan.max_stalled {
return Err(AutotuneAbort::Stalled);
}
Ok(())
}
fn done(&self) -> bool {
self.summary.count() >= 2 * self.pairs
}
fn step_test<G>(&mut self, on: Decide, gains: G) -> Action<G> {
match on {
Decide::Start => Action::probe(self.probe()),
Decide::Measured {
measurement: Measurement::Step(metrics),
stalled,
} => match self.record(&metrics, stalled) {
Err(abort) => Action::Fail(abort),
Ok(()) if self.done() => Action::Finish {
gains,
outcome: Outcome::Measured,
steps: Some(self.summary),
baseline: None,
},
Ok(()) => Action::probe(self.probe()),
},
Decide::Stalled => match self.stall() {
Err(abort) => Action::Fail(abort),
Ok(()) => Action::probe(self.probe()),
},
Decide::Aborted { abort } => Action::Fail(AutotuneAbort::Probe(abort)),
Decide::Breached { reason } => Action::Fail(reason),
Decide::Unsettled => Action::Fail(AutotuneAbort::NotSettled),
Decide::Measured { .. } | Decide::Held { .. } | Decide::Computing => {
Action::Fail(AutotuneAbort::Interrupted)
}
}
}
fn take(&mut self, input: &Input) -> Option<Batch> {
let batch = match *input {
Input::Measured {
measurement: Measurement::Step(metrics),
stalled,
..
} => match self.record(&metrics, stalled) {
Err(abort @ AutotuneAbort::Stalled) => Batch::Fail(abort),
Err(_) => Batch::Ended { complete: false },
Ok(()) if self.done() => Batch::Ended { complete: true },
Ok(()) => Batch::Next,
},
Input::Stalled { .. } => match self.stall() {
Err(abort) => Batch::Fail(abort),
Ok(()) => Batch::Next,
},
Input::Aborted {
abort: ProbeAbort::Step(_),
..
} => Batch::Ended { complete: false },
_ => return None,
};
Some(batch)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Batch {
Next,
Ended { complete: bool },
Fail(AutotuneAbort),
}