pub fn gain(k: f64, u: f64) -> f64 {
k * u
}
pub fn sum(inputs: &[f64], signs: &[f64]) -> f64 {
assert_eq!(inputs.len(), signs.len(), "one sign per input");
inputs.iter().zip(signs).map(|(u, s)| u * s).sum()
}
pub fn product(inputs: &[f64]) -> f64 {
inputs.iter().product()
}
pub fn complementary_pwm_with_deadtime(
theta: f64,
duty: f64,
red_frac: f64,
fed_frac: f64,
) -> (bool, bool) {
let duty = duty.clamp(0.0, 1.0);
let red_frac = red_frac.max(0.0);
let fed_frac = fed_frac.max(0.0);
let main = theta >= red_frac && theta < duty;
let complement = theta >= duty + fed_frac;
(main, complement)
}
pub fn saturation(u: f64, limit: f64) -> f64 {
assert!(limit >= 0.0, "limit must be nonnegative");
crate::waveform_arithmetic::limit(u, -limit, limit)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gain_scales() {
assert_eq!(gain(3.0, 4.0), 12.0);
}
#[test]
fn sum_applies_signs() {
assert_eq!(sum(&[5.0, 2.0, 1.0], &[1.0, -1.0, 1.0]), 4.0);
}
#[test]
fn product_multiplies_all_inputs() {
assert_eq!(product(&[2.0, 3.0, 4.0]), 24.0);
}
#[test]
fn saturation_clamps_both_sides() {
assert_eq!(saturation(5.0, 2.0), 2.0);
assert_eq!(saturation(-5.0, 2.0), -2.0);
assert_eq!(saturation(1.0, 2.0), 1.0);
}
#[test]
fn complementary_pwm_with_zero_deadtime_is_an_exact_partition() {
for theta in [0.0, 0.1, 0.29, 0.3, 0.5, 0.99] {
let (main, comp) = complementary_pwm_with_deadtime(theta, 0.3, 0.0, 0.0);
assert_ne!(
main, comp,
"theta={theta}: exactly one of main/complement must be on"
);
}
}
#[test]
fn complementary_pwm_with_deadtime_leaves_both_off_during_each_gap() {
let cases = [
(0.0, false, false), (0.03, false, false), (0.05, true, false), (0.2, true, false), (0.3, false, false), (0.31, false, false), (0.32, false, true), (0.9, false, true), ];
for (theta, exp_main, exp_comp) in cases {
let (main, comp) = complementary_pwm_with_deadtime(theta, 0.3, 0.05, 0.02);
assert_eq!(
(main, comp),
(exp_main, exp_comp),
"theta={theta}: expected (main={exp_main}, complement={exp_comp})"
);
}
}
#[test]
fn complementary_pwm_never_both_on_regardless_of_deadtime() {
for i in 0..1000 {
let theta = i as f64 / 1000.0;
let (main, comp) = complementary_pwm_with_deadtime(theta, 0.4, 0.05, 0.1);
assert!(!(main && comp), "theta={theta}: both on simultaneously");
}
}
}