use std::collections::BTreeMap;
use general_mna::block_graph::{
BlockInstance, BlockKind, ConstValue, GainValue, GateBinding, Signal,
};
const GATE_THRESHOLD: f64 = 0.5;
const MAX_DEPTH: usize = 8;
pub fn dead_gates(gates: &BTreeMap<String, GateBinding>, blocks: &[BlockInstance]) -> Vec<String> {
let by_name: BTreeMap<&str, &BlockInstance> =
blocks.iter().map(|b| (b.name.as_str(), b)).collect();
let mut found = Vec::new();
for (switch, binding) in gates {
for source in binding.source_blocks().into_iter().flatten() {
let Some(Constant { value, origin }) = constant_output(&by_name, source, 0) else {
continue;
};
if value >= GATE_THRESHOLD {
continue;
}
let through = if origin == source {
String::new()
} else {
format!(" (through '{source}')")
};
found.push(format!(
"warning: switch '{switch}' can never conduct: its gate is fixed at {value} by \
'{origin}'{through}, and a gate turns on at {GATE_THRESHOLD}. The run will \
simulate this switch as permanently open -- which still charges and still \
settles, so the waveform will not look wrong. If that is deliberate, leave a \
comment saying so; if not, check `ctrl=` and the modulator. (`v_f` on the \
switch line is its body diode's threshold, not the gate's.)"
));
}
}
found
}
struct Constant {
value: f64,
origin: String,
}
fn constant_output(
blocks: &BTreeMap<&str, &BlockInstance>,
name: &str,
depth: usize,
) -> Option<Constant> {
if depth >= MAX_DEPTH {
return None;
}
let block = blocks.get(name)?;
let input = |index: usize| -> Option<Constant> {
match block.inputs.get(index)? {
Signal::Block(from) => constant_output(blocks, from, depth + 1),
_ => None,
}
};
let here = |value: f64| {
Some(Constant {
value,
origin: name.to_string(),
})
};
match &block.kind {
BlockKind::Const(ConstValue::Scalar(value)) => here(*value),
BlockKind::Const(ConstValue::Vector(_)) => None,
BlockKind::Gain(GainValue::Scalar(gain)) => here(gain * input(0)?.value),
BlockKind::Gain(GainValue::Matrix(_)) => None,
BlockKind::Sum(signs) => {
let mut total = 0.0;
for (index, sign) in signs.iter().enumerate() {
total += sign * input(index)?.value;
}
here(total)
}
BlockKind::Saturation(limit) => here(input(0)?.value.clamp(-*limit, *limit)),
BlockKind::Sig2Phys { .. } => input(0),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use general_mna::block_graph::PhysicalDomain;
fn block(name: &str, kind: BlockKind, inputs: &[&str]) -> BlockInstance {
BlockInstance {
name: name.to_string(),
kind,
inputs: inputs
.iter()
.map(|from| Signal::Block((*from).to_string()))
.collect(),
ic: None,
}
}
fn gated(source: Vec<BlockInstance>) -> (BTreeMap<String, GateBinding>, Vec<BlockInstance>) {
let last = source.last().expect("a source block").name.clone();
let mut blocks = source;
blocks.push(block(
"GATE",
BlockKind::Sig2Phys {
domain: PhysicalDomain::Voltage,
},
&[last.as_str()],
));
(
BTreeMap::from([(
"DSW".to_string(),
GateBinding::Block {
ctrl: "GATE".to_string(),
v_gs_th: 0.5,
},
)]),
blocks,
)
}
#[test]
fn a_gate_pinned_below_the_threshold_is_reported() {
let (gates, blocks) = gated(vec![block(
"DEAD",
BlockKind::Const(ConstValue::Scalar(0.0)),
&[],
)]);
let found = dead_gates(&gates, &blocks);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].contains("fixed at 0 by 'DEAD'"), "{}", found[0]);
assert!(found[0].contains("through 'GATE'"), "{}", found[0]);
}
#[test]
fn a_gate_that_can_reach_the_threshold_is_not_reported() {
let (gates, blocks) = gated(vec![block(
"LIVE",
BlockKind::Const(ConstValue::Scalar(0.6)),
&[],
)]);
assert!(dead_gates(&gates, &blocks).is_empty());
}
#[test]
fn a_constant_scaled_down_past_the_threshold_is_still_decidable() {
let (gates, blocks) = gated(vec![
block("ONE", BlockKind::Const(ConstValue::Scalar(1.0)), &[]),
block("SMALL", BlockKind::Gain(GainValue::Scalar(0.2)), &["ONE"]),
]);
let found = dead_gates(&gates, &blocks);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].contains("fixed at 0.2"), "{}", found[0]);
}
#[test]
fn a_constant_scaled_up_past_the_threshold_is_silent() {
let (gates, blocks) = gated(vec![
block("ONE", BlockKind::Const(ConstValue::Scalar(1.0)), &[]),
block("BIG", BlockKind::Gain(GainValue::Scalar(0.8)), &["ONE"]),
]);
assert!(dead_gates(&gates, &blocks).is_empty());
}
#[test]
fn a_sum_of_constants_is_decidable() {
let (gates, blocks) = gated(vec![
block("A", BlockKind::Const(ConstValue::Scalar(1.0)), &[]),
block("B", BlockKind::Const(ConstValue::Scalar(0.9)), &[]),
block("DIFF", BlockKind::Sum(vec![1.0, -1.0]), &["A", "B"]),
]);
let found = dead_gates(&gates, &blocks);
assert_eq!(found.len(), 1, "1 - 0.9 is below the threshold: {found:?}");
}
#[test]
fn a_signal_this_check_cannot_decide_produces_no_warning() {
let (gates, blocks) = gated(vec![
block("D", BlockKind::Const(ConstValue::Scalar(0.4)), &[]),
block(
"PWM1",
BlockKind::Pwm {
freq_hz: 100e3,
red: 0.0,
fed: 0.0,
output_names: Vec::new(),
},
&["D"],
),
]);
assert!(
dead_gates(&gates, &blocks).is_empty(),
"a 0.4 duty is not a 0.4 output"
);
}
#[test]
fn a_gate_naming_a_block_that_does_not_exist_is_left_to_the_real_validator() {
let gates = BTreeMap::from([(
"DSW".to_string(),
GateBinding::Block {
ctrl: "NOPE".to_string(),
v_gs_th: 0.5,
},
)]);
assert!(dead_gates(&gates, &[]).is_empty());
}
}