Skip to main content

general_mna/
transient_source.rs

1//! Time-varying independent-source functions: `SIN`, `PULSE`, `EXP`, `PWL`, `SFFM` — the same
2//! five transient-function forms `general-spice-core`'s own grammar reference documents as common to
3//! both ngspice and Xyce (`docs/GRAMMAR.md` in that repo, "same names/arg order in both, minor
4//! default-value wording differences"), same argument order.
5//!
6//! `general-spice-core` tokenizes a `V`/`I` element's parameters purely lexically (whitespace-split,
7//! parentheses left attached to whichever token they landed on — confirmed directly this
8//! session, not assumed): `SIN(0 10 1000)` arrives as `["SIN(0", "10", "1000)"]`, three plain
9//! string tokens, with no notion that they form one function call. This module owns turning
10//! that back into a real function: [`TransientFunction::parse`] detects and reassembles the
11//! call, [`TransientFunction::value_at`] evaluates it at a given time.
12//!
13//! This module has **no notion of "now"** on its own — a [`TransientFunction`] is pure data
14//! plus a pure `f64 -> f64` function. Feeding a source's *current* value into a solve at each
15//! step is the caller's job, exactly the same delegation this crate already uses for a
16//! PWL diode's per-step Norton current (`{name}_Ioff`, an [`crate::Expression::symbol`] the
17//! caller supplies numerically via [`crate::MnaSystem::evaluate`]'s `values` map) — a
18//! `TransientFunction`-bearing source is stamped as that same kind of named symbol (see
19//! `builder.rs`'s `source_value`), not as a baked-in literal, so the caller supplies
20//! `values.insert(name, transient_sources[name].value_at(t))` before every step, using
21//! [`crate::MnaSystem::transient_sources`] to know which sources need it.
22
23/// One parsed transient-function call, in the same field order and names ngspice/Xyce use.
24#[derive(Debug, Clone, PartialEq)]
25pub enum TransientFunction {
26    /// `SIN(V0 VA FREQ TD THETA PHASE)` — a damped sinusoid superimposed on an offset,
27    /// starting flat at `V0` until `TD`, then `V0 + VA*sin(2*pi*FREQ*(t-TD) + PHASE) *
28    /// exp(-(t-TD)*THETA)` (`THETA=0` is a plain undamped sinusoid; `FREQ` in Hz, `PHASE` in
29    /// degrees, matching every SPICE dialect's own convention for this source).
30    Sin {
31        /// Offset value held before `td` and added under the sinusoid afterward.
32        v0: f64,
33        /// Sinusoid amplitude.
34        va: f64,
35        /// Sinusoid frequency in Hz.
36        freq: f64,
37        /// Delay, in seconds, before the sinusoid starts.
38        td: f64,
39        /// Exponential damping factor (`0` = undamped).
40        theta: f64,
41        /// Phase offset in degrees.
42        phase: f64,
43    },
44    /// `PULSE(V1 V2 TD TR TF PW PER)` — a periodic trapezoid: `V1` until `TD`, linear ramp to
45    /// `V2` over `TR`, hold at `V2` for `PW`, linear ramp back to `V1` over `TF`, hold at `V1`
46    /// for the remainder of one period `PER`, repeating. `TR`/`TF` of exactly `0` are treated
47    /// as instantaneous edges (division by a real, if tiny, ramp time is what every real SPICE
48    /// implementation does instead; `0` is special-cased here to avoid dividing by zero).
49    Pulse {
50        /// Initial (and final, between periods) value.
51        v1: f64,
52        /// Pulsed value.
53        v2: f64,
54        /// Delay, in seconds, before the first pulse starts.
55        td: f64,
56        /// Rise time from `v1` to `v2`; `0` is treated as an instantaneous edge.
57        tr: f64,
58        /// Fall time from `v2` back to `v1`; `0` is treated as an instantaneous edge.
59        tf: f64,
60        /// Duration held at `v2`.
61        pw: f64,
62        /// Total period; the remainder after `td + tr + pw + tf` is held at `v1`.
63        per: f64,
64    },
65    /// `EXP(V1 V2 TD1 TAU1 TD2 TAU2)` — flat at `V1` until `TD1`, exponential transition
66    /// toward `V2` with time constant `TAU1` starting at `TD1`, exponential transition back
67    /// toward `V1` with time constant `TAU2` starting at `TD2`.
68    Exp {
69        /// Initial value, held until `td1`.
70        v1: f64,
71        /// Value the first exponential transition rises or decays toward.
72        v2: f64,
73        /// Delay, in seconds, before the transition toward `v2` starts.
74        td1: f64,
75        /// Time constant of the transition toward `v2`.
76        tau1: f64,
77        /// Delay, in seconds, before the transition back toward `v1` starts.
78        td2: f64,
79        /// Time constant of the transition back toward `v1`.
80        tau2: f64,
81    },
82    /// `PWL(t1 v1 t2 v2 ...)` — linearly interpolated between explicit `(time, value)`
83    /// breakpoints (unlike `dae_runtime::block_graph::BlockKind::Pwl`, which is
84    /// piecewise-*constant* — this is real SPICE `PWL`, piecewise-*linear*, matching the
85    /// source syntax's own name). Held at the first point's value before the first breakpoint,
86    /// and at the last point's value after the last one.
87    Pwl(PwlPoints),
88    /// `SFFM(V0 VA FC MDI FS)` — single-frequency FM: `V0 + VA*sin(2*pi*FC*t + MDI*sin(2*pi*FS*t))`.
89    Sffm {
90        /// Offset value.
91        v0: f64,
92        /// Carrier amplitude.
93        va: f64,
94        /// Carrier frequency in Hz.
95        fc: f64,
96        /// Modulation index.
97        mdi: f64,
98        /// Signal (modulating) frequency in Hz.
99        fs: f64,
100    },
101}
102
103/// A breakpoint list for [`TransientFunction::Pwl`] — heap-allocated (unlike every other
104/// variant's plain `f64` fields): a real `PWL` source can have an arbitrary number of
105/// breakpoints, and a fixed-capacity inline array sized for a generous case would make every
106/// `TransientFunction` value pay for that space even for a plain `SIN`/`PULSE`/`EXP`/`SFFM`
107/// (`clippy::large_enum_variant` flags exactly this).
108#[derive(Debug, Clone, PartialEq)]
109pub struct PwlPoints(Vec<(f64, f64)>);
110
111impl PwlPoints {
112    /// Builds a breakpoint list, or `None` if `points` is empty (a `PWL` source needs at least
113    /// one `(time, value)` pair).
114    pub fn new(points: &[(f64, f64)]) -> Option<Self> {
115        if points.is_empty() {
116            return None;
117        }
118        Some(PwlPoints(points.to_vec()))
119    }
120
121    /// The breakpoints in declaration order, each as `(time, value)`.
122    pub fn as_slice(&self) -> &[(f64, f64)] {
123        &self.0
124    }
125}
126
127impl TransientFunction {
128    /// Evaluates this source at time `t` (seconds), per the standard SPICE definition for its
129    /// own function form.
130    pub fn value_at(&self, t: f64) -> f64 {
131        match self {
132            TransientFunction::Sin {
133                v0,
134                va,
135                freq,
136                td,
137                theta,
138                phase,
139            } => {
140                if t < *td {
141                    *v0
142                } else {
143                    let dt = t - td;
144                    let phase_rad = phase.to_radians();
145                    let envelope = if *theta == 0.0 {
146                        1.0
147                    } else {
148                        (-dt * theta).exp()
149                    };
150                    v0 + va * (2.0 * std::f64::consts::PI * freq * dt + phase_rad).sin() * envelope
151                }
152            }
153            TransientFunction::Pulse {
154                v1,
155                v2,
156                td,
157                tr,
158                tf,
159                pw,
160                per,
161            } => {
162                let t = if t < *td {
163                    0.0
164                } else {
165                    (t - td) % per.max(f64::EPSILON)
166                };
167                if t < *tr {
168                    if *tr <= 0.0 {
169                        *v2
170                    } else {
171                        v1 + (v2 - v1) * (t / tr)
172                    }
173                } else if t < tr + pw {
174                    *v2
175                } else if t < tr + pw + tf {
176                    if *tf <= 0.0 {
177                        *v1
178                    } else {
179                        v2 + (v1 - v2) * ((t - tr - pw) / tf)
180                    }
181                } else {
182                    *v1
183                }
184            }
185            TransientFunction::Exp {
186                v1,
187                v2,
188                td1,
189                tau1,
190                td2,
191                tau2,
192            } => {
193                if t < *td1 {
194                    *v1
195                } else if t < *td2 {
196                    v1 + (v2 - v1) * (1.0 - (-(t - td1) / tau1.max(f64::EPSILON)).exp())
197                } else {
198                    let rise_at_td2 =
199                        v1 + (v2 - v1) * (1.0 - (-(td2 - td1) / tau1.max(f64::EPSILON)).exp());
200                    rise_at_td2
201                        + (v1 - rise_at_td2) * (1.0 - (-(t - td2) / tau2.max(f64::EPSILON)).exp())
202                }
203            }
204            TransientFunction::Pwl(points) => {
205                let points = points.as_slice();
206                if t <= points[0].0 {
207                    return points[0].1;
208                }
209                let last = points[points.len() - 1];
210                if t >= last.0 {
211                    return last.1;
212                }
213                for window in points.windows(2) {
214                    let (t0, v0) = window[0];
215                    let (t1, v1) = window[1];
216                    if t >= t0 && t <= t1 {
217                        if (t1 - t0).abs() < f64::EPSILON {
218                            return v1;
219                        }
220                        return v0 + (v1 - v0) * ((t - t0) / (t1 - t0));
221                    }
222                }
223                last.1
224            }
225            TransientFunction::Sffm {
226                v0,
227                va,
228                fc,
229                mdi,
230                fs,
231            } => {
232                let two_pi = 2.0 * std::f64::consts::PI;
233                v0 + va * (two_pi * fc * t + mdi * (two_pi * fs * t).sin()).sin()
234            }
235        }
236    }
237
238    /// The names of the five transient-function forms this type implements, uppercase, in the
239    /// order they are declared above, and exactly the set [`Self::parse`]'s own match arms
240    /// cover (a unit test below asserts that, so the two cannot drift). [`Self::parse_params`]
241    /// scans for these names, and `builder.rs`'s device-card validation rejects a misspelled
242    /// one (`SNI(...)`) by asking whether the name is in here rather than by writing the list
243    /// out a second time.
244    pub const FUNCTION_NAMES: [&'static str; 5] = ["SIN", "PULSE", "EXP", "PWL", "SFFM"];
245
246    /// Whether `name` (compared case-insensitively) is one of [`Self::FUNCTION_NAMES`].
247    pub fn is_function_name(name: &str) -> bool {
248        Self::FUNCTION_NAMES
249            .iter()
250            .any(|known| name.eq_ignore_ascii_case(known))
251    }
252
253    /// The token range of the first transient-function call inside an independent source's
254    /// parameter list, as `(first, last)` inclusive indices into `tokens`, or `None` if the
255    /// list contains no recognized call.
256    ///
257    /// Needed because the call is *not* always the first parameter: `V1 1 0 DC 0 SIN(0 1 1k)`
258    /// is ordinary SPICE, and scanning only `tokens[0]` (which is all [`Self::parse`] does, by
259    /// design — it takes a slice that already starts at the call) silently dropped the whole
260    /// waveform and simulated a flat 0 V source instead. The end index is the token carrying
261    /// the closing `)`, since `general-spice-core` splits `SIN(0 10 1000)` across three tokens.
262    pub fn find_call(tokens: &[String]) -> Option<(usize, usize)> {
263        let first = tokens.iter().position(|token| {
264            token
265                .find('(')
266                .is_some_and(|paren| Self::is_function_name(&token[..paren]))
267        })?;
268        let last = tokens[first..]
269            .iter()
270            .position(|token| token.contains(')'))?
271            + first;
272        Some((first, last))
273    }
274
275    /// Parses the first transient-function call appearing anywhere in an independent source's
276    /// parameter list, or `None` when it contains none.
277    ///
278    /// This is what a caller holding a whole `V`/`I` card's `raw_params` wants;
279    /// [`Self::parse`] is the narrower primitive that assumes the slice already begins at the
280    /// call. See [`Self::find_call`] for why the difference matters.
281    pub fn parse_params(tokens: &[String]) -> Option<TransientFunction> {
282        let (first, last) = Self::find_call(tokens)?;
283        Self::parse(&tokens[first..=last])
284    }
285
286    /// Detects and parses one of the five transient-function forms from an already-tokenized
287    /// parameter list (as `general-spice-core` hands back — see the module doc comment for exactly how
288    /// mangled that tokenization is: parentheses stuck to whichever token they landed on).
289    /// Returns `None` if `tokens` doesn't start with a recognized function name, so the caller
290    /// can fall back to treating the source as an ordinary static value.
291    pub fn parse(tokens: &[String]) -> Option<TransientFunction> {
292        let first = tokens.first()?;
293        let paren = first.find('(')?;
294        let name = first[..paren].to_ascii_uppercase();
295
296        // Reassemble the numeric argument list: the rest of `first` after '(', then every
297        // later token, with a trailing ')' stripped off whichever token has it.
298        let mut args: Vec<f64> = Vec::new();
299        let first_rest = first[paren + 1..].trim_end_matches(')');
300        if !first_rest.is_empty() {
301            args.push(crate::expression::parse_spice_number(first_rest)?);
302        }
303        for token in &tokens[1..] {
304            let cleaned = token.trim_end_matches(')');
305            if cleaned.is_empty() {
306                continue;
307            }
308            args.push(crate::expression::parse_spice_number(cleaned)?);
309        }
310
311        match name.as_str() {
312            "SIN" => {
313                let get = |i: usize, default: f64| args.get(i).copied().unwrap_or(default);
314                Some(TransientFunction::Sin {
315                    v0: get(0, 0.0),
316                    va: get(1, 0.0),
317                    freq: get(2, 0.0),
318                    td: get(3, 0.0),
319                    theta: get(4, 0.0),
320                    phase: get(5, 0.0),
321                })
322            }
323            "PULSE" => {
324                if args.len() < 2 {
325                    return None;
326                }
327                let get = |i: usize, default: f64| args.get(i).copied().unwrap_or(default);
328                Some(TransientFunction::Pulse {
329                    v1: args[0],
330                    v2: args[1],
331                    td: get(2, 0.0),
332                    tr: get(3, 0.0),
333                    tf: get(4, 0.0),
334                    pw: get(5, f64::MAX / 4.0),
335                    per: get(6, f64::MAX / 4.0),
336                })
337            }
338            "EXP" => {
339                if args.len() < 2 {
340                    return None;
341                }
342                let get = |i: usize, default: f64| args.get(i).copied().unwrap_or(default);
343                Some(TransientFunction::Exp {
344                    v1: args[0],
345                    v2: args[1],
346                    td1: get(2, 0.0),
347                    tau1: get(3, 1.0),
348                    td2: get(4, get(2, 0.0)),
349                    tau2: get(5, 1.0),
350                })
351            }
352            "PWL" => {
353                if args.len() < 2 || !args.len().is_multiple_of(2) {
354                    return None;
355                }
356                let points: Vec<(f64, f64)> = args
357                    .as_chunks::<2>()
358                    .0
359                    .iter()
360                    .map(|&[t, v]| (t, v))
361                    .collect();
362                PwlPoints::new(&points).map(TransientFunction::Pwl)
363            }
364            "SFFM" => {
365                let get = |i: usize, default: f64| args.get(i).copied().unwrap_or(default);
366                Some(TransientFunction::Sffm {
367                    v0: get(0, 0.0),
368                    va: get(1, 0.0),
369                    fc: get(2, 0.0),
370                    mdi: get(3, 0.0),
371                    fs: get(4, 0.0),
372                })
373            }
374            _ => None,
375        }
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    fn toks(s: &str) -> Vec<String> {
384        s.split_whitespace().map(String::from).collect()
385    }
386
387    #[test]
388    fn sin_matches_hand_computed_values() {
389        let tf = TransientFunction::parse(&toks("SIN(0 10 1000 0 0 0)")).unwrap();
390        assert!((tf.value_at(0.0) - 0.0).abs() < 1e-9);
391        // Quarter period: t = 1/(4*1000) = 250us -> sin(pi/2) = 1 -> value = 10
392        assert!((tf.value_at(2.5e-4) - 10.0).abs() < 1e-6);
393        // Half period -> back to 0
394        assert!((tf.value_at(5e-4) - 0.0).abs() < 1e-6);
395    }
396
397    #[test]
398    fn sin_respects_delay_and_damping() {
399        let tf = TransientFunction::parse(&toks("SIN(1 2 100 0.01 5 0)")).unwrap();
400        assert_eq!(tf.value_at(0.0), 1.0); // before td, flat at v0
401        assert_eq!(tf.value_at(0.005), 1.0);
402        // Right at td, undamped sin(0) = 0, so value = v0 exactly.
403        assert!((tf.value_at(0.01) - 1.0).abs() < 1e-9);
404    }
405
406    #[test]
407    fn pulse_matches_hand_computed_trapezoid() {
408        // V1=0 V2=10 TD=0 TR=1 TF=1 PW=2 PER=10 (arbitrary time units for a clean hand check)
409        let tf = TransientFunction::parse(&toks("PULSE(0 10 0 1 1 2 10)")).unwrap();
410        assert_eq!(tf.value_at(0.0), 0.0);
411        assert_eq!(tf.value_at(0.5), 5.0); // mid-rise
412        assert_eq!(tf.value_at(1.0), 10.0); // start of plateau
413        assert_eq!(tf.value_at(2.5), 10.0); // mid-plateau
414        assert_eq!(tf.value_at(3.5), 5.0); // mid-fall
415        assert_eq!(tf.value_at(4.0), 0.0); // back to v1
416        assert_eq!(tf.value_at(9.9), 0.0); // still low, before next period
417        assert_eq!(tf.value_at(10.5), 5.0); // second period, mid-rise
418    }
419
420    #[test]
421    fn exp_matches_hand_computed_values() {
422        // V1=0 V2=1 TD1=0 TAU1=1 TD2=1000 TAU2=1 (TD2 far away so only the rise matters here)
423        let tf = TransientFunction::parse(&toks("EXP(0 1 0 1 1000 1)")).unwrap();
424        assert_eq!(tf.value_at(0.0), 0.0);
425        // At t=tau1, rise = 1 - e^-1 ~= 0.6321
426        assert!((tf.value_at(1.0) - (1.0 - (-1.0_f64).exp())).abs() < 1e-9);
427    }
428
429    #[test]
430    fn pwl_interpolates_linearly_and_holds_ends() {
431        let tf = TransientFunction::parse(&toks("PWL(0 0 1 10 2 0)")).unwrap();
432        assert_eq!(tf.value_at(-1.0), 0.0); // before first point: held
433        assert_eq!(tf.value_at(0.0), 0.0);
434        assert_eq!(tf.value_at(0.5), 5.0); // linear interpolation
435        assert_eq!(tf.value_at(1.0), 10.0);
436        assert_eq!(tf.value_at(1.5), 5.0);
437        assert_eq!(tf.value_at(2.0), 0.0);
438        assert_eq!(tf.value_at(3.0), 0.0); // after last point: held
439    }
440
441    #[test]
442    fn sffm_matches_hand_computed_value_at_t_zero() {
443        let tf = TransientFunction::parse(&toks("SFFM(0 5 1000 10 100)")).unwrap();
444        // At t=0, both sines are 0 -> value = v0 = 0.
445        assert_eq!(tf.value_at(0.0), 0.0);
446    }
447
448    #[test]
449    fn non_function_tokens_return_none() {
450        assert!(TransientFunction::parse(&toks("10")).is_none());
451        assert!(TransientFunction::parse(&toks("DC 5")).is_none());
452    }
453
454    #[test]
455    fn pulse_accepts_spice_numeric_suffixes() {
456        // Same shape as pulse_matches_hand_computed_trapezoid, but with realistic
457        // SPICE-suffixed arguments (TD=1m, TR=100n, TF=100n, PW=2m, PER=4m) -- this is
458        // the exact case that silently failed to parse before parse() switched from
459        // plain f64::parse to crate::expression::parse_spice_number.
460        let tf = TransientFunction::parse(&toks("PULSE(0 5 1m 100n 100n 2m 4m)")).unwrap();
461        match tf {
462            TransientFunction::Pulse {
463                v1,
464                v2,
465                td,
466                tr,
467                tf: fall,
468                pw,
469                per,
470            } => {
471                assert_eq!(v1, 0.0);
472                assert_eq!(v2, 5.0);
473                assert!((td - 1e-3).abs() < 1e-15);
474                assert!((tr - 100e-9).abs() < 1e-15);
475                assert!((fall - 100e-9).abs() < 1e-15);
476                assert!((pw - 2e-3).abs() < 1e-15);
477                assert!((per - 4e-3).abs() < 1e-15);
478            }
479            other => panic!("expected Pulse, got {other:?}"),
480        }
481    }
482
483    #[test]
484    fn sin_accepts_spice_numeric_suffixes() {
485        let tf = TransientFunction::parse(&toks("SIN(0 10 50k 0 0 0)")).unwrap();
486        match tf {
487            TransientFunction::Sin { freq, .. } => {
488                assert!((freq - 50e3).abs() < 1e-9);
489            }
490            other => panic!("expected Sin, got {other:?}"),
491        }
492    }
493
494    #[test]
495    fn function_names_are_exactly_what_parse_dispatches_on() {
496        // Keeps `FUNCTION_NAMES` and `parse`'s own match arms from drifting apart, which would
497        // make `builder.rs` bless a call it then refuses to parse, or vice versa.
498        for name in TransientFunction::FUNCTION_NAMES {
499            assert!(
500                TransientFunction::parse(&toks(&format!("{name}(0 1 2 3 4 5)"))).is_some(),
501                "{name} is listed in FUNCTION_NAMES but parse does not accept it"
502            );
503        }
504        assert!(TransientFunction::parse(&toks("SNI(0 1 2)")).is_none());
505        assert!(TransientFunction::is_function_name("sin"));
506        assert!(!TransientFunction::is_function_name("sni"));
507    }
508
509    #[test]
510    fn a_function_call_is_found_after_a_dc_clause() {
511        // The bug: `parse` alone only ever looks at token 0, so this card used to simulate a
512        // flat 0 V source and drop the sinusoid without a word.
513        let tokens = toks("DC 0 SIN(0 10 1000)");
514        assert_eq!(TransientFunction::find_call(&tokens), Some((2, 4)));
515        match TransientFunction::parse_params(&tokens).unwrap() {
516            TransientFunction::Sin { v0, va, freq, .. } => {
517                assert_eq!((v0, va, freq), (0.0, 10.0, 1000.0));
518            }
519            other => panic!("expected Sin, got {other:?}"),
520        }
521    }
522
523    #[test]
524    fn parse_params_is_unchanged_for_a_call_in_the_first_position() {
525        let tokens = toks("PULSE(0 5 1m 100n 100n 2m 4m)");
526        assert_eq!(
527            TransientFunction::parse_params(&tokens),
528            TransientFunction::parse(&tokens)
529        );
530    }
531
532    #[test]
533    fn parse_params_finds_nothing_in_a_plain_dc_card() {
534        assert!(TransientFunction::parse_params(&toks("DC 10")).is_none());
535        assert!(TransientFunction::parse_params(&toks("10")).is_none());
536    }
537}