1use std::cell::RefCell;
9use std::collections::{BTreeMap, BTreeSet};
10
11use continuous_blocks::{
12 CoordinateTransform, DiscreteIntegrationMethod, DiscretePid, FlipFlopKind, Hysteresis,
13 LatchPriority, LogicOp, Pid, SettledStateError, StateSpace, TransferFunction, Vco,
14};
15use general_spice_core::ast::Statement;
16use general_spice_core::dialect::Dialect;
17use general_spice_core::{lexer, parser};
18use pwl_devices::{IdealDiode, IdealSwitch};
19
20use crate::block_graph::{
21 BlockInstance, BlockKind, ConstValue, GainValue, GateBinding, Phys2SigTarget, PhysicalDomain,
22 PidClamp, SampleTimeSpec, Signal,
23};
24use crate::hierarchy;
25use crate::{MnaBuilder, MnaSystem, TransientFunction};
26
27#[derive(Debug)]
31pub struct System {
32 pub mna: MnaSystem,
34 pub ideal_diodes: BTreeMap<String, IdealDiode>,
36 pub ideal_switches: BTreeMap<String, IdealSwitch>,
38 pub gates: BTreeMap<String, GateBinding>,
41 pub blocks: Vec<BlockInstance>,
43 pub shared_r_on: f64,
47}
48
49enum Kind {
50 IdealDiode(IdealDiode),
51 IdealSwitch {
52 ideal_switch: IdealSwitch,
53 r_on: f64,
54 gate: GateBinding,
55 },
56 Block(BlockInstance),
57}
58
59pub fn parse_and_flatten(source: &str, dialect: Dialect) -> Result<Vec<Statement>, String> {
75 let processed = lexer::preprocess(source, dialect);
76 let statements: Vec<Statement> = parser::parse(&processed, dialect)
77 .into_iter()
78 .collect::<Result<_, _>>()
79 .map_err(|e: parser::ParseError| format!("line {}: {}", e.span.start, e.message))?;
80 hierarchy::flatten(&statements)
81}
82
83pub fn build_system(source: &str, dialect: Dialect) -> Result<System, String> {
92 let statements = parse_and_flatten(source, dialect)?;
93
94 let mna = MnaBuilder::new(dialect)
95 .build_statements(&statements)
96 .map_err(|e| e.to_string())?;
100
101 let mut ideal_diodes = BTreeMap::new();
102 let mut ideal_switches = BTreeMap::new();
103 let mut gates = BTreeMap::new();
104 let mut blocks = Vec::new();
105 let mut shared_r_on: Option<f64> = None;
106 let mut phys2sig_branch_checks: Vec<(String, String, usize)> = Vec::new();
113
114 for stmt in &statements {
115 let Statement::BlockInstance(bi) = stmt else {
116 continue;
117 };
118 match build_kind(bi)? {
119 Kind::IdealDiode(d) => {
120 ideal_diodes.insert(bi.name.clone(), d);
121 }
122 Kind::IdealSwitch {
123 ideal_switch,
124 r_on,
125 gate,
126 } => {
127 match shared_r_on {
128 None => shared_r_on = Some(r_on),
129 Some(existing) if (existing - r_on).abs() > 1e-15 => {
130 return Err(format!(
131 "all ideal switches must share the same r_on (dae-runtime's switch \
132 model uses one shared on-resistance per call); got {existing} and \
133 {r_on}"
134 ));
135 }
136 Some(_) => {}
137 }
138 gates.insert(bi.name.clone(), gate);
139 ideal_switches.insert(bi.name.clone(), ideal_switch);
140 }
141 Kind::Block(instance) => {
142 if let BlockKind::Phys2Sig(Phys2SigTarget::Current(branch)) = &instance.kind {
143 let line_number = bi.span.start.saturating_sub(1);
144 phys2sig_branch_checks.push((
145 instance.name.clone(),
146 branch.clone(),
147 line_number,
148 ));
149 }
150 blocks.push(instance);
151 }
152 }
153 }
154
155 for (phys2sig_name, branch, line_number) in &phys2sig_branch_checks {
156 let unknown = format!("I({branch})");
157 if mna.unknowns.iter().any(|u| u == &unknown) {
158 continue;
159 }
160 let element_exists = statements.iter().any(|s| {
161 matches!(
162 s,
163 Statement::ElementInstance(e) if e.name.eq_ignore_ascii_case(branch)
164 )
165 });
166 if element_exists {
167 return Err(format!(
168 "line {}: device '{phys2sig_name}' kind='phys2sig' branch='{branch}' has no \
169 current unknown available (only V/L/E/H sources carry a branch-current \
170 unknown) -- insert a 0V voltage source in series in the branch you want to \
171 measure and probe its current instead",
172 line_number + 1
173 ));
174 }
175 return Err(format!(
176 "line {}: device '{phys2sig_name}' kind='phys2sig' branch='{branch}' names no such \
177 element",
178 line_number + 1
179 ));
180 }
181
182 Ok(System {
183 mna,
184 ideal_diodes,
185 ideal_switches,
186 gates,
187 blocks,
188 shared_r_on: shared_r_on.unwrap_or(0.0),
189 })
190}
191
192fn parse_signal(text: &str) -> Signal {
193 match text.strip_prefix("prev:") {
194 Some(name) => Signal::BlockPrev(name.to_string()),
195 None => Signal::Block(text.to_string()),
196 }
197}
198
199fn split_top_level(text: &str) -> Vec<&str> {
205 let mut depth = 0i32;
206 let mut start = 0usize;
207 let mut parts = Vec::new();
208 for (i, c) in text.char_indices() {
209 match c {
210 '[' => depth += 1,
211 ']' => depth -= 1,
212 ',' if depth == 0 => {
213 parts.push(text[start..i].trim());
214 start = i + c.len_utf8();
215 }
216 _ => {}
217 }
218 }
219 parts.push(text[start..].trim());
220 parts
221}
222
223fn strip_brackets<'a>(
229 text: &'a str,
230 name: &str,
231 field: &str,
232 line_number: usize,
233) -> Result<&'a str, String> {
234 let trimmed = text.trim();
235 trimmed
236 .strip_prefix('[')
237 .and_then(|s| s.strip_suffix(']'))
238 .ok_or_else(|| {
239 format!(
240 "line {}: device '{name}' field '{field}' must be a Python-style list, e.g. \
241 '[1,2,3]' or '[[1,2],[3,4]]' (got '{text}')",
242 line_number + 1
243 )
244 })
245}
246
247fn parse_xy_points(
252 text: &str,
253 name: &str,
254 field: &str,
255 line_number: usize,
256) -> Result<Vec<(f64, f64)>, String> {
257 let rows = parse_matrix_rows(text, name, field, line_number)?;
258 let mut points = Vec::with_capacity(rows.len());
259 for row in rows {
260 let [x, y] = row.as_slice() else {
261 return Err(format!(
262 "line {}: device '{name}' field '{field}': each entry must be a 2-element \
263 '[x,y]' list (got '{row:?}')",
264 line_number + 1
265 ));
266 };
267 points.push((*x, *y));
268 }
269 points.sort_by(|a, b| a.0.total_cmp(&b.0));
270 Ok(points)
271}
272
273struct Fields {
287 map: BTreeMap<String, String>,
288 looked_up: RefCell<BTreeSet<String>>,
289}
290
291impl Fields {
292 fn new(map: BTreeMap<String, String>) -> Self {
293 Self {
294 map,
295 looked_up: RefCell::new(BTreeSet::new()),
296 }
297 }
298
299 fn get(&self, key: &str) -> Option<&String> {
300 self.looked_up.borrow_mut().insert(key.to_string());
301 self.map.get(key)
302 }
303
304 fn contains_key(&self, key: &str) -> bool {
305 self.get(key).is_some()
306 }
307
308 fn present_unread(&self, key: &str) -> bool {
315 self.map.contains_key(key)
316 }
317
318 fn unread(&self) -> Option<(&str, Vec<String>)> {
322 let looked_up = self.looked_up.borrow();
323 let stray = self
324 .map
325 .keys()
326 .find(|key| key.as_str() != "kind" && !looked_up.contains(key.as_str()))?;
327 let accepted = looked_up
328 .iter()
329 .filter(|key| key.as_str() != "kind")
330 .cloned()
331 .collect();
332 Some((stray.as_str(), accepted))
333 }
334}
335
336fn parse_sample_time(
347 fields: &Fields,
348 name: &str,
349 line_number: usize,
350 allow_variable: bool,
351 kind_str: &str,
352) -> Result<Option<SampleTimeSpec>, String> {
353 let get = |key: &str| -> Result<f64, String> {
354 fields
355 .get(key)
356 .ok_or_else(|| {
357 format!(
358 "line {}: device '{name}' missing field '{key}'",
359 line_number + 1
360 )
361 })?
362 .parse::<f64>()
363 .map_err(|_| {
364 format!(
365 "line {}: device '{name}' field '{key}' is not a number",
366 line_number + 1
367 )
368 })
369 };
370
371 if fields.get("ts").map(String::as_str) == Some("variable") {
372 if !allow_variable {
373 let suggestion = if kind_str == "pyfunc" {
378 " -- use kind=pyblock instead"
379 } else {
380 ""
381 };
382 return Err(format!(
383 "line {}: device '{name}': ts=variable is not available for kind={kind_str} (a \
384 stateless function call has no instance to remember a requested next-hit \
385 time against){suggestion}",
386 line_number + 1
387 ));
388 }
389 if fields.contains_key("freq") || fields.contains_key("to") {
390 return Err(format!(
391 "line {}: device '{name}': ts=variable is exclusive with 'freq'/'to' (the \
392 block computes its own schedule; there's no fixed period/offset to combine \
393 it with)",
394 line_number + 1
395 ));
396 }
397 return Ok(Some(SampleTimeSpec::Variable));
398 }
399
400 let period = match (fields.get("ts"), fields.get("freq")) {
401 (Some(_), Some(_)) => {
402 return Err(format!(
403 "line {}: device '{name}': 'ts' and 'freq' are mutually exclusive (both set \
404 this block's sample time)",
405 line_number + 1
406 ))
407 }
408 (Some(_), None) => Some(get("ts")?),
409 (None, Some(_)) => Some(1.0 / get("freq")?),
410 (None, None) => None,
411 };
412
413 match (period, fields.get("to")) {
414 (None, Some(_)) => Err(format!(
415 "line {}: device '{name}': 'to' requires 'ts' or 'freq' (a phase offset has \
416 nothing to offset without a period)",
417 line_number + 1
418 )),
419 (None, None) => Ok(None),
420 (Some(period), None) => Ok(Some(SampleTimeSpec::Periodic {
421 period,
422 offset: 0.0,
423 })),
424 (Some(period), Some(_)) => {
425 let offset = get("to")?;
426 if !(0.0..period).contains(&offset) {
427 return Err(format!(
428 "line {}: device '{name}': 'to' ({offset}) must satisfy 0 <= to < ts \
429 ({period})",
430 line_number + 1
431 ));
432 }
433 Ok(Some(SampleTimeSpec::Periodic { period, offset }))
434 }
435 }
436}
437
438fn parse_required_periodic_sample_time(
445 fields: &Fields,
446 name: &str,
447 line_number: usize,
448) -> Result<SampleTimeSpec, String> {
449 match parse_sample_time(fields, name, line_number, true, "")? {
450 Some(SampleTimeSpec::Periodic { period, offset }) => {
451 Ok(SampleTimeSpec::Periodic { period, offset })
452 }
453 Some(SampleTimeSpec::Variable) => Err(format!(
454 "line {}: device '{name}': ts=variable is not available here -- a discrete block's \
455 own recursion has its coefficients baked in at one fixed sample period, which \
456 'the block decides its own next execution time' doesn't compose with",
457 line_number + 1
458 )),
459 None => Err(format!(
460 "line {}: device '{name}': missing 'ts=' or 'freq=' -- a discrete-time block's own \
461 sample period is not optional (its dynamics *are* that period), unlike the \
462 optional 'ts='/'freq=' on kind=cscript/pyblock/pyfunc",
463 line_number + 1
464 )),
465 }
466}
467
468fn parse_const_value(
472 text: &str,
473 name: &str,
474 field: &str,
475 line_number: usize,
476) -> Result<ConstValue, String> {
477 if text.trim().starts_with('[') {
478 Ok(ConstValue::Vector(parse_vector(
479 text,
480 name,
481 field,
482 line_number,
483 )?))
484 } else {
485 text.trim()
486 .parse::<f64>()
487 .map(ConstValue::Scalar)
488 .map_err(|_| {
489 format!(
490 "line {}: device '{name}' field '{field}' is not a number",
491 line_number + 1
492 )
493 })
494 }
495}
496
497fn parse_gain_value(
503 text: &str,
504 name: &str,
505 field: &str,
506 line_number: usize,
507) -> Result<GainValue, String> {
508 let trimmed = text.trim();
509 if trimmed.starts_with('[') {
510 let inner = strip_brackets(text, name, field, line_number)?;
511 if inner.trim_start().starts_with('[') {
512 return Ok(GainValue::Matrix(parse_matrix_rows(
513 text,
514 name,
515 field,
516 line_number,
517 )?));
518 }
519 return Err(format!(
520 "line {}: device '{name}' field '{field}' must be a scalar (e.g. '2.0') or a \
521 matrix (e.g. '[[1,0],[0,1]]') -- got a flat list '{text}', which is not a valid \
522 Gain shape",
523 line_number + 1
524 ));
525 }
526 trimmed.parse::<f64>().map(GainValue::Scalar).map_err(|_| {
527 format!(
528 "line {}: device '{name}' field '{field}' is not a number",
529 line_number + 1
530 )
531 })
532}
533
534fn parse_matrix_or_vector_shorthand(
540 text: &str,
541 name: &str,
542 field: &str,
543 line_number: usize,
544 as_column: bool,
545) -> Result<Vec<Vec<f64>>, String> {
546 let inner = strip_brackets(text, name, field, line_number)?;
547 if inner.trim_start().starts_with('[') {
548 return parse_matrix_rows(text, name, field, line_number);
549 }
550 let v = parse_vector(text, name, field, line_number)?;
551 Ok(if as_column {
552 v.into_iter().map(|x| vec![x]).collect()
553 } else {
554 vec![v]
555 })
556}
557
558fn parse_vector(
561 text: &str,
562 name: &str,
563 field: &str,
564 line_number: usize,
565) -> Result<Vec<f64>, String> {
566 let inner = strip_brackets(text, name, field, line_number)?;
567 if inner.is_empty() {
568 return Ok(Vec::new());
569 }
570 split_top_level(inner)
571 .into_iter()
572 .map(|v| {
573 let parsed: f64 = v.parse().map_err(|_| {
574 format!(
575 "line {}: device '{name}' field '{field}' entry '{v}' is not a number",
576 line_number + 1
577 )
578 })?;
579 if !parsed.is_finite() {
584 return Err(format!(
585 "line {}: device '{name}' field '{field}' entry '{v}' must be a finite \
586 number (got {parsed})",
587 line_number + 1
588 ));
589 }
590 Ok(parsed)
591 })
592 .collect()
593}
594
595fn parse_matrix_rows(
598 text: &str,
599 name: &str,
600 field: &str,
601 line_number: usize,
602) -> Result<Vec<Vec<f64>>, String> {
603 let inner = strip_brackets(text, name, field, line_number)?;
604 if inner.is_empty() {
605 return Ok(Vec::new());
606 }
607 split_top_level(inner)
608 .into_iter()
609 .map(|row| parse_vector(row, name, field, line_number))
610 .collect()
611}
612
613fn build_kind(stmt: &general_spice_core::ast::BlockInstance) -> Result<Kind, String> {
614 let name = &stmt.name;
615 let line_number = stmt.span.start.saturating_sub(1);
616 let fields = Fields::new(stmt.fields.iter().cloned().collect());
617
618 let get = |key: &str| -> Result<f64, String> {
619 fields
620 .get(key)
621 .ok_or_else(|| {
622 format!(
623 "line {}: device '{name}' missing field '{key}'",
624 line_number + 1
625 )
626 })?
627 .parse::<f64>()
628 .map_err(|_| {
629 format!(
630 "line {}: device '{name}' field '{key}' is not a number",
631 line_number + 1
632 )
633 })
634 };
635
636 let get_str = |key: &str| -> Result<String, String> {
637 fields.get(key).cloned().ok_or_else(|| {
638 format!(
639 "line {}: device '{name}' missing field '{key}'",
640 line_number + 1
641 )
642 })
643 };
644
645 let renamed = |old: &str, replacement: &str, why: &str| -> Option<String> {
659 fields.present_unread(old).then(|| {
660 format!(
661 "line {}: device '{name}' field '{old}' no longer exists -- write \
662 '{replacement}'. {why}",
663 line_number + 1
664 )
665 })
666 };
667
668 let kind = fields
669 .get("kind")
670 .map(String::as_str)
671 .unwrap_or("ideal_diode");
672 let entry = match kind {
673 "ideal_diode" => {
674 if let Some(message) = renamed(
675 "v_th",
676 "v_f",
677 "A diode's forward threshold is $V_F$ on every datasheet; `v_th` means the \
678 MOSFET gate threshold and belongs to no diode.",
679 ) {
680 return Err(message);
681 }
682 Kind::IdealDiode(IdealDiode::new(
683 get("g_breakdown")?,
684 get("v_breakdown")?,
685 get("g_off")?,
686 get("v_f")?,
687 get("g_on")?,
688 ))
689 }
690 "ideal_switch" => {
691 if let Some(message) = renamed(
692 "v_th",
693 "body_v_f",
694 "On a switch this field was never the gate threshold: it is the body diode's \
695 forward voltage, and the gate path never read it. If you meant the gate \
696 threshold, that is 'v_gs_th' and it defaults to 0.5.",
697 ) {
698 return Err(message);
699 }
700 for (old, replacement) in [
704 ("g_on", "body_g_on"),
705 ("g_off", "body_g_off"),
706 ("v_breakdown", "body_v_breakdown"),
707 ("g_breakdown", "body_g_breakdown"),
708 ] {
709 if let Some(message) = renamed(
710 old,
711 replacement,
712 "On a switch, every field describing the body diode carries the `body_` \
713 prefix; `r_on` stays bare because it is the channel, which is the switch's \
714 own.",
715 ) {
716 return Err(message);
717 }
718 }
719 let body_diode = IdealDiode::new(
720 get("body_g_breakdown")?,
721 get("body_v_breakdown")?,
722 get("body_g_off")?,
723 get("body_v_f")?,
724 get("body_g_on")?,
725 );
726 let r_on = get("r_on")?;
727 let v_gs_th = match fields.get("v_gs_th") {
736 None => 0.5,
737 Some(_) => get("v_gs_th")?,
738 };
739 let gate = match fields.get("gate").map(String::as_str) {
740 Some("block") => GateBinding::Block {
741 ctrl: get_str("ctrl")?,
742 v_gs_th,
743 },
744 Some(other) => {
745 return Err(format!(
746 "line {}: unknown gate spec '{other}' (only gate=block ctrl=<name> \
747 exists -- every gate is block-driven)",
748 line_number + 1
749 ))
750 }
751 None => {
752 return Err(format!(
753 "line {}: device '{name}' missing field 'gate' (gate=block \
754 ctrl=<name> -- every gate is block-driven, see this file's own \
755 module doc comment)",
756 line_number + 1
757 ))
758 }
759 };
760 Kind::IdealSwitch {
761 ideal_switch: IdealSwitch::new(r_on, body_diode),
762 r_on,
763 gate,
764 }
765 }
766 "const" => Kind::Block(BlockInstance {
767 name: name.to_string(),
768 kind: BlockKind::Const(parse_const_value(
769 &get_str("value")?,
770 name,
771 "value",
772 line_number,
773 )?),
774 inputs: Vec::new(),
775 ic: None,
776 }),
777 "time" => Kind::Block(BlockInstance {
778 name: name.to_string(),
779 kind: BlockKind::Time,
780 inputs: Vec::new(),
781 ic: None,
782 }),
783 "pwc" => {
792 let points = parse_xy_points(&get_str("points")?, name, "points", line_number)?;
793 let repeat = fields.get("repeat").map(|s| s == "true").unwrap_or(false);
794 Kind::Block(BlockInstance {
795 name: name.to_string(),
796 kind: BlockKind::Pwc { points, repeat },
797 inputs: Vec::new(),
798 ic: None,
799 })
800 }
801 "pwl" => {
802 let points = parse_xy_points(&get_str("points")?, name, "points", line_number)?;
803 let repeat = fields.get("repeat").map(|s| s == "true").unwrap_or(false);
804 Kind::Block(BlockInstance {
805 name: name.to_string(),
806 kind: BlockKind::Pwl { points, repeat },
807 inputs: Vec::new(),
808 ic: None,
809 })
810 }
811 "sinwave" => {
823 let get_opt = |key: &str, default: f64| -> f64 {
824 fields
825 .get(key)
826 .and_then(|s| s.parse::<f64>().ok())
827 .unwrap_or(default)
828 };
829 Kind::Block(BlockInstance {
830 name: name.to_string(),
831 kind: BlockKind::Waveform(TransientFunction::Sin {
832 v0: get_opt("v0", 0.0),
833 va: get("va")?,
834 freq: get("freq")?,
835 td: get_opt("td", 0.0),
836 theta: get_opt("theta", 0.0),
837 phase: get_opt("phase", 0.0),
838 }),
839 inputs: Vec::new(),
840 ic: None,
841 })
842 }
843 "pulsewave" => {
844 let get_opt = |key: &str, default: f64| -> f64 {
845 fields
846 .get(key)
847 .and_then(|s| s.parse::<f64>().ok())
848 .unwrap_or(default)
849 };
850 Kind::Block(BlockInstance {
851 name: name.to_string(),
852 kind: BlockKind::Waveform(TransientFunction::Pulse {
853 v1: get("v1")?,
854 v2: get("v2")?,
855 td: get_opt("td", 0.0),
856 tr: get_opt("tr", 0.0),
857 tf: get_opt("tf", 0.0),
858 pw: get_opt("pw", f64::MAX / 4.0),
859 per: get_opt("per", f64::MAX / 4.0),
860 }),
861 inputs: Vec::new(),
862 ic: None,
863 })
864 }
865 "expwave" => {
866 let get_opt = |key: &str, default: f64| -> f64 {
867 fields
868 .get(key)
869 .and_then(|s| s.parse::<f64>().ok())
870 .unwrap_or(default)
871 };
872 let td1 = get_opt("td1", 0.0);
873 Kind::Block(BlockInstance {
879 name: name.to_string(),
880 kind: BlockKind::Waveform(TransientFunction::Exp {
881 v1: get("v1")?,
882 v2: get("v2")?,
883 td1,
884 tau1: get_opt("tau1", 1.0),
885 td2: get_opt("td2", f64::MAX / 4.0),
886 tau2: get_opt("tau2", 1.0),
887 }),
888 inputs: Vec::new(),
889 ic: None,
890 })
891 }
892 "sffmwave" => {
893 let get_opt = |key: &str, default: f64| -> f64 {
894 fields
895 .get(key)
896 .and_then(|s| s.parse::<f64>().ok())
897 .unwrap_or(default)
898 };
899 Kind::Block(BlockInstance {
900 name: name.to_string(),
901 kind: BlockKind::Waveform(TransientFunction::Sffm {
902 v0: get_opt("v0", 0.0),
903 va: get("va")?,
904 fc: get("fc")?,
905 mdi: get_opt("mdi", 0.0),
906 fs: get("fs")?,
907 }),
908 inputs: Vec::new(),
909 ic: None,
910 })
911 }
912 "sum" => {
913 let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
914 let signs: Vec<f64> = get_str("signs")?
915 .split(',')
916 .map(|s| {
917 s.parse::<f64>().map_err(|_| {
918 format!(
919 "line {}: device '{name}' field 'signs' entry '{s}' is not a \
920 number",
921 line_number + 1
922 )
923 })
924 })
925 .collect::<Result<_, _>>()?;
926 if inputs.len() != signs.len() {
927 return Err(format!(
928 "line {}: device '{name}': 'inputs' has {} entries but 'signs' has {} \
929 (need one sign per input)",
930 line_number + 1,
931 inputs.len(),
932 signs.len()
933 ));
934 }
935 Kind::Block(BlockInstance {
936 name: name.to_string(),
937 kind: BlockKind::Sum(signs),
938 inputs,
939 ic: None,
940 })
941 }
942 "gain" => Kind::Block(BlockInstance {
943 name: name.to_string(),
944 kind: BlockKind::Gain(parse_gain_value(&get_str("k")?, name, "k", line_number)?),
945 inputs: vec![parse_signal(&get_str("in")?)],
946 ic: None,
947 }),
948 "pid" => {
949 let pid = Pid::new(get("kp")?, get("ki")?, get("kd")?, get("n")?).map_err(|e| {
950 format!(
951 "line {}: device '{name}': invalid PID ({e:?})",
952 line_number + 1
953 )
954 })?;
955 let error_input = parse_signal(&get_str("in")?);
956 let (clamp, inputs) = match (fields.get("clamp_lo_in"), fields.get("clamp_hi_in")) {
957 (Some(lo), Some(hi)) => (
958 PidClamp::Dynamic,
959 vec![error_input, parse_signal(lo), parse_signal(hi)],
960 ),
961 (None, None) => (
962 PidClamp::Fixed(get("clamp_lo")?, get("clamp_hi")?),
963 vec![error_input],
964 ),
965 _ => {
966 return Err(format!(
967 "line {}: device '{name}': 'clamp_lo_in'/'clamp_hi_in' must both be \
968 given together (dynamic clamp) or both omitted (fixed clamp= \
969 clamp_lo/clamp_hi)",
970 line_number + 1
971 ))
972 }
973 };
974 Kind::Block(BlockInstance {
975 name: name.to_string(),
976 kind: BlockKind::Pid { pid, clamp },
977 inputs,
978 ic: None,
979 })
980 }
981 "vco" => {
982 let vco = Vco::new(get("f_min")?, get("f_max")?).map_err(|e| {
983 format!(
984 "line {}: device '{name}': invalid vco ({e:?})",
985 line_number + 1
986 )
987 })?;
988 Kind::Block(BlockInstance {
989 name: name.to_string(),
990 kind: BlockKind::Vco(vco),
991 inputs: vec![parse_signal(&get_str("in")?)],
992 ic: None,
993 })
994 }
995 "pwm" => {
1000 let output_names = match fields.get("outputs") {
1001 Some(names) => {
1002 let names: Vec<String> = names.split(',').map(str::to_string).collect();
1003 if names.len() != 2 {
1004 return Err(format!(
1005 "line {}: device '{name}': 'outputs' needs exactly 2 entries \
1006 (main, complement; got {})",
1007 line_number + 1,
1008 names.len()
1009 ));
1010 }
1011 names
1012 }
1013 None => vec![name.to_string(), format!("{name}_comp")],
1014 };
1015 Kind::Block(BlockInstance {
1016 name: name.to_string(),
1017 kind: BlockKind::Pwm {
1018 freq_hz: get("freq")?,
1019 red: fields
1020 .get("red")
1021 .map(|s| s.parse::<f64>())
1022 .transpose()
1023 .map_err(|_| {
1024 format!(
1025 "line {}: device '{name}' field 'red' is not a number",
1026 line_number + 1
1027 )
1028 })?
1029 .unwrap_or(0.0),
1030 fed: fields
1031 .get("fed")
1032 .map(|s| s.parse::<f64>())
1033 .transpose()
1034 .map_err(|_| {
1035 format!(
1036 "line {}: device '{name}' field 'fed' is not a number",
1037 line_number + 1
1038 )
1039 })?
1040 .unwrap_or(0.0),
1041 output_names,
1042 },
1043 inputs: vec![parse_signal(&get_str("in")?)],
1044 ic: None,
1045 })
1046 }
1047 "pspwm" => {
1048 let osc = Vco::new(get("f_min")?, get("f_max")?).map_err(|e| {
1049 format!(
1050 "line {}: device '{name}': invalid pspwm oscillator ({e:?})",
1051 line_number + 1
1052 )
1053 })?;
1054 let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
1055 if inputs.len() != 3 {
1056 return Err(format!(
1057 "line {}: device '{name}' kind='pspwm' needs 3 inputs \
1058 (freq,phase,duty; got {})",
1059 line_number + 1,
1060 inputs.len()
1061 ));
1062 }
1063 let output_names = match fields.get("outputs") {
1064 Some(names) => {
1065 let names: Vec<String> = names.split(',').map(str::to_string).collect();
1066 if names.len() != 2 {
1067 return Err(format!(
1068 "line {}: device '{name}': 'outputs' needs exactly 2 entries \
1069 (main, complement; got {})",
1070 line_number + 1,
1071 names.len()
1072 ));
1073 }
1074 names
1075 }
1076 None => vec![name.to_string(), format!("{name}_comp")],
1077 };
1078 let get_opt = |key: &str| -> Result<f64, String> {
1079 fields
1080 .get(key)
1081 .map(|s| s.parse::<f64>())
1082 .transpose()
1083 .map_err(|_| {
1084 format!(
1085 "line {}: device '{name}' field '{key}' is not a number",
1086 line_number + 1
1087 )
1088 })
1089 .map(|v| v.unwrap_or(0.0))
1090 };
1091 Kind::Block(BlockInstance {
1092 name: name.to_string(),
1093 kind: BlockKind::PhaseShiftPwm {
1094 osc,
1095 red: get_opt("red")?,
1096 fed: get_opt("fed")?,
1097 output_names,
1098 },
1099 inputs,
1100 ic: None,
1101 })
1102 }
1103 "hysteresis" => {
1104 let hysteresis = Hysteresis::new(get("high")?, get("low")?).map_err(|e| {
1105 format!(
1106 "line {}: device '{name}': invalid hysteresis ({e:?})",
1107 line_number + 1
1108 )
1109 })?;
1110 Kind::Block(BlockInstance {
1111 name: name.to_string(),
1112 kind: BlockKind::Hysteresis(hysteresis),
1113 inputs: vec![parse_signal(&get_str("in")?)],
1114 ic: None,
1115 })
1116 }
1117 "srlatch" => {
1118 let priority = match fields.get("priority") {
1119 Some(s) => LatchPriority::from_name(s).ok_or_else(|| {
1120 format!(
1121 "line {}: device '{name}' field 'priority' must be 'set' or 'reset' \
1122 (got '{s}')",
1123 line_number + 1
1124 )
1125 })?,
1126 None => LatchPriority::Set,
1127 };
1128 Kind::Block(BlockInstance {
1129 name: name.to_string(),
1130 kind: BlockKind::SrLatch { priority },
1131 inputs: vec![
1132 parse_signal(&get_str("set")?),
1133 parse_signal(&get_str("reset")?),
1134 ],
1135 ic: None,
1136 })
1137 }
1138 "counter" => {
1139 let modulus = match fields.get("modulus") {
1140 Some(s) => Some(s.parse::<u32>().map_err(|_| {
1141 format!(
1142 "line {}: device '{name}' field 'modulus' is not a non-negative integer",
1143 line_number + 1
1144 )
1145 })?),
1146 None => None,
1147 };
1148 let mut inputs = vec![parse_signal(&get_str("clk")?)];
1149 let up_down = fields.contains_key("up_down");
1150 if up_down {
1151 inputs.push(parse_signal(&get_str("up_down")?));
1152 }
1153 let reset = fields.contains_key("reset");
1154 if reset {
1155 inputs.push(parse_signal(&get_str("reset")?));
1156 }
1157 Kind::Block(BlockInstance {
1158 name: name.to_string(),
1159 kind: BlockKind::Counter {
1160 up_down,
1161 modulus,
1162 reset,
1163 },
1164 inputs,
1165 ic: None,
1166 })
1167 }
1168 "cscript" => {
1169 let lib = std::path::PathBuf::from(get_str("lib")?);
1170 let output_names = match fields.get("outputs") {
1171 Some(names) => names.split(',').map(str::to_string).collect(),
1172 None => vec![name.to_string()],
1173 };
1174 let inputs = match fields.get("inputs") {
1175 Some(list) => list.split(',').map(parse_signal).collect(),
1176 None => vec![parse_signal(&get_str("in")?)],
1177 };
1178 let sample_time = parse_sample_time(&fields, name, line_number, true, "cscript")?;
1179 let xc_count = match fields.get("xc_count") {
1180 Some(s) => s.parse::<usize>().map_err(|_| {
1181 format!(
1182 "line {}: device '{name}' field 'xc_count' is not a non-negative \
1183 integer",
1184 line_number + 1
1185 )
1186 })?,
1187 None => 0,
1188 };
1189 Kind::Block(BlockInstance {
1190 name: name.to_string(),
1191 kind: BlockKind::CScript {
1192 lib,
1193 output_names,
1194 sample_time,
1195 xc_count,
1196 },
1197 inputs,
1198 ic: None,
1199 })
1200 }
1201 "pyblock" => {
1202 let path = std::path::PathBuf::from(get_str("path")?);
1206 let output_names = match fields.get("outputs") {
1207 Some(names) => names.split(',').map(str::to_string).collect(),
1208 None => vec![name.to_string()],
1209 };
1210 let inputs = match fields.get("inputs") {
1211 Some(list) => list.split(',').map(parse_signal).collect(),
1212 None => vec![parse_signal(&get_str("in")?)],
1213 };
1214 let sample_time = parse_sample_time(&fields, name, line_number, true, "pyblock")?;
1215 let xc_count = match fields.get("xc_count") {
1216 Some(s) => s.parse::<usize>().map_err(|_| {
1217 format!(
1218 "line {}: device '{name}' field 'xc_count' is not a non-negative \
1219 integer",
1220 line_number + 1
1221 )
1222 })?,
1223 None => 0,
1224 };
1225 Kind::Block(BlockInstance {
1226 name: name.to_string(),
1227 kind: BlockKind::PyBlock {
1228 path,
1229 output_names,
1230 sample_time,
1231 xc_count,
1232 },
1233 inputs,
1234 ic: None,
1235 })
1236 }
1237 "pyfunc" => {
1238 let path = std::path::PathBuf::from(get_str("path")?);
1243 let function = get_str("function")?;
1244 let output_names = match fields.get("outputs") {
1245 Some(names) => names.split(',').map(str::to_string).collect(),
1246 None => vec![name.to_string()],
1247 };
1248 let inputs = match fields.get("inputs") {
1249 Some(list) => list.split(',').map(parse_signal).collect(),
1250 None => vec![parse_signal(&get_str("in")?)],
1251 };
1252 let sample_time = parse_sample_time(&fields, name, line_number, false, "pyfunc")?;
1253 Kind::Block(BlockInstance {
1254 name: name.to_string(),
1255 kind: BlockKind::PyFunction {
1256 path,
1257 function,
1258 output_names,
1259 sample_time,
1260 },
1261 inputs,
1262 ic: None,
1263 })
1264 }
1265 "octfunc" => {
1266 let path = std::path::PathBuf::from(get_str("path")?);
1271 let function = get_str("function")?;
1272 let output_names = match fields.get("outputs") {
1273 Some(names) => names.split(',').map(str::to_string).collect(),
1274 None => vec![name.to_string()],
1275 };
1276 let inputs = match fields.get("inputs") {
1277 Some(list) => list.split(',').map(parse_signal).collect(),
1278 None => vec![parse_signal(&get_str("in")?)],
1279 };
1280 let sample_time = parse_sample_time(&fields, name, line_number, false, "octfunc")?;
1281 Kind::Block(BlockInstance {
1282 name: name.to_string(),
1283 kind: BlockKind::OctFunc {
1284 path,
1285 function,
1286 output_names,
1287 sample_time,
1288 },
1289 inputs,
1290 ic: None,
1291 })
1292 }
1293 "octblock" => {
1294 let path = std::path::PathBuf::from(get_str("path")?);
1300 let function = get_str("function")?;
1301 let output_names = match fields.get("outputs") {
1302 Some(names) => names.split(',').map(str::to_string).collect(),
1303 None => vec![name.to_string()],
1304 };
1305 let inputs = match fields.get("inputs") {
1306 Some(list) => list.split(',').map(parse_signal).collect(),
1307 None => vec![parse_signal(&get_str("in")?)],
1308 };
1309 let sample_time = parse_sample_time(&fields, name, line_number, true, "octblock")?;
1310 let xc_count = match fields.get("xc_count") {
1311 Some(s) => s.parse::<usize>().map_err(|_| {
1312 format!(
1313 "line {}: device '{name}' field 'xc_count' is not a non-negative \
1314 integer",
1315 line_number + 1
1316 )
1317 })?,
1318 None => 0,
1319 };
1320 Kind::Block(BlockInstance {
1321 name: name.to_string(),
1322 kind: BlockKind::OctBlock {
1323 path,
1324 function,
1325 output_names,
1326 sample_time,
1327 xc_count,
1328 },
1329 inputs,
1330 ic: None,
1331 })
1332 }
1333 "statespace" => {
1334 let a = parse_matrix_rows(&get_str("a")?, name, "a", line_number)?;
1335 let b = parse_matrix_or_vector_shorthand(&get_str("b")?, name, "b", line_number, true)?;
1342 let c =
1343 parse_matrix_or_vector_shorthand(&get_str("c")?, name, "c", line_number, false)?;
1344 let p = b.first().map_or(0, |row| row.len());
1345 let q = c.len();
1346 let d = match fields.get("d") {
1352 None => vec![vec![0.0; p]; q],
1353 Some(text) if text.trim().starts_with('[') => {
1354 parse_matrix_rows(text, name, "d", line_number)?
1355 }
1356 Some(text) => {
1357 if q != 1 || p != 1 {
1358 return Err(format!(
1359 "line {}: device '{name}' field 'd' is a bare scalar, but this \
1360 system has {q} output(s) and {p} input(s) -- declare \
1361 'd=[[...],...]' ({q}x{p}) for a MIMO system, a bare scalar is only \
1362 valid for a 1x1 (SISO) one",
1363 line_number + 1
1364 ));
1365 }
1366 let v: f64 = text.trim().parse().map_err(|_| {
1367 format!(
1368 "line {}: device '{name}' field 'd' is not a number",
1369 line_number + 1
1370 )
1371 })?;
1372 vec![vec![v]]
1373 }
1374 };
1375 let ss = StateSpace::new(a, b, c, d, None).map_err(|e| {
1380 format!(
1381 "line {}: device '{name}': invalid statespace ({e:?})",
1382 line_number + 1
1383 )
1384 })?;
1385 let inputs = match fields.get("inputs") {
1392 Some(list) => list.split(',').map(parse_signal).collect(),
1393 None => vec![parse_signal(&get_str("in")?)],
1394 };
1395 Kind::Block(BlockInstance {
1396 name: name.to_string(),
1397 kind: BlockKind::StateSpace(ss),
1398 inputs,
1399 ic: None,
1400 })
1401 }
1402 "tf" => {
1403 let num = parse_vector(&get_str("num")?, name, "num", line_number)?;
1404 let den = parse_vector(&get_str("den")?, name, "den", line_number)?;
1405 let tf = TransferFunction::new(num, den).map_err(|e| {
1406 format!(
1407 "line {}: device '{name}': invalid transfer function ({e:?})",
1408 line_number + 1
1409 )
1410 })?;
1411 Kind::Block(BlockInstance {
1412 name: name.to_string(),
1413 kind: BlockKind::TransferFunction(tf),
1414 inputs: vec![parse_signal(&get_str("in")?)],
1415 ic: None,
1416 })
1417 }
1418 "discretestatespace" => {
1419 let a = parse_matrix_rows(&get_str("a")?, name, "a", line_number)?;
1420 let b = parse_matrix_or_vector_shorthand(&get_str("b")?, name, "b", line_number, true)?;
1421 let c =
1422 parse_matrix_or_vector_shorthand(&get_str("c")?, name, "c", line_number, false)?;
1423 let p = b.first().map_or(0, |row| row.len());
1424 let q = c.len();
1425 let d = match fields.get("d") {
1426 None => vec![vec![0.0; p]; q],
1427 Some(text) if text.trim().starts_with('[') => {
1428 parse_matrix_rows(text, name, "d", line_number)?
1429 }
1430 Some(text) => {
1431 if q != 1 || p != 1 {
1432 return Err(format!(
1433 "line {}: device '{name}' field 'd' is a bare scalar, but this \
1434 system has {q} output(s) and {p} input(s) -- declare \
1435 'd=[[...],...]' ({q}x{p}) for a MIMO system, a bare scalar is only \
1436 valid for a 1x1 (SISO) one",
1437 line_number + 1
1438 ));
1439 }
1440 let v: f64 = text.trim().parse().map_err(|_| {
1441 format!(
1442 "line {}: device '{name}' field 'd' is not a number",
1443 line_number + 1
1444 )
1445 })?;
1446 vec![vec![v]]
1447 }
1448 };
1449 let ss = StateSpace::new(a, b, c, d, None).map_err(|e| {
1450 format!(
1451 "line {}: device '{name}': invalid discrete statespace ({e:?})",
1452 line_number + 1
1453 )
1454 })?;
1455 let sample_time = parse_required_periodic_sample_time(&fields, name, line_number)?;
1456 let inputs = match fields.get("inputs") {
1457 Some(list) => list.split(',').map(parse_signal).collect(),
1458 None => vec![parse_signal(&get_str("in")?)],
1459 };
1460 Kind::Block(BlockInstance {
1461 name: name.to_string(),
1462 kind: BlockKind::DiscreteStateSpace { ss, sample_time },
1463 inputs,
1464 ic: None,
1465 })
1466 }
1467 "discretetf" => {
1468 let num = parse_vector(&get_str("num")?, name, "num", line_number)?;
1469 let den = parse_vector(&get_str("den")?, name, "den", line_number)?;
1470 let tf = TransferFunction::new(num, den).map_err(|e| {
1471 format!(
1472 "line {}: device '{name}': invalid discrete transfer function ({e:?})",
1473 line_number + 1
1474 )
1475 })?;
1476 let sample_time = parse_required_periodic_sample_time(&fields, name, line_number)?;
1477 Kind::Block(BlockInstance {
1478 name: name.to_string(),
1479 kind: BlockKind::DiscreteTransferFunction { tf, sample_time },
1480 inputs: vec![parse_signal(&get_str("in")?)],
1481 ic: None,
1482 })
1483 }
1484 "discretepid" => {
1485 let sample_time = parse_required_periodic_sample_time(&fields, name, line_number)?;
1486 let period = match sample_time {
1487 SampleTimeSpec::Periodic { period, .. } => period,
1488 SampleTimeSpec::Variable => {
1489 unreachable!("parse_required_periodic_sample_time already rejected ts=variable")
1490 }
1491 };
1492 let method_name = fields
1493 .get("integration_method")
1494 .map(String::as_str)
1495 .unwrap_or("forward");
1496 let method = DiscreteIntegrationMethod::from_name(method_name).ok_or_else(|| {
1497 format!(
1498 "line {}: device '{name}': unknown integration_method '{method_name}' \
1499 (expected 'forward', 'backward', or 'trapezoidal')",
1500 line_number + 1
1501 )
1502 })?;
1503 let pid = DiscretePid {
1504 kp: get("kp")?,
1505 ki: get("ki")?,
1506 kd: get("kd")?,
1507 n: get("n")?,
1508 period,
1509 method,
1510 };
1511 let error_input = parse_signal(&get_str("in")?);
1512 let (clamp, inputs) = match (fields.get("clamp_lo_in"), fields.get("clamp_hi_in")) {
1513 (Some(lo), Some(hi)) => (
1514 PidClamp::Dynamic,
1515 vec![error_input, parse_signal(lo), parse_signal(hi)],
1516 ),
1517 (None, None) => (
1518 PidClamp::Fixed(get("clamp_lo")?, get("clamp_hi")?),
1519 vec![error_input],
1520 ),
1521 _ => {
1522 return Err(format!(
1523 "line {}: device '{name}': 'clamp_lo_in'/'clamp_hi_in' must both be \
1524 given together (dynamic clamp) or both omitted (fixed clamp= \
1525 clamp_lo/clamp_hi)",
1526 line_number + 1
1527 ))
1528 }
1529 };
1530 Kind::Block(BlockInstance {
1531 name: name.to_string(),
1532 kind: BlockKind::DiscretePid {
1533 pid,
1534 clamp,
1535 sample_time,
1536 },
1537 inputs,
1538 ic: None,
1539 })
1540 }
1541 "product" => Kind::Block(BlockInstance {
1542 name: name.to_string(),
1543 kind: BlockKind::Product,
1544 inputs: get_str("inputs")?.split(',').map(parse_signal).collect(),
1545 ic: None,
1546 }),
1547 "saturation" => Kind::Block(BlockInstance {
1548 name: name.to_string(),
1549 kind: BlockKind::Saturation(get("limit")?),
1550 inputs: vec![parse_signal(&get_str("in")?)],
1551 ic: None,
1552 }),
1553 "table" => {
1554 let points = parse_xy_points(&get_str("points")?, name, "points", line_number)?;
1555 Kind::Block(BlockInstance {
1556 name: name.to_string(),
1557 kind: BlockKind::Table(points),
1558 inputs: vec![parse_signal(&get_str("in")?)],
1559 ic: None,
1560 })
1561 }
1562 "phys2sig" => {
1563 let target = match (fields.get("node"), fields.get("branch")) {
1564 (Some(node), None) => Phys2SigTarget::Voltage(node.clone()),
1565 (None, Some(branch)) => Phys2SigTarget::Current(branch.clone()),
1566 (Some(_), Some(_)) => {
1567 return Err(format!(
1568 "line {}: device '{name}': 'node' and 'branch' are mutually \
1569 exclusive (a phys2sig reads either a node voltage or a branch \
1570 current, never both)",
1571 line_number + 1
1572 ))
1573 }
1574 (None, None) => {
1575 return Err(format!(
1576 "line {}: device '{name}' kind='phys2sig' needs 'node=<name>' (reads \
1577 V(node)) or 'branch=<name>' (reads I(branch))",
1578 line_number + 1
1579 ))
1580 }
1581 };
1582 Kind::Block(BlockInstance {
1583 name: name.to_string(),
1584 kind: BlockKind::Phys2Sig(target),
1585 inputs: Vec::new(),
1586 ic: None,
1587 })
1588 }
1589 "sig2phys" => {
1590 let domain = match get_str("domain")?.as_str() {
1591 "voltage" => PhysicalDomain::Voltage,
1592 "current" => PhysicalDomain::Current,
1593 other => {
1594 return Err(format!(
1595 "line {}: device '{name}' field 'domain' must be 'voltage' or \
1596 'current' (got '{other}')",
1597 line_number + 1
1598 ))
1599 }
1600 };
1601 Kind::Block(BlockInstance {
1602 name: name.to_string(),
1603 kind: BlockKind::Sig2Phys { domain },
1604 inputs: vec![parse_signal(&get_str("in")?)],
1605 ic: None,
1606 })
1607 }
1608 "clarke" | "clarkeinv" | "park" | "parkinv" | "clarkepark" | "clarkeparkinv" => {
1609 let ct = match kind {
1610 "clarke" => CoordinateTransform::Clarke,
1611 "clarkeinv" => CoordinateTransform::ClarkeInv,
1612 "park" => CoordinateTransform::Park,
1613 "parkinv" => CoordinateTransform::ParkInv,
1614 "clarkepark" => CoordinateTransform::ClarkePark,
1615 "clarkeparkinv" => CoordinateTransform::ClarkeParkInv,
1616 _ => unreachable!("matched above"),
1617 };
1618 let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
1619 if inputs.len() != ct.input_count() {
1620 return Err(format!(
1621 "line {}: device '{name}' kind='{kind}' needs {} inputs (got {})",
1622 line_number + 1,
1623 ct.input_count(),
1624 inputs.len()
1625 ));
1626 }
1627 let output_names = match fields.get("outputs") {
1628 Some(names) => {
1629 let names: Vec<String> = names.split(',').map(str::to_string).collect();
1630 if names.len() != 3 {
1631 return Err(format!(
1632 "line {}: device '{name}': 'outputs' needs exactly 3 entries \
1633 (got {})",
1634 line_number + 1,
1635 names.len()
1636 ));
1637 }
1638 names
1639 }
1640 None => {
1644 let suffixes = ct.output_names();
1645 std::iter::once(name.to_string())
1646 .chain(suffixes[1..].iter().map(|s| format!("{name}_{s}")))
1647 .collect()
1648 }
1649 };
1650 Kind::Block(BlockInstance {
1651 name: name.to_string(),
1652 kind: BlockKind::CoordinateTransform {
1653 kind: ct,
1654 output_names,
1655 },
1656 inputs,
1657 ic: None,
1658 })
1659 }
1660 "pmsm" => {
1661 let pmsm = continuous_blocks::Pmsm::new(
1662 get("r_s")?,
1663 get("l_d")?,
1664 get("l_q")?,
1665 get("lambda_pm")?,
1666 get("pole_pairs")?,
1667 get("inertia")?,
1668 get("friction")?,
1669 )
1670 .map_err(|e| {
1671 format!(
1672 "line {}: device '{name}': invalid pmsm ({e:?})",
1673 line_number + 1
1674 )
1675 })?;
1676 let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
1677 if inputs.len() != 3 {
1678 return Err(format!(
1679 "line {}: device '{name}' kind='pmsm' needs 3 inputs (vd,vq,t_load; \
1680 got {})",
1681 line_number + 1,
1682 inputs.len()
1683 ));
1684 }
1685 let output_names = match fields.get("outputs") {
1686 Some(names) => {
1687 let names: Vec<String> = names.split(',').map(str::to_string).collect();
1688 if names.len() != 4 {
1689 return Err(format!(
1690 "line {}: device '{name}': 'outputs' needs exactly 4 entries \
1691 (got {})",
1692 line_number + 1,
1693 names.len()
1694 ));
1695 }
1696 names
1697 }
1698 None => {
1702 let suffixes = ["id", "iq", "omega_m", "theta_e"];
1703 std::iter::once(name.to_string())
1704 .chain(suffixes[1..].iter().map(|s| format!("{name}_{s}")))
1705 .collect()
1706 }
1707 };
1708 Kind::Block(BlockInstance {
1709 name: name.to_string(),
1710 kind: BlockKind::Pmsm { pmsm, output_names },
1711 inputs,
1712 ic: None,
1713 })
1714 }
1715 other => {
1716 if let Some(f) = continuous_blocks::MathFn1::from_name(other) {
1720 Kind::Block(BlockInstance {
1721 name: name.to_string(),
1722 kind: BlockKind::MathFn1(f),
1723 inputs: vec![parse_signal(&get_str("in")?)],
1724 ic: None,
1725 })
1726 } else if let Some(f) = continuous_blocks::MathFn2::from_name(other) {
1727 Kind::Block(BlockInstance {
1728 name: name.to_string(),
1729 kind: BlockKind::MathFn2(f),
1730 inputs: vec![
1731 parse_signal(&get_str("in1")?),
1732 parse_signal(&get_str("in2")?),
1733 ],
1734 ic: None,
1735 })
1736 } else if let Some(f) = continuous_blocks::MathFn3::from_name(other) {
1737 Kind::Block(BlockInstance {
1738 name: name.to_string(),
1739 kind: BlockKind::MathFn3(f),
1740 inputs: vec![
1741 parse_signal(&get_str("in1")?),
1742 parse_signal(&get_str("in2")?),
1743 parse_signal(&get_str("in3")?),
1744 ],
1745 ic: None,
1746 })
1747 } else if let Some(op) = LogicOp::from_name(other) {
1748 let inputs = if op.is_unary() {
1749 vec![parse_signal(&get_str("in")?)]
1750 } else {
1751 let list = get_str("inputs")?;
1752 let parsed: Vec<Signal> = list.split(',').map(parse_signal).collect();
1753 if parsed.len() < 2 {
1754 return Err(format!(
1755 "line {}: device '{name}': kind={other} needs at least 2 \
1756 comma-separated inputs= entries (got {})",
1757 line_number + 1,
1758 parsed.len()
1759 ));
1760 }
1761 parsed
1762 };
1763 Kind::Block(BlockInstance {
1764 name: name.to_string(),
1765 kind: BlockKind::LogicGate(op),
1766 inputs,
1767 ic: None,
1768 })
1769 } else if let Some(kind) = FlipFlopKind::from_name(other) {
1770 let mut inputs = vec![parse_signal(&get_str("clk")?)];
1771 match kind {
1772 FlipFlopKind::D => inputs.push(parse_signal(&get_str("d")?)),
1773 FlipFlopKind::T => inputs.push(parse_signal(&get_str("t")?)),
1774 FlipFlopKind::Jk => {
1775 inputs.push(parse_signal(&get_str("j")?));
1776 inputs.push(parse_signal(&get_str("k")?));
1777 }
1778 }
1779 let reset = fields.contains_key("reset");
1780 if reset {
1781 inputs.push(parse_signal(&get_str("reset")?));
1782 }
1783 Kind::Block(BlockInstance {
1784 name: name.to_string(),
1785 kind: BlockKind::FlipFlop { kind, reset },
1786 inputs,
1787 ic: None,
1788 })
1789 } else {
1790 return Err(format!(
1791 "line {}: unknown device kind '{other}'",
1792 line_number + 1
1793 ));
1794 }
1795 }
1796 };
1797
1798 let entry = match entry {
1799 Kind::Block(mut block) => {
1800 block.ic = parse_block_initial_condition(&block.kind, &fields, name, line_number)?;
1801 Kind::Block(block)
1802 }
1803 other => other,
1804 };
1805
1806 if let Some((stray, accepted)) = fields.unread() {
1813 return Err(format!(
1814 "line {}: device '{name}' unknown field '{stray}' (kind={kind} accepts only: {})",
1815 line_number + 1,
1816 accepted.join(", ")
1817 ));
1818 }
1819 Ok(entry)
1820}
1821
1822fn parse_block_initial_condition(
1832 kind: &BlockKind,
1833 fields: &Fields,
1834 name: &str,
1835 line_number: usize,
1836) -> Result<Option<Vec<f64>>, String> {
1837 let line = line_number + 1;
1838 let ic_text = fields.get("ic");
1839 let y0_text = fields.get("y0");
1840 let accepts_y0 = matches!(
1841 kind,
1842 BlockKind::TransferFunction(_) | BlockKind::DiscreteTransferFunction { .. }
1843 );
1844 if y0_text.is_some() && !accepts_y0 {
1845 return Err(format!(
1846 "line {line}: device '{name}' field 'y0' is only valid on kind=tf/kind=discretetf \
1847 (a settled output to start from) -- use 'ic' for this kind's initial condition"
1848 ));
1849 }
1850 if ic_text.is_some() && y0_text.is_some() {
1851 return Err(format!(
1852 "line {line}: device '{name}': 'ic' (the state vector) and 'y0' (the settled \
1853 output) both set an initial condition -- give one or the other"
1854 ));
1855 }
1856
1857 let finite = |values: Vec<f64>| -> Result<Vec<f64>, String> {
1858 match values.iter().find(|v| !v.is_finite()) {
1859 Some(v) => Err(format!(
1860 "line {line}: device '{name}' initial condition must be finite (got {v})"
1861 )),
1862 None => Ok(values),
1863 }
1864 };
1865 let state_vector = |text: &str, states: usize| -> Result<Vec<f64>, String> {
1867 let values = if text.trim().starts_with('[') {
1868 parse_vector(text, name, "ic", line_number)?
1869 } else {
1870 vec![text
1871 .trim()
1872 .parse::<f64>()
1873 .map_err(|_| format!("line {line}: device '{name}' field 'ic' is not a number"))?]
1874 };
1875 if values.len() != states {
1876 return Err(format!(
1877 "line {line}: device '{name}' field 'ic' has {} value(s), but this block has \
1878 {states} state(s)",
1879 values.len()
1880 ));
1881 }
1882 finite(values)
1883 };
1884 let scalar = |text: &str, key: &str| -> Result<f64, String> {
1885 let v = text
1886 .trim()
1887 .parse::<f64>()
1888 .map_err(|_| format!("line {line}: device '{name}' field '{key}' is not a number"))?;
1889 finite(vec![v]).map(|v| v[0])
1890 };
1891 let settled = |result: Result<Vec<f64>, SettledStateError>, key: &str, what: &str| {
1892 result.map_err(|e| match e {
1893 SettledStateError::NoStates => format!(
1894 "line {line}: device '{name}' field '{key}': this {what} has no state to \
1895 initialize (its denominator is a constant)"
1896 ),
1897 SettledStateError::ZeroDcNumerator => format!(
1898 "line {line}: device '{name}' field '{key}': this {what}'s numerator is zero \
1899 at DC, so its settled output is always 0 and no state holds the requested one"
1900 ),
1901 })
1902 };
1903
1904 let Some(ic_text) = ic_text else {
1905 return match (kind, y0_text) {
1906 (BlockKind::TransferFunction(tf), Some(y0)) => settled(
1907 tf.settled_state(scalar(y0, "y0")?),
1908 "y0",
1909 "transfer function",
1910 )
1911 .map(Some),
1912 (BlockKind::DiscreteTransferFunction { tf, .. }, Some(y0)) => settled(
1913 tf.settled_state_discrete(scalar(y0, "y0")?),
1914 "y0",
1915 "transfer function",
1916 )
1917 .map(Some),
1918 _ => Ok(None),
1919 };
1920 };
1921
1922 let ic = match kind {
1923 BlockKind::StateSpace(ss) | BlockKind::DiscreteStateSpace { ss, .. } => {
1924 state_vector(ic_text, ss.states())?
1925 }
1926 BlockKind::TransferFunction(tf) | BlockKind::DiscreteTransferFunction { tf, .. } => {
1927 state_vector(ic_text, tf.den.len() - 1)?
1928 }
1929 BlockKind::Pid { pid, .. } => {
1930 if pid.ki == 0.0 {
1931 return Err(format!(
1932 "line {line}: device '{name}' field 'ic' pre-loads the integrator, but this \
1933 PID has ki=0 -- there is no integrator to hold it"
1934 ));
1935 }
1936 settled(
1937 pid.to_transfer_function()
1938 .settled_state(scalar(ic_text, "ic")?),
1939 "ic",
1940 "PID",
1941 )?
1942 }
1943 BlockKind::DiscretePid { pid, .. } => {
1944 if pid.ki == 0.0 {
1945 return Err(format!(
1946 "line {line}: device '{name}' field 'ic' pre-loads the integrator, but this \
1947 PID has ki=0 -- there is no integrator to hold it"
1948 ));
1949 }
1950 vec![scalar(ic_text, "ic")? / pid.ki]
1951 }
1952 BlockKind::Vco(_) | BlockKind::PhaseShiftPwm { .. } => {
1953 let phase = scalar(ic_text, "ic")?;
1954 if !(0.0..1.0).contains(&phase) {
1955 return Err(format!(
1956 "line {line}: device '{name}' field 'ic' is the initial phase in cycles and \
1957 must satisfy 0 <= ic < 1 (got {phase})"
1958 ));
1959 }
1960 vec![phase]
1961 }
1962 BlockKind::Pmsm { .. } => state_vector(ic_text, 4)?,
1963 BlockKind::Hysteresis(_) | BlockKind::SrLatch { .. } | BlockKind::FlipFlop { .. } => {
1964 match ic_text.trim() {
1965 "0" => vec![0.0],
1966 "1" => vec![1.0],
1967 other => {
1968 return Err(format!(
1969 "line {line}: device '{name}' field 'ic' is the initial logic output \
1970 and must be 0 or 1 (got '{other}')"
1971 ))
1972 }
1973 }
1974 }
1975 BlockKind::Counter { modulus, .. } => {
1976 let count = ic_text.trim().parse::<i64>().map_err(|_| {
1977 format!("line {line}: device '{name}' field 'ic' is not an integer")
1978 })?;
1979 if let Some(m) = modulus {
1980 if count < 0 || count >= i64::from(*m) {
1981 return Err(format!(
1982 "line {line}: device '{name}' field 'ic' must satisfy 0 <= ic < \
1983 modulus ({m}) (got {count})"
1984 ));
1985 }
1986 }
1987 vec![count as f64]
1988 }
1989 _ => {
1990 return Err(format!(
1991 "line {line}: device '{name}' field 'ic': this kind has no state to \
1992 initialize -- 'ic' is accepted on statespace, tf, pid, discretestatespace, \
1993 discretetf, discretepid, vco, pspwm, pmsm, hysteresis, srlatch, the \
1994 flip-flops, and counter"
1995 ))
1996 }
1997 };
1998 Ok(Some(ic))
1999}