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
//! The gain search: see [`Search`].
use super::{Action, Batch, Input, MAX_START_LOWERINGS, Pairs, Verdict};
use crate::controllers::Gains;
use crate::tuning::StepSummary;
use crate::tuning::autotune::{AutotuneAbort, KeepReason, Outcome, SearchPlan, with_i_per_p};
#[cfg(test)]
mod tests;
/// A [`SearchPlan`] as a pure state machine: baseline, bracket and bisect, verify.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::tuning::autotune) struct Search {
plan: SearchPlan,
leg: Leg,
/// The loop's gains at the stage's start.
start: Gains,
/// What stays when the search keeps no result and the start's steps missed the criterion:
/// the loop's gains at the run's start, lowered to `max` when the stage starts from them.
fallback: Gains,
/// The largest gain that passed.
pass: Option<f32>,
/// The smallest gain that failed.
fail: Option<f32>,
/// The steps on the gain under test.
pairs: Pairs,
/// The steps on the start gains: empty when they weren't flown (the start is above `max`)
/// or couldn't be measured (a step aborted or kept clipping).
baseline: StepSummary,
/// The last judgment, until taken.
verdict: Option<Verdict>,
/// Times the start was lowered for not settling.
lowerings: usize,
}
/// Where a search is.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Leg {
/// Stepping on the start gains.
Baseline,
/// Stepping on a bracket point that has passed `passes` pairs in a row.
Try { gain: f32, passes: usize },
/// Stepping on the result.
Verify(f32),
}
impl Search {
pub(super) fn new(plan: SearchPlan) -> Self {
Self {
plan,
leg: Leg::Baseline,
start: Gains::default(),
fallback: Gains::default(),
pass: None,
fail: None,
pairs: Pairs::new(plan.test, plan.test.pairs),
baseline: StepSummary::default(),
verdict: None,
lowerings: 0,
}
}
pub(super) fn next(&mut self, input: Input) -> Action {
if let Some(batch) = self.pairs.take(&input) {
return match batch {
Batch::Next => self.step(),
Batch::Ended { complete } => self.judge(complete),
Batch::Fail(abort) => Action::Fail(abort),
};
}
match input {
Input::Start {
gains, run_start, ..
} => {
self.start = gains;
self.fallback = run_start;
self.baseline()
}
// A candidate that took the vehicle past the envelope fails.
Input::Breached { .. } if matches!(self.leg, Leg::Try { .. } | Leg::Verify(_)) => {
self.judge(false)
}
Input::Breached { reason, .. } => Action::Fail(reason),
Input::Unsettled { .. } if self.leg == Leg::Baseline => self.lower_unsettled(),
Input::Unsettled { .. } => Action::Fail(AutotuneAbort::NotSettled),
_ => Action::Fail(AutotuneAbort::Interrupted),
}
}
pub(super) fn take_verdict(&mut self) -> Option<Verdict> {
self.verdict.take()
}
/// Steps on the start gains, or, when the searched term starts above `max` (a gain the
/// search would never pick), goes on without a baseline rather than fly it (#361) and
/// commits the start with its term at `max` in its place: a start that high can ring once
/// disturbed and never settle (#375). Those gains are what stays if nothing better passes.
fn baseline(&mut self) -> Action {
if self.plan.term.get(self.start) > self.plan.max {
let lowered = self.lower_start(self.plan.max);
return match self.advance() {
Action::Probe { probe, gains, .. } => Action::Probe {
probe,
gains,
commit: Some(lowered),
wait_for_settle: true,
},
end => end,
};
}
self.leg = Leg::Baseline;
self.step()
}
/// Lowers a start the vehicle won't settle on by the bracket's `factor`, commits it, and
/// steps the baseline again on it; fails `NotSettled` once the term would fall below
/// `min` or after [`MAX_START_LOWERINGS`]. A start that rings keeps every stage after
/// it from settling, or, on an axis another stage's settle leaves out, spoils its steps.
fn lower_unsettled(&mut self) -> Action {
let gain = self.plan.term.get(self.start) / self.plan.factor;
if gain < self.plan.min || self.lowerings >= MAX_START_LOWERINGS {
return Action::Fail(AutotuneAbort::NotSettled);
}
self.lowerings += 1;
let lowered = self.lower_start(gain);
self.pairs.restart(self.plan.test.pairs);
Action::Probe {
probe: self.pairs.probe(),
gains: None,
commit: Some(lowered),
wait_for_settle: true,
}
}
/// Replaces the start with its searched term at `gain`, returning it for the caller to
/// commit. The run's own start lowered stays lowered if nothing better passes; a seeded
/// start (a design) goes back to the run's start.
fn lower_start(&mut self, gain: f32) -> Gains {
let lowered = self.with(gain);
if self.fallback == self.start {
self.fallback = lowered;
}
self.start = lowered;
lowered
}
/// The next step on the gain under test.
fn step(&self) -> Action {
let gains = match self.leg {
Leg::Try { gain, .. } | Leg::Verify(gain) => Some(self.with(gain)),
Leg::Baseline => None,
};
Action::Probe {
probe: self.pairs.probe(),
gains,
commit: None,
wait_for_settle: true,
}
}
/// The start gains with the searched term at `gain`, and I at the plan's
/// [`i_per_p`](crate::tuning::autotune::SearchPlan::i_per_p) of P if it sets one. The other
/// terms stay the start's: a rate search from a design keeps its D, since a D that grows
/// with P lets the search climb past where overshoot would stop it
/// (`docs/architecture/autotune-design-search.md#search`, #683).
fn with(&self, gain: f32) -> Gains {
with_i_per_p(self.plan.term.with(self.start, gain), self.plan.i_per_p)
}
/// Judges the batch on the gain under test (`complete`: every step ran; else one
/// aborted, too many were invalid, or the vehicle breached the envelope, which fails it)
/// and moves on. A bracket point needs `confirm` passing pairs in a row.
fn judge(&mut self, complete: bool) -> Action {
let steps = self.pairs.summary;
let passed = complete && self.plan.criterion.passes(&steps);
let (gains, bracketed) = match self.leg {
// The baseline is the first bracket point. Incomplete, it's no baseline: the start
// gains aborted or clipped.
Leg::Baseline => {
self.baseline = if complete {
steps
} else {
StepSummary::default()
};
(self.start, true)
}
Leg::Try { gain, .. } => (self.with(gain), true),
Leg::Verify(gain) => return self.verified(gain, complete, steps),
};
self.verdict = Some(Verdict {
gains,
passed,
steps,
});
// A passing pair short of `confirm` in a row: another pair on the same gain.
if let Leg::Try { gain, passes } = self.leg
&& passed
&& passes + 1 < self.plan.confirm
{
self.leg = Leg::Try {
gain,
passes: passes + 1,
};
self.pairs.restart(1);
return self.step();
}
if bracketed {
let gain = self.plan.term.get(gains);
if passed {
self.pass = Some(self.pass.map_or(gain, |pass| pass.max(gain)));
} else {
self.fail = Some(self.fail.map_or(gain, |fail| fail.min(gain)));
}
}
self.advance()
}
/// Keeps the verified `gain` if its steps (`complete`: none aborted or kept clipping):
/// - fly no worse than a baseline that met the criterion ([`Acceptance`]);
/// - with a baseline that failed it, meet the criterion, or else miss it by no more than
/// the baseline did (`Criterion::no_further_than`);
/// - with no baseline (the start's steps weren't flown, aborted, or kept clipping), meet
/// the criterion.
///
/// Else the [`kept`](Self::kept) gains stay. A start that fails the criterion isn't a
/// standard to hold the result's settling to: a too-high rate P settles fast because it
/// overshoots within the settle band (#361). Nor is it a gain to go back to over a result
/// that flew closer to the criterion: under gyro noise, `racer`'s yaw kept a start
/// overshooting 15% over a verify that bounced back 11% against the 10% limit (#680).
///
/// [`Acceptance`]: crate::tuning::autotune::Acceptance
fn verified(&self, gain: f32, complete: bool, steps: StepSummary) -> Action {
let SearchPlan {
criterion,
acceptance,
..
} = self.plan;
let accepted = complete
// An empty baseline doesn't pass the criterion, nor is a verify closer than it.
&& if criterion.passes(&self.baseline) {
acceptance.accepts(&criterion, &self.baseline, &steps)
} else {
criterion.passes(&steps) || criterion.no_further_than(&self.baseline, &steps)
};
if accepted {
self.finish(self.with(gain), Outcome::Tuned, Some(steps))
} else {
self.finish(self.kept(), Outcome::Kept(KeepReason::Worse), Some(steps))
}
}
/// Tries the next bracket point, or verifies the result once the bracket is narrow
/// enough.
fn advance(&mut self) -> Action {
let SearchPlan {
factor,
resolution,
margin,
min,
max,
..
} = self.plan;
let next = match (self.pass, self.fail) {
(Some(pass), Some(fail)) => {
(fail > pass * resolution).then(|| libm::sqrtf(pass * fail))
}
(Some(pass), None) => (pass < max).then(|| (pass * factor).min(max)),
(None, Some(fail)) if fail > min => Some((fail / factor).max(min)),
(None, Some(_)) => {
return self.finish(self.kept(), Outcome::Kept(KeepReason::NoPass), None);
}
// Nothing tried yet: the start's gain.
(None, None) => Some(self.plan.term.get(self.start).clamp(min, max)),
};
let (leg, pairs) = match next {
Some(gain) => (Leg::Try { gain, passes: 0 }, 1),
None => {
let pass = self.pass.unwrap_or(min);
let result = (margin * pass).clamp(min, max);
(Leg::Verify(result), self.plan.test.pairs)
}
};
self.leg = leg;
self.pairs.restart(pairs);
self.step()
}
/// The gains that stay when the search keeps no result: the start, if its steps met the
/// criterion, else the fallback. A start the search was seeded with (a design) and never
/// saw pass doesn't outlive the search.
fn kept(&self) -> Gains {
if self.plan.criterion.passes(&self.baseline) {
self.start
} else {
self.fallback
}
}
fn finish(&self, gains: Gains, outcome: Outcome, steps: Option<StepSummary>) -> Action {
Action::Finish {
gains,
outcome,
steps,
baseline: Some(self.baseline),
}
}
}