Skip to main content

sim_components/
tune.rs

1//! Tuning of the velocity loops from their measured margins: the procedure the shipped gains were found with by hand
2//! (`sim-cli margins` at every pose of the cycle, the gain raised until 35 degrees and 6 dB are the least left, the notch
3//! put where a resonance holds the gain back), run by the program.
4
5use crate::analysis::{LoopMargins, check_cancelled, plan_steps, step_done, velocity_loop_margins};
6use crate::catalog::{motor_config, resolve};
7use sim_core::{Config, ConfigError, MachineEntry};
8use toml::Value;
9
10/// What the tuning holds the loops to, and whether it may use the notch.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct Targets {
13    /// The least phase margin over all poses, degrees. 35 is what the shipped configs are held to.
14    pub phase_margin_deg: f64,
15    /// The least gain margin over all poses, dB. 6 as shipped.
16    pub gain_margin_db: f64,
17    /// Try the velocity loop's notch where a resonance holds the gain back.
18    pub notch: bool,
19}
20
21impl Default for Targets {
22    fn default() -> Self {
23        Targets { phase_margin_deg: 35.0, gain_margin_db: 6.0, notch: true }
24    }
25}
26
27/// Per motor the gain is searched over a bracket of `BRACKET` doublings or halvings from the config's own (together: a
28/// start that fails is doubled once to see which way the slack grows), then by `BISECTIONS` bisections (in the
29/// logarithm): at most 1 + 8 + 6 = 15 evaluations (`velocity_loop_margins`, which
30/// measures every motor at every pose), the last resolving the gain to 1.1 %.
31pub const BRACKET: usize = 8;
32pub const BISECTIONS: usize = 6;
33/// The joint check at the end lowers a gain that fails with all motors tuned by this factor, at most `JOINT_ROUNDS` times.
34pub const JOINT_FACTOR: f64 = 0.8;
35pub const JOINT_ROUNDS: usize = 4;
36/// A notch stays only where the verified gain rises at least by this factor: one that buys less costs phase for nothing.
37pub const NOTCH_MIN_GAIN: f64 = 1.15;
38/// The notch's width as a share of its centre frequency, as the flying saw's (250 Hz at 360 Hz, hand-tuned).
39pub const NOTCH_WIDTH: f64 = 0.7;
40/// A gain margin limit counts as a resonance's where the sensitivity peaks at a mode of the machine or up to this factor
41/// above it (the flying saw without its notch: the mode at 367 Hz, the peak at 475 to 520 Hz).
42pub const PEAK_OVER_MODE: f64 = 1.5;
43
44/// A velocity loop's gains: Kp (N m s/rad), Tn (s) and the position loop's Kv (1/s).
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct Gains {
47    pub kp: f64,
48    pub tn: f64,
49    pub kv: f64,
50}
51
52/// The least margins of one motor's loop over the poses, with the pose (the run's name, "" the start pose).
53#[derive(Debug, Clone, PartialEq)]
54pub struct Least {
55    /// NaN where no pose has a gain crossover in the measured band.
56    pub phase_deg: f64,
57    pub phase_pose: String,
58    pub gain_db: f64,
59    pub gain_pose: String,
60    /// Every pose valid and `LoopMargins::stable`.
61    pub stable: bool,
62}
63
64impl Least {
65    fn of(runs: &[(String, Vec<LoopMargins>)], motor: usize) -> Least {
66        let mut least = Least {
67            phase_deg: f64::NAN,
68            phase_pose: String::new(),
69            gain_db: f64::INFINITY,
70            gain_pose: String::new(),
71            stable: true,
72        };
73        for (pose, margins) in runs {
74            let m = &margins[motor];
75            least.stable &= m.stable();
76            if m.phase_margin_deg.is_nan() {
77                continue;
78            }
79            if least.phase_deg.is_nan() || m.phase_margin_deg < least.phase_deg {
80                (least.phase_deg, least.phase_pose) = (m.phase_margin_deg, pose.clone());
81            }
82        }
83        for (pose, margins) in runs {
84            let g = margins[motor].gain_margin_db;
85            if g.is_nan() {
86                least.gain_db = f64::NAN;
87            } else if !least.gain_db.is_nan() && (g < least.gain_db || least.gain_pose.is_empty()) {
88                (least.gain_db, least.gain_pose) = (g, pose.clone());
89            }
90        }
91        least
92    }
93
94    /// Stable and both least margins at their targets (a loop without a crossover has no phase margin to miss).
95    fn meets(&self, t: &Targets) -> bool {
96        self.stable
97            && (self.phase_deg.is_nan() || self.phase_deg >= t.phase_margin_deg)
98            && self.gain_db >= t.gain_margin_db
99    }
100
101    /// How far from meeting the targets (negative) or beyond them: the smaller slack of the two, in degrees and dB.
102    fn score(&self, t: &Targets) -> f64 {
103        if !self.stable || self.gain_db.is_nan() {
104            return -1.0e3;
105        }
106        let phase = if self.phase_deg.is_nan() { f64::INFINITY } else { self.phase_deg - t.phase_margin_deg };
107        phase.min(self.gain_db - t.gain_margin_db)
108    }
109}
110
111/// What came out for one motor.
112#[derive(Debug, Clone, PartialEq)]
113pub struct MotorTuning {
114    pub id: String,
115    /// The config keys that hold the gains (`drive.<id>.velocity_kp_nm_s_rad` where the config gives the motor its own,
116    /// else the shared ones) and the position gain's, which is written only where it changed.
117    pub kp_key: String,
118    pub kv_key: String,
119    pub before: Gains,
120    pub after: Gains,
121    pub before_least: Least,
122    pub after_least: Least,
123    /// The tuned gain met the targets at every pose, in the final measurement of the whole machine.
124    pub met: bool,
125    /// The joint check (all motors tuned) lowered this gain: the motors act on each other.
126    pub lowered_in_joint_check: bool,
127}
128
129/// A notch the tuning kept.
130#[derive(Debug, Clone, Copy, PartialEq)]
131pub struct Notch {
132    /// The motor's index in `Tuned::motors`.
133    pub motor: usize,
134    pub frequency_hz: f64,
135    pub bandwidth_hz: f64,
136    /// The tuned gain with it over the tuned gain without it.
137    pub gain_factor: f64,
138}
139
140/// The result of `velocity_loops`.
141#[derive(Debug, Clone)]
142pub struct Tuned {
143    /// The config with the new gains (and the notch), as verified by the last `velocity_loop_margins` call.
144    pub config: Config,
145    pub motors: Vec<MotorTuning>,
146    /// The notches kept, one per motor at most; the other motors then have none (frequency 0).
147    pub notches: Vec<Notch>,
148    /// Every motor meets the targets at every pose in that last measurement.
149    pub met: bool,
150    /// The calls of `velocity_loop_margins` made.
151    pub evaluations: usize,
152}
153
154impl Tuned {
155    /// The `path=value` words that make the new config out of the old one (for `--set`).
156    pub fn settings(&self) -> Vec<String> {
157        let mut out = Vec::new();
158        for m in &self.motors {
159            out.push(format!("{}={:?}", m.kp_key, m.after.kp));
160            if m.after.kv != m.before.kv {
161                out.push(format!("{}={:?}", m.kv_key, m.after.kv));
162            }
163        }
164        if !self.notches.is_empty() {
165            out.push("effects.notch_filter=true".into());
166            for (k, m) in self.motors.iter().enumerate() {
167                let key = |leaf: &str| m.kp_key.replace("velocity_kp_nm_s_rad", leaf);
168                match self.notches.iter().find(|n| n.motor == k) {
169                    Some(n) => {
170                        out.push(format!("{}={:?}", key("notch_frequency_hz"), n.frequency_hz));
171                        out.push(format!("{}={:?}", key("notch_bandwidth_hz"), n.bandwidth_hz));
172                    }
173                    None => out.push(format!("{}=0.0", key("notch_frequency_hz"))),
174                }
175            }
176        }
177        out
178    }
179}
180
181/// Where a motor's drive keys live: the shared `[drive]`, or its own `[drive.<id>]`.
182#[derive(Clone)]
183enum Place {
184    Shared,
185    Own(String),
186}
187
188impl Place {
189    fn path(&self, leaf: &str) -> String {
190        match self {
191            Place::Shared => format!("drive.{leaf}"),
192            Place::Own(id) => format!("drive.{id}.{leaf}"),
193        }
194    }
195
196    /// `value` at `leaf` of this place; a motor's own key is added where its table does not have it yet.
197    fn put(&self, entry: &MachineEntry, cfg: &mut Config, leaf: &str, value: f64) -> Result<(), ConfigError> {
198        crate::sim::set_config(entry, cfg, &self.path(leaf), Value::Float(value))
199    }
200}
201
202/// The motor's gains as its drive sees them (`motor_config` of the resolved config).
203fn gains_of(entry: &MachineEntry, cfg: &Config, id: &str) -> Result<Gains, ConfigError> {
204    let own = motor_config(&resolve(entry, cfg)?, id)?;
205    Ok(Gains {
206        kp: own.positive("drive.velocity_kp_nm_s_rad")?,
207        tn: own.positive("drive.velocity_tn_s")?,
208        kv: own.positive("drive.kv_1_s")?,
209    })
210}
211
212/// `cfg` with motor `place`'s velocity gain `kp`. Tn stays. Kv stays where the gain rises (the position loop's margin
213/// Kp / J (Tn + 1 / Kv) only grows then) and is lowered where it falls, so that the product stays the config's own:
214/// 1 / Kv' = (Tn + 1 / Kv) Kp / Kp' - Tn. (`catalog::retuned` lowers Kv to a floor of 1.25 or the config's own margin
215/// by the same relation, with the inertia known; without it the config's own margin is the floor.)
216fn with_gain(entry: &MachineEntry, cfg: &Config, place: &Place, base: Gains, kp: f64) -> Result<Config, ConfigError> {
217    let mut out = cfg.clone();
218    place.put(entry, &mut out, "velocity_kp_nm_s_rad", kp)?;
219    // Written at either side: `cfg` may hold a Kv lowered for a smaller gain (the search without the notch).
220    place.put(entry, &mut out, "kv_1_s", kv_for(base, kp))?;
221    Ok(out)
222}
223
224fn kv_for(base: Gains, kp: f64) -> f64 {
225    if kp < base.kp { 1.0 / ((base.tn + 1.0 / base.kv) * base.kp / kp - base.tn) } else { base.kv }
226}
227
228struct Probe {
229    gain: f64,
230    least: Least,
231    /// The motor's margin at the pose with the least gain margin (its crossover and the frequency of the sensitivity's
232    /// peak), for the notch, and that pose's index in `analysis::margin_poses`.
233    worst: LoopMargins,
234    worst_pose: usize,
235}
236
237struct Tuner<'a> {
238    entry: &'a MachineEntry,
239    targets: Targets,
240    evaluations: usize,
241    /// The runs of one pass of `measure` (the poses of `margin_poses`), to tell a pose's index from the pass's.
242    poses: usize,
243}
244
245/// The switches of the friction the shipped gains are also judged without (`loops_keep_their_margins`): the motors' and
246/// the guides', joints', winches' or dancer's (whichever the machine has). In a cruise friction adds no damping to the loop.
247const FRICTION_SWITCHES: [&str; 5] = [
248    "effects.motor_friction",
249    "effects.guide_friction",
250    "effects.joint_friction",
251    "effects.winch_friction",
252    "effects.dancer_friction",
253];
254
255/// `cfg` with the friction off as `FRICTION_SWITCHES` say (the motors' and the first other kind the config has), or None
256/// where it is off already.
257fn without_friction(cfg: &Config) -> Result<Option<Config>, ConfigError> {
258    let other = FRICTION_SWITCHES[1..].iter().find(|key| cfg.bool(key).is_ok());
259    let mut off = cfg.clone();
260    let mut changed = false;
261    for key in [FRICTION_SWITCHES[0]].iter().chain(other) {
262        if cfg.bool(key).unwrap_or(false) {
263            off.set_text(&format!("{key} = false"))?;
264            changed = true;
265        }
266    }
267    Ok(changed.then_some(off))
268}
269
270impl Tuner<'_> {
271    /// The margins at every pose with friction as configured, then (where the config has friction on) with it off, those
272    /// runs named `friction=off` and `friction=off start.pose=[...]`: a gain has to meet the targets in both.
273    fn measure(&mut self, cfg: &Config) -> Result<Vec<(String, Vec<LoopMargins>)>, ConfigError> {
274        check_cancelled();
275        plan_steps(1);
276        let mut runs = velocity_loop_margins(self.entry, cfg, &[])?;
277        self.poses = runs.len();
278        if let Some(off) = without_friction(cfg)? {
279            let more = velocity_loop_margins(self.entry, &off, &[])?;
280            runs.extend(more.into_iter().map(|(name, m)| (format!("friction=off {name}").trim_end().to_string(), m)));
281        }
282        step_done();
283        self.evaluations += 1;
284        Ok(runs)
285    }
286
287    fn probe(&mut self, cfg: &Config, motor: usize, gain: f64) -> Result<Probe, ConfigError> {
288        let runs = self.measure(cfg)?;
289        let least = Least::of(&runs, motor);
290        let (worst_pose, worst) = runs
291            .iter()
292            .map(|(_, m)| m[motor])
293            .enumerate()
294            .min_by(|a, b| a.1.gain_margin_db.total_cmp(&b.1.gain_margin_db))
295            .ok_or_else(|| ConfigError::Invalid("margins".into()))?;
296        Ok(Probe { gain, least, worst, worst_pose: worst_pose % self.poses })
297    }
298
299    /// The largest gain of motor `motor` that meets the targets: bracket, then bisection. Returns the best probe (the
300    /// largest that meets, or where none does the one with the most slack) and the lowest probe above it that fails.
301    fn search(
302        &mut self,
303        cfg: &Config,
304        motor: usize,
305        place: &Place,
306        base: Gains,
307        start: f64,
308    ) -> Result<(Probe, Option<Probe>), ConfigError> {
309        let t = self.targets;
310        let probe = |s: &mut Self, gain: f64| -> Result<Probe, ConfigError> {
311            let candidate = with_gain(s.entry, cfg, place, base, gain)?;
312            s.probe(&candidate, motor, gain)
313        };
314        // The better of two failing probes (the one with the most slack) is kept, for where none meets.
315        let keep = |best: &mut Option<Probe>, p: Probe| {
316            *best = Some(match best.take() {
317                Some(b) if b.least.score(&t) >= p.least.score(&t) => b,
318                _ => p,
319            })
320        };
321        let (mut lo, mut hi, mut best_failing): (Option<Probe>, Option<Probe>, Option<Probe>) = (None, None, None);
322        // The bracket's probes, doublings and halvings together.
323        let mut left = BRACKET;
324        let first = probe(self, start)?;
325        if first.least.meets(&t) {
326            lo = Some(first);
327        } else {
328            // A gain fails on either side of those that meet: above them on the gain margin, below them on the phase
329            // margin (the integral's lag at a low crossover: one motor's axis at a quarter of its gain had 27 degrees).
330            // The way to them is the side the slack grows to.
331            let up = probe(self, 2.0 * start)?;
332            left -= 1;
333            if up.least.meets(&t) || up.least.score(&t) > first.least.score(&t) {
334                keep(&mut best_failing, first);
335                let mut current = up;
336                while !current.least.meets(&t) && left > 0 {
337                    let next = probe(self, 2.0 * current.gain)?;
338                    left -= 1;
339                    keep(&mut best_failing, current);
340                    current = next;
341                }
342                if current.least.meets(&t) {
343                    lo = Some(current);
344                } else {
345                    keep(&mut best_failing, current);
346                }
347            } else {
348                keep(&mut best_failing, up);
349                hi = Some(first);
350                while left > 0 {
351                    let p = probe(self, hi.as_ref().unwrap().gain / 2.0)?;
352                    left -= 1;
353                    if p.least.meets(&t) {
354                        lo = Some(p);
355                        break;
356                    }
357                    keep(&mut best_failing, hi.replace(p).unwrap());
358                }
359                if lo.is_none() {
360                    keep(&mut best_failing, hi.take().unwrap());
361                }
362            }
363        }
364        // From a gain that meets, up to the first that fails, where that is not known yet.
365        if hi.is_none() && lo.is_some() {
366            while left > 0 {
367                let p = probe(self, 2.0 * lo.as_ref().unwrap().gain)?;
368                left -= 1;
369                if p.least.meets(&t) {
370                    lo = Some(p);
371                } else {
372                    hi = Some(p);
373                    break;
374                }
375            }
376        }
377        let Some(mut lo) = lo else {
378            // Nothing in the bracket meets the targets: the probe with the most slack.
379            return Ok((best_failing.expect("every failing probe is kept"), None));
380        };
381        if let Some(mut high) = hi {
382            for _ in 0..BISECTIONS {
383                let p = probe(self, (lo.gain * high.gain).sqrt())?;
384                if p.least.meets(&t) {
385                    lo = p;
386                } else {
387                    high = p;
388                }
389            }
390            hi = Some(high);
391        }
392        Ok((lo, hi))
393    }
394}
395
396/// Tunes every motor's velocity loop: for each motor, in the order the machine lists them, the largest velocity gain
397/// at which the least phase margin and the least gain margin over all poses of `margin_poses` meet `targets` and the
398/// loop is `LoopMargins::stable` at every pose (the other motors as they are at that point). Tn stays and Kv follows as
399/// `with_gain` says. Then, where `targets.notch` is set and the notch is off, for each motor in turn: if the gain margin
400/// is what stops its gain, at a resonance (the sensitivity of the gain that fails peaks at a mode of the machine,
401/// `Machine::modes` at that pose, or up to `PEAK_OVER_MODE` times above it), a notch is put on that mode (the highest
402/// such) with `NOTCH_WIDTH` times its frequency as its width, the gain is searched again,
403/// and the notch stays only where the gain is `NOTCH_MIN_GAIN` times higher. The switch is the whole machine's: where a
404/// notch stays it is on, and every motor without one gets `notch_frequency_hz = 0` (no notch). A final call of
405/// `velocity_loop_margins` on the whole tuned config verifies all motors; a motor that fails there is lowered by
406/// `JOINT_FACTOR`, at most `JOINT_ROUNDS` times, and says so (`lowered_in_joint_check`). The gains returned are those
407/// of the last verification. Every measurement is taken with friction as configured and with it off (`measure`).
408/// Where no gain meets the targets `met` is false and the gains are the best found.
409/// One search takes at most `BRACKET + BISECTIONS + 1` calls per motor (and as many for the notch).
410pub fn velocity_loops(entry: &MachineEntry, cfg: &Config, targets: &Targets) -> Result<Tuned, ConfigError> {
411    let mut tuner = Tuner { entry, targets: *targets, evaluations: 0, poses: 1 };
412    let motors: Vec<String> = (entry.build)(cfg)?.motors().iter().map(|m| m.id.to_string()).collect();
413    let before_runs = tuner.measure(cfg)?;
414    let (mut config, mut gains, mut places) = (cfg.clone(), Vec::new(), Vec::new());
415    for id in &motors {
416        let base = gains_of(entry, cfg, id)?;
417        let own = !id.is_empty() && cfg.get(&format!("drive.{id}.velocity_kp_nm_s_rad")).is_ok();
418        // The shared key only where it is the gain the drive uses (a named part retunes it) and no other motor shares it.
419        let shared = motors.len() == 1 && (cfg.f64("drive.velocity_kp_nm_s_rad")? - base.kp).abs() <= 1e-9 * base.kp;
420        places.push(if own || !(id.is_empty() || shared) { Place::Own(id.clone()) } else { Place::Shared });
421        gains.push(base);
422    }
423    let mut last_fail: Vec<Option<Probe>> = Vec::new();
424    let mut found: Vec<f64> = Vec::new();
425    let mut reached: Vec<bool> = Vec::new();
426    for k in 0..motors.len() {
427        let (best, fail) = tuner.search(&config, k, &places[k], gains[k], gains[k].kp)?;
428        config = with_gain(entry, &config, &places[k], gains[k], best.gain)?;
429        found.push(best.gain);
430        reached.push(best.least.meets(&tuner.targets));
431        last_fail.push(fail);
432    }
433    // The notch, motor by motor: tried against a config with the switch on and every motor's notch at 0 (none), which is
434    // the config without it.
435    let mut notches = Vec::new();
436    if targets.notch && cfg.bool("effects.notch_filter").is_ok_and(|on| !on) {
437        let mut none = config.clone();
438        none.set_text("effects.notch_filter = true")?;
439        for place in &places {
440            place.put(entry, &mut none, "notch_frequency_hz", 0.0)?;
441        }
442        for k in 0..motors.len() {
443            let Some(fail) = &last_fail[k] else { continue };
444            let (t, w) = (&tuner.targets, &fail.worst);
445            let at_gain = fail.least.stable && fail.least.gain_db < t.gain_margin_db;
446            if !(at_gain && w.peak_frequency_hz.is_finite()) {
447                continue;
448            }
449            // The notch goes on the machine's mode that makes the peak: the highest at or below it at that pose, within
450            // `PEAK_OVER_MODE`. On the peak itself it lags the loop where it already turns (the flying saw: a notch at
451            // its peak of 520 Hz left 2.8 dB at a gain that kept 6 without it; on its mode at 367 Hz, 7.3 dB at 1.5 times
452            // that gain).
453            let resolved = resolve(entry, &config)?;
454            let pose = &crate::analysis::margin_poses(&resolved)?[fail.worst_pose];
455            // With the payload the cycle has at that pose (`margin_payloads`).
456            let mut resolved = resolved;
457            if !crate::analysis::margin_payloads(&resolved)?[fail.worst_pose] {
458                resolved.set_text("effects.payload = false")?;
459            }
460            let mode = (entry.build)(&resolved)?
461                .modes(pose)
462                .iter()
463                .map(|m| m.hz)
464                .filter(|hz| *hz <= w.peak_frequency_hz && w.peak_frequency_hz <= PEAK_OVER_MODE * hz)
465                .fold(f64::NAN, f64::max);
466            if !mode.is_finite() {
467                continue;
468            }
469            let (f, bw) = (mode, NOTCH_WIDTH * mode);
470            let mut trial = none.clone();
471            places[k].put(entry, &mut trial, "notch_frequency_hz", f)?;
472            places[k].put(entry, &mut trial, "notch_bandwidth_hz", bw)?;
473            let (best, _) = tuner.search(&trial, k, &places[k], gains[k], found[k])?;
474            if best.least.meets(&tuner.targets) && best.gain >= NOTCH_MIN_GAIN * found[k] {
475                notches.push(Notch { motor: k, frequency_hz: f, bandwidth_hz: bw, gain_factor: best.gain / found[k] });
476                none = with_gain(entry, &trial, &places[k], gains[k], best.gain)?;
477                found[k] = best.gain;
478            }
479        }
480        if !notches.is_empty() {
481            config = none;
482        }
483    }
484    // The joint check, on the whole tuned config.
485    let mut lowered = vec![false; motors.len()];
486    let mut runs = tuner.measure(&config)?;
487    for _ in 0..JOINT_ROUNDS {
488        let failing: Vec<usize> =
489            (0..motors.len()).filter(|&k| reached[k] && !Least::of(&runs, k).meets(&tuner.targets)).collect();
490        if failing.is_empty() {
491            break;
492        }
493        for k in failing {
494            found[k] *= JOINT_FACTOR;
495            lowered[k] = true;
496            config = with_gain(entry, &config, &places[k], gains[k], found[k])?;
497        }
498        runs = tuner.measure(&config)?;
499    }
500    let mut out = Vec::new();
501    for (k, id) in motors.iter().enumerate() {
502        let after = gains_of(entry, &config, id)?;
503        let least = Least::of(&runs, k);
504        out.push(MotorTuning {
505            id: id.clone(),
506            kp_key: places[k].path("velocity_kp_nm_s_rad"),
507            kv_key: places[k].path("kv_1_s"),
508            before: gains[k],
509            after,
510            before_least: Least::of(&before_runs, k),
511            met: least.meets(&tuner.targets),
512            after_least: least,
513            lowered_in_joint_check: lowered[k],
514        });
515    }
516    let met = out.iter().all(|m| m.met);
517    Ok(Tuned { config, motors: out, notches, met, evaluations: tuner.evaluations })
518}