use std::collections::BTreeMap;
use std::fs;
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use dae_runtime::{GateState, OperatingPoint, SignalValue};
use general_mna::block_graph::GateBinding;
use general_spice_core::ast::{ElementInstance, Statement};
use general_spice_core::Dialect;
use gsim_rules::{
Action, Condition, EventRecord, PeriodBoundary, PeriodMeasure, Qualifiers, Rule, RuleSummary,
Sample, Severity, Watch,
};
#[derive(Debug, Clone, PartialEq)]
pub struct Port {
pub name: String,
pub positive: String,
pub negative: String,
pub branch: String,
pub negate: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchChannel {
pub positive: String,
pub negative: String,
pub r_on: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DiodeCurve {
pub positive: String,
pub negative: String,
pub v_f: f64,
pub g_on: f64,
pub g_off: f64,
pub v_breakdown: f64,
pub g_breakdown: f64,
}
impl DiodeCurve {
fn current_at(&self, v: f64) -> f64 {
if v < self.v_breakdown {
self.g_breakdown * (v - self.v_breakdown) + self.g_off * self.v_breakdown
} else if v < self.v_f {
self.g_off * v
} else {
self.g_off * self.v_f + self.g_on * (v - self.v_f)
}
}
}
#[derive(Debug)]
pub struct Extracted {
pub netlist: String,
pub rules: Vec<Rule>,
pub ports: BTreeMap<String, Port>,
pub switches: BTreeMap<String, SwitchChannel>,
pub diodes: BTreeMap<String, DiodeCurve>,
}
fn parse_port(name: &str, line: usize, fields: &BTreeMap<&str, &str>) -> Result<Port, String> {
let ctx = |msg: String| format!("line {line}: port '{name}': {msg}");
let pair = fields.get("v").copied().ok_or_else(|| {
ctx("missing field 'v' -- the node pair the voltage is across, v=(p,n)".into())
})?;
let inner = pair
.strip_prefix('(')
.and_then(|rest| rest.strip_suffix(')'))
.ok_or_else(|| {
ctx(format!(
"field 'v' must be a node pair like v=(out,0), not '{pair}'"
))
})?;
let (positive, negative) = inner.split_once(',').ok_or_else(|| {
ctx(format!(
"field 'v' needs two nodes separated by a comma, not '{pair}'"
))
})?;
if positive.trim().is_empty() || negative.trim().is_empty() {
return Err(ctx(format!("field 'v' has an empty node: '{pair}'")));
}
let branch = fields
.get("i")
.copied()
.ok_or_else(|| {
ctx(
"missing field 'i' -- the element whose branch current is this port's current \
(a V, L, E or H; put a zero-volt sense source in series to measure anywhere \
else)"
.into(),
)
})?
.trim()
.to_string();
let (negate, branch) = match branch.strip_prefix('-') {
Some(rest) => (true, rest.trim().to_string()),
None => (false, branch),
};
if branch.is_empty() {
return Err(ctx("field 'i' names no element".into()));
}
Ok(Port {
name: name.to_string(),
positive: positive.trim().to_string(),
negative: negative.trim().to_string(),
branch,
negate,
})
}
pub fn extract(source: &str, dialect: Dialect) -> Result<Extracted, String> {
let statements = general_mna::parse_and_flatten(source, dialect)?;
let mut rules = Vec::new();
let mut ports: BTreeMap<String, Port> = BTreeMap::new();
let mut switch_nodes: BTreeMap<String, (String, String)> = BTreeMap::new();
let mut switch_r_on: BTreeMap<String, f64> = BTreeMap::new();
let mut diode_curves: BTreeMap<String, (f64, f64, f64, f64, f64)> = BTreeMap::new();
let mut pending: Vec<(String, usize, BTreeMap<&str, &str>)> = Vec::new();
let mut blank_lines: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
let mut cut_tokens: BTreeMap<usize, Vec<String>> = BTreeMap::new();
for stmt in &statements {
if let Statement::ElementInstance(element) = stmt {
if let [positive, negative] = element.nodes.as_slice() {
switch_nodes.insert(element.name.clone(), (positive.clone(), negative.clone()));
}
let (element_rules, cuts) = ratings_of(element)?;
rules.extend(element_rules);
for token in cuts {
for line in element.span.clone() {
let already = cut_tokens.entry(line).or_default();
let text = source.lines().nth(line - 1).unwrap_or("");
if contains_token(text, &token) && !already.contains(&token) {
already.push(token.clone());
break;
}
}
}
continue;
}
let Statement::BlockInstance(bi) = stmt else {
continue;
};
let fields: BTreeMap<&str, &str> = bi
.fields
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
match fields.get("kind").copied() {
Some("port") => {
let port = parse_port(&bi.name, bi.span.start, &fields)?;
if let Some(first) = ports.insert(port.name.clone(), port) {
return Err(format!(
"line {}: port '{}' is declared twice -- two ports of one name would make a rule naming it ambiguous",
bi.span.start, first.name
));
}
}
Some("rule") => pending.push((bi.name.clone(), bi.span.start, fields)),
Some("ideal_switch") => {
if let Some(r_on) = fields.get("r_on").and_then(|raw| parse_number(raw)) {
switch_r_on.insert(bi.name.clone(), r_on);
}
continue;
}
Some("ideal_diode") => {
let number = |key: &str| fields.get(key).and_then(|raw| parse_number(raw));
if let (Some(v_f), Some(g_on), Some(g_off), Some(v_bd), Some(g_bd)) = (
number("v_f"),
number("g_on"),
number("g_off"),
number("v_breakdown"),
number("g_breakdown"),
) {
diode_curves.insert(bi.name.clone(), (v_f, g_on, g_off, v_bd, g_bd));
}
continue;
}
_ => continue,
}
for line in bi.span.clone() {
blank_lines.insert(line);
}
}
let switches: BTreeMap<String, SwitchChannel> = switch_r_on
.into_iter()
.filter_map(|(name, r_on)| {
let (positive, negative) = switch_nodes.get(&name)?.clone();
Some((
name,
SwitchChannel {
positive,
negative,
r_on,
},
))
})
.collect();
let diodes: BTreeMap<String, DiodeCurve> = diode_curves
.into_iter()
.filter_map(|(name, (v_f, g_on, g_off, v_breakdown, g_breakdown))| {
let (positive, negative) = switch_nodes.get(&name)?.clone();
Some((
name,
DiodeCurve {
positive,
negative,
v_f,
g_on,
g_off,
v_breakdown,
g_breakdown,
},
))
})
.collect();
for (name, line, fields) in &pending {
rules.push(parse_rule(name, *line, fields, &switches, &diodes)?);
}
if blank_lines.is_empty() && cut_tokens.is_empty() {
return Ok(Extracted {
netlist: source.to_string(),
rules,
ports,
switches,
diodes,
});
}
let mut out = String::with_capacity(source.len());
for (i, line) in source.lines().enumerate() {
let number = i + 1;
if !blank_lines.contains(&number) {
match cut_tokens.get(&number) {
None => out.push_str(line),
Some(tokens) => out.push_str(&without_tokens(line, tokens)),
}
}
out.push('\n');
}
Ok(Extracted {
netlist: out,
rules,
ports,
switches,
diodes,
})
}
fn contains_token(line: &str, token: &str) -> bool {
line.split_whitespace().any(|found| found == token)
}
fn without_tokens(line: &str, tokens: &[String]) -> String {
let mut remaining: Vec<&String> = tokens.iter().collect();
let kept: Vec<&str> = line
.split_whitespace()
.filter(|found| {
if let Some(index) = remaining.iter().position(|token| token.as_str() == *found) {
remaining.remove(index);
return false;
}
true
})
.collect();
let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
format!("{indent}{}", kept.join(" "))
}
pub const RATING_FIELDS: &[&str] = &[
"i_max",
"i_sat",
"v_max",
"on_violation",
"severity",
"hold",
];
fn ratings_of(element: &ElementInstance) -> Result<(Vec<Rule>, Vec<String>), String> {
let line = element.span.start;
let name = &element.name;
let ctx = |msg: String| format!("line {line}: device '{name}': {msg}");
let mut written: Vec<(String, String, String)> = Vec::new();
for token in &element.raw_params {
let Some((key, value)) = token.split_once('=') else {
continue;
};
let key = key.trim().to_ascii_lowercase();
if RATING_FIELDS.contains(&key.as_str()) {
written.push((key, value.to_string(), token.clone()));
}
}
if written.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
if written
.iter()
.all(|(key, _, _)| matches!(key.as_str(), "on_violation" | "severity" | "hold"))
{
let names: Vec<&str> = written.iter().map(|(key, _, _)| key.as_str()).collect();
return Err(ctx(format!(
"'{}' modifies a rating, and this device declares none -- add one of \
i_max, i_sat or v_max, or remove the field",
names.join("', '")
)));
}
let cuts: Vec<String> = written.iter().map(|(_, _, token)| token.clone()).collect();
let field = |wanted: &str| -> Option<&str> {
written
.iter()
.find(|(key, _, _)| key == wanted)
.map(|(_, value, _)| value.as_str())
};
let severity = match field("severity").unwrap_or("error") {
"info" => Severity::Info,
"warning" => Severity::Warning,
"error" => Severity::Error,
"fatal" => Severity::Fatal,
other => {
return Err(ctx(format!(
"unknown severity '{other}' -- one of info, warning, error, fatal"
)))
}
};
let default_action = if severity >= Severity::Error {
"console"
} else {
"log"
};
let action = match field("on_violation").unwrap_or(default_action) {
"log" => Action::Log,
"console" => Action::Console,
"stop" => Action::Stop,
"pause" => Action::Pause,
other => {
return Err(ctx(format!(
"unknown on_violation '{other}' -- one of log, console, stop, pause"
)))
}
};
let hold = match field("hold") {
None => None,
Some(raw) => {
Some(parse_number(raw).ok_or_else(|| ctx(format!("'hold' is not a number: '{raw}'")))?)
}
};
let qualifiers = |min_duration: Option<f64>| Qualifiers {
min_duration,
hysteresis: None,
after: None,
before: None,
max_events: None,
stop_after: None,
};
let mut rules = Vec::new();
for (key, raw, _) in &written {
let limit = match key.as_str() {
"on_violation" | "severity" | "hold" => continue,
_ => {
parse_number(raw).ok_or_else(|| ctx(format!("'{key}' is not a number: '{raw}'")))?
}
};
if limit <= 0.0 {
return Err(ctx(format!(
"'{key}' must be greater than zero, not '{raw}' -- it is a limit on magnitude"
)));
}
let (quantity, unit) = match key.as_str() {
"i_max" | "i_sat" => (branch_current(element).map_err(ctx)?, " A"),
"v_max" => (element_voltage(element).map_err(ctx)?, " V"),
_ => unreachable!("key came from RATING_FIELDS"),
};
rules.push(Rule {
name: key.clone(),
target: name.clone(),
watch: Watch::Quantity { quantity },
unit: unit.to_string(),
condition: Condition::Outside {
low: -limit,
high: limit,
},
qualifiers: qualifiers(hold),
severity,
action,
});
}
Ok((rules, cuts))
}
fn branch_current(element: &ElementInstance) -> Result<String, String> {
match element.device_letter {
'V' | 'L' | 'E' | 'H' => Ok(format!("I({})", element.name)),
letter => Err(format!(
"a current rating needs a branch current, and device {letter} does not have one \
(only V, L, E and H do -- a resistor's or a switch's current is computed from the \
solution, not solved for). Write a `kind=rule` card naming a current you do have, \
or probe this one first."
)),
}
}
fn element_voltage(element: &ElementInstance) -> Result<String, String> {
match element.nodes.as_slice() {
[positive, negative] => Ok(format!("V({positive},{negative})")),
nodes => Err(format!(
"a voltage rating needs two terminals, and this device has {} \
(write a `kind=rule` card naming the voltage you mean)",
nodes.len()
)),
}
}
fn parse_boundary(
fields: &BTreeMap<&str, &str>,
ctx: &impl Fn(String) -> String,
) -> Result<PeriodBoundary, String> {
let period = match fields.get("period").copied() {
None => None,
Some(raw) => Some(
parse_number(raw)
.ok_or_else(|| ctx(format!("field 'period' is not a number: '{raw}'")))?,
),
};
match (period, fields.get("sync").copied()) {
(Some(_), Some(_)) => Err(ctx(
"'period' and 'sync' both given -- a period is either stated or taken from a \
switch, not both"
.into(),
)),
(None, None) => Err(ctx(
"needs 'period=<seconds>' or 'sync=<switch>' to know what one period is".into(),
)),
(Some(period), None) => {
if period <= 0.0 {
return Err(ctx(format!(
"'period' must be greater than zero, not '{period}'"
)));
}
Ok(PeriodBoundary::Fixed(period))
}
(None, Some(switch)) => Ok(PeriodBoundary::Sync(switch.to_string())),
}
}
fn parse_rule(
name: &str,
line: usize,
fields: &BTreeMap<&str, &str>,
switches: &BTreeMap<String, SwitchChannel>,
diodes: &BTreeMap<String, DiodeCurve>,
) -> Result<Rule, String> {
let ctx = |msg: String| format!("line {line}: rule '{name}': {msg}");
let rule_type = fields
.get("type")
.copied()
.ok_or_else(|| ctx("missing field 'type'".into()))?;
let severity = match fields.get("severity").copied().unwrap_or("warning") {
"info" => Severity::Info,
"warning" => Severity::Warning,
"error" => Severity::Error,
"fatal" => Severity::Fatal,
other => {
return Err(ctx(format!(
"unknown severity '{other}' -- one of info, warning, error, fatal"
)))
}
};
let default_action = if severity >= Severity::Error {
"console"
} else {
"log"
};
let action = match fields.get("action").copied().unwrap_or(default_action) {
"log" => Action::Log,
"console" => Action::Console,
"stop" => Action::Stop,
"pause" => Action::Pause,
other => {
return Err(ctx(format!(
"unknown action '{other}' -- one of log, console, stop, pause"
)))
}
};
let number = |key: &str| -> Result<f64, String> {
let raw = fields
.get(key)
.copied()
.ok_or_else(|| ctx(format!("missing field '{key}'")))?;
parse_number(raw).ok_or_else(|| ctx(format!("field '{key}' is not a number: '{raw}'")))
};
let number_opt = |key: &str| -> Result<Option<f64>, String> {
match fields.get(key).copied() {
None => Ok(None),
Some(raw) => Some(
parse_number(raw)
.ok_or_else(|| ctx(format!("field '{key}' is not a number: '{raw}'"))),
)
.transpose(),
}
};
let list = |key: &str| -> Result<Vec<String>, String> {
let raw = fields
.get(key)
.copied()
.ok_or_else(|| ctx(format!("missing field '{key}'")))?;
let items: Vec<String> = raw
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
if items.is_empty() {
return Err(ctx(format!("field '{key}' lists nothing")));
}
Ok(items)
};
let (watch, condition, target, unit) = match rule_type {
"above" | "below" | "outside" | "inside" => {
let quantity = fields
.get("target")
.copied()
.ok_or_else(|| ctx("missing field 'target'".into()))?
.to_string();
for (gone, replacement) in [
("limit", if rule_type == "below" { "min" } else { "max" }),
("low", "min"),
("high", "max"),
] {
if fields.contains_key(gone) {
return Err(ctx(format!(
"field '{gone}' no longer exists -- write '{replacement}'. Every bound \
on a rule's own target is 'min' or 'max', on every rule type"
)));
}
}
let condition = match rule_type {
"above" => Condition::Above {
limit: number("max")?,
},
"below" => Condition::Below {
limit: number("min")?,
},
"outside" => Condition::Outside {
low: number("min")?,
high: number("max")?,
},
_ => Condition::Inside {
low: number("min")?,
high: number("max")?,
},
};
let unit = fields.get("unit").copied().unwrap_or("").to_string();
(
Watch::Quantity {
quantity: quantity.clone(),
},
condition,
quantity,
unit,
)
}
"forbidden_state" => {
let switches = list("switches")?;
let max_on = match number_opt("max_on")? {
Some(v) => v as usize,
None => 1,
};
let target = fields
.get("name")
.copied()
.map(str::to_string)
.unwrap_or_else(|| switches.join("+"));
(
Watch::ForbiddenState {
switches,
max_on,
min_deadtime: number_opt("min_deadtime")?,
},
Condition::Above {
limit: max_on as f64,
},
target,
" conducting".to_string(),
)
}
"required_path" => {
let switches = list("switches")?;
let current = fields
.get("current")
.copied()
.ok_or_else(|| ctx("missing field 'current'".into()))?
.to_string();
let i_min = number_opt("i_min")?.unwrap_or(0.0);
let target = fields
.get("name")
.copied()
.map(str::to_string)
.unwrap_or_else(|| switches.join("+"));
(
Watch::RequiredPath {
switches,
current,
i_min,
},
Condition::Above { limit: i_min },
target,
fields.get("unit").copied().unwrap_or(" A").to_string(),
)
}
"switch_timing" => {
let switches = list("switches")?;
let target = fields
.get("name")
.copied()
.map(str::to_string)
.unwrap_or_else(|| switches.join("+"));
let require_commutation = match fields.get("require_commutation").copied() {
None | Some("yes") | Some("true") | Some("1") => true,
Some("no") | Some("false") | Some("0") => false,
Some(other) => {
return Err(ctx(format!(
"require_commutation must be yes or no, not '{other}'"
)))
}
};
let watch = Watch::SwitchTiming {
switches,
min_on: number_opt("min_on")?,
min_off: number_opt("min_off")?,
f_min: number_opt("f_min")?,
f_max: number_opt("f_max")?,
require_commutation,
};
(
watch,
Condition::Above { limit: 0.0 },
target,
String::new(),
)
}
"rate_of_change" => {
let quantity = fields
.get("target")
.copied()
.ok_or_else(|| ctx("missing field 'target'".into()))?
.to_string();
let max_slope = number("max_slope")?;
if max_slope <= 0.0 {
return Err(ctx(format!(
"'max_slope' must be greater than zero, not '{max_slope}' -- it bounds a \
magnitude"
)));
}
(
Watch::RateOfChange {
quantity: quantity.clone(),
max_slope,
},
Condition::Above { limit: max_slope },
quantity,
fields
.get("unit")
.copied()
.map(str::to_string)
.unwrap_or_else(|| " /s".to_string()),
)
}
"body_diode" => {
let switches = list("switches")?;
let currents = list("currents")?;
if currents.len() != switches.len() {
return Err(ctx(format!(
"'currents' lists {} name(s) for {} switch(es) -- a switch's own current \
is not an MNA unknown, so each one has to be named",
currents.len(),
switches.len()
)));
}
let i_min = number("i_min")?;
let target = fields
.get("name")
.copied()
.map(str::to_string)
.unwrap_or_else(|| switches.join("+"));
(
Watch::BodyDiode {
switches,
i_min,
currents,
},
Condition::Above { limit: i_min },
target,
" A".to_string(),
)
}
"per_period" => {
let quantity = fields
.get("target")
.copied()
.ok_or_else(|| ctx("missing field 'target'".into()))?
.to_string();
let measure = match fields.get("measure").copied() {
Some("rms") => PeriodMeasure::Rms,
Some("mean") => PeriodMeasure::Mean,
Some("abs_mean") => PeriodMeasure::AbsMean,
Some("integral") => PeriodMeasure::Integral,
None => return Err(ctx("missing field 'measure'".into())),
Some(other) => {
return Err(ctx(format!(
"unknown measure '{other}' -- one of rms, mean, abs_mean, integral"
)))
}
};
let boundary = parse_boundary(fields, &ctx)?;
let (min, max) = (number_opt("min")?, number_opt("max")?);
if min.is_none() && max.is_none() {
return Err(ctx(
"needs 'min' or 'max' -- a measure with no bound is a measurement, and \
`kind=measure` already makes those"
.into(),
));
}
(
Watch::PerPeriod {
quantity: quantity.clone(),
measure,
boundary,
min,
max,
},
Condition::Above {
limit: max.or(min).unwrap_or(0.0),
},
quantity,
fields.get("unit").copied().unwrap_or("").to_string(),
)
}
"efficiency" => {
let port = |key: &str| -> Result<String, String> {
Ok(fields
.get(key)
.copied()
.ok_or_else(|| {
ctx(format!(
"missing field '{key}' -- the name of a `kind=port` declaration"
))
})?
.to_string())
};
let numerator = port("out")?;
let denominator = port("in")?;
if numerator == denominator {
return Err(ctx(format!(
"'in' and 'out' are both '{numerator}' -- a port's efficiency against \
itself is 1 by construction"
)));
}
let boundary = parse_boundary(fields, &ctx)?;
let (min, max) = (number_opt("min")?, number_opt("max")?);
if min.is_none() && max.is_none() {
return Err(ctx(
"needs 'min' or 'max' -- 'max=1' is the one that says this is a converter \
rather than a source of energy"
.into(),
));
}
(
Watch::Efficiency {
numerator: numerator.clone(),
denominator: denominator.clone(),
boundary,
min,
max,
},
Condition::Above {
limit: max.or(min).unwrap_or(0.0),
},
format!("{numerator}/{denominator}"),
fields.get("unit").copied().unwrap_or("").to_string(),
)
}
"zvs" => {
let named = list("switches")?;
let mut voltages = Vec::with_capacity(named.len());
for switch in &named {
let channel = switches.get(switch).ok_or_else(|| {
ctx(format!(
"'{switch}' is not a declared `kind=ideal_switch` with two nodes, so \
there is no voltage across it to read at turn-on"
))
})?;
voltages.push(format!("V({},{})", channel.positive, channel.negative));
}
let v_max = number("v_max")?;
if v_max < 0.0 {
return Err(ctx(format!(
"'v_max' is a magnitude and cannot be negative, not '{v_max}'"
)));
}
let target = fields
.get("name")
.copied()
.map(str::to_string)
.unwrap_or_else(|| named.join(","));
(
Watch::Zvs {
switches: named,
voltages,
v_max,
},
Condition::Above { limit: v_max },
target,
fields.get("unit").copied().unwrap_or(" V").to_string(),
)
}
"loss_closure" => {
let port = |key: &str| -> Result<String, String> {
Ok(fields
.get(key)
.copied()
.ok_or_else(|| {
ctx(format!(
"missing field '{key}' -- the name of a `kind=port` declaration"
))
})?
.to_string())
};
let in_port = port("in")?;
let out_port = port("out")?;
let named = list("devices")?;
if named.is_empty() {
return Err(ctx(
"'devices' is empty -- with nothing modelled the whole deficit is \
unaccounted for, which is a true statement about no loss model rather \
than a check on one"
.into(),
));
}
let mut devices = Vec::with_capacity(named.len());
for device in &named {
if !switches.contains_key(device) && !diodes.contains_key(device) {
return Err(ctx(format!(
"'{device}' is not a declared `kind=ideal_switch` or `kind=ideal_diode`, \
so it has no conduction loss to account for"
)));
}
devices.push(format!("P_cond({device})"));
}
let boundary = parse_boundary(fields, &ctx)?;
let max = number("max")?;
if !(0.0..=1.0).contains(&max) {
return Err(ctx(format!(
"'max' is a fraction of the input power, so it belongs in 0..1, not '{max}'"
)));
}
(
Watch::LossClosure {
in_port: in_port.clone(),
out_port: out_port.clone(),
devices,
boundary,
max,
},
Condition::Above { limit: max },
format!("{out_port}/{in_port}"),
fields.get("unit").copied().unwrap_or("").to_string(),
)
}
"commutation_order" => {
let sequence = list("sequence")?;
if sequence.len() < 2 {
return Err(ctx(
"'sequence' needs at least two switches -- an order of one is not an order"
.into(),
));
}
let target = fields
.get("name")
.copied()
.map(str::to_string)
.unwrap_or_else(|| sequence.join("->"));
(
Watch::CommutationOrder { sequence },
Condition::Above { limit: 0.0 },
target,
String::new(),
)
}
other => {
return Err(ctx(format!(
"unknown rule type '{other}' -- one of above, below, outside, inside, \
forbidden_state, required_path, switch_timing, rate_of_change, body_diode, \
commutation_order, per_period, efficiency, zvs, loss_closure"
)))
}
};
Ok(Rule {
name: name.to_string(),
target,
watch,
unit,
condition,
qualifiers: Qualifiers {
min_duration: number_opt("hold")?,
hysteresis: number_opt("hyst")?,
after: number_opt("after")?,
before: number_opt("before")?,
max_events: number_opt("max_events")?.map(|v| v as usize),
stop_after: number_opt("stop_after")?.map(|v| v as usize),
},
severity,
action,
})
}
pub fn parse_number(raw: &str) -> Option<f64> {
let raw = raw.trim();
if let Ok(value) = raw.parse::<f64>() {
return Some(value);
}
const POWERS: &[(&str, i32)] = &[
("meg", 6),
("t", 12),
("g", 9),
("k", 3),
("m", -3),
("u", -6),
("n", -9),
("p", -12),
("f", -15),
];
let lowered = raw.to_ascii_lowercase();
if let Some(head) = lowered.strip_suffix("mil") {
if let Ok(value) = head.parse::<f64>() {
return Some(value * 25.4e-6);
}
}
for (suffix, exponent) in POWERS {
if let Some(head) = lowered.strip_suffix(suffix) {
if head.parse::<f64>().is_ok() {
if let Ok(value) = format!("{head}e{exponent}").parse::<f64>() {
return Some(value);
}
}
}
}
None
}
pub struct StepSample<'a> {
pub point: &'a OperatingPoint,
pub outputs: &'a BTreeMap<String, SignalValue>,
pub gates: &'a BTreeMap<String, GateState>,
pub ports: &'a BTreeMap<String, Port>,
pub switches: &'a BTreeMap<String, SwitchChannel>,
pub diodes: &'a BTreeMap<String, DiodeCurve>,
}
impl Sample for StepSample<'_> {
fn get(&self, quantity: &str) -> Option<f64> {
if let Some(port) = self.ports.get(quantity) {
return self.port_power(port);
}
if let Some(switch) = quantity
.strip_prefix("P_cond(")
.and_then(|rest| rest.strip_suffix(')'))
{
return self.conduction_power(switch.trim());
}
if let Some(value) = self.point.value(quantity) {
return Some(value);
}
if let Some(SignalValue::Scalar(v)) = self.outputs.get(quantity) {
return Some(*v);
}
if let Some(pair) = quantity
.strip_prefix("V(")
.or_else(|| quantity.strip_prefix("v("))
.and_then(|rest| rest.strip_suffix(')'))
{
if let Some((positive, negative)) = pair.split_once(',') {
let node = |name: &str| -> Option<f64> {
let name = name.trim();
if name == "0" {
return Some(0.0);
}
self.point.value(&format!("V({name})"))
};
return Some(node(positive)? - node(negative)?);
}
}
let (name, index) = quantity.strip_suffix(']')?.split_once('[')?;
let index: usize = index.parse().ok()?;
match self.outputs.get(name) {
Some(SignalValue::Vector(v)) => v.get(index).copied(),
_ => None,
}
}
fn switch_on(&self, switch: &str) -> Option<bool> {
self.gates.get(switch).map(|state| *state == GateState::On)
}
fn body_diode_on(&self, switch: &str) -> Option<bool> {
let position = self.point.diode_names.iter().position(|n| n == switch)?;
let (breakdown, forward) = self.point.diode_z.get(position)?;
Some(*breakdown > 0.0 || *forward > 0.0)
}
}
impl StepSample<'_> {
fn conduction_power(&self, device: &str) -> Option<f64> {
let node = |name: &str| -> Option<f64> {
if name == "0" {
return Some(0.0);
}
self.point.value(&format!("V({name})"))
};
if let Some(channel) = self.switches.get(device) {
if !self.switch_on(device)? {
return Some(0.0);
}
let across = node(&channel.positive)? - node(&channel.negative)?;
return Some(across * across / channel.r_on);
}
let curve = self.diodes.get(device)?;
let across = node(&curve.positive)? - node(&curve.negative)?;
Some(across * curve.current_at(across))
}
fn port_power(&self, port: &Port) -> Option<f64> {
let node = |name: &str| -> Option<f64> {
if name == "0" {
return Some(0.0);
}
self.point.value(&format!("V({name})"))
};
let voltage = node(&port.positive)? - node(&port.negative)?;
let current = self.point.value(&format!("I({})", port.branch))?;
Some(voltage * if port.negate { -current } else { current })
}
}
pub fn gate_states(
gates: &BTreeMap<String, GateBinding>,
outputs: &BTreeMap<String, SignalValue>,
) -> BTreeMap<String, GateState> {
gates
.iter()
.filter(|(_, binding)| {
binding
.source_blocks()
.iter()
.flatten()
.all(|name| outputs.contains_key(*name))
})
.map(|(name, binding)| (name.clone(), binding.resolve(outputs)))
.collect()
}
pub struct Reporter {
jsonl: Option<BufWriter<fs::File>>,
text: Option<BufWriter<fs::File>>,
console_at: Severity,
pub worst: Option<Severity>,
pub written: usize,
}
#[derive(Debug, Default, Clone)]
pub struct EventPaths {
pub jsonl: Option<PathBuf>,
pub text: Option<PathBuf>,
}
impl Reporter {
pub fn new(stem: &Path, console_at: Severity, paths: &EventPaths) -> Result<Reporter, String> {
let jsonl_path = paths
.jsonl
.clone()
.unwrap_or_else(|| stem.with_extension("events.jsonl"));
let text_path = paths
.text
.clone()
.unwrap_or_else(|| stem.with_extension("events.txt"));
let open = |path: &Path| -> Result<BufWriter<fs::File>, String> {
fs::File::create(path).map(BufWriter::new).map_err(|e| {
format!("creating the event log {}: {e}", path.display())
})
};
Ok(Reporter {
jsonl: Some(open(&jsonl_path)?),
text: Some(open(&text_path)?),
console_at,
worst: None,
written: 0,
})
}
pub fn record(&mut self, event: &EventRecord) -> Result<(), String> {
self.worst = Some(match self.worst {
Some(worst) => worst.max(event.severity),
None => event.severity,
});
self.written += 1;
if let Some(writer) = &mut self.jsonl {
writeln!(writer, "{}", event.to_json_line())
.map_err(|e| format!("writing the event log: {e}"))?;
}
let line = event.console_line();
if let Some(writer) = &mut self.text {
writeln!(writer, "{line}").map_err(|e| format!("writing the event log: {e}"))?;
}
if event.action != Action::Log || event.severity >= self.console_at {
eprintln!("{line}");
}
Ok(())
}
pub fn finish(&mut self, summaries: &[RuleSummary]) -> Result<(), String> {
let report = summary_report(summaries);
if let Some(writer) = &mut self.text {
writeln!(writer, "\n{report}").map_err(|e| format!("writing the event log: {e}"))?;
writer
.flush()
.map_err(|e| format!("writing the event log: {e}"))?;
}
if let Some(writer) = &mut self.jsonl {
for summary in summaries {
writeln!(writer, "{}", summary.to_json_line())
.map_err(|e| format!("writing the event log: {e}"))?;
}
writer
.flush()
.map_err(|e| format!("writing the event log: {e}"))?;
}
eprintln!("{report}");
Ok(())
}
}
pub fn summary_report(summaries: &[RuleSummary]) -> String {
if summaries.is_empty() {
return String::new();
}
let mut out = String::from("--- rules ---\n");
for summary in summaries {
out.push_str(&summary.line());
out.push('\n');
}
let violated = summaries
.iter()
.filter(|s| s.entries > 0 || s.instants > 0)
.count();
let blind = summaries
.iter()
.filter(|s| s.missing_samples > 0 && s.entries == 0 && s.instants == 0)
.count();
out.push_str(&format!(
"{} rule(s): {} violated, {} passed",
summaries.len(),
violated,
summaries.len() - violated - blind,
));
if blind > 0 {
out.push_str(&format!(", {blind} not evaluated"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn ratings(source: &str) -> (String, Vec<Rule>) {
let out = extract(source, Dialect::Ngspice).expect("the deck parses");
(out.netlist, out.rules)
}
fn declared_ports(source: &str) -> BTreeMap<String, Port> {
extract(source, Dialect::Ngspice)
.expect("the deck parses")
.ports
}
fn rating_error(source: &str) -> String {
extract(source, Dialect::Ngspice).expect_err("the deck should be rejected")
}
#[test]
fn a_rating_compiles_to_a_magnitude_rule_on_the_elements_own_current() {
let (_, rules) = ratings("V1 a 0 10\nL1 a 0 36u i_max=60\n");
assert_eq!(rules.len(), 1);
let rule = &rules[0];
assert_eq!(rule.name, "i_max");
assert_eq!(rule.target, "L1");
assert_eq!(rule.unit, " A");
assert_eq!(
rule.watch,
Watch::Quantity {
quantity: "I(L1)".to_string()
}
);
assert_eq!(
rule.condition,
Condition::Outside {
low: -60.0,
high: 60.0
}
);
assert!(rule.condition.margin(-70.0) > 0.0, "a reverse overload");
assert!(rule.condition.margin(70.0) > 0.0, "a forward overload");
assert!(rule.condition.margin(59.0) <= 0.0, "within the rating");
}
#[test]
fn a_rating_defaults_to_error_where_a_card_defaults_to_warning() {
let (_, rules) = ratings("V1 a 0 10\nL1 a 0 36u i_max=60\n");
assert_eq!(rules[0].severity, Severity::Error);
assert_eq!(rules[0].action, Action::Console);
}
#[test]
fn a_voltage_rating_watches_the_difference_across_the_component() {
let (_, rules) = ratings("V1 a 0 10\nC1 a b 1u v_max=400\n");
assert_eq!(
rules[0].watch,
Watch::Quantity {
quantity: "V(a,b)".to_string()
}
);
assert_eq!(rules[0].unit, " V");
assert_eq!(rules[0].target, "C1");
}
#[test]
fn modifiers_apply_to_every_rating_on_the_line() {
let (_, rules) = ratings(
"V1 a 0 10\nL1 a 0 36u i_max=60 i_sat=70 on_violation=stop severity=warning hold=2u\n",
);
assert_eq!(rules.len(), 2, "i_max and i_sat, not the three modifiers");
for rule in &rules {
assert_eq!(rule.action, Action::Stop);
assert_eq!(rule.severity, Severity::Warning);
assert_eq!(rule.qualifiers.min_duration, Some(2e-6));
}
let names: Vec<&str> = rules.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, vec!["i_max", "i_sat"]);
}
#[test]
fn the_rating_leaves_the_device_line_otherwise_untouched() {
let (stripped, _) = ratings("V1 a 0 10\nL1 a 0 36u i_max=60 ic=2\n");
assert_eq!(stripped, "V1 a 0 10\nL1 a 0 36u ic=2\n");
}
#[test]
fn two_decks_differing_only_in_a_limit_strip_to_the_same_text() {
let (low, _) = ratings("V1 a 0 10\nL1 a 0 36u i_max=60\n");
let (high, _) = ratings("V1 a 0 10\nL1 a 0 36u i_max=4000\n");
assert_eq!(low, high);
}
#[test]
fn a_rating_on_a_continuation_line_is_cut_from_that_line() {
let (stripped, rules) = ratings("V1 a 0 10\nL1 a 0 36u\n+ i_max=60 ic=2\n");
assert_eq!(rules.len(), 1);
assert_eq!(stripped, "V1 a 0 10\nL1 a 0 36u\n+ ic=2\n");
}
#[test]
fn a_current_rating_needs_a_device_that_has_a_current() {
let error = rating_error("V1 a 0 10\nR1 a 0 50 i_max=2\n");
assert!(error.contains("device R does not have one"), "{error}");
assert!(error.contains("only V, L, E and H"), "{error}");
assert!(error.starts_with("line 2: device 'R1'"), "{error}");
}
#[test]
fn a_modifier_without_a_rating_is_refused() {
let error = rating_error("V1 a 0 10\nL1 a 0 36u on_violation=stop\n");
assert!(error.contains("modifies a rating"), "{error}");
}
#[test]
fn a_limit_of_zero_or_less_is_a_typo_not_a_rule() {
for raw in ["0", "-5"] {
let error = rating_error(&format!("V1 a 0 10\nL1 a 0 36u i_max={raw}\n"));
assert!(
error.contains("must be greater than zero"),
"{raw}: {error}"
);
}
}
#[test]
fn a_rating_that_is_not_a_number_says_so() {
let error = rating_error("V1 a 0 10\nL1 a 0 36u i_max=plenty\n");
assert!(error.contains("'i_max' is not a number"), "{error}");
}
#[test]
fn general_mna_accepts_every_rating_field_once_it_is_registered() {
let mut options = general_mna::BuildOptions::default();
for field in RATING_FIELDS {
options.annotate(field);
}
let deck = "V1 a 0 10\nL1 a 0 36u i_max=60 i_sat=70 v_max=400 \
on_violation=console severity=error hold=2u\n";
let system = general_mna::MnaBuilder::with_options(Dialect::Ngspice, options)
.build_fragment(deck)
.expect("general-mna must accept every field this crate claims");
let mut carried: Vec<&str> = system.annotations.iter().map(|a| a.key.as_str()).collect();
carried.sort_unstable();
let mut expected: Vec<&str> = RATING_FIELDS.to_vec();
expected.sort_unstable();
assert_eq!(
carried, expected,
"every claimed field must survive the build"
);
}
#[test]
fn a_deck_with_no_ratings_comes_back_unchanged() {
let source = "V1 a 0 10\nR1 a 0 50\n";
let (stripped, rules) = ratings(source);
assert_eq!(stripped, source);
assert!(rules.is_empty());
}
#[test]
fn numbers_follow_the_netlists_own_grammar() {
assert_eq!(parse_number("50"), Some(50.0));
assert_eq!(parse_number("1.5e3"), Some(1500.0));
assert_eq!(parse_number("200n").unwrap().to_bits(), 200e-9f64.to_bits());
assert_eq!(parse_number("200n"), Some(2e-7));
assert_eq!(parse_number("36u"), Some(36e-6));
assert_eq!(parse_number("20m"), Some(20e-3));
assert_eq!(parse_number("31.25k"), Some(31_250.0));
assert_eq!(parse_number("x"), None);
}
#[test]
fn meg_is_mega_and_m_is_milli() {
assert_eq!(parse_number("2MEG"), Some(2e6));
assert_eq!(parse_number("2meg"), Some(2e6));
assert_eq!(parse_number("2M"), Some(2e-3));
assert_eq!(parse_number("2m"), Some(2e-3));
}
#[test]
fn a_port_declaration_is_taken_out_of_the_netlist_and_parsed() {
let deck = "V1 in 0 10\nR1 in 0 5\nP_IN kind=port v=(in,0) i=-V1\n";
let ports = declared_ports(deck);
assert_eq!(ports.len(), 1);
let port = &ports["P_IN"];
assert_eq!(port.positive, "in");
assert_eq!(port.negative, "0");
assert_eq!(port.branch, "V1");
assert!(
port.negate,
"the leading minus is the whole sign convention"
);
let (netlist, _) = ratings(deck);
assert!(!netlist.contains("kind=port"), "{netlist}");
assert_eq!(netlist.lines().count(), deck.lines().count(), "{netlist}");
}
#[test]
fn a_port_on_a_sense_element_carries_no_minus() {
let ports = declared_ports(
"V1 in 0 10\nVSENSE out load 0\nR1 load 0 5\nP_OUT kind=port v=(out,0) i=VSENSE\n",
);
assert!(
!ports["P_OUT"].negate,
"a series sense element's current already flows into its positive terminal"
);
}
#[test]
fn a_port_missing_either_half_of_its_definition_is_refused() {
let no_current = rating_error("V1 in 0 10\nP kind=port v=(in,0)\n");
assert!(
no_current.contains("missing field 'i'") && no_current.contains("sense source"),
"{no_current}"
);
let no_voltage = rating_error("V1 in 0 10\nP kind=port i=V1\n");
assert!(
no_voltage.contains("missing field 'v'") && no_voltage.contains("v=(p,n)"),
"{no_voltage}"
);
}
#[test]
fn a_port_whose_node_pair_is_malformed_names_the_shape_it_wanted() {
for bad in ["v=in", "v=(in)", "v=(,0)", "v=(in,)"] {
let message = rating_error(&format!("V1 in 0 10\nP kind=port {bad} i=V1\n"));
assert!(
message.contains("field 'v'"),
"'{bad}' should be refused by name: {message}"
);
}
}
#[test]
fn two_ports_of_one_name_are_refused() {
let message = rating_error(
"V1 in 0 10\nR1 in 0 5\nP kind=port v=(in,0) i=V1\nP kind=port v=(in,0) i=-V1\n",
);
assert!(message.contains("declared twice"), "{message}");
}
#[test]
fn an_efficiency_card_compiles_to_a_ratio_of_two_ports() {
let (_, rules) = ratings(
"V1 in 0 10\nR1 in 0 5\n\
P_IN kind=port v=(in,0) i=-V1\n\
P_OUT kind=port v=(in,0) i=V1\n\
ETA kind=rule type=efficiency in=P_IN out=P_OUT max=1 period=1e-5\n",
);
assert_eq!(rules.len(), 1);
let rule = &rules[0];
assert_eq!(rule.target, "P_OUT/P_IN");
assert_eq!(
rule.watch,
Watch::Efficiency {
numerator: "P_OUT".to_string(),
denominator: "P_IN".to_string(),
boundary: PeriodBoundary::Fixed(1e-5),
min: None,
max: Some(1.0),
}
);
}
#[test]
fn an_efficiency_card_with_no_bound_is_refused_and_recommends_max_one() {
let message = rating_error(
"V1 in 0 10\nP_IN kind=port v=(in,0) i=-V1\nP_OUT kind=port v=(in,0) i=V1\n\
ETA kind=rule type=efficiency in=P_IN out=P_OUT period=1e-5\n",
);
assert!(
message.contains("needs 'min' or 'max'") && message.contains("max=1"),
"{message}"
);
}
#[test]
fn an_efficiency_of_a_port_against_itself_is_refused() {
let message = rating_error(
"V1 in 0 10\nP kind=port v=(in,0) i=-V1\n\
ETA kind=rule type=efficiency in=P out=P max=1 period=1e-5\n",
);
assert!(message.contains("against itself"), "{message}");
}
#[test]
fn an_efficiency_card_needs_exactly_one_period_boundary() {
let both = rating_error(
"V1 in 0 10\nP_IN kind=port v=(in,0) i=-V1\nP_OUT kind=port v=(in,0) i=V1\n\
ETA kind=rule type=efficiency in=P_IN out=P_OUT max=1 period=1e-5 sync=DSW\n",
);
assert!(both.contains("both given"), "{both}");
let neither = rating_error(
"V1 in 0 10\nP_IN kind=port v=(in,0) i=-V1\nP_OUT kind=port v=(in,0) i=V1\n\
ETA kind=rule type=efficiency in=P_IN out=P_OUT max=1\n",
);
assert!(neither.contains("what one period is"), "{neither}");
}
fn channels(source: &str) -> BTreeMap<String, SwitchChannel> {
extract(source, Dialect::Ngspice)
.expect("the deck parses")
.switches
}
const ONE_SWITCH: &str = "\
VIN in 0 12
DSW in mid idealswitchmodel
DSW kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=G
R1 mid 0 5
D kind=const value=1
G kind=sig2phys domain=voltage in=D
";
#[test]
fn a_switch_channel_is_assembled_from_the_two_lines_that_share_its_name() {
let channels = channels(ONE_SWITCH);
assert_eq!(channels.len(), 1);
let channel = &channels["DSW"];
assert_eq!(channel.positive, "in");
assert_eq!(channel.negative, "mid");
assert_eq!(channel.r_on, 0.02);
}
#[test]
fn the_ideal_switch_line_stays_in_the_netlist_after_extraction() {
let (netlist, _) = ratings(ONE_SWITCH);
assert!(
netlist.contains("kind=ideal_switch"),
"the solver still needs this line:\n{netlist}"
);
}
struct Fixture {
point: OperatingPoint,
outputs: BTreeMap<String, SignalValue>,
gates: BTreeMap<String, GateState>,
ports: BTreeMap<String, Port>,
switches: BTreeMap<String, SwitchChannel>,
diodes: BTreeMap<String, DiodeCurve>,
}
impl Fixture {
fn new(unknowns: &[&str], x: &[f64]) -> Fixture {
Fixture {
point: OperatingPoint {
unknowns: unknowns.iter().map(|s| s.to_string()).collect(),
x: x.to_vec(),
diode_names: Vec::new(),
diode_z: Vec::new(),
diode_raw_ioff: Vec::new(),
},
outputs: BTreeMap::new(),
gates: BTreeMap::new(),
ports: BTreeMap::new(),
switches: BTreeMap::new(),
diodes: BTreeMap::new(),
}
}
fn with_switch(mut self, name: &str, channel: SwitchChannel, state: GateState) -> Fixture {
self.switches.insert(name.to_string(), channel);
self.gates.insert(name.to_string(), state);
self
}
fn sample(&self) -> StepSample<'_> {
StepSample {
point: &self.point,
outputs: &self.outputs,
gates: &self.gates,
ports: &self.ports,
switches: &self.switches,
diodes: &self.diodes,
}
}
}
#[test]
fn a_commanded_on_switch_dissipates_the_square_of_its_drop_over_r_on() {
let fixture = Fixture::new(&["V(in)", "V(mid)"], &[12.0, 11.98]).with_switch(
"DSW",
SwitchChannel {
positive: "in".to_string(),
negative: "mid".to_string(),
r_on: 0.02,
},
GateState::On,
);
let power = fixture
.sample()
.get("P_cond(DSW)")
.expect("a commanded-on switch");
assert!(
(power - 0.02).abs() < 1e-12,
"(0.02 V)^2 / 0.02 ohm = 0.02 W, got {power}"
);
}
#[test]
fn a_commanded_off_switch_dissipates_exactly_zero_whatever_is_across_it() {
let fixture = Fixture::new(&["V(in)", "V(mid)"], &[12.0, 0.0]).with_switch(
"DSW",
SwitchChannel {
positive: "in".to_string(),
negative: "mid".to_string(),
r_on: 0.02,
},
GateState::Off,
);
assert_eq!(fixture.sample().get("P_cond(DSW)"), Some(0.0));
}
#[test]
fn an_undeclared_device_has_no_conduction_power_rather_than_zero() {
let fixture = Fixture::new(&["V(in)"], &[12.0]);
assert_eq!(fixture.sample().get("P_cond(NOPE)"), None);
}
#[test]
fn a_zvs_card_fills_in_each_switchs_voltage_from_its_declared_nodes() {
let (_, rules) = ratings(&format!(
"{ONE_SWITCH}ZVS kind=rule type=zvs switches=DSW v_max=5\n"
));
assert_eq!(rules.len(), 1);
assert_eq!(
rules[0].watch,
Watch::Zvs {
switches: vec!["DSW".to_string()],
voltages: vec!["V(in,mid)".to_string()],
v_max: 5.0,
}
);
assert_eq!(rules[0].unit, " V");
}
#[test]
fn a_zvs_card_naming_something_that_is_not_a_switch_is_refused_by_name() {
let message = rating_error(&format!(
"{ONE_SWITCH}ZVS kind=rule type=zvs switches=DSW,NOPE v_max=5\n"
));
assert!(
message.contains("'NOPE' is not a declared") && message.contains("turn-on"),
"{message}"
);
}
#[test]
fn a_zvs_card_can_be_written_above_the_switch_it_names() {
let (_, rules) = ratings(&format!(
"ZVS kind=rule type=zvs switches=DSW v_max=5\n{ONE_SWITCH}"
));
assert_eq!(rules.len(), 1);
assert!(matches!(rules[0].watch, Watch::Zvs { .. }));
}
#[test]
fn a_negative_v_max_is_refused_because_the_reading_is_a_magnitude() {
let message = rating_error(&format!(
"{ONE_SWITCH}ZVS kind=rule type=zvs switches=DSW v_max=-1\n"
));
assert!(message.contains("magnitude"), "{message}");
}
#[test]
fn every_bound_on_a_rules_own_target_is_min_or_max() {
let (_, rules) = ratings(
"V1 a 0 10\nL1 a 0 36u\n\
HI kind=rule type=above target=I(L1) max=3\n\
LO kind=rule type=below target=V(a) min=1\n\
BAND kind=rule type=outside target=V(a) min=9 max=11\n\
FORBID kind=rule type=inside target=V(a) min=4 max=6\n",
);
let by = |name: &str| {
rules
.iter()
.find(|r| r.name == name)
.unwrap_or_else(|| panic!("no rule {name}"))
};
assert_eq!(by("HI").condition, Condition::Above { limit: 3.0 });
assert_eq!(by("LO").condition, Condition::Below { limit: 1.0 });
assert_eq!(
by("BAND").condition,
Condition::Outside {
low: 9.0,
high: 11.0
}
);
assert_eq!(
by("FORBID").condition,
Condition::Inside {
low: 4.0,
high: 6.0
}
);
}
#[test]
fn the_old_bound_spellings_are_refused_with_the_right_end_named() {
for (card, gone, replacement) in [
(
"R kind=rule type=above target=I(L1) limit=3",
"limit",
"'max'",
),
(
"R kind=rule type=below target=I(L1) limit=3",
"limit",
"'min'",
),
(
"R kind=rule type=outside target=I(L1) low=1 max=3",
"low",
"'min'",
),
(
"R kind=rule type=inside target=I(L1) min=1 high=3",
"high",
"'max'",
),
] {
let message = rating_error(&format!("V1 a 0 10\nL1 a 0 36u\n{card}\n"));
assert!(
message.contains(&format!("field '{gone}' no longer exists"))
&& message.contains(replacement),
"'{gone}' on this card should be refused and name {replacement}: {message}"
);
}
}
#[test]
fn a_prefixed_bound_is_left_alone_because_its_prefix_names_a_quantity() {
let (_, rules) = ratings(
"V1 a 0 10\nL1 a 0 36u\n\
DSW a 0 idealswitchmodel\n\
DSW kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 \
body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=G\n\
ONE kind=const value=1\n\
G kind=sig2phys domain=voltage in=ONE\n\
T kind=rule type=switch_timing switches=DSW f_min=1000 f_max=100000\n\
Z kind=rule type=zvs switches=DSW v_max=5\n\
S kind=rule type=rate_of_change target=I(L1) max_slope=1e6\n",
);
assert_eq!(
rules.len(),
3,
"all three prefixed-bound cards should parse"
);
}
const CLOSURE_DECK: &str = "\
VIN in 0 12
DSW in sw idealswitchmodel
DSW kind=ideal_switch r_on=0.05 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 \
body_v_f=0.5 body_g_on=100 gate=block ctrl=G
D1 0 sw idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=100
R1 sw 0 5
ONE kind=const value=1
G kind=sig2phys domain=voltage in=ONE
P_IN kind=port v=(in,0) i=-VIN
P_OUT kind=port v=(sw,0) i=-VIN
";
#[test]
fn a_loss_closure_card_synthesises_the_conduction_quantity_for_each_device() {
let (_, rules) = ratings(&format!(
"{CLOSURE_DECK}CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT \
devices=DSW,D1 max=0.01 period=1e-5\n"
));
assert_eq!(rules.len(), 1);
assert_eq!(
rules[0].watch,
Watch::LossClosure {
in_port: "P_IN".to_string(),
out_port: "P_OUT".to_string(),
devices: vec!["P_cond(DSW)".to_string(), "P_cond(D1)".to_string()],
boundary: PeriodBoundary::Fixed(1e-5),
max: 0.01,
}
);
}
#[test]
fn a_device_the_netlist_does_not_have_is_refused_by_name() {
let message = rating_error(&format!(
"{CLOSURE_DECK}CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT \
devices=DSW,D9 max=0.01 period=1e-5\n"
));
assert!(
message.contains("'D9' is not a declared") && message.contains("conduction loss"),
"{message}"
);
}
#[test]
fn a_loss_closure_card_with_no_devices_is_refused() {
let message = rating_error(&format!(
"{CLOSURE_DECK}CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT devices= \
max=0.01 period=1e-5\n"
));
assert!(message.contains("devices"), "{message}");
}
#[test]
fn a_closure_bound_outside_zero_to_one_is_refused_because_it_is_a_fraction() {
let message = rating_error(&format!(
"{CLOSURE_DECK}CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT devices=DSW \
max=5 period=1e-5\n"
));
assert!(message.contains("fraction of the input power"), "{message}");
}
#[test]
fn a_diode_curve_is_assembled_like_a_switch_channel() {
let out = extract(CLOSURE_DECK, Dialect::Ngspice).expect("the deck parses");
let curve = &out.diodes["D1"];
assert_eq!(
(curve.positive.as_str(), curve.negative.as_str()),
("0", "sw")
);
assert_eq!(curve.v_f, 0.4);
assert_eq!(curve.g_on, 100.0);
assert!((curve.current_at(1.4) - 100.0).abs() < 1e-12);
assert_eq!(curve.current_at(0.2), 0.0);
}
}