1use 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#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct Targets {
13 pub phase_margin_deg: f64,
15 pub gain_margin_db: f64,
17 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
27pub const BRACKET: usize = 8;
32pub const BISECTIONS: usize = 6;
33pub const JOINT_FACTOR: f64 = 0.8;
35pub const JOINT_ROUNDS: usize = 4;
36pub const NOTCH_MIN_GAIN: f64 = 1.15;
38pub const NOTCH_WIDTH: f64 = 0.7;
40pub const PEAK_OVER_MODE: f64 = 1.5;
43
44#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct Gains {
47 pub kp: f64,
48 pub tn: f64,
49 pub kv: f64,
50}
51
52#[derive(Debug, Clone, PartialEq)]
54pub struct Least {
55 pub phase_deg: f64,
57 pub phase_pose: String,
58 pub gain_db: f64,
59 pub gain_pose: String,
60 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 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 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#[derive(Debug, Clone, PartialEq)]
113pub struct MotorTuning {
114 pub id: String,
115 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 pub met: bool,
125 pub lowered_in_joint_check: bool,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq)]
131pub struct Notch {
132 pub motor: usize,
134 pub frequency_hz: f64,
135 pub bandwidth_hz: f64,
136 pub gain_factor: f64,
138}
139
140#[derive(Debug, Clone)]
142pub struct Tuned {
143 pub config: Config,
145 pub motors: Vec<MotorTuning>,
146 pub notches: Vec<Notch>,
148 pub met: bool,
150 pub evaluations: usize,
152}
153
154impl Tuned {
155 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#[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 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
202fn 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
212fn 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 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 worst: LoopMargins,
234 worst_pose: usize,
235}
236
237struct Tuner<'a> {
238 entry: &'a MachineEntry,
239 targets: Targets,
240 evaluations: usize,
241 poses: usize,
243}
244
245const 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
255fn 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 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 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 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 let mut left = BRACKET;
324 let first = probe(self, start)?;
325 if first.least.meets(&t) {
326 lo = Some(first);
327 } else {
328 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 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 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
396pub 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 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 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 let resolved = resolve(entry, &config)?;
454 let pose = &crate::analysis::margin_poses(&resolved)?[fail.worst_pose];
455 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 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}