mod finite;
mod measure;
mod raw_format;
mod rules;
mod static_checks;
use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use dae_runtime::checkpoint::Checkpoint;
use dae_runtime::{
simulate_transient, simulate_transient_with_blocks_checkpointed, solve_dc, AdaptiveConfig,
BlockInstance, BlockKind, CheckpointControl, CheckpointSink, DaeError, GateBinding, TimeStep,
ADAPTIVE_STEP_HARD_CAP,
};
use general_spice_core::Dialect;
use pwl_devices::{IdealDiode, IdealSwitch};
#[derive(Clone)]
struct Waveform {
headers: Vec<String>,
rows: Vec<Vec<f64>>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum OutputFormat {
Csv,
Raw,
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code),
Err(message) => {
eprintln!("error: {message}");
ExitCode::FAILURE
}
}
}
mod exit {
pub const OK: u8 = 0;
pub const RULE_ERROR: u8 = 2;
pub const STOPPED_BY_RULE: u8 = 3;
pub const NOT_FINITE: u8 = 4;
}
fn run() -> Result<u8, String> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
return Err(usage());
}
match args[1].as_str() {
"--help" | "-h" => {
println!("{}", help());
return Ok(0);
}
"--version" | "-V" => {
println!("{}", version_line());
return Ok(0);
}
other if other.starts_with('-') => {
return Err(format!(
"unrecognized argument '{other}', or a flag given before the netlist.\n\
The netlist path comes first: general-simulator <netlist> [OPTIONS]\n\
Run `general-simulator --help` for the full list."
));
}
_ => {}
}
let netlist_path = &args[1];
let mut devices_path: Option<String> = None;
let mut mode = "dc".to_string();
let mut t_final = 1.0;
let mut dt: Option<f64> = None;
let mut dt_max: Option<f64> = None;
let mut dt_min: Option<f64> = None;
let mut dt_init: Option<f64> = None;
let mut reltol: Option<f64> = None;
let mut abstol: Option<f64> = None;
let mut max_steps: Option<usize> = None;
let mut format = "csv".to_string();
let mut out_path: Option<String> = None;
let mut events_jsonl: Option<String> = None;
let mut events_text: Option<String> = None;
let mut out_every: usize = 1;
let mut checkpoint_out: Option<String> = None;
let mut checkpoint_every: Option<f64> = None;
let mut resume: Option<String> = None;
let mut i = 2;
while i < args.len() {
let parse_f64 = |flag: &'static str, i: &mut usize| -> Result<f64, String> {
let v = args
.get(*i + 1)
.ok_or_else(|| format!("{flag} needs a value"))?
.parse()
.map_err(|_| format!("bad {flag}"))?;
*i += 2;
Ok(v)
};
match args[i].as_str() {
"--devices" => {
devices_path = Some(args.get(i + 1).ok_or("--devices needs a value")?.clone());
i += 2;
}
"--mode" => {
mode = args.get(i + 1).ok_or("--mode needs a value")?.clone();
i += 2;
}
"--tfinal" => t_final = parse_f64("--tfinal", &mut i)?,
"--dt" => dt = Some(parse_f64("--dt", &mut i)?),
"--dt-max" => dt_max = Some(parse_f64("--dt-max", &mut i)?),
"--dt-min" => dt_min = Some(parse_f64("--dt-min", &mut i)?),
"--dt-init" => dt_init = Some(parse_f64("--dt-init", &mut i)?),
"--reltol" => reltol = Some(parse_f64("--reltol", &mut i)?),
"--abstol" => abstol = Some(parse_f64("--abstol", &mut i)?),
"--max-steps" => {
let v: usize = args
.get(i + 1)
.ok_or("--max-steps needs a value")?
.parse()
.map_err(|_| "bad --max-steps".to_string())?;
max_steps = Some(v);
i += 2;
}
"--out-every" => {
let v: usize = args
.get(i + 1)
.ok_or("--out-every needs a value")?
.parse()
.map_err(|_| "bad --out-every".to_string())?;
if v == 0 {
return Err("--out-every must be at least 1".to_string());
}
out_every = v;
i += 2;
}
"--format" => {
format = args.get(i + 1).ok_or("--format needs a value")?.clone();
i += 2;
}
"--checkpoint-out" => {
checkpoint_out = Some(
args.get(i + 1)
.ok_or("--checkpoint-out needs a value")?
.clone(),
);
i += 2;
}
"--checkpoint-every" => {
let v = parse_f64("--checkpoint-every", &mut i)?;
if v <= 0.0 {
return Err("--checkpoint-every must be positive".to_string());
}
checkpoint_every = Some(v);
}
"--resume" => {
resume = Some(args.get(i + 1).ok_or("--resume needs a value")?.clone());
i += 2;
}
"--out" => {
out_path = Some(args.get(i + 1).ok_or("--out needs a value")?.clone());
i += 2;
}
"--events" => {
events_jsonl = Some(args.get(i + 1).ok_or("--events needs a value")?.clone());
i += 2;
}
"--events-text" => {
events_text = Some(
args.get(i + 1)
.ok_or("--events-text needs a value")?
.clone(),
);
i += 2;
}
other => return Err(format!("unrecognized argument '{other}'\n{}", usage())),
}
}
let output_format = match format.as_str() {
"csv" => OutputFormat::Csv,
"raw" => OutputFormat::Raw,
other => {
return Err(format!(
"unknown --format '{other}' (expected 'csv' or 'raw')"
))
}
};
let raw_out_path: Option<PathBuf> = if output_format == OutputFormat::Raw {
Some(match &out_path {
Some(p) => PathBuf::from(p),
None => default_raw_path(netlist_path),
})
} else {
None
};
if dt.is_some()
&& (dt_max.is_some()
|| dt_min.is_some()
|| dt_init.is_some()
|| reltol.is_some()
|| abstol.is_some())
{
return Err(
"--dt (fixed step) and --dt-max/--dt-min/--dt-init/--reltol/--abstol (adaptive \
step) are mutually exclusive — pick one"
.to_string(),
);
}
let step = match dt {
Some(dt) => TimeStep::Fixed(dt),
None => {
let mut config = AdaptiveConfig::from_t_final(t_final);
if let Some(v) = dt_max {
config.dt_max = v;
}
if let Some(v) = dt_min {
config.dt_min = v;
}
if let Some(v) = dt_init {
config.dt_init = v;
}
if let Some(v) = reltol {
config.reltol = v;
}
if let Some(v) = abstol {
config.abstol = v;
}
TimeStep::Adaptive(config)
}
};
let netlist =
fs::read_to_string(netlist_path).map_err(|e| format!("reading {netlist_path}: {e}"))?;
let dialect = Dialect::Ngspice;
let devices_source = match &devices_path {
Some(path) => fs::read_to_string(path).map_err(|e| format!("reading {path}: {e}"))?,
None => netlist.clone(),
};
let (devices_for_build, measurements) = measure::extract(&devices_source, dialect)
.map_err(|e| format!("parsing kind=measure declarations: {e}"))?;
let rules::Extracted {
netlist: devices_for_build,
rules: device_rules,
ports: device_ports,
switches: device_switch_channels,
diodes: device_diode_curves,
} = rules::extract(&devices_for_build, dialect).map_err(|e| {
format!("parsing kind=rule cards, kind=port declarations and device ratings: {e}")
})?;
let rules::Extracted {
netlist,
rules: netlist_rules,
ports: netlist_ports,
switches: netlist_switch_channels,
diodes: netlist_diode_curves,
} = rules::extract(&netlist, dialect).map_err(|e| {
format!("parsing kind=rule cards, kind=port declarations and device ratings: {e}")
})?;
let declared_rules = if devices_path.is_some() {
let mut all = netlist_rules;
all.extend(device_rules);
all
} else {
device_rules
};
let declared_ports = if devices_path.is_some() {
let mut all = netlist_ports;
all.extend(device_ports);
all
} else {
device_ports
};
let switch_channels = if devices_path.is_some() {
let mut all = netlist_switch_channels;
all.extend(device_switch_channels);
all
} else {
device_switch_channels
};
let diode_curves = if devices_path.is_some() {
let mut all = netlist_diode_curves;
all.extend(device_diode_curves);
all
} else {
device_diode_curves
};
let general_mna::System {
ideal_diodes: diodes,
ideal_switches,
gates,
blocks,
shared_r_on,
..
} = general_mna::build_system(&devices_for_build, dialect)
.map_err(|e| format!("parsing device/block declarations: {e}"))?;
for warning in static_checks::dead_gates(&gates, &blocks) {
eprintln!("{warning}");
}
let statements = general_mna::parse_and_flatten(&netlist, dialect)
.map_err(|e| format!("parsing netlist: {e}"))?;
if let Err(e) = dae_runtime::reject_sig2phys_wired_into_circuit(&statements, &blocks) {
return Err(match &e {
DaeError::Sig2PhysUsedAsCircuitNode {
block,
element,
node,
} => format!(
"{e:?}: element '{element}' wires node '{node}', but '{block}' is a \
kind=sig2phys converter, not a device with terminals -- it has no pins and \
stamps nothing into the circuit, so that node would be undriven and silently \
solve to V({node}) = 0. A converter is consumed by name, never by a wire: name \
it in an independent source's own value field (e.g. `V1 a 0 {block}`) or in an \
ideal switch's gate=/ctrl= field."
),
other => format!("{other:?}"),
});
}
let event_paths = rules::EventPaths {
jsonl: events_jsonl.as_deref().map(PathBuf::from),
text: events_text.as_deref().map(PathBuf::from),
};
let (waveform, plot_name) = if mode == "dc" {
let point = if ideal_switches.is_empty() {
solve_dc(&netlist, dialect, &diodes).map_err(|e| format!("{e:?}"))?
} else {
let name = ideal_switches
.keys()
.next()
.expect("ideal_switches is non-empty here");
return Err(format!(
"device '{name}': every gate is block-driven (gate=block), which needs \
--mode transient, not 'dc' (a DC operating point has no notion of a block's \
time-stepped state)"
));
};
let mut headers = vec!["t".to_string()];
headers.extend(point.unknowns.iter().cloned());
let mut row = vec![0.0];
row.extend(point.x.iter().copied());
(
Waveform {
headers,
rows: vec![row],
},
"DC transfer characteristic",
)
} else if mode == "transient" {
let checkpointing = checkpoint_out.is_some() || resume.is_some();
if checkpoint_every.is_some() && checkpoint_out.is_none() {
return Err("--checkpoint-every needs --checkpoint-out <file>".to_string());
}
if checkpointing && mode != "transient" {
return Err("--checkpoint-out/--resume only apply to --mode transient".to_string());
}
if ideal_switches.is_empty()
&& blocks.is_empty()
&& !checkpointing
&& declared_rules.is_empty()
{
let trace = simulate_transient(&netlist, dialect, &diodes, None, t_final, step)
.map_err(|e| format!("{e:?}"))?;
let headers = match trace.first() {
Some((_, first)) => {
let mut headers = vec!["t".to_string()];
headers.extend(first.unknowns.iter().cloned());
headers
}
None => vec!["t".to_string()],
};
let rows = trace
.iter()
.map(|(t, point)| {
let mut row = vec![*t];
row.extend(point.x.iter().copied());
row
})
.collect();
(Waveform { headers, rows }, "Transient Analysis")
} else {
return run_transient_streamed(
&netlist,
dialect,
&diodes,
&ideal_switches,
&gates,
&blocks,
shared_r_on,
t_final,
step,
max_steps.unwrap_or(ADAPTIVE_STEP_HARD_CAP),
output_format,
out_every,
raw_out_path.as_deref(),
netlist_path,
&measurements,
declared_rules,
&declared_ports,
&switch_channels,
&diode_curves,
&event_paths,
CheckpointArgs {
out: checkpoint_out.as_deref().map(Path::new),
every: checkpoint_every,
resume: resume.as_deref().map(Path::new),
},
);
}
} else {
return Err(format!(
"unknown --mode '{mode}' (expected 'dc' or 'transient')"
));
};
let out_waveform = decimate(&waveform, out_every);
match output_format {
OutputFormat::Csv => print_csv(&out_waveform),
OutputFormat::Raw => {
let out_path = raw_out_path.expect("raw_out_path is Some when output_format is Raw");
write_raw_file(&out_path, &out_waveform, plot_name, netlist_path)?;
}
}
if !measurements.is_empty() {
write_measurements_log(&measurements, &waveform, &default_log_path(netlist_path))?;
}
Ok(exit::OK)
}
fn default_log_path(netlist_path: &str) -> PathBuf {
Path::new(netlist_path).with_extension("log")
}
fn default_raw_path(netlist_path: &str) -> PathBuf {
let path = Path::new(netlist_path);
path.with_extension("raw")
}
fn decimate(waveform: &Waveform, stride: usize) -> Waveform {
if stride <= 1 {
return waveform.clone();
}
Waveform {
headers: waveform.headers.clone(),
rows: waveform.rows.iter().step_by(stride).cloned().collect(),
}
}
fn write_raw_file(
out_path: &Path,
waveform: &Waveform,
plot_name: &'static str,
netlist_path: &str,
) -> Result<(), String> {
let file = fs::File::create(out_path)
.map_err(|e| format!("creating raw output file {}: {e}", out_path.display()))?;
let mut writer = BufWriter::new(file);
let rendered = raw_format::Waveform {
names: &waveform.headers,
rows: &waveform.rows,
plot_name,
title: netlist_path,
};
raw_format::write_raw(&mut writer, &rendered)
.map_err(|e| format!("writing raw output file {}: {e}", out_path.display()))
}
#[allow(clippy::too_many_arguments)]
fn run_transient_streamed(
netlist: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, IdealSwitch>,
gates: &BTreeMap<String, GateBinding>,
blocks: &[BlockInstance],
shared_r_on: f64,
t_final: f64,
step: TimeStep,
max_steps: usize,
output_format: OutputFormat,
out_every: usize,
raw_out_path: Option<&Path>,
netlist_path: &str,
measurements: &[measure::MeasureSpec],
declared_rules: Vec<gsim_rules::Rule>,
declared_ports: &BTreeMap<String, rules::Port>,
switch_channels: &BTreeMap<String, rules::SwitchChannel>,
diode_curves: &BTreeMap<String, rules::DiodeCurve>,
event_paths: &rules::EventPaths,
checkpoints: CheckpointArgs<'_>,
) -> Result<u8, String> {
let resume_from = match checkpoints.resume {
Some(path) => Some(Checkpoint::read_from(path).map_err(|e| format!("{e:?}"))?),
None => None,
};
let mut write_checkpoint = |c: &Checkpoint| -> Result<(), DaeError> {
match checkpoints.out {
Some(path) => c.write_to(path),
None => Ok(()),
}
};
let mut block_names: Vec<String> = blocks.iter().map(|b| b.name.clone()).collect();
for block in blocks {
match &block.kind {
BlockKind::CScript { output_names, .. }
| BlockKind::PyBlock { output_names, .. }
| BlockKind::PyFunction { output_names, .. }
| BlockKind::OctFunc { output_names, .. }
| BlockKind::OctBlock { output_names, .. }
| BlockKind::CoordinateTransform { output_names, .. }
| BlockKind::Pmsm { output_names, .. }
| BlockKind::Pwm { output_names, .. }
| BlockKind::PhaseShiftPwm { output_names, .. } => {
block_names.extend(output_names.iter().skip(1).cloned());
}
_ => {}
}
}
let referenced = measure::referenced_signals(measurements);
let mut measured: BTreeMap<String, (Vec<f64>, Vec<f64>)> = referenced
.iter()
.map(|n| (n.clone(), (Vec::new(), Vec::new())))
.collect();
let mut referenced_index: Vec<(String, usize)> = Vec::new();
let mut headers: Option<Vec<String>> = None;
let stdout = io::stdout();
let mut csv_writer =
(output_format == OutputFormat::Csv).then(|| BufWriter::new(stdout.lock()));
let raw_tmp_path = raw_out_path.map(|p| p.with_extension("raw.tmp"));
let mut raw_tmp_writer = match &raw_tmp_path {
Some(p) => Some(BufWriter::new(fs::File::create(p).map_err(|e| {
format!("creating temporary raw output {}: {e}", p.display())
})?)),
None => None,
};
let mut n_points: usize = 0;
let mut n_resolved: usize = 0;
let mut engine = gsim_rules::RuleEngine::new(declared_rules, false);
let mut reporter = if engine.is_empty() {
None
} else {
Some(rules::Reporter::new(
Path::new(netlist_path),
gsim_rules::Severity::Warning,
event_paths,
)?)
};
let mut steps_seen: usize = 0;
let mut non_finite: Option<(String, usize, f64)> = None;
let final_checkpoint = simulate_transient_with_blocks_checkpointed(
netlist,
dialect,
diodes,
ideal_switches,
blocks,
gates,
shared_r_on,
None,
t_final,
step,
max_steps,
CheckpointControl {
resume: resume_from.as_ref(),
every: checkpoints.every,
on_checkpoint: checkpoints
.every
.map(|_| &mut write_checkpoint as &mut CheckpointSink<'_>),
final_snapshot: checkpoints.out.is_some(),
},
|t, point, outputs| {
if headers.is_none() {
let mut h = vec!["t".to_string()];
h.extend(point.unknowns.iter().cloned());
if !block_names.is_empty() {
h.extend(block_names.iter().flat_map(|name| {
match outputs.get(name) {
Some(dae_runtime::SignalValue::Vector(v)) => (0..v.len())
.map(|i| format!("{name}[{i}]"))
.collect::<Vec<_>>(),
_ => vec![name.clone()],
}
}));
}
referenced_index = referenced
.iter()
.filter_map(|name| {
h.iter()
.position(|c| c == name)
.map(|idx| (name.clone(), idx))
})
.collect();
if let Some(w) = &mut csv_writer {
writeln!(w, "{}", h.join(",")).map_err(|e| DaeError::Io(e.to_string()))?;
}
headers = Some(h);
}
let mut row = vec![t];
row.extend(point.x.iter().copied());
if !block_names.is_empty() {
row.extend(block_names.iter().flat_map(|name| match outputs.get(name) {
Some(dae_runtime::SignalValue::Scalar(x)) => vec![*x],
Some(dae_runtime::SignalValue::Vector(v)) => v.clone(),
None => vec![f64::NAN],
}));
}
for (name, idx) in &referenced_index {
if let Some((ts, vs)) = measured.get_mut(name) {
ts.push(t);
vs.push(row[*idx]);
}
}
if non_finite.is_none() {
let broken = finite::first_non_finite(&point)
.map(|(name, value)| (name.to_string(), value))
.or_else(|| finite::first_non_finite_output(&outputs));
if let Some((name, value)) = broken {
let record = finite::event(&name, value, steps_seen, t);
eprintln!("{}", record.console_line());
if let Some(reporter) = &mut reporter {
reporter.record(&record).map_err(DaeError::Io)?;
}
non_finite = Some((name, steps_seen, t));
}
}
if let Some(reporter) = &mut reporter {
let gate_states = rules::gate_states(gates, &outputs);
let sample = rules::StepSample {
point: &point,
outputs: &outputs,
gates: &gate_states,
ports: declared_ports,
switches: switch_channels,
diodes: diode_curves,
};
for event in engine.observe(steps_seen, t, &sample) {
reporter.record(&event).map_err(DaeError::Io)?;
}
steps_seen += 1;
}
let stop_now = engine.stop_requested().is_some() || non_finite.is_some();
let emit = n_resolved.is_multiple_of(out_every);
n_resolved += 1;
if !emit {
return if stop_now {
Err(DaeError::StopRequested)
} else {
Ok(())
};
}
if let Some(w) = &mut csv_writer {
let values: Vec<String> = row.iter().map(|v| v.to_string()).collect();
writeln!(w, "{}", values.join(",")).map_err(|e| DaeError::Io(e.to_string()))?;
}
if let Some(w) = &mut raw_tmp_writer {
raw_format::write_row(w, &row, row.len())
.map_err(|e| DaeError::Io(e.to_string()))?;
}
n_points += 1;
if stop_now {
return Err(DaeError::StopRequested);
}
Ok(())
},
)
.map_err(|e| format!("{e:?}"))?;
let stopped_by = engine.stop_requested().map(str::to_string);
if let Some(reporter) = &mut reporter {
let (tail, summaries) = engine.finish(steps_seen);
for event in &tail {
reporter.record(event)?;
}
reporter.finish(&summaries)?;
}
if let (Some(path), Some(final_checkpoint)) = (checkpoints.out, final_checkpoint) {
final_checkpoint
.write_to(path)
.map_err(|e| format!("{e:?}"))?;
}
if let Some(w) = &mut csv_writer {
w.flush()
.map_err(|e| format!("writing CSV to stdout: {e}"))?;
}
if let Some(tmp_path) = &raw_tmp_path {
drop(raw_tmp_writer);
let out_path = raw_out_path.expect("raw_out_path is Some when raw_tmp_path is Some");
let final_headers = headers.clone().unwrap_or_else(|| vec!["t".to_string()]);
let file = fs::File::create(out_path)
.map_err(|e| format!("creating raw output file {}: {e}", out_path.display()))?;
let mut writer = BufWriter::new(file);
raw_format::write_header(
&mut writer,
&final_headers,
n_points,
"Transient Analysis",
netlist_path,
)
.map_err(|e| format!("writing raw output file {}: {e}", out_path.display()))?;
if n_points > 0 {
let mut tmp_file = fs::File::open(tmp_path)
.map_err(|e| format!("reading temporary raw output {}: {e}", tmp_path.display()))?;
io::copy(&mut tmp_file, &mut writer).map_err(|e| {
format!(
"copying temporary raw output into {}: {e}",
out_path.display()
)
})?;
}
writer
.flush()
.map_err(|e| format!("writing raw output file {}: {e}", out_path.display()))?;
let _ = fs::remove_file(tmp_path);
}
if !measurements.is_empty() {
let names_in_order: Vec<String> = referenced_index.iter().map(|(n, _)| n.clone()).collect();
let series: Vec<&(Vec<f64>, Vec<f64>)> =
names_in_order.iter().map(|n| &measured[n]).collect();
let n_rows = series.first().map_or(0, |(ts, _)| ts.len());
let mut shadow_headers = vec!["t".to_string()];
shadow_headers.extend(names_in_order);
let mut shadow_rows = Vec::with_capacity(n_rows);
for i in 0..n_rows {
let mut row = Vec::with_capacity(shadow_headers.len());
row.push(series[0].0[i]);
row.extend(series.iter().map(|(_, vs)| vs[i]));
shadow_rows.push(row);
}
let shadow = Waveform {
headers: shadow_headers,
rows: shadow_rows,
};
write_measurements_log(measurements, &shadow, &default_log_path(netlist_path))?;
}
if let Some((name, step, when)) = non_finite {
eprintln!(
"abandoned at step {step} (t = {when:e} s): '{name}' is not a finite number. \
Nothing in the waveform after this point means anything."
);
return Ok(exit::NOT_FINITE);
}
if let Some(name) = stopped_by {
eprintln!("stopped by rule '{name}'");
return Ok(exit::STOPPED_BY_RULE);
}
match reporter.as_ref().and_then(|r| r.worst) {
Some(severity) if severity >= gsim_rules::Severity::Error => Ok(exit::RULE_ERROR),
_ => Ok(exit::OK),
}
}
fn print_csv(waveform: &Waveform) {
if waveform.rows.is_empty() {
return;
}
println!("{}", waveform.headers.join(","));
for row in &waveform.rows {
let values: Vec<String> = row.iter().map(|v| v.to_string()).collect();
println!("{}", values.join(","));
}
}
fn write_measurements_log(
measurements: &[measure::MeasureSpec],
waveform: &Waveform,
log_path: &Path,
) -> Result<(), String> {
let file = fs::File::create(log_path)
.map_err(|e| format!("creating measurement log {}: {e}", log_path.display()))?;
let mut writer = BufWriter::new(file);
let results = measure::evaluate_all(measurements, &waveform.headers, &waveform.rows);
for (name, result) in results {
match result {
Ok(values) => {
for (label, value) in values {
writeln!(writer, "{label} = {value}").map_err(|e| {
format!("writing measurement log {}: {e}", log_path.display())
})?;
}
}
Err(e) => writeln!(writer, "measurement '{name}' failed: {e}")
.map_err(|e| format!("writing measurement log {}: {e}", log_path.display()))?,
}
}
writer
.flush()
.map_err(|e| format!("writing measurement log {}: {e}", log_path.display()))
}
struct CheckpointArgs<'a> {
out: Option<&'a Path>,
every: Option<f64>,
resume: Option<&'a Path>,
}
fn version_line() -> String {
format!("general-simulator {}", env!("CARGO_PKG_VERSION"))
}
fn help() -> String {
format!(
"\
{version}
A piecewise-linear circuit and block-diagram simulator. Device segments are resolved as a
linear complementarity problem rather than by Newton-Raphson, so there is no voltage limiting.
USAGE
general-simulator <netlist> [OPTIONS]
<netlist> The .cir deck to run. Required, and positional: it comes
first. Device and block declarations may sit in the same
file or in a separate --devices file.
ANALYSIS
--mode dc|transient `dc` solves a single operating point; `transient` runs the
resolved timestep loop. [default: dc]
--tfinal T End time in seconds, under --mode transient. [default: 1.0]
TIME STEPPING Fixed or adaptive -- these two groups are mutually exclusive.
--dt DT Fix the step size. Deterministic and exactly reproducible;
the right choice while a deck is being developed.
--dt-max T Adaptive bounds, used when --dt is omitted.
--dt-min T
--dt-init T
--reltol R Adaptive local-truncation-error tolerances. --abstol has to
--abstol A match your own circuit's signal magnitudes: a value carried
over from a smaller circuit drives the step size into the
ground.
--max-steps N Cap on accepted adaptive steps, after which the run aborts
rather than growing its in-memory trace without limit.
Adaptive only. [default: 10000000]
OUTPUT
--format csv|raw `csv` prints to stdout; `raw` writes a binary SPICE rawfile,
which ngspice and PySpice read. [default: csv]
--out <path> Destination for --format raw. Ignored for csv, which always
goes to stdout -- redirect it.
--out-every N Write only every Nth resolved point. Thins the file, never
the computation: every step is still taken and kind=measure
still sees every point. [default: 1]
EVENTS
--events <path> Where the JSONL event stream goes.
[default: <netlist stem>.events.jsonl]
--events-text <path> Where its human-readable twin goes. Moves independently of
--events. [default: <netlist stem>.events.txt]
Both are written only for a netlist that declares rules.
CHECKPOINTS
--checkpoint-out <file> Write the run's complete state at --tfinal, so a later run
can --resume it and continue bit-identically.
--checkpoint-every T Also rewrite that file every T seconds of simulated time, so
a killed run loses at most T.
--resume <file> Continue from a checkpoint. --tfinal stays absolute, and a
checkpoint only loads into the deck it came from.
OTHER
--devices <file> Read PWL-device and block declarations from a second file
instead of the netlist itself.
-h, --help Print this help.
-V, --version Print the version.
EXAMPLES
general-simulator rc.cir --mode transient --tfinal 20e-3 --dt 10e-9 > out.csv
# A long switching run: compute every step, write a thousandth of them.
general-simulator conv.cir --mode transient --tfinal 20e-3 --dt 10e-9 --out-every 1000
# Same data as a binary rawfile instead of CSV.
general-simulator conv.cir --mode transient --tfinal 1e-3 --dt 1e-9 --format raw --out run.raw
NOTES
kind=measure lines write their results to <netlist stem>.log, whatever --format says.
kind=pyblock and kind=pyfunc need a `--features python` build of this binary.
Full documentation is in book/user-guide/ -- start with cli-reference.md and
time-stepping.md.",
version = version_line()
)
}
fn usage() -> String {
"usage: general-simulator <netlist> [--devices <file>] [--mode dc|transient] [--tfinal T] \
[--dt DT | --dt-max T --dt-min T --dt-init T --reltol R --abstol A] [--max-steps N] \
[--format csv|raw] [--out <path>] [--out-every N]\n\
[--events <path>] [--events-text <path>]\n\
[--checkpoint-out <file>] [--checkpoint-every T] [--resume <file>]\n\
\n\
--checkpoint-out writes the run's complete state at --tfinal (and, with --checkpoint-every T, \
every T seconds of simulated time, replacing the same file) so a later run can --resume it \
and continue to a larger --tfinal bit-identically to a run that never stopped. A checkpoint \
only loads into the deck it came from.\n\
\n\
--dt fixes the step size every step (deterministic, exactly reproducible). Omit it (and \
optionally tune --dt-max/--dt-min/--dt-init/--reltol/--abstol) for adaptive step-size \
control instead — small steps where the solution is changing fast, large steps where it's \
settled, the same local-truncation-error approach every real SPICE-family tool uses by \
default. --dt and any --dt-*/--reltol/--abstol flag are mutually exclusive.\n\
\n\
--max-steps N caps how many accepted TimeStep::Adaptive steps one run may take before \
aborting with an error, instead of running unboundedly (each accepted step holds its own \
row in memory for the rest of the run -- an adaptive step-size controller that's stalled, \
whether from a real bug or a pathological netlist/tolerance combination, would otherwise \
grow that memory without limit until the process, or the whole machine, runs out of it -- \
this happened on a real run before this flag existed). Defaults to 10,000,000, far above \
any legitimate run this project has needed; only relevant under adaptive stepping (--dt \
runs a fixed, precomputed number of steps and can't stall this way).\n\
\n\
--format selects the output serialization: 'csv' (the default, unchanged from before this \
flag existed) prints t,V(node1),V(node2),...,<block names> to stdout, one row per resolved \
point. 'raw' writes the same data as a binary SPICE rawfile instead (the format ngspice and \
the wider SPICE-tooling ecosystem, including Python readers such as PySpice, read and \
write) -- since a binary format has nowhere sensible to go on a terminal, this always \
writes to a file: --out <path> if given, otherwise <netlist stem>.raw next to the input \
file.\n\
\n\
--out-every N writes only every Nth resolved point (default 1, i.e. every point). It \
thins the output, never the computation: every step is still taken, the solution is \
unchanged, and kind=measure still sees every point -- only serialization is skipped. This \
exists because the timestep and the useful output rate can legitimately differ by orders \
of magnitude: verifying zero-voltage switching needs a step below r_on*C_oss (0.4 ps at \
1 mOhm and 400 pF), which is 3.75 M steps across a 150 ns commutation window, while the \
measurement itself needs a few thousand points. Without this flag that run is affordable \
to compute and not to write down.\n\
\n\
--events <path> and --events-text <path> say where the two event files go, instead of \
<netlist stem>.events.jsonl and <netlist stem>.events.txt beside the netlist. They move \
independently: a tool reads the JSONL and a person reads the text, and a caller that \
redirects one should not be handed the other somewhere it never looks. Both are created \
only for a netlist that declares rules, and a path that cannot be created is an error -- a \
diagnostics channel that vanishes without a word is the failure these flags exist to fix.\n\
\n\
Any kind=measure lines in the netlist write their results to <netlist stem>.log, regardless \
of --format -- see book/user-guide/src/measurements.md."
.to_string()
}