use crate::flatten::{Endpoint, Engine, FlatBoard, FlatPart, Rail};
use litz_analog::{
BjtModel, DiodeModel, Element, ElementId, MosfetModel, Netlist, OpAmpModel,
Solution as NetlistSolution, THERMAL_VOLTAGE,
};
use litz_core::{Drive, Level, Part, PartState, PinId, Strength};
use std::collections::{BTreeMap, BTreeSet};
const MIN_OHMS: f64 = 1e-3;
const SWITCH_CLOSED_OHMS: f64 = 0.1;
const SWITCH_OPEN_OHMS: f64 = 10_000_000.0;
const SENSOR_OHMS: f64 = 10_000.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AnalogConfig {
pub v33: f64,
pub v5: f64,
pub vin: f64,
pub driver_ohms: f64,
pub led_series_ohms: f64,
pub led_lit_amps: f64,
pub pot_ohms: f64,
}
impl Default for AnalogConfig {
fn default() -> Self {
Self {
v33: 3.3,
v5: 5.0,
vin: 5.0,
driver_ohms: 50.0,
led_series_ohms: 20.0,
led_lit_amps: 1e-4,
pot_ohms: 10_000.0,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct AnalogSolution {
net_volts: Vec<Option<f64>>,
pin_volts: BTreeMap<(u16, u16), f64>,
gpio_volts: BTreeMap<(u16, u8), f64>,
part_currents: BTreeMap<u16, f64>,
leds: BTreeSet<u16>,
lit: BTreeSet<u16>,
part_ids: Vec<String>,
pin_names: Vec<Vec<String>>,
}
impl AnalogSolution {
pub fn node_voltage(&self, part: &str, pin: &str) -> Option<f64> {
let index = self.part_index(part)?;
let pin = self
.pin_names
.get(index as usize)?
.iter()
.position(|name| name == pin)? as u16;
self.node_voltage_pin(index, pin)
}
pub fn node_voltage_gpio(&self, gpio: u8) -> Option<f64> {
self.node_voltage_gpio_on(0, gpio)
}
pub fn node_voltage_gpio_on(&self, board: u16, gpio: u8) -> Option<f64> {
self.gpio_volts.get(&(board, gpio)).copied()
}
pub fn node_voltage_net(&self, net: u16) -> Option<f64> {
self.net_volts.get(net as usize).copied().flatten()
}
pub fn node_voltage_pin(&self, part: u16, pin: u16) -> Option<f64> {
self.pin_volts.get(&(part, pin)).copied()
}
pub fn node_is_high_z(&self, part: &str, pin: &str) -> Option<bool> {
let index = self.part_index(part)?;
let pin = self
.pin_names
.get(index as usize)?
.iter()
.position(|name| name == pin)? as u16;
Some(!self.pin_volts.contains_key(&(index, pin)))
}
pub fn current(&self, part: &str) -> Option<f64> {
let index = self.part_index(part)?;
self.part_currents.get(&index).copied()
}
pub fn is_lit(&self, part: &str) -> Option<bool> {
let index = self.part_index(part)?;
self.leds
.contains(&index)
.then(|| self.lit.contains(&index))
}
pub fn net_count(&self) -> usize {
self.net_volts.len()
}
fn part_index(&self, part: &str) -> Option<u16> {
self.part_ids
.iter()
.position(|id| id == part)
.map(|i| i as u16)
}
}
pub(crate) fn solve(
flat: &FlatBoard,
drives: &BTreeMap<(u16, u8), Drive>,
parts: &[Box<dyn Part>],
config: &AnalogConfig,
) -> Result<AnalogSolution, String> {
build_operating(flat, drives, parts, config, false)?.solve_dc(config)
}
pub(crate) fn build_operating(
flat: &FlatBoard,
drives: &BTreeMap<(u16, u8), Drive>,
parts: &[Box<dyn Part>],
config: &AnalogConfig,
transient: bool,
) -> Result<Circuit, String> {
let mut limited = BTreeSet::new();
loop {
let circuit = build(flat, drives, parts, config, transient, &limited)?;
let solution = circuit.solve_dc(config)?;
let folded = folded_sources(flat, parts, &solution);
let grown: BTreeSet<u16> = limited.union(&folded).copied().collect();
if grown == limited {
return Ok(circuit);
}
limited = grown;
}
}
fn folded_sources(
flat: &FlatBoard,
parts: &[Box<dyn Part>],
solution: &AnalogSolution,
) -> BTreeSet<u16> {
parts
.iter()
.enumerate()
.filter_map(|(index, part)| {
let limit = part.current_limit()?;
let delivered = -solution.current(flat.parts.get(index)?.id.as_str())?;
(delivered > f64::from(limit) + 1e-9).then_some(index as u16)
})
.collect()
}
pub(crate) fn is_analog_only_engine(part: &FlatPart) -> bool {
matches!(
&part.engine,
Engine::Builtin(engine)
if matches!(
engine.as_str(),
"capacitor" | "inductor" | "bjt" | "mosfet" | "opamp" | "op-amp"
)
)
}
pub(crate) struct Circuit {
netlist: Netlist,
node_of_net: Vec<Option<usize>>,
nets: Vec<Vec<Endpoint>>,
net_count: usize,
part_ids: Vec<String>,
pin_names: Vec<Vec<String>>,
current_elements: Vec<(u16, ElementId)>,
leds: BTreeSet<u16>,
}
impl Circuit {
pub(crate) fn netlist(&self) -> &Netlist {
&self.netlist
}
pub(crate) fn solve_dc(&self, config: &AnalogConfig) -> Result<AnalogSolution, String> {
if self.netlist.is_empty() {
return Ok(self.blank());
}
let solved = self
.netlist
.solve_dc()
.map_err(|e| format!("analog: the netlist could not be solved: {e}"))?;
Ok(self.solution(&solved, config))
}
pub(crate) fn solution(
&self,
solved: &NetlistSolution,
config: &AnalogConfig,
) -> AnalogSolution {
let mut solution = self.blank();
for (net, node) in self.node_of_net.iter().enumerate() {
if let Some(node) = *node {
solution.net_volts[net] = solved.node_volts.get(node).copied();
}
}
self.place_endpoints(&mut solution);
for &(part, element) in &self.current_elements {
if let Ok(amps) = solved.probe_current(element) {
solution.part_currents.insert(part, amps);
if self.leds.contains(&part) && amps > config.led_lit_amps {
solution.lit.insert(part);
}
}
}
solution.leds.clone_from(&self.leds);
solution
}
pub(crate) fn initial_solution(&self) -> AnalogSolution {
let mut solution = self.blank();
for (net, node) in self.node_of_net.iter().enumerate() {
if node.is_some() {
solution.net_volts[net] = Some(0.0);
}
}
self.place_endpoints(&mut solution);
solution.leds.clone_from(&self.leds);
solution
}
fn blank(&self) -> AnalogSolution {
AnalogSolution {
net_volts: vec![None; self.net_count],
part_ids: self.part_ids.clone(),
pin_names: self.pin_names.clone(),
..AnalogSolution::default()
}
}
fn place_endpoints(&self, solution: &mut AnalogSolution) {
for (net, members) in self.nets.iter().enumerate() {
let Some(volts) = solution.net_volts.get(net).copied().flatten() else {
continue;
};
for endpoint in members {
match *endpoint {
Endpoint::Chip(gpio) => {
solution.gpio_volts.insert((0, gpio), volts);
}
Endpoint::ChipOn { board, pin } => {
solution.gpio_volts.insert((board, pin), volts);
}
Endpoint::Part { part, pin } => {
solution.pin_volts.insert((part, pin), volts);
}
Endpoint::Rail(_) => {}
}
}
}
}
}
pub(crate) fn build(
flat: &FlatBoard,
drives: &BTreeMap<(u16, u8), Drive>,
parts: &[Box<dyn Part>],
config: &AnalogConfig,
transient: bool,
limited: &BTreeSet<u16>,
) -> Result<Circuit, String> {
let net_count = flat.nets.len();
let ground = net_count;
let mut sets = DisjointSet::new(net_count + 1);
let mut rail_nets: BTreeMap<Rail, usize> = BTreeMap::new();
for (net, members) in flat.nets.iter().enumerate() {
for endpoint in members {
if let Endpoint::Rail(rail) = *endpoint {
rail_nets.entry(rail).or_insert(net);
}
}
}
for net in rail_nets.values() {
sets.union(*net, ground);
}
for (net, members) in flat.nets.iter().enumerate() {
for endpoint in members {
if let Some((board, gpio)) = endpoint.chip_pin()
&& chip_volts(
drives.get(&(board, gpio)).copied().unwrap_or(Drive::HIGH_Z),
config,
)
.is_some()
{
sets.union(net, ground);
}
}
}
let mut models = Vec::new();
for (index, part) in flat.parts.iter().enumerate() {
if let Some(model) =
part_model(flat, parts, index as u16, part, config, &rail_nets, limited)
{
model.union(&mut sets, transient);
models.push(model);
}
}
let ground_root = sets.find(ground);
let mut solvable = |net: usize| sets.find(net) == ground_root;
let ground_net = rail_nets.get(&Rail::Gnd).copied();
let mut node_of_net = vec![None; net_count];
let mut next_node = 1usize;
for (net, slot) in node_of_net.iter_mut().enumerate() {
if !solvable(net) {
continue;
}
if Some(net) == ground_net {
*slot = Some(0);
} else {
*slot = Some(next_node);
next_node += 1;
}
}
let mut internal = 0usize;
for model in &models {
internal += model.internal_nodes(&node_of_net);
}
for (net, members) in flat.nets.iter().enumerate() {
if node_of_net[net].is_none() {
continue;
}
for endpoint in members {
if let Some((board, gpio)) = endpoint.chip_pin()
&& chip_volts(
drives.get(&(board, gpio)).copied().unwrap_or(Drive::HIGH_Z),
config,
)
.is_some()
{
internal += 1;
}
}
}
let node_count = next_node + internal;
let mut netlist = Netlist::new(node_count);
let mut next_internal = next_node;
let mut alloc = || {
let node = next_internal;
next_internal += 1;
node
};
for (&rail, &net) in &rail_nets {
if rail == Rail::Gnd {
continue;
}
let Some(node) = node_of_net[net] else {
continue;
};
netlist
.add(Element::VoltageSource {
p: node,
n: 0,
volts: rail_volts(rail, config),
})
.map_err(|e| format!("analog: rail {rail:?}: {e}"))?;
}
for (net, members) in flat.nets.iter().enumerate() {
let Some(node) = node_of_net[net] else {
continue;
};
for endpoint in members {
let Some((board, gpio)) = endpoint.chip_pin() else {
continue;
};
let Some(volts) = chip_volts(
drives.get(&(board, gpio)).copied().unwrap_or(Drive::HIGH_Z),
config,
) else {
continue;
};
let source = alloc();
netlist
.add(Element::VoltageSource {
p: source,
n: 0,
volts,
})
.map_err(|e| format!("analog: {} driver: {e}", chip_label(board, gpio)))?;
netlist
.add(Element::Resistor {
a: source,
b: node,
ohms: config.driver_ohms,
})
.map_err(|e| format!("analog: {} driver: {e}", chip_label(board, gpio)))?;
}
}
let mut current_elements: Vec<(u16, ElementId)> = Vec::new();
let mut leds = BTreeSet::new();
for model in &models {
model.build(
&mut netlist,
&node_of_net,
&mut alloc,
config,
&mut current_elements,
&mut leds,
)?;
}
Ok(Circuit {
netlist,
node_of_net,
nets: flat.nets.clone(),
net_count,
part_ids: flat.parts.iter().map(|part| part.id.clone()).collect(),
pin_names: flat.parts.iter().map(|part| part.pins.clone()).collect(),
current_elements,
leds,
})
}
fn chip_volts(drive: Drive, config: &AnalogConfig) -> Option<f64> {
if drive.strength != Strength::Strong {
return None;
}
match drive.level {
Level::High => Some(config.v33),
Level::Low => Some(0.0),
Level::HighZ => None,
}
}
fn chip_label(board: u16, gpio: u8) -> String {
if board == 0 {
format!("GPIO{gpio}")
} else {
format!("board {board} GPIO{gpio}")
}
}
fn rail_volts(rail: Rail, config: &AnalogConfig) -> f64 {
match rail {
Rail::Gnd => 0.0,
Rail::V33 => config.v33,
Rail::V5 => config.v5,
Rail::Vin => config.vin,
}
}
enum Model {
Resistor {
part: u16,
a: Option<usize>,
b: Option<usize>,
ohms: f64,
},
Led {
part: u16,
anode: Option<usize>,
cathode: Option<usize>,
color: String,
},
Potentiometer {
end1: Option<usize>,
wiper: Option<usize>,
end3: Option<usize>,
total_ohms: f64,
travel: f64,
},
Diode {
part: u16,
anode: Option<usize>,
cathode: Option<usize>,
model: DiodeModel,
},
VoltageSource {
part: u16,
p: Option<usize>,
n: Option<usize>,
volts: f64,
},
CurrentSource {
part: u16,
p: Option<usize>,
n: Option<usize>,
amps: f64,
},
Capacitor {
part: u16,
a: Option<usize>,
b: Option<usize>,
farads: f64,
},
Inductor {
part: u16,
a: Option<usize>,
b: Option<usize>,
henries: f64,
},
Pushbutton {
part: u16,
contacts: [[Option<usize>; 2]; 2],
closed: bool,
},
SlideSwitch {
part: u16,
throw1: Option<usize>,
common: Option<usize>,
throw3: Option<usize>,
on: bool,
},
SensorDivider {
ao: Option<usize>,
reference: Option<usize>,
ground: Option<usize>,
fraction: f64,
total_ohms: f64,
},
Bjt {
part: u16,
collector: Option<usize>,
base: Option<usize>,
emitter: Option<usize>,
model: BjtModel,
},
Mosfet {
part: u16,
drain: Option<usize>,
gate: Option<usize>,
source: Option<usize>,
model: MosfetModel,
},
OpAmp {
plus: Option<usize>,
minus: Option<usize>,
out: Option<usize>,
model: OpAmpModel,
},
}
impl Model {
fn union(&self, sets: &mut DisjointSet, transient: bool) {
match self {
Model::Resistor {
a: Some(a),
b: Some(b),
..
} => sets.union(*a, *b),
Model::Led {
anode: Some(a),
cathode: Some(c),
..
}
| Model::Diode {
anode: Some(a),
cathode: Some(c),
..
} => sets.union(*a, *c),
Model::Potentiometer {
end1, wiper, end3, ..
} => {
if let (Some(a), Some(w)) = (end1, wiper) {
sets.union(*a, *w);
}
if let (Some(w), Some(b)) = (wiper, end3) {
sets.union(*w, *b);
}
}
Model::VoltageSource {
p: Some(p),
n: Some(n),
..
} => sets.union(*p, *n),
Model::Capacitor {
a: Some(a),
b: Some(b),
..
} if transient => sets.union(*a, *b),
Model::Inductor {
a: Some(a),
b: Some(b),
..
} => sets.union(*a, *b),
Model::Pushbutton {
contacts, closed, ..
} => {
for contact in contacts {
if let (Some(a), Some(b)) = (contact[0], contact[1]) {
sets.union(a, b);
}
}
if *closed
&& let (Some(a), Some(b)) =
(first_wired(&contacts[0]), first_wired(&contacts[1]))
{
sets.union(a, b);
}
}
Model::SlideSwitch {
throw1,
common: Some(common),
throw3,
on,
..
} => {
let selected = if *on { *throw3 } else { *throw1 };
if let Some(selected) = selected {
sets.union(*common, selected);
}
}
Model::SensorDivider {
ao: Some(ao),
reference,
ground,
..
} => {
if let Some(reference) = *reference {
sets.union(*ao, reference);
}
if let Some(ground) = *ground {
sets.union(*ao, ground);
}
}
Model::Bjt {
collector: Some(c),
base: Some(b),
emitter: Some(e),
..
} => {
sets.union(*c, *e);
sets.union(*b, *e);
}
Model::Mosfet {
drain: Some(d),
source: Some(s),
..
} => sets.union(*d, *s),
_ => {}
}
}
fn internal_nodes(&self, node_of_net: &[Option<usize>]) -> usize {
match self {
Model::Led {
anode: Some(a),
cathode: Some(c),
..
} => usize::from(
node_of_net.get(*a).copied().flatten().is_some()
&& node_of_net.get(*c).copied().flatten().is_some(),
),
_ => 0,
}
}
#[allow(clippy::too_many_arguments)]
fn build(
&self,
netlist: &mut Netlist,
node_of_net: &[Option<usize>],
alloc: &mut impl FnMut() -> usize,
config: &AnalogConfig,
currents: &mut Vec<(u16, ElementId)>,
leds: &mut BTreeSet<u16>,
) -> Result<(), String> {
let node = |net: Option<usize>| -> Option<usize> {
let net = net?;
node_of_net.get(net).copied().flatten()
};
let add = |netlist: &mut Netlist, element: Element, what: &str| {
netlist
.add(element)
.map_err(|e| format!("analog: {what}: {e}"))
};
match self {
Model::Resistor { part, a, b, ohms } => {
if let (Some(a), Some(b)) = (node(*a), node(*b)) {
let id = add(
netlist,
Element::Resistor {
a,
b,
ohms: (*ohms).max(MIN_OHMS),
},
"resistor",
)?;
currents.push((*part, id));
}
}
Model::Led {
part,
anode,
cathode,
color,
} => {
if let (Some(anode), Some(cathode)) = (node(*anode), node(*cathode)) {
let junction = alloc();
let model = led_model(color);
let id = add(
netlist,
Element::Diode {
anode,
cathode: junction,
model,
},
"LED",
)?;
add(
netlist,
Element::Resistor {
a: junction,
b: cathode,
ohms: config.led_series_ohms.max(MIN_OHMS),
},
"LED series resistance",
)?;
currents.push((*part, id));
leds.insert(*part);
}
}
Model::Potentiometer {
end1,
wiper,
end3,
total_ohms,
travel,
} => {
let Some(wiper) = node(*wiper) else {
return Ok(());
};
if let Some(end1) = node(*end1) {
add(
netlist,
Element::Resistor {
a: end1,
b: wiper,
ohms: (total_ohms * travel).max(MIN_OHMS),
},
"potentiometer track",
)?;
}
if let Some(end3) = node(*end3) {
add(
netlist,
Element::Resistor {
a: wiper,
b: end3,
ohms: (total_ohms * (1.0 - travel)).max(MIN_OHMS),
},
"potentiometer track",
)?;
}
}
Model::Diode {
part,
anode,
cathode,
model,
} => {
if let (Some(anode), Some(cathode)) = (node(*anode), node(*cathode)) {
let id = add(
netlist,
Element::Diode {
anode,
cathode,
model: *model,
},
"diode",
)?;
currents.push((*part, id));
}
}
Model::VoltageSource { part, p, n, volts } => {
if let (Some(p), Some(n)) = (node(*p), node(*n)) {
let id = add(
netlist,
Element::VoltageSource {
p,
n,
volts: *volts,
},
"source",
)?;
currents.push((*part, id));
}
}
Model::CurrentSource { part, p, n, amps } => {
if let (Some(p), Some(n)) = (node(*p), node(*n)) {
let id = add(
netlist,
Element::CurrentSource { p, n, amps: *amps },
"source",
)?;
currents.push((*part, id));
}
}
Model::Capacitor { part, a, b, farads } => {
if let (Some(a), Some(b)) = (node(*a), node(*b)) {
let id = add(
netlist,
Element::Capacitor {
a,
b,
farads: (*farads).max(f64::MIN_POSITIVE),
},
"capacitor",
)?;
currents.push((*part, id));
}
}
Model::Inductor {
part,
a,
b,
henries,
} => {
if let (Some(a), Some(b)) = (node(*a), node(*b)) {
let id = add(
netlist,
Element::Inductor {
a,
b,
henries: (*henries).max(f64::MIN_POSITIVE),
},
"inductor",
)?;
currents.push((*part, id));
}
}
Model::Pushbutton {
part,
contacts,
closed,
} => {
for contact in contacts {
if let (Some(a), Some(b)) = (node(contact[0]), node(contact[1])) {
add(
netlist,
Element::Resistor {
a,
b,
ohms: MIN_OHMS,
},
"pushbutton contact",
)?;
}
}
let a = node(first_wired(&contacts[0]));
let b = node(first_wired(&contacts[1]));
if let (Some(a), Some(b)) = (a, b) {
let id = add(
netlist,
Element::Resistor {
a,
b,
ohms: contact_ohms(*closed),
},
"pushbutton",
)?;
currents.push((*part, id));
}
}
Model::SlideSwitch {
part,
throw1,
common,
throw3,
on,
} => {
let Some(common) = node(*common) else {
return Ok(());
};
if let Some(throw1) = node(*throw1) {
let id = add(
netlist,
Element::Resistor {
a: common,
b: throw1,
ohms: contact_ohms(!*on),
},
"slide switch",
)?;
if !*on {
currents.push((*part, id));
}
}
if let Some(throw3) = node(*throw3) {
let id = add(
netlist,
Element::Resistor {
a: common,
b: throw3,
ohms: contact_ohms(*on),
},
"slide switch",
)?;
if *on {
currents.push((*part, id));
}
}
}
Model::SensorDivider {
ao,
reference,
ground,
fraction,
total_ohms,
} => {
let (Some(ao), Some(reference), Some(ground)) =
(node(*ao), node(*reference), node(*ground))
else {
return Ok(());
};
let fraction = fraction.clamp(0.0, 1.0);
add(
netlist,
Element::Resistor {
a: reference,
b: ao,
ohms: (total_ohms * (1.0 - fraction)).max(MIN_OHMS),
},
"sensor divider",
)?;
add(
netlist,
Element::Resistor {
a: ao,
b: ground,
ohms: (total_ohms * fraction).max(MIN_OHMS),
},
"sensor divider",
)?;
}
Model::Bjt {
part,
collector,
base,
emitter,
model,
} => {
if let (Some(collector), Some(base), Some(emitter)) =
(node(*collector), node(*base), node(*emitter))
{
let id = add(
netlist,
Element::Bjt {
collector,
base,
emitter,
model: *model,
},
"BJT",
)?;
currents.push((*part, id));
}
}
Model::Mosfet {
part,
drain,
gate,
source,
model,
} => {
if let (Some(drain), Some(gate), Some(source)) =
(node(*drain), node(*gate), node(*source))
{
let id = add(
netlist,
Element::Mosfet {
drain,
gate,
source,
model: *model,
},
"MOSFET",
)?;
currents.push((*part, id));
}
}
Model::OpAmp {
plus,
minus,
out,
model,
} => {
if let (Some(plus), Some(minus), Some(out)) =
(node(*plus), node(*minus), node(*out))
{
add(
netlist,
Element::OpAmp {
plus,
minus,
out,
model: *model,
},
"op-amp",
)?;
}
}
}
Ok(())
}
}
fn first_wired(legs: &[Option<usize>; 2]) -> Option<usize> {
legs[0].or(legs[1])
}
fn contact_ohms(closed: bool) -> f64 {
if closed {
SWITCH_CLOSED_OHMS
} else {
SWITCH_OPEN_OHMS
}
}
fn part_model(
flat: &FlatBoard,
parts: &[Box<dyn Part>],
index: u16,
part: &FlatPart,
config: &AnalogConfig,
rail_nets: &BTreeMap<Rail, usize>,
limited: &BTreeSet<u16>,
) -> Option<Model> {
let Engine::Builtin(engine) = &part.engine else {
return None;
};
let pin = |names: &[&str]| {
names
.iter()
.find_map(|name| part.pins.iter().position(|candidate| candidate == name))
.map(|pin| pin as u16)
};
let net = |pin: Option<u16>| -> Option<usize> {
let pin = pin?;
flat.endpoint_net
.get(&Endpoint::Part { part: index, pin })
.map(|net| *net as usize)
};
let attr = |name: &str| part.attrs.get(name).map(String::as_str);
let state = || parts.get(index as usize).map(|part| part.state());
match engine.as_str() {
"resistor" => {
let ohms = attr("value").and_then(parse_resistance).unwrap_or(220.0);
Some(Model::Resistor {
part: index,
a: net(pin(&["1"]).or(Some(0))),
b: net(pin(&["2"]).or(Some(1))),
ohms,
})
}
"led" => Some(Model::Led {
part: index,
anode: net(pin(&["A", "anode"])),
cathode: net(pin(&["C", "cathode"])),
color: attr("color").unwrap_or("red").to_string(),
}),
"potentiometer" => {
let total_ohms = attr("resistance")
.and_then(parse_resistance)
.unwrap_or(config.pot_ohms);
let travel = match state() {
Some(PartState::Knob { permille }) => f64::from(permille) / 1000.0,
_ => attr("value").map_or(0.5, parse_percent),
};
Some(Model::Potentiometer {
end1: net(pin(&["1"])),
wiper: net(pin(&["2", "W", "wiper"])),
end3: net(pin(&["3"])),
total_ohms,
travel: travel.clamp(0.0, 1.0),
})
}
"diode" => {
let model = attr("vf")
.or_else(|| attr("forward_voltage"))
.or_else(|| attr("forward-voltage"))
.and_then(parse_volts)
.map_or_else(DiodeModel::silicon, diode_at_forward_volts);
Some(Model::Diode {
part: index,
anode: net(pin(&["A", "anode"])),
cathode: net(pin(&["C", "cathode"])),
model,
})
}
"voltage-source" | "dc-source" | "vsource" | "battery" => {
let positive = pin(&["+", "V+", "P", "p", "1"]);
let negative = pin(&["-", "V-", "N", "n", "2"]);
let volts = parts
.get(index as usize)
.and_then(|part| positive.and_then(|pin| part.analog(PinId(pin))))
.map_or_else(
|| {
attr("voltage")
.or_else(|| attr("volts"))
.or_else(|| attr("value"))
.and_then(parse_volts)
.unwrap_or(0.0)
},
f64::from,
);
if limited.contains(&index) {
let amps = parts
.get(index as usize)
.and_then(|part| part.current_limit())
.map_or(0.0, |limit| -f64::from(limit));
return Some(Model::CurrentSource {
part: index,
p: net(positive),
n: net(negative),
amps,
});
}
Some(Model::VoltageSource {
part: index,
p: net(positive),
n: net(negative),
volts,
})
}
"signal-generator" => {
let out_pin = pin(&["OUT"])?;
let volts = parts.get(index as usize)?.analog(PinId(out_pin))?;
Some(Model::VoltageSource {
part: index,
p: net(Some(out_pin)),
n: net(pin(&["GND"])),
volts: f64::from(volts),
})
}
"current-source" | "isource" => {
let amps = attr("amps")
.or_else(|| attr("current"))
.or_else(|| attr("value"))
.and_then(parse_volts)
.unwrap_or(0.0);
Some(Model::CurrentSource {
part: index,
p: net(pin(&["+", "P", "p", "1"])),
n: net(pin(&["-", "N", "n", "2"])),
amps,
})
}
"capacitor" => {
let farads = attr("value")
.or_else(|| attr("capacitance"))
.and_then(parse_capacitance)
.unwrap_or(1e-6);
Some(Model::Capacitor {
part: index,
a: net(pin(&["1", "A", "+"])),
b: net(pin(&["2", "B", "-"])),
farads,
})
}
"inductor" => {
let henries = attr("value")
.or_else(|| attr("inductance"))
.and_then(parse_inductance)
.unwrap_or(1e-3);
Some(Model::Inductor {
part: index,
a: net(pin(&["1", "A"])),
b: net(pin(&["2", "B"])),
henries,
})
}
"pushbutton" => {
let legs = [
[net(pin(&["1.l"])), net(pin(&["1.r"]))],
[net(pin(&["2.l"])), net(pin(&["2.r"]))],
];
let closed = matches!(state(), Some(PartState::Button { pressed: true }));
Some(Model::Pushbutton {
part: index,
contacts: legs,
closed,
})
}
"slide-switch" => {
let on = matches!(state(), Some(PartState::Switch { on: true }));
Some(Model::SlideSwitch {
part: index,
throw1: net(pin(&["1"])),
common: net(pin(&["2"])),
throw3: net(pin(&["3"])),
on,
})
}
"ntc-temperature-sensor" => {
let fraction = match state() {
Some(PartState::Knob { permille }) => f64::from(permille) / 1000.0,
_ => {
let celsius = attr("temperature")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(25.0);
((celsius + 20.0) / 120.0).clamp(0.0, 1.0)
}
};
Some(Model::SensorDivider {
ao: net(pin(&["AO"])),
reference: net(pin(&["VCC", "V+", "Vdd", "VDD"]))
.or_else(|| rail_net(rail_nets, Rail::V33)),
ground: net(pin(&["GND", "G"])).or_else(|| rail_net(rail_nets, Rail::Gnd)),
fraction,
total_ohms: SENSOR_OHMS,
})
}
"photoresistor-sensor" => {
let fraction = match state() {
Some(PartState::Knob { permille }) => f64::from(permille) / 1000.0,
_ => attr("light")
.and_then(|text| text.trim().parse::<f64>().ok())
.map_or(0.5, |light| (light / 1000.0).clamp(0.0, 1.0)),
};
Some(Model::SensorDivider {
ao: net(pin(&["AO"])),
reference: net(pin(&["VCC", "V+", "Vdd", "VDD"]))
.or_else(|| rail_net(rail_nets, Rail::V33)),
ground: net(pin(&["GND", "G"])).or_else(|| rail_net(rail_nets, Rail::Gnd)),
fraction,
total_ohms: SENSOR_OHMS,
})
}
"bjt" => {
if attr("polarity").is_some_and(|polarity| polarity.eq_ignore_ascii_case("pnp")) {
return None;
}
let beta = attr("beta")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(100.0);
let vbe_on = attr("vbe")
.or_else(|| attr("vbe_on"))
.and_then(parse_volts)
.unwrap_or(0.7);
let early_voltage = attr("early_voltage")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(100.0);
Some(Model::Bjt {
part: index,
collector: net(pin(&["C", "collector", "c"])),
base: net(pin(&["B", "base", "b"])),
emitter: net(pin(&["E", "emitter", "e"])),
model: BjtModel {
beta,
vbe_on,
early_voltage,
},
})
}
"mosfet" => {
if attr("channel").is_some_and(|channel| channel.eq_ignore_ascii_case("p")) {
return None;
}
let threshold = attr("vth")
.or_else(|| attr("threshold"))
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(2.0);
let k = attr("k")
.or_else(|| attr("beta"))
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(1e-2);
let lambda = attr("lambda")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(0.0);
Some(Model::Mosfet {
part: index,
drain: net(pin(&["D", "drain", "d"])),
gate: net(pin(&["G", "gate", "g"])),
source: net(pin(&["S", "source", "s"])),
model: MosfetModel {
threshold,
k,
lambda,
},
})
}
"opamp" | "op-amp" => {
let gain = attr("gain")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(1e5);
let rail_low = attr("rail_low")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(0.0);
let rail_high = attr("rail_high")
.and_then(|text| text.trim().parse::<f64>().ok())
.unwrap_or(config.v33);
Some(Model::OpAmp {
plus: net(pin(&["+", "plus", "IN+", "INP", "P"])),
minus: net(pin(&["-", "minus", "IN-", "INN", "N"])),
out: net(pin(&["OUT", "out", "O"])),
model: OpAmpModel {
gain,
rail_low,
rail_high,
},
})
}
_ => None,
}
}
fn rail_net(rail_nets: &BTreeMap<Rail, usize>, rail: Rail) -> Option<usize> {
rail_nets.get(&rail).copied()
}
fn led_forward_volts(color: &str) -> f64 {
match color.to_ascii_lowercase().as_str() {
"red" => 1.8,
"green" => 2.0,
"yellow" => 2.0,
"orange" => 2.0,
"blue" => 3.0,
"white" => 3.2,
"purple" | "pink" => 3.0,
"cyan" => 3.0,
_ => 1.8,
}
}
fn led_model(color: &str) -> DiodeModel {
diode_at_forward_volts(led_forward_volts(color))
}
fn diode_at_forward_volts(vf: f64) -> DiodeModel {
const NOMINAL_AMPS: f64 = 0.02;
const IDEALITY: f64 = 2.0;
let scale = (vf / (IDEALITY * THERMAL_VOLTAGE)).exp() - 1.0;
let saturation_current = if scale > 0.0 {
NOMINAL_AMPS / scale
} else {
1e-14
};
DiodeModel::led(saturation_current, IDEALITY)
}
pub(crate) fn parse_resistance(text: &str) -> Option<f64> {
let cleaned = text.trim().replace([' ', '_'], "");
let mut text = cleaned.as_str();
for suffix in ["ohms", "ohm", "Ohms", "Ohm", "OHM", "OHMS", "Ω", "ω"] {
if let Some(stripped) = text.strip_suffix(suffix) {
text = stripped.trim();
break;
}
}
if text.is_empty() {
return None;
}
if let Ok(value) = text.parse::<f64>() {
return (value > 0.0).then_some(value);
}
let split = text.find(|c: char| c.is_ascii_alphabetic())?;
let (leading, rest) = text.split_at(split);
let mut chars = rest.chars();
let prefix = chars.next()?;
let trailing = chars.as_str();
let factor = match prefix {
'k' | 'K' => 1e3,
'M' => 1e6,
'm' => 1e-3,
'G' | 'g' => 1e9,
'R' | 'r' => 1.0,
_ => return None,
};
let value: f64 = if trailing.is_empty() {
leading.parse().ok()?
} else {
format!("{leading}.{trailing}").parse().ok()?
};
let ohms = value * factor;
(ohms > 0.0).then_some(ohms)
}
pub(crate) fn parse_capacitance(text: &str) -> Option<f64> {
parse_si_value(text, &["F", "f"])
}
pub(crate) fn parse_inductance(text: &str) -> Option<f64> {
parse_si_value(text, &["H", "h"])
}
fn parse_si_value(text: &str, units: &[&str]) -> Option<f64> {
let cleaned = text.trim().replace([' ', '_'], "").replace(['µ', 'μ'], "u");
let mut text = cleaned.as_str();
for unit in units {
if let Some(stripped) = text.strip_suffix(unit) {
text = stripped;
break;
}
}
if text.is_empty() {
return None;
}
if let Ok(value) = text.parse::<f64>() {
return (value > 0.0).then_some(value);
}
let split = text.find(|c: char| c.is_ascii_alphabetic())?;
let (leading, rest) = text.split_at(split);
let mut chars = rest.chars();
let prefix = chars.next()?;
let trailing = chars.as_str();
let factor = match prefix {
'p' | 'P' => 1e-12,
'n' | 'N' => 1e-9,
'u' | 'U' => 1e-6,
'm' => 1e-3,
'k' | 'K' => 1e3,
'M' => 1e6,
'G' | 'g' => 1e9,
_ => return None,
};
let value: f64 = if trailing.is_empty() {
leading.parse().ok()?
} else {
format!("{leading}.{trailing}").parse().ok()?
};
let value = value * factor;
(value > 0.0).then_some(value)
}
fn parse_volts(text: &str) -> Option<f64> {
let text = text.trim().trim_end_matches(['V', 'v']);
text.trim().parse().ok()
}
fn parse_percent(text: &str) -> f64 {
text.trim()
.parse::<f64>()
.map_or(0.5, |percent| (percent / 100.0).clamp(0.0, 1.0))
}
struct DisjointSet {
parent: Vec<usize>,
}
impl DisjointSet {
fn new(len: usize) -> Self {
Self {
parent: (0..len).collect(),
}
}
fn find(&mut self, mut index: usize) -> usize {
while self.parent[index] != index {
self.parent[index] = self.parent[self.parent[index]];
index = self.parent[index];
}
index
}
fn union(&mut self, a: usize, b: usize) {
let (a, b) = (self.find(a), self.find(b));
if a != b {
self.parent[a.max(b)] = a.min(b);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resistance_text_uses_electronics_notation() {
assert_eq!(parse_resistance("220"), Some(220.0));
assert_eq!(parse_resistance("10k"), Some(10_000.0));
assert_eq!(parse_resistance("4k7"), Some(4_700.0));
assert_eq!(parse_resistance("4K7"), Some(4_700.0));
assert_eq!(parse_resistance("2.2k"), Some(2_200.0));
assert_eq!(parse_resistance("1M"), Some(1_000_000.0));
assert_eq!(parse_resistance("4R7"), Some(4.7));
assert_eq!(parse_resistance("1e3"), Some(1_000.0));
assert_eq!(parse_resistance("10 k"), Some(10_000.0));
assert_eq!(parse_resistance("4k7Ω"), Some(4_700.0));
assert_eq!(parse_resistance("nonsense"), None);
assert_eq!(parse_resistance("0"), None);
}
#[test]
fn capacitance_and_inductance_text_accept_si_prefixes() {
let close = |actual: Option<f64>, expected: f64| {
let actual = actual.expect("the text parses");
assert!(
(actual - expected).abs() <= expected.abs() * 1e-12,
"{actual:e} F/H is not {expected:e}"
);
};
close(parse_capacitance("100n"), 100e-9);
close(parse_capacitance("100nF"), 100e-9);
close(parse_capacitance("4.7u"), 4.7e-6);
close(parse_capacitance("2.2µF"), 2.2e-6);
close(parse_capacitance("10p"), 10e-12);
close(parse_capacitance("1mF"), 1e-3);
assert_eq!(parse_capacitance("nonsense"), None);
close(parse_inductance("10uH"), 10e-6);
close(parse_inductance("4.7mH"), 4.7e-3);
close(parse_inductance("100n"), 100e-9);
}
#[test]
fn an_led_model_drops_its_forward_voltage_at_the_rated_current() {
let model = led_model("green");
let vf = 2.0 * THERMAL_VOLTAGE * (0.02 / model.saturation_current + 1.0).ln();
assert!((vf - 2.0).abs() < 1e-9, "{vf}");
}
}