Skip to main content

sim_app/
frequency.rs

1//! The loop-response tab's measurement: per motor the open-loop response of its velocity loop as `sim-cli margins`
2//! measures it (`analysis::velocity_loop_responses`, refined where it changes fast), its margins, the machine's
3//! resonances and the input shaper's and the notch filter's frequencies, and what the plots draw of it (closed loop,
4//! phases, the phase crossover). It runs in a thread of its own, with progress and a cancel switch, as the app's other
5//! long runs do. No text for the user is written here.
6
7use crate::model::Message;
8use sim_components::analysis::{
9    CANCELLED, LoopMargins, LoopPoint, Progress, backlash_hammering, loop_margins, velocity_loop_responses,
10};
11use sim_core::{Config, ConfigError, MachineEntry};
12use std::sync::atomic::Ordering::Relaxed;
13use std::sync::mpsc::{Receiver, TryRecvError, channel};
14use std::sync::{Arc, Mutex};
15
16/// What the measurement gives the tab.
17#[derive(Debug, Clone)]
18pub struct Response {
19    /// Per motor its points, in frequency order, and their margins.
20    pub curves: Vec<Vec<LoopPoint>>,
21    pub margins: Vec<LoopMargins>,
22    /// The machine's resonances at the start pose, Hz (`Machine::modes`).
23    pub modes: Vec<f64>,
24    /// The input shaper's and the notch filter's frequencies, where they are on: (translation key, Hz).
25    pub markers: Vec<(&'static str, f64)>,
26}
27
28type Answer = Result<(Config, Response), Message>;
29
30/// The tab's state: the last result with the config it was measured for, the motor shown, and the job under way.
31#[derive(Default)]
32pub struct LoopResponse {
33    pub result: Option<(Config, Response)>,
34    pub motor: usize,
35    job: Option<(Arc<Progress>, Mutex<Receiver<Answer>>)>,
36}
37
38impl LoopResponse {
39    /// Starts the measurement with `config` as it is now; one under way is cancelled.
40    pub fn start(&mut self, entry: &'static MachineEntry, config: &Config) {
41        self.cancel();
42        let (progress, config, (send, receive)) = (Arc::new(Progress::default()), config.clone(), channel());
43        let watch = progress.clone();
44        std::thread::spawn(move || {
45            let answer = measure(entry, &config, &watch).map_err(|e| (e.key(), e.detail().to_string()));
46            let _ = send.send(answer.map(|response| (config, response)));
47        });
48        self.job = Some((progress, Mutex::new(receive)));
49    }
50
51    /// Stops the measurement under way: its thread ends after the points it is measuring, and nothing of it arrives.
52    pub fn cancel(&mut self) {
53        if let Some((progress, _)) = self.job.take() {
54            progress.cancel.store(true, Relaxed);
55        }
56    }
57
58    pub fn running(&self) -> bool {
59        self.job.is_some()
60    }
61
62    /// Measurements done and planned so far (the refinement adds to them).
63    pub fn progress(&self) -> Option<(usize, usize)> {
64        self.job.as_ref().map(|(p, _)| (p.done.load(Relaxed), p.total.load(Relaxed)))
65    }
66
67    /// Takes in the answer, if there is one; the message of a measurement that failed. A thread gone without an
68    /// answer (it panicked) answers with a message.
69    pub fn poll(&mut self) -> Option<Message> {
70        let answer = match self.job.as_ref()?.1.lock().map(|job| job.try_recv()) {
71            Ok(Err(TryRecvError::Empty)) => return None,
72            Ok(Ok(answer)) => answer,
73            _ => Err(("ui-job-ended", String::new())),
74        };
75        self.job = None;
76        match answer {
77            Ok(result) => {
78                self.motor = self.motor.min(result.1.curves.len().saturating_sub(1));
79                self.result = Some(result);
80                None
81            }
82            Err(message) => Some(message),
83        }
84    }
85}
86
87impl Drop for LoopResponse {
88    /// A machine switched or a window closed stops the measurement rather than leave it running for nothing.
89    fn drop(&mut self) {
90        self.cancel();
91    }
92}
93
94/// The measurement: the responses of the config's motors (`velocity_loop_responses`), their margins with the time run
95/// for hammering across a play (`backlash_hammering`), and what the plots mark. A cancelled one answers
96/// `ConfigError::Invalid(CANCELLED)`.
97pub fn measure(entry: &MachineEntry, config: &Config, progress: &Progress) -> Result<Response, ConfigError> {
98    let cfg = &sim_components::catalog::resolve(entry, config)?;
99    let curves = velocity_loop_responses(entry, std::slice::from_ref(cfg), progress)?.remove(0);
100    let modes = (entry.build)(cfg)?.modes(&cfg.f64s("start.pose")?).iter().map(|m| m.hz).collect();
101    let margins = curves
102        .iter()
103        .enumerate()
104        .map(|(motor, c)| Ok(LoopMargins { hammering: backlash_hammering(entry, cfg, motor)?, ..loop_margins(c) }))
105        .collect::<Result<_, ConfigError>>()?;
106    Ok(Response { margins, curves, modes, markers: markers(cfg) })
107}
108
109/// Whether an error is the answer of a cancelled measurement.
110pub fn cancelled(e: &ConfigError) -> bool {
111    matches!(e, ConfigError::Invalid(key) if key == CANCELLED)
112}
113
114/// The frequencies the config filters or shapes at: the input shaper's (the first, the second and each of
115/// `profile.shaper_modes`) with `effects.input_shaping` on, the velocity loop's notch filter with
116/// `effects.notch_filter` on.
117pub fn markers(cfg: &Config) -> Vec<(&'static str, f64)> {
118    let mut out = Vec::new();
119    if cfg.bool("effects.input_shaping").unwrap_or(false) {
120        for path in ["profile.shaper_frequency_hz", "profile.shaper2_frequency_hz"] {
121            out.extend(cfg.f64(path).ok().filter(|hz| *hz > 0.0).map(|hz| ("ui-loop-shaper", hz)));
122        }
123        let hz =
124            |m: &toml::Value| m.get("frequency_hz").and_then(|v| v.as_float().or(v.as_integer().map(|i| i as f64)));
125        out.extend(
126            cfg.array("profile.shaper_modes").into_iter().flatten().filter_map(hz).map(|hz| ("ui-loop-shaper", hz)),
127        );
128    }
129    if cfg.bool("effects.notch_filter").unwrap_or(false) {
130        out.extend(cfg.f64("drive.notch_frequency_hz").ok().filter(|hz| *hz > 0.0).map(|hz| ("ui-loop-notch", hz)));
131    }
132    out
133}
134
135/// The closed loop T = L / (1 + L) of a point, (real, imaginary part).
136pub fn closed_loop(p: &LoopPoint) -> [f64; 2] {
137    let (dr, di) = (1.0 + p.re, p.im);
138    let d2 = dr * dr + di * di;
139    [(p.re * dr + p.im * di) / d2, (p.im * dr - p.re * di) / d2]
140}
141
142/// The phase `raw` (degrees) turned by whole turns to lie within half a turn of the previous one, `last`: unwrapped in
143/// both directions.
144pub fn unwrap_near(raw: f64, last: f64) -> f64 {
145    raw + 360.0 * ((last - raw) / 360.0).round()
146}
147
148/// Phases in degrees of complex values in frequency order, unwrapped along the frequency axis and turned by whole
149/// turns so that the first lies in (-270, 90], as `loop_margins` takes the loop's phase. A value that is not a number
150/// gives NaN and the next one is unwrapped from the last that was.
151pub fn phases(values: impl IntoIterator<Item = [f64; 2]>) -> Vec<f64> {
152    let (mut out, mut last, mut shift) = (Vec::new(), None::<f64>, None);
153    for [re, im] in values {
154        let raw = im.atan2(re).to_degrees();
155        if raw.is_nan() {
156            out.push(f64::NAN);
157            continue;
158        }
159        let unwrapped = last.map_or(raw, |last| unwrap_near(raw, last));
160        let shift = *shift.get_or_insert(-360.0 * ((unwrapped - 90.0) / 360.0).ceil());
161        last = Some(unwrapped);
162        out.push(unwrapped + shift);
163    }
164    out
165}
166
167/// Where the gain margin is read: the crossing `loop_margins` takes. The phase (`phases`) starts from 0 at the first
168/// point's gain; of its crossings of odd multiples of -180 degrees only falling ones count (interpolated on the
169/// logarithmic frequency axis, linearly in the phase), and a rising one at |L| > 1 cancels the latest falling one at
170/// |L| > 1 (Nyquist). Of those left the one with the largest |L|; `None` without one.
171pub fn phase_crossover(points: &[LoopPoint]) -> Option<f64> {
172    let phase = phases(points.iter().map(|p| [p.re, p.im]));
173    let gain = |p: &LoopPoint| p.re.hypot(p.im).ln();
174    let first = points.first()?;
175    let samples: Vec<(f64, f64, f64)> = std::iter::once((0.0, gain(first), first.frequency))
176        .chain(points.iter().zip(&phase).map(|(p, ph)| (*ph, gain(p), p.frequency)))
177        .collect();
178    let (mut open, mut worst): (Vec<(f64, f64)>, Option<(f64, f64)>) = (Vec::new(), None);
179    for w in samples.windows(2) {
180        let ((pa, ga, fa), (pb, gb, fb)) = (w[0], w[1]);
181        let at = |level: f64| {
182            let share = (pa - level) / (pa - pb);
183            (ga + (gb - ga) * share, fa * (fb / fa).powf(share))
184        };
185        let mut level = -180.0 + 360.0 * ((pa + 180.0) / 360.0).floor();
186        while pb < level && level <= pa {
187            let (g, f) = at(level);
188            if g > 0.0 {
189                open.push((g, f));
190            } else if worst.is_none_or(|(w, _)| g > w) {
191                worst = Some((g, f));
192            }
193            level -= 360.0;
194        }
195        level += 360.0;
196        while pa < level && level <= pb {
197            if at(level).0 > 0.0 {
198                open.pop();
199            }
200            level += 360.0;
201        }
202    }
203    open.into_iter().chain(worst).max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, f)| f)
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    fn point(frequency: f64, [re, im]: [f64; 2]) -> LoopPoint {
211        LoopPoint { frequency, re, im, sensitivity: 0.0, plant: [0.0; 2] }
212    }
213
214    /// L(s) = K / (s (1 + s / w0)^2), K = 1000 1/s, w0 = 2 pi 100 Hz: the phase is -90 - 2 atan(w / w0) and reaches
215    /// -180 degrees at w = w0, 100 Hz, where |L| = K / (w0 * 2) = 1000 / 1256.6 = 0.7958: a gain margin of 1.98 dB.
216    /// T at that frequency is L / (1 + L) = -0.7958 / 0.2042 = -3.897.
217    #[test]
218    fn phase_crossover_and_closed_loop_of_a_hand_calculated_loop() {
219        let (k, w0) = (1000.0, std::f64::consts::TAU * 100.0);
220        let loop_at = |f: f64| {
221            let w = std::f64::consts::TAU * f;
222            // (1 + j w / w0)^2 = 1 - x^2 + 2 j x; s = j w.
223            let x = w / w0;
224            let (ar, ai) = (-w * 2.0 * x, w * (1.0 - x * x));
225            let d2 = ar * ar + ai * ai;
226            point(f, [k * ar / d2, -k * ai / d2])
227        };
228        let points: Vec<_> = sim_components::analysis::log_spaced(10.0, 1000.0, 200).into_iter().map(loop_at).collect();
229        let crossing = phase_crossover(&points).unwrap();
230        assert!((crossing / 100.0 - 1.0).abs() < 2e-3, "{crossing}");
231        let phase = phases(points.iter().map(|p| [p.re, p.im]));
232        assert!((phase[0] - (-90.0 - 2.0 * (0.1f64).atan().to_degrees())).abs() < 1e-9, "{}", phase[0]);
233        let t = closed_loop(&loop_at(100.0));
234        assert!((t[0] + 3.897).abs() < 1e-3 && t[1].abs() < 1e-9, "{t:?}");
235        let m = loop_margins(&points);
236        assert!((m.gain_margin_db - 1.984).abs() < 0.01, "{m:?}");
237    }
238
239    /// A phase that rises through a branch cut is carried up as it is carried down: 170 after -170 is -190, 3 turns
240    /// of lead give 1080 + 10 from 1075.
241    #[test]
242    fn phases_unwrap_in_both_directions() {
243        assert!((unwrap_near(170.0, -170.0) + 190.0).abs() < 1e-9);
244        assert!((unwrap_near(-170.0, 170.0) - 190.0).abs() < 1e-9);
245        assert!((unwrap_near(10.0, 1075.0) - 1090.0).abs() < 1e-9);
246    }
247
248    /// Phase -200 degrees at 10 Hz, rising to -120 at 50 Hz, then falling to -250 at 1 kHz (linear in the phase over
249    /// log f); gain 30 dB at 10 Hz, -30 dB/decade. The rising crossing of -180 (share 20/80 of 10..50 Hz: 14.95 Hz,
250    /// 25.7 dB) undoes the falling one before the first point; the falling one at share 60/130 of 50..1000 Hz is at
251    /// 50 * 20^0.4615 = 199.2 Hz (-9.1 dB), the one the margin is read at, not the 14.95 Hz of the largest |L|.
252    #[test]
253    fn phase_crossover_follows_loop_margins_rule() {
254        let at = |f: f64, deg: f64| {
255            let g = 10f64.powf((30.0 - 30.0 * (f / 10.0).log10()) / 20.0);
256            point(f, [g * deg.to_radians().cos(), g * deg.to_radians().sin()])
257        };
258        let points = [at(10.0, -200.0), at(50.0, -120.0), at(1000.0, -250.0)];
259        let crossing = phase_crossover(&points).unwrap();
260        assert!((crossing / 199.2 - 1.0).abs() < 2e-3, "{crossing}");
261    }
262
263    /// The measurement on the first registered machine with one motor (a belt axis): a response per motor, refined
264    /// beyond the 60 points of `loop_frequencies`, the margins `sim-cli margins` prints for it (59.92 degrees, 11.56 dB;
265    /// 61.2 degrees with the gearbox's efficiency in the loop, which `velocity_loop_response` leaves out since 16 November
266    /// 2026: its fade at standstill is a damper the small-signal loop does not have). With friction on, the plant at
267    /// 10 Hz leads (+47 degrees): at a tenth of the rated torque the LuGre bristles hold the axis like a spring. Without
268    /// friction it is the inertia far below the belt's resonance: speed lags torque by 90 degrees (within 5).
269    #[test]
270    fn a_one_motor_belt_axis_is_measured_with_its_margins_and_an_inertia_for_a_plant() {
271        let motors = |e: &MachineEntry| (e.build)(&e.config()).unwrap().motors().len();
272        let entry = sim_machines::MACHINES.iter().copied().find(|e| motors(e) == 1).unwrap();
273        let progress = Progress::default();
274        let response = measure(entry, &entry.config(), &progress).unwrap();
275        assert_eq!(response.curves.len(), 1);
276        let m = response.margins[0];
277        assert!((m.phase_margin_deg - 59.92).abs() < 0.1 && (m.gain_margin_db - 11.56).abs() < 0.01, "{m:?}");
278        assert_eq!(progress.done.load(Relaxed), progress.total.load(Relaxed));
279        assert!(response.curves[0][0].plant[0] > 0.0, "{:?}", response.curves[0][0]);
280        let mut cfg = entry.config();
281        cfg.set_text("effects.motor_friction = false").unwrap();
282        cfg.set_text("effects.guide_friction = false").unwrap();
283        let plant = measure(entry, &cfg, &Progress::default()).unwrap().curves[0][0].plant;
284        assert!((plant[1].atan2(plant[0]).to_degrees() + 90.0).abs() < 5.0, "{plant:?}");
285        let cancelled_one = Progress::default();
286        cancelled_one.cancel.store(true, Relaxed);
287        assert!(super::cancelled(&measure(entry, &entry.config(), &cancelled_one).unwrap_err()));
288    }
289}