use core::f32::consts::PI;
use nalgebra::Complex;
use thiserror::Error;
use super::RateModel;
use super::identify::unit_delay;
use crate::controllers::low_pass::LowPass;
use crate::controllers::{Gains, InvalidConfig, check, check_positive};
#[cfg(test)]
mod tests;
const LOWEST_RADPS: f32 = 0.1;
const GRID_POINTS: usize = 400;
const BISECTIONS: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LoopShapingConfig {
pub rate_margin_deg: f32,
pub angle_margin_deg: f32,
pub angle_p_min: f32,
pub angle_p_max: f32,
pub angle_back_off: f32,
}
impl LoopShapingConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
let margin = |deg: f32| deg > 0.0 && deg < 90.0;
check(
"rate_margin_deg",
margin(self.rate_margin_deg),
"in (0, 90)",
)?;
check(
"angle_margin_deg",
margin(self.angle_margin_deg),
"in (0, 90)",
)?;
check_positive("angle_p_min", self.angle_p_min)?;
check(
"angle_p_max",
self.angle_p_max.is_finite() && self.angle_p_max >= self.angle_p_min,
"finite and at least angle_p_min",
)?;
check(
"angle_back_off",
self.angle_back_off > 0.0 && self.angle_back_off <= 1.0,
"in (0, 1]",
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum DesignError {
#[error("the fitted model has no motor lag")]
NotALag,
#[error("no frequency meets the rate margin")]
NoCrossover,
#[error("the least angle P misses the angle margin")]
AngleUnstable,
}
pub fn design_rate(
model: &RateModel,
start: Gains,
gyro_cutoff_hz: f32,
config: &LoopShapingConfig,
) -> Result<Gains, DesignError> {
let model = &integrating(model);
let lag_s = model.lag_s().ok_or(DesignError::NotALag)?;
if model.moment_effect() <= 0.0 {
return Err(DesignError::NoCrossover);
}
let dt_s = model.dt_s;
let unit_pd = Gains {
p: 1.0,
i: 0.0,
d: lag_s,
};
let open_loop = |w_radps: f32| {
let z1 = unit_delay(w_radps, dt_s);
pid_response(unit_pd, z1, dt_s)
* model.response(w_radps)
* LowPass::response(gyro_cutoff_hz, dt_s, z1)
};
let floor_deg = config.rate_margin_deg - 180.0;
let crossover = first_crossing(dt_s, open_loop, |point| point.phase_deg > floor_deg)
.ok_or(DesignError::NoCrossover)?;
let p = 1.0 / crossover.gain;
Ok(Gains {
p,
i: start.i,
d: lag_s * p,
})
}
pub fn design_angle_p(
model: &RateModel,
rate: Gains,
angle: Gains,
gyro_cutoff_hz: f32,
config: &LoopShapingConfig,
) -> Result<f32, DesignError> {
let model = &integrating(model);
let dt_s = model.dt_s;
let one = Complex::new(1.0, 0.0);
let rate = Gains { i: 0.0, ..rate };
let open_loop = |w_radps: f32, angle_p: f32| {
let z1 = unit_delay(w_radps, dt_s);
let rate_pid = pid_response(rate, z1, dt_s);
let plant = model.response(w_radps);
let gyro = LowPass::response(gyro_cutoff_hz, dt_s, z1);
let closed_rate = plant * rate.p / (one + rate_pid * plant * gyro);
let angle_pid = pid_response(
Gains {
p: angle_p,
..angle
},
z1,
dt_s,
);
let to_angle = Complex::new(dt_s, 0.0) / (one - z1);
angle_pid * closed_rate * to_angle
};
let floor_deg = config.angle_margin_deg - 180.0;
let keeps_margin = |angle_p: f32| {
let crossover = first_crossing(dt_s, |w| open_loop(w, angle_p), |point| point.gain > 1.0);
crossover.is_some_and(|point| point.phase_deg > floor_deg)
};
let (low, high) = (config.angle_p_min, config.angle_p_max);
if !keeps_margin(low) {
return Err(DesignError::AngleUnstable);
}
if keeps_margin(high) {
return Ok(high * config.angle_back_off);
}
Ok(bisect_geometric(low, high, keeps_margin) * config.angle_back_off)
}
fn integrating(model: &RateModel) -> RateModel {
let [_, r2] = model.rate_weights;
if model.rate_weights.iter().sum::<f32>() <= 1.0 {
return *model;
}
RateModel {
rate_weights: [1.0 - r2, r2],
..*model
}
}
fn pid_response(gains: Gains, z1: Complex<f32>, dt_s: f32) -> Complex<f32> {
let one = Complex::new(1.0, 0.0);
let integral = Complex::new(dt_s, 0.0) / (one - z1);
let difference = (one - z1) / dt_s;
one * gains.p + integral * gains.i + difference * gains.d
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Point {
w_radps: f32,
gain: f32,
phase_deg: f32,
}
fn first_crossing(
dt_s: f32,
open_loop: impl Fn(f32) -> Complex<f32>,
above: impl Fn(&Point) -> bool,
) -> Option<Point> {
let point = |w_radps: f32, near_deg: f32| {
let response = open_loop(w_radps);
let raw_deg = libm::atan2f(response.im, response.re).to_degrees();
let turns = libm::roundf((near_deg - raw_deg) / 360.0);
Point {
w_radps,
gain: libm::hypotf(response.re, response.im),
phase_deg: raw_deg + 360.0 * turns,
}
};
let nyquist_radps = PI / dt_s;
let step = libm::powf(nyquist_radps / LOWEST_RADPS, 1.0 / (GRID_POINTS - 1) as f32);
let mut last = point(LOWEST_RADPS, -90.0);
if !above(&last) {
return None;
}
for i in 1..GRID_POINTS {
let next = point(LOWEST_RADPS * libm::powf(step, i as f32), last.phase_deg);
if !above(&next) {
let keeps = |w_radps: f32| above(&point(w_radps, last.phase_deg));
let w_radps = bisect_geometric(last.w_radps, next.w_radps, keeps);
return Some(point(w_radps, last.phase_deg));
}
last = next;
}
None
}
fn bisect_geometric(mut keeps: f32, mut misses: f32, holds: impl Fn(f32) -> bool) -> f32 {
for _ in 0..BISECTIONS {
let middle = libm::sqrtf(keeps * misses);
if holds(middle) {
keeps = middle;
} else {
misses = middle;
}
}
keeps
}