Skip to main content

continuous_blocks/
waveform_arithmetic.rs

1//! A standard real-valued scalar function library — trig, exponential/log, rounding, sign,
2//! select/clamp, and table lookup — offered here as ordinary stateless blocks alongside
3//! [`crate::math_ops`]'s `gain`/`sum`/`product`/`saturation`. This is the common vocabulary
4//! most waveform-arithmetic/expression languages across circuit simulation tools converge on
5//! (trig, exponential/log, sign, min/max, a select/if, a clamp, a lookup table), offered here
6//! as composable blocks instead of a second expression language. Each function is a pure
7//! function of its argument(s), evaluated fresh every step, exactly like the rest of
8//! `math_ops`.
9//!
10//! Not included, on purpose:
11//! - A finite-difference derivative, or random/noise generators — genuinely stateful or
12//!   history-dependent, not stateless math, so they don't belong in this module (a derivative
13//!   belongs in `dynamics`/an explicit `StateSpace`; a real PRNG/noise block would be a
14//!   legitimate future addition, just a different one).
15//! - Complex-data functions (real/imaginary part, phase, magnitude, conjugate) — this project
16//!   has no complex-valued signals; everything here is a real-valued time-domain transient.
17//! - Boolean/comparison *operators* (bitwise and/or/xor, greater/less-than, negation) — those
18//!   belong to a plot-expression language for post-processing saved waveforms, not simulation
19//!   blocks; `if`/`limit` below cover the actual control-logic use case (a comparator/select
20//!   block) a real circuit's controller would need.
21//!
22//! [`MathFn1`]/[`MathFn2`]/[`MathFn3`] group the one/two/three-argument functions so
23//! `dae-runtime`'s block graph (and `general-simulator-cli`'s device-file parser) can dispatch by
24//! name without one bespoke `BlockKind` variant per function.
25
26/// Sign of `x`: `-1`, `0`, or `1` — deliberately *not* `f64::signum` (which returns `1.0` for
27/// `0.0`; this `sgn` returns `0` at the origin instead, the conventional signum definition).
28pub fn sgn(x: f64) -> f64 {
29    if x > 0.0 {
30        1.0
31    } else if x < 0.0 {
32        -1.0
33    } else {
34        0.0
35    }
36}
37
38/// `abs(x)**y` — like [`pow`], but always real-valued (a negative base raised to a
39/// non-integer power would otherwise be complex).
40pub fn pwr(x: f64, y: f64) -> f64 {
41    x.abs().powf(y)
42}
43
44/// `sgn(x) * abs(x)**y` — [`pwr`] with the original sign of `x` reapplied, an odd-symmetric
45/// power function (stays real and odd-symmetric where a plain signed power would not).
46pub fn pwrs(x: f64, y: f64) -> f64 {
47    sgn(x) * x.abs().powf(y)
48}
49
50/// Unit step: `1` if `x > 0`, else `0`.
51pub fn u(x: f64) -> f64 {
52    if x > 0.0 {
53        1.0
54    } else {
55        0.0
56    }
57}
58
59/// `x` if `x > 0`, else `0` (a ramp that starts at the origin — the same function most
60/// block-diagram tools call `Relu`/`Ramp`).
61pub fn uramp(x: f64) -> f64 {
62    if x > 0.0 {
63        x
64    } else {
65        0.0
66    }
67}
68
69/// `1` if `x > 0.5`, else `0` — a threshold/buffer, the companion to [`inv`].
70pub fn buf(x: f64) -> f64 {
71    if x > 0.5 {
72        1.0
73    } else {
74        0.0
75    }
76}
77
78/// `0` if `x > 0.5`, else `1` — the complement of [`buf`].
79pub fn inv(x: f64) -> f64 {
80    if x > 0.5 {
81        0.0
82    } else {
83        1.0
84    }
85}
86
87/// `y` if `x > 0.5`, else `z` — a select/comparator block (the control-logic use case a
88/// separate Boolean expression language would otherwise cover, expressed here as an ordinary
89/// three-input block instead).
90pub fn if_then_else(x: f64, y: f64, z: f64) -> f64 {
91    if x > 0.5 {
92        y
93    } else {
94        z
95    }
96}
97
98/// Clamps `x` to the range spanned by `y` and `z` (whichever of `y`/`z` is smaller is the
99/// floor) — the "intermediate value of x, y, and z."
100pub fn limit(x: f64, y: f64, z: f64) -> f64 {
101    let (lo, hi) = if y <= z { (y, z) } else { (z, y) };
102    x.clamp(lo, hi)
103}
104
105/// Linear interpolation through a set of `(x, y)` points (sorted by `x`, not necessarily
106/// evenly spaced) — a `table(x, a, b, c, d, ...)`-style lookup. Clamped (not extrapolated)
107/// outside the given range, holding the nearest endpoint's `y`. `points` must have at least
108/// one entry and be sorted ascending by `x` (the caller's responsibility — a device-file-level
109/// parser is the natural place to sort once at load time, not every step).
110pub fn table(x: f64, points: &[(f64, f64)]) -> f64 {
111    assert!(!points.is_empty(), "table needs at least one point");
112    if x <= points[0].0 {
113        return points[0].1;
114    }
115    let last = points.len() - 1;
116    if x >= points[last].0 {
117        return points[last].1;
118    }
119    let i = points.partition_point(|&(px, _)| px < x);
120    let (x0, y0) = points[i - 1];
121    let (x1, y1) = points[i];
122    y0 + (y1 - y0) * (x - x0) / (x1 - x0)
123}
124
125/// One of the single-argument real waveform-arithmetic functions.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum MathFn1 {
128    Abs,
129    Acos,
130    Acosh,
131    Asin,
132    Asinh,
133    Atan,
134    Atanh,
135    Buf,
136    Ceil,
137    Cos,
138    Cosh,
139    Exp,
140    Floor,
141    Int,
142    Inv,
143    Ln,
144    Log10,
145    Round,
146    Sgn,
147    Sin,
148    Sinh,
149    Sqrt,
150    Tan,
151    Tanh,
152    U,
153    Uramp,
154}
155
156impl MathFn1 {
157    /// Matches the conventional lowercase function name exactly (case-sensitive).
158    pub fn from_name(name: &str) -> Option<Self> {
159        use MathFn1::*;
160        Some(match name {
161            "abs" => Abs,
162            "acos" => Acos,
163            "acosh" => Acosh,
164            "asin" => Asin,
165            "asinh" => Asinh,
166            "atan" => Atan,
167            "atanh" => Atanh,
168            "buf" => Buf,
169            "ceil" => Ceil,
170            "cos" => Cos,
171            "cosh" => Cosh,
172            "exp" => Exp,
173            "floor" => Floor,
174            "int" => Int,
175            "inv" => Inv,
176            "ln" => Ln,
177            "log10" => Log10,
178            "round" => Round,
179            "sgn" => Sgn,
180            "sin" => Sin,
181            "sinh" => Sinh,
182            "sqrt" => Sqrt,
183            "tan" => Tan,
184            "tanh" => Tanh,
185            "u" => U,
186            "uramp" => Uramp,
187            _ => return None,
188        })
189    }
190
191    /// The exact inverse of [`Self::from_name`] — the `kind=` keyword that selects this
192    /// function at the CLI level. Used for diagnostics that need to name *this specific*
193    /// function rather than the `MathFn1` family as a whole, e.g. `dae-runtime`'s own
194    /// `block_kind_name`.
195    pub fn name(self) -> &'static str {
196        use MathFn1::*;
197        match self {
198            Abs => "abs",
199            Acos => "acos",
200            Acosh => "acosh",
201            Asin => "asin",
202            Asinh => "asinh",
203            Atan => "atan",
204            Atanh => "atanh",
205            Buf => "buf",
206            Ceil => "ceil",
207            Cos => "cos",
208            Cosh => "cosh",
209            Exp => "exp",
210            Floor => "floor",
211            Int => "int",
212            Inv => "inv",
213            Ln => "ln",
214            Log10 => "log10",
215            Round => "round",
216            Sgn => "sgn",
217            Sin => "sin",
218            Sinh => "sinh",
219            Sqrt => "sqrt",
220            Tan => "tan",
221            Tanh => "tanh",
222            U => "u",
223            Uramp => "uramp",
224        }
225    }
226
227    pub fn call(self, x: f64) -> f64 {
228        use MathFn1::*;
229        match self {
230            Abs => x.abs(),
231            Acos => x.acos(),
232            Acosh => x.acosh(),
233            Asin => x.asin(),
234            Asinh => x.asinh(),
235            Atan => x.atan(),
236            Atanh => x.atanh(),
237            Buf => buf(x),
238            Ceil => x.ceil(),
239            Cos => x.cos(),
240            Cosh => x.cosh(),
241            Exp => x.exp(),
242            Floor => x.floor(),
243            Int => x.trunc(),
244            Inv => inv(x),
245            Ln => x.ln(),
246            Log10 => x.log10(),
247            Round => x.round(),
248            Sgn => sgn(x),
249            Sin => x.sin(),
250            Sinh => x.sinh(),
251            Sqrt => x.sqrt(),
252            Tan => x.tan(),
253            Tanh => x.tanh(),
254            U => u(x),
255            Uramp => uramp(x),
256        }
257    }
258}
259
260/// One of the two-argument real waveform-arithmetic functions.
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub enum MathFn2 {
263    Atan2,
264    /// `(alpha, beta) -> theta`, wrapped to `[0, 2*pi)` — see
265    /// [`crate::coordinate_transforms::anglewrap`], the angle-tracking half of a
266    /// synchronous-reference-frame PLL. Grouped here rather than with the other Clarke/Park
267    /// transforms since, unlike those, it is single-output — an ordinary two-argument function
268    /// like every other [`MathFn2`], just implemented in `coordinate_transforms` because it's
269    /// conceptually paired with [`crate::coordinate_transforms::park`]/
270    /// [`crate::coordinate_transforms::clarke_park`], which consume its output.
271    AngleWrapped,
272    Hypot,
273    Max,
274    Min,
275    Pow,
276    Pwr,
277    Pwrs,
278}
279
280impl MathFn2 {
281    pub fn from_name(name: &str) -> Option<Self> {
282        use MathFn2::*;
283        Some(match name {
284            "atan2" => Atan2,
285            "anglewrap" => AngleWrapped,
286            "hypot" => Hypot,
287            "max" => Max,
288            "min" => Min,
289            "pow" => Pow,
290            "pwr" => Pwr,
291            "pwrs" => Pwrs,
292            _ => return None,
293        })
294    }
295
296    /// The exact inverse of [`Self::from_name`] — see [`MathFn1::name`]'s own doc comment.
297    pub fn name(self) -> &'static str {
298        use MathFn2::*;
299        match self {
300            Atan2 => "atan2",
301            AngleWrapped => "anglewrap",
302            Hypot => "hypot",
303            Max => "max",
304            Min => "min",
305            Pow => "pow",
306            Pwr => "pwr",
307            Pwrs => "pwrs",
308        }
309    }
310
311    pub fn call(self, x: f64, y: f64) -> f64 {
312        use MathFn2::*;
313        match self {
314            Atan2 => x.atan2(y),
315            AngleWrapped => crate::coordinate_transforms::anglewrap(x, y),
316            Hypot => x.hypot(y),
317            Max => x.max(y),
318            Min => x.min(y),
319            Pow => x.powf(y),
320            Pwr => pwr(x, y),
321            Pwrs => pwrs(x, y),
322        }
323    }
324}
325
326/// One of the three-argument real waveform-arithmetic functions.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub enum MathFn3 {
329    If,
330    Limit,
331}
332
333impl MathFn3 {
334    pub fn from_name(name: &str) -> Option<Self> {
335        use MathFn3::*;
336        Some(match name {
337            "if" => If,
338            "limit" => Limit,
339            _ => return None,
340        })
341    }
342
343    /// The exact inverse of [`Self::from_name`] — see [`MathFn1::name`]'s own doc comment.
344    pub fn name(self) -> &'static str {
345        match self {
346            MathFn3::If => "if",
347            MathFn3::Limit => "limit",
348        }
349    }
350
351    pub fn call(self, x: f64, y: f64, z: f64) -> f64 {
352        match self {
353            MathFn3::If => if_then_else(x, y, z),
354            MathFn3::Limit => limit(x, y, z),
355        }
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use std::f64::consts::{E, PI};
363
364    #[test]
365    fn sgn_returns_zero_at_origin_unlike_f64_signum() {
366        assert_eq!(sgn(5.0), 1.0);
367        assert_eq!(sgn(-5.0), -1.0);
368        assert_eq!(sgn(0.0), 0.0);
369        // the whole reason this isn't just f64::signum:
370        assert_eq!(0.0_f64.signum(), 1.0);
371    }
372
373    #[test]
374    fn trig_and_exp_match_hand_known_values() {
375        assert!((MathFn1::Cos.call(0.0) - 1.0).abs() < 1e-12);
376        assert!((MathFn1::Sin.call(PI / 2.0) - 1.0).abs() < 1e-12);
377        assert!((MathFn1::Exp.call(1.0) - E).abs() < 1e-12);
378        assert!((MathFn1::Ln.call(E) - 1.0).abs() < 1e-12);
379        assert!((MathFn1::Sqrt.call(4.0) - 2.0).abs() < 1e-12);
380        assert!((MathFn1::Log10.call(100.0) - 2.0).abs() < 1e-12);
381    }
382
383    #[test]
384    fn u_and_uramp_match_hand_derived_step_and_ramp() {
385        assert_eq!(u(-1.0), 0.0);
386        assert_eq!(u(1.0), 1.0);
387        assert_eq!(uramp(-3.0), 0.0);
388        assert_eq!(uramp(3.0), 3.0);
389    }
390
391    #[test]
392    fn buf_and_inv_threshold_at_one_half() {
393        assert_eq!(buf(0.4), 0.0);
394        assert_eq!(buf(0.6), 1.0);
395        assert_eq!(inv(0.4), 1.0);
396        assert_eq!(inv(0.6), 0.0);
397    }
398
399    #[test]
400    fn if_then_else_selects_by_threshold() {
401        assert_eq!(if_then_else(1.0, 10.0, 20.0), 10.0);
402        assert_eq!(if_then_else(0.0, 10.0, 20.0), 20.0);
403    }
404
405    #[test]
406    fn limit_clamps_to_the_span_of_its_two_bounds_either_order() {
407        // Hand-derived: limit(x, lo, hi) = min(max(x, lo), hi) for lo <= hi.
408        assert_eq!(limit(5.0, 0.0, 3.0), 3.0); // clamp(5, 0, 3) == 3 (above hi)
409        assert_eq!(limit(-2.0, 0.0, 3.0), 0.0); // clamp(-2, 0, 3) == 0 (below lo)
410        assert_eq!(limit(1.0, 0.0, 3.0), 1.0); // clamp(1, 0, 3) == 1 (inside range)
411        assert_eq!(limit(5.0, 2.0, 0.0), 2.0); // bounds given reversed
412    }
413
414    #[test]
415    fn pow_pwr_pwrs_hand_derived() {
416        assert!((MathFn2::Pow.call(2.0, 3.0) - 8.0).abs() < 1e-12);
417        // pwr(x,y) = abs(x)**y -- stays real for a negative base and non-integer exponent,
418        // where a plain pow() would go complex.
419        assert!((pwr(-8.0, 1.0 / 3.0) - 2.0).abs() < 1e-9);
420        // pwrs reapplies the original sign on top of pwr.
421        assert!((pwrs(-8.0, 1.0 / 3.0) - (-2.0)).abs() < 1e-9);
422    }
423
424    #[test]
425    fn atan2_and_hypot_match_hand_derived_values() {
426        // atan2(1,1) = 45 degrees = pi/4
427        assert!((MathFn2::Atan2.call(1.0, 1.0) - PI / 4.0).abs() < 1e-12);
428        // hypot(3,4) = 5, the textbook 3-4-5 triangle
429        assert!((MathFn2::Hypot.call(3.0, 4.0) - 5.0).abs() < 1e-12);
430    }
431
432    #[test]
433    fn anglewrap_dispatch_matches_direct_call() {
434        assert_eq!(
435            MathFn2::AngleWrapped.call(-1.0, -1.0),
436            crate::coordinate_transforms::anglewrap(-1.0, -1.0)
437        );
438        assert_eq!(MathFn2::from_name("anglewrap"), Some(MathFn2::AngleWrapped));
439    }
440
441    #[test]
442    fn min_max_pick_the_right_side() {
443        assert_eq!(MathFn2::Min.call(3.0, 7.0), 3.0);
444        assert_eq!(MathFn2::Max.call(3.0, 7.0), 7.0);
445    }
446
447    #[test]
448    fn table_interpolates_linearly_and_clamps_outside_range() {
449        let points = [(0.0, 0.0), (1.0, 10.0), (2.0, 10.0), (3.0, 0.0)];
450        assert_eq!(table(0.5, &points), 5.0); // halfway between (0,0) and (1,10)
451        assert_eq!(table(1.5, &points), 10.0); // flat segment
452        assert_eq!(table(-1.0, &points), 0.0); // clamped below range
453        assert_eq!(table(10.0, &points), 0.0); // clamped above range
454    }
455
456    #[test]
457    fn from_name_matches_conventional_names_and_rejects_unknown() {
458        assert_eq!(MathFn1::from_name("cos"), Some(MathFn1::Cos));
459        assert_eq!(MathFn1::from_name("nope"), None);
460        assert_eq!(MathFn2::from_name("atan2"), Some(MathFn2::Atan2));
461        assert_eq!(MathFn3::from_name("if"), Some(MathFn3::If));
462    }
463}