Skip to main content

continuous_blocks/
math_ops.rs

1//! `Math Operations`-style blocks that don't need state: gain, sum, product, saturation.
2//! These are pure functions of their inputs, not descriptor-DAE fragments — a `dae-runtime`
3//! integration (a later milestone) would evaluate them inline while assembling the global
4//! system rather than adding unknowns/rows for them, the same way a resistor's Ohm's-law
5//! relationship needs no extra unknown.
6
7pub fn gain(k: f64, u: f64) -> f64 {
8    k * u
9}
10
11pub fn sum(inputs: &[f64], signs: &[f64]) -> f64 {
12    assert_eq!(inputs.len(), signs.len(), "one sign per input");
13    inputs.iter().zip(signs).map(|(u, s)| u * s).sum()
14}
15
16pub fn product(inputs: &[f64]) -> f64 {
17    inputs.iter().product()
18}
19
20/// Compares a carrier phase `theta` (`[0, 1)`, e.g. a periodic ramp's own `(ramp +
21/// phase_offset).rem_euclid(1.0)`, as produced by [`crate::Vco`], or
22/// [`crate::closed_loop::sawtooth_carrier`]) against `duty`,
23/// producing an **active-high complementary pair** `(main, complement)` with independently
24/// configurable dead time on each edge — the shared primitive every gate-driving modulator in
25/// this crate uses, so "how dead time is inserted" only has one implementation to get right.
26///
27/// Without dead time, `main` is on for `theta` in `[0, duty)` and `complement` is on for
28/// `theta` in `[duty, 1)` — an exact partition, no gap, no overlap (this is what `red_frac =
29/// fed_frac = 0.0` recovers exactly). Real dead time delays only the two **rising** (turn-on)
30/// edges, never a falling (turn-off) edge — the standard technique (the same one real hardware
31/// timer dead-time generators use) that guarantees both outputs are provably low during the
32/// gap, since whichever switch was conducting always turns off exactly on schedule and the
33/// *other* one is held off a little longer before it's allowed to turn on:
34/// - `main`'s own rising edge (at `theta=0`) is delayed by `red_frac` (Rising-Edge Delay, as a
35///   fraction of one carrier period) — `main` is on for `theta` in `[red_frac, duty)`.
36/// - `complement`'s own rising edge (at `theta=duty`) is delayed by `fed_frac` (Falling-Edge
37///   Delay — named for *which duty transition* it guards, `main`'s own falling edge, not
38///   because it delays a falling edge itself; it never does) — `complement` is on for `theta`
39///   in `[duty + fed_frac, 1)`.
40///
41/// Both dead gaps this leaves — `[0, red_frac)` and `[duty, duty+fed_frac)` — have `main` and
42/// `complement` simultaneously off. Callers are responsible for keeping `red_frac`/`fed_frac`
43/// small relative to `duty`/`1-duty` respectively (this function doesn't validate that — a
44/// `red_frac` exceeding `duty`, for instance, just makes `main` never turn on that cycle rather
45/// than panicking, the same "degenerate but not a crash" policy [`saturation`]'s own limit
46/// clamp uses).
47pub fn complementary_pwm_with_deadtime(
48    theta: f64,
49    duty: f64,
50    red_frac: f64,
51    fed_frac: f64,
52) -> (bool, bool) {
53    let duty = duty.clamp(0.0, 1.0);
54    let red_frac = red_frac.max(0.0);
55    let fed_frac = fed_frac.max(0.0);
56    let main = theta >= red_frac && theta < duty;
57    let complement = theta >= duty + fed_frac;
58    (main, complement)
59}
60
61/// <!-- doc-ref: saturation -->
62/// Clamps `u` to `[-limit, limit]`. Piecewise, like a PWL device, but evaluated directly here
63/// rather than through the LCP machinery: a saturation block's active segment depends only on
64/// its own input, never on other unknowns it doesn't already know, so there is no
65/// simultaneous-resolution problem the way there is for a diode's terminal voltage (which
66/// depends on the very unknowns the LCP is solving for).
67///
68/// The fixed, symmetric special case of [`crate::waveform_arithmetic::limit`] (`saturation(u,
69/// limit) == limit(u, -limit, limit)` for every `u`/nonnegative `limit`) — kept as its own
70/// block purely for netlist ergonomics (`limit=<f64>` is a plain literal; `kind=limit`'s three
71/// inputs are all wired signals, so expressing a fixed bound through it needs two extra
72/// `kind=const` blocks), not because the clamp itself needs a second implementation.
73pub fn saturation(u: f64, limit: f64) -> f64 {
74    assert!(limit >= 0.0, "limit must be nonnegative");
75    crate::waveform_arithmetic::limit(u, -limit, limit)
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn gain_scales() {
84        assert_eq!(gain(3.0, 4.0), 12.0);
85    }
86
87    #[test]
88    fn sum_applies_signs() {
89        assert_eq!(sum(&[5.0, 2.0, 1.0], &[1.0, -1.0, 1.0]), 4.0);
90    }
91
92    #[test]
93    fn product_multiplies_all_inputs() {
94        assert_eq!(product(&[2.0, 3.0, 4.0]), 24.0);
95    }
96
97    #[test]
98    fn saturation_clamps_both_sides() {
99        assert_eq!(saturation(5.0, 2.0), 2.0);
100        assert_eq!(saturation(-5.0, 2.0), -2.0);
101        assert_eq!(saturation(1.0, 2.0), 1.0);
102    }
103
104    #[test]
105    fn complementary_pwm_with_zero_deadtime_is_an_exact_partition() {
106        // duty=0.3, no dead time: main on [0,0.3), complement on [0.3,1) -- exactly one of the
107        // two is on at every theta, never both, never neither.
108        for theta in [0.0, 0.1, 0.29, 0.3, 0.5, 0.99] {
109            let (main, comp) = complementary_pwm_with_deadtime(theta, 0.3, 0.0, 0.0);
110            assert_ne!(
111                main, comp,
112                "theta={theta}: exactly one of main/complement must be on"
113            );
114        }
115    }
116
117    #[test]
118    fn complementary_pwm_with_deadtime_leaves_both_off_during_each_gap() {
119        // duty=0.3, red_frac=0.05, fed_frac=0.02: main on [0.05,0.3), complement on [0.32,1).
120        let cases = [
121            (0.0, false, false),  // gap 1: main not yet risen, complement already fell
122            (0.03, false, false), // still gap 1
123            (0.05, true, false),  // main's delayed rising edge
124            (0.2, true, false),   // mid main-on
125            (0.3, false, false),  // main's (undelayed) falling edge -> gap 2 starts
126            (0.31, false, false), // still gap 2
127            (0.32, false, true),  // complement's delayed rising edge
128            (0.9, false, true),   // mid complement-on
129        ];
130        for (theta, exp_main, exp_comp) in cases {
131            let (main, comp) = complementary_pwm_with_deadtime(theta, 0.3, 0.05, 0.02);
132            assert_eq!(
133                (main, comp),
134                (exp_main, exp_comp),
135                "theta={theta}: expected (main={exp_main}, complement={exp_comp})"
136            );
137        }
138    }
139
140    #[test]
141    fn complementary_pwm_never_both_on_regardless_of_deadtime() {
142        // Sweep a fine grid: whatever red_frac/fed_frac, main and complement must never both
143        // be true simultaneously (the whole point of dead time is preventing shoot-through).
144        for i in 0..1000 {
145            let theta = i as f64 / 1000.0;
146            let (main, comp) = complementary_pwm_with_deadtime(theta, 0.4, 0.05, 0.1);
147            assert!(!(main && comp), "theta={theta}: both on simultaneously");
148        }
149    }
150}