| Title: | Circuit Simulation with a 'SPICE3f5'-Derived Engine |
|---|---|
| Description: | Runs 'SPICE3' circuit netlists (operating point, DC sweep, transient, small-signal AC, pole-zero, noise, distortion, transfer function and sensitivity analyses) on 'Dune', a circuit simulator written in 'Rust' and derived from Berkeley 'SPICE3f5', validated against 'ngspice'. Results come back as long tibbles ready for plotting, and plots can be read from and written to 'SPICE3' rawfiles for exchange with other simulators. |
| Authors: | André Leite [aut, cre], The Regents of the University of California [cph] ('SPICE3f5', from which the simulation engine is derived), The authors of the dependency Rust crates [cph] (see inst/AUTHORS for details) |
| Maintainer: | André Leite <[email protected]> |
| License: | BSD_3_clause + file LICENSE |
| Version: | 0.1.0 |
| Built: | 2026-12-05 20:00:43 UTC |
| Source: | https://github.com/cran/spice |
Draws every non-scale variable of a plot against its scale, one
line per variable, faceted by type (voltages and currents get their
own panels). Complex plots show the magnitude in dB. Requires the
ggplot2 package; for anything more specific, start from
tibble::as_tibble() of the plot.
## S3 method for class 'spice_plot' autoplot(object, ...)## S3 method for class 'spice_plot' autoplot(object, ...)
object |
A |
... |
Unused. |
A ggplot object.
res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") ggplot2::autoplot(spice_plots(res)[[1]])res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") ggplot2::autoplot(spice_plots(res)[[1]])
The alter command of SPICE3, with ngspice's parameter names: an
unnamed value sets the element's principal value; named values set the
named parameters.
spice_alter(session, refdes, ...)spice_alter(session, refdes, ...)
session |
|
refdes |
The element name, a string. |
... |
The new value(s): one unnamed number, or |
| element | unnamed value | named parameters |
| R | resistance (nonzero) | resistance |
| C, L | capacitance, inductance | capacitance/inductance, ic |
| V, I | DC level | dc, acmag, acphase (degrees), and pulse, sin, exp, pwl, sffm (a numeric vector of the card's arguments; replaces the transient function) |
| E, F, G, H | gain | gain |
| M (every level, BSIM) | -- | w, l (meters); temp (degrees C, levels 1/2/3/6) |
| D, Q, J | area | area, temp (degrees C) |
| Z | area | area
|
The units are the card's. Element names are case-insensitive;
subcircuit elements go by their expanded name (r.x1.r1). The circuit
temperature is spice_set_temp().
A value equals the altered card when it is the same double: the card
parser is SPICE3's, which reads 10u as 10 * 1e-6
(9.999999999999999e-06, not 1e-05).
session, invisibly (modified in place).
A refused value – unknown element or parameter, non-finite value, zero
resistance, nonpositive w/l/area – is an error of class
spice_error_alter; the parameters before it in the same call stay
altered, the refused one and those after it do not.
s <- spice_session("amp vdd 1 0 dc 5 vin 2 0 dc 1.2 ac 1 rd 1 3 10k m1 3 2 0 0 nm l=2u w=10u .model nm nmos level=1 vto=0.7 kp=50u .op .end") s |> spice_alter("rd", 4.7e3) |> spice_alter("m1", w = 20e-6, l = 1e-6) |> spice_alter("vin", dc = 1.5) spice_param(s, "m1", "w")s <- spice_session("amp vdd 1 0 dc 5 vin 2 0 dc 1.2 ac 1 rd 1 3 10k m1 3 2 0 0 nm l=2u w=10u .model nm nmos level=1 vto=0.7 kp=50u .op .end") s |> spice_alter("rd", 4.7e3) |> spice_alter("m1", w = 20e-6, l = 1e-6) |> spice_alter("vin", dc = 1.5) spice_param(s, "m1", "w")
Loading spice registers a spice engine with knitr (when knitr is
installed), so an R Markdown or Quarto document can hold a deck in a
chunk of its own and plot the results in the R chunks that follow:
```{spice rc}
rc low-pass
vin 1 0 pulse(0 1)
r1 1 2 1k
c1 2 0 1u
.tran 0.1m 5m
.end
```
```{r}
ggplot2::autoplot(spice_plots(rc)[[1]])
```
The chunk body is the netlist, title line first, exactly as
spice_run() takes it as text (.include cards are not read from
disk; see spice.includes below). The engine runs it and assigns the
spice_result to a variable in the knitting environment.
echo: show the deck (default TRUE, as for any chunk).
spice.output (or output): what the chunk prints. "tidy"
(default) prints spice_tidy() of the result, as a tibble prints
(its first rows), followed by any notes and parser diagnostics;
"raw" prints the result itself (see spice_run(): the plots and
their sizes, notes and diagnostics). results = "hide" prints
nothing. output is read only when it is one of these two
strings, so Quarto's own output: false keeps its meaning.
spice.var: the name of the variable that receives the result.
Defaults to the chunk label; chunks without a label (knitr's
unnamed-chunk-N) assign nothing unless spice.var is given.
spice.var = FALSE assigns nothing. A label such as rc-tran is
used as is, and is then read back as `rc-tran`.
spice.options: a named list passed as options to spice_run().
spice.includes: a named list passed as includes to
spice_run().
A deck that fails to parse, build or simulate stops the knitting
with the spice_error of spice_run(), whose message carries the
file:line:col of the offending card (the chunk body is the file
deck.cir). With the chunk option error = TRUE (or 0) the
message is printed in the document instead and knitting goes on.
Note that knitr::knit() defaults to error = TRUE, while R
Markdown and Quarto default to error = FALSE.
# The engine knitr calls for a ```{spice} chunk: "spice" %in% names(knitr::knit_engines$get())# The engine knitr calls for a ```{spice} chunk: "spice" %in% names(knitr::knit_engines$get())
Scalar measurements of a plot with the .measure grammar of
ngspice-47 (SPICE3f5 has none): rise and fall times and delays
(TRIG ... TARG ...), level crossings (WHEN), values at a point
or at an event (FIND ... AT= / FIND ... WHEN), derivatives
(DERIV, a Dune extension), and window statistics (MIN, MAX,
MIN_AT, MAX_AT, PP, AVG, RMS, INTEG). The engine does
the measuring, exactly as for the deck's own .measure cards (which
spice_run() returns in $measurements); measurements read the
plot only and never change a simulation.
spice_measure(plot, spec)spice_measure(plot, spec)
plot |
A |
spec |
A character vector of measurements, e.g.
|
Each spec is what follows .meas <analysis> <name> on a card; the
analysis is the plot's own. Values take SPICE suffixes (2n, 1meg).
Crossings interpolate linearly between points; AVG integrates by
trapezoids over the window's points, RMS and INTEG by Simpson's
rules with the window edges interpolated, all as ngspice does.
A tibble with one row per measurement:
name (chr), analysis (chr: "tran", "ac", "dc", "sp")
and plot (chr: the plot's label);
value (dbl): the result – a time for WHEN and delays, a value
for FIND/MIN/AVG/..., the scale value for MIN_AT/MAX_AT;
NA when the measurement failed;
trig, targ, at, with, from, to (dbl): the extra
numbers ngspice prints beside the value (delay ends; where a
MIN/MAX occurs; the extremum of MIN_AT/MAX_AT; the window
of AVG/RMS/INTEG/PP), NA where they do not apply;
error (chr): why the measurement failed ("out of interval (WHEN)": the event never happens in the window), NA otherwise.
An event that never happens is a row with error set, not an R
error. A malformed spec is an error of class
spice_error_measure.
This is spice.measure(); the deck's measurements are
Result.measurements there.
spice_run() (its measurements field).
res <- spice_run("rc step v1 in 0 pulse(0 1 1n 1p 1p 20n 40n) r1 in out 1k c1 out 0 1p .tran 10p 10n .meas tran trise trig v(out) val=0.1 rise=1 targ v(out) val=0.9 rise=1 .end") res$measurements tran <- spice_plots(res)[["Transient Analysis"]] spice_measure(tran, c( t50 = "when v(out)=0.5", slope = "deriv v(out) at=2n", vmax = "max v(out)" ))res <- spice_run("rc step v1 in 0 pulse(0 1 1n 1p 1p 20n 40n) r1 in out 1k c1 out 0 1p .tran 10p 10n .meas tran trise trig v(out) val=0.1 rise=1 targ v(out) val=0.9 rise=1 .end") res$measurements tran <- spice_plots(res)[["Transient Analysis"]] spice_measure(tran, c( t50 = "when v(out)=0.5", slope = "deriv v(out) at=2n", vmax = "max v(out)" ))
The values of a result's operating-point plot (.op), named by
variable: node voltages and source currents.
spice_op(result, vars = NULL)spice_op(result, vars = NULL)
result |
A |
vars |
Optional: names of the variables to keep, as in
|
A named double vector.
res <- spice_run("divider\nv1 1 0 dc 10\nr1 1 2 1k\nr2 2 0 3k\n.op\n.end") spice_op(res) res |> spice_op("v(2)")res <- spice_run("divider\nv1 1 0 dc 10\nr1 1 2 1k\nr2 2 0 3k\n.op\n.end") spice_op(res) res |> spice_op("v(2)")
spice_param() reads the current value of an alterable parameter
(names and units as spice_alter()); spice_alterable() lists the
parameters an element has.
spice_param(session, refdes, param = "") spice_alterable(session, refdes)spice_param(session, refdes, param = "") spice_alterable(session, refdes)
session |
|
refdes |
The element name. |
param |
The parameter name; |
spice_param(): a number, a numeric vector (a source
function's arguments) or NULL for a value the element never got (a
MOS w left to .options defw, a source without AC).
spice_alterable(): a character vector.
s <- spice_session("t\nv1 1 0 dc 1 sin(0 1 1k)\nr1 1 0 1k\n.op\n.end") spice_param(s, "v1", "sin") spice_alterable(s, "v1")s <- spice_session("t\nv1 1 0 dc 1 sin(0 1 1k)\nr1 1 0 1k\n.op\n.end") spice_param(s, "v1", "sin") spice_alterable(s, "v1")
Compiles an rpic figure drawn
with the dune spice.pic prelude (resistor(), vsource(), npn(),
...; the figure opts in with spice = 1) and extracts its SPICE3
netlist: one card per labeled element (the label is the refdes),
nodes from the wires, ground blocks and named places, and the
figure's column-1 . lines as the deck's analysis and control cards.
The result runs directly: spice_pic("fig.pic") |> spice_run().
spice_pic(src, snap = NULL, includes = NULL)spice_pic(src, snap = NULL, includes = NULL)
src |
The figure: the path to a |
snap |
|
includes |
For a figure given as text only: the files its
netlist's |
Extraction problems in a figure that compiles – a dangling pin, a
floating net, an element without a value – are not errors here: the
netlist is still emitted and the problems are listed in
diagnostics. Running a figure whose diagnostics include an error
(with spice_run(), spice_session(), spice_sweep() or
spice_pss()) is refused with a spice_error_pic condition, as
dune pic --run refuses it.
A spice_pic: a list with
netlist: the SPICE3 netlist, one string ending in .end;
diagnostics: a tibble with one row per extraction problem:
severity ("error" or "warning"), kind ("dangling-pin",
"floating-net", "missing-value", "duplicate-refdes",
"unknown-element", "missing-pin", "unlabeled-element",
"node-name-conflict", "prelude"), message, and the span in
the figure: file (NA for the figure itself, "spice.pic" for
the prelude), 1-based line, column and an exclusive
end_column;
map: the overlay map from netlist names back to the drawing of
spice_pic_svg() (the SVG group <g id="sN"> is shape N):
elements: a tibble, one row per card in card order: refdes;
shape_start/shape_end, the half-open range of the element's
shape numbers, and ids, the same as "sN..sM"; principal,
the parameter spice_alter(s, refdes, value) changes (NA for
M, S, W, X, T, O, K); value, the value argument
verbatim as written in the figure, and its range value_line,
value_col, value_end_line, value_end_col (1-based, end
exclusive, columns in characters) – all NA when there is no
range an editor can trust (no value argument, a user wrapper
macro, a K);
pins: a tibble, one row per terminal in card order: refdes,
pin (the prelude's pin name, P, N, C, B, E, ...),
net (the node name on the card) and the point x, y in pic
inches;
params: a tibble of the alterable parameters spelled inside
each value (refdes, name as spice_alter() names it, text,
line, col, end_line, end_col);
nets: a tibble of the named nets (name, and shapes, a list
of the wire, dot and ground shape numbers of each);
canvas: the SVG frame, list(w, h, origin, rescale): the page
size in inches (the viewBox is 0 0 w*96 h*96) and the pic
origin; the point (x, y) is at SVG user units
((x + origin[1]) * 96, (h - (y + origin[2])) * 96);
includes: the .include files the netlist reads, as a named
character vector (path as written on the card = text);
source: the figure text;
path: the figure's path, or NA for figure text.
A figure that yields no netlist is signalled with cli::cli_abort()
as a condition of class spice_error_pic (and spice_error): rpic
rejected it (a syntax error, an unknown label, ...) or it is not
marked spice = 1. The message carries the figure's line:col; the
condition's fields line and column hold them (NA when there is
no position), and diagnostics holds the one diagnostic, of kind
"compile" or "not-marked". An unreadable figure file is a
spice_error_io, a bad snap a spice_error_input.
This is spice.pic.extract() in Python; spice_run(spice_pic(...))
is spice.simulate(spice.pic.extract(...)).
spice_pic_svg() to draw the figure, spice_run() to
simulate it.
fig <- ".PS spice = 1 In: (0,1); Out: (2,1) V1: vsource(In, (0,0), DC 5) R1: resistor(In, Out, 1k) C1: capacitor(Out, (2,0), 1u) line from C1.N to V1.N; ground(V1.N) .tran 10u 5m .PE" p <- spice_pic(fig) p cat(p$netlist) p$map$pins # The extraction runs as a deck res <- spice_run(p) tail(spice_plots(res)[[1]]$values[["v(out)"]], 1)fig <- ".PS spice = 1 In: (0,1); Out: (2,1) V1: vsource(In, (0,0), DC 5) R1: resistor(In, Out, 1k) C1: capacitor(Out, (2,0), 1u) line from C1.N to V1.N; ground(V1.N) .tran 10u 5m .PE" p <- spice_pic(fig) p cat(p$netlist) p$map$pins # The extraction runs as a deck res <- spice_run(p) tail(spice_plots(res)[[1]]$values[["v(out)"]], 1)
Compiles a figure with the dune spice.pic prelude, as spice_pic()
does, and renders it to SVG: the drawing whose shape numbers
spice_pic()'s overlay map refers to. A figure need not be marked
spice = 1 to be drawn, and a figure whose extraction has errors still
draws.
spice_pic_svg(x) spice_pic_texlabels()spice_pic_svg(x) spice_pic_texlabels()
x |
The figure: a |
Labels written entirely in $...$ ("$T_1$", "$V_{CC}$") are
typeset as math when the figure turns on rpic's texlabels = 1 and the
package was built with its texlabels feature (the default; check with
spice_pic_texlabels()); otherwise they stay literal. Typesetting never
changes the netlist.
The SVG document, a single string.
spice_pic_texlabels(): TRUE when this build typesets
$...$ labels.
A figure rpic rejects is a spice_error_pic condition with its
line and column, as for spice_pic().
This is spice.pic.render() in Python; spice_pic_texlabels() is
spice.pic.TEXLABELS.
fig <- '.PS spice = 1 texlabels = 1 V1: vsource((0,1), (0,0), DC 5, "$V_1$") R1: resistor((0,1), (1.5,1), 1k) line from R1.N to (1.5,0) then to V1.N; ground(V1.N) .op .PE' svg <- spice_pic_svg(fig) substr(svg, 1, 60) spice_pic_texlabels()fig <- '.PS spice = 1 texlabels = 1 V1: vsource((0,1), (0,0), DC 5, "$V_1$") R1: resistor((0,1), (1.5,1), 1k) line from R1.N to (1.5,0) then to V1.N; ground(V1.N) .op .PE' svg <- spice_pic_svg(fig) substr(svg, 1, 60) spice_pic_texlabels()
A spice_plot is one rawfile plot: a set of named vectors of the
same length (one per circuit variable) sharing a scale (time,
frequency, the swept source of a .dc, ...). It is a list with
label: the plot's name within its result (see spice_run());
plotname, title, date: the rawfile header fields;
scale: the name of the scale vector, or NA for plots without
one (operating point, .tf, .pz, DC .sens, integrated noise);
variables: a tibble with the name and type ("voltage",
"current", "time", "frequency", ...) of every vector;
values: a named list of the vectors, double for real plots and
complex for complex ones (.ac, .pz, AC .sens, .disto);
padded, commands, options, dimensions: the remaining
rawfile header fields, kept so a plot writes back unchanged.
## S3 method for class 'spice_plot' as_tibble(x, ...)## S3 method for class 'spice_plot' as_tibble(x, ...)
x |
A |
... |
Unused. |
A tibble in the long format described above.
as_tibble() returns one row per point and non-scale variable, with
the scale repeated on every row:
plot (chr): the plot's label;
point (int): the point index, from 1;
scale_name (chr) and scale (dbl): the scale vector's name and
value at that point (NA for plots without a scale; the real part
of the scale for complex plots, whose scale is real by
construction);
variable (chr) and type (chr): the vector's name and type;
for real plots, value (dbl);
for complex plots, instead of value: re and im (dbl), and
derived from them mag (the modulus), db (20 * log10(mag))
and phase (the argument, in degrees).
This is the long ("tidy") layout ggplot2 expects:
ggplot(df, aes(scale, value, colour = variable)) + geom_line().
res <- spice_run("rc\nvin 1 0 dc 0 ac 1\nr1 1 2 1k\nc1 2 0 1u\n.ac dec 5 10 10k\n.end") ac <- spice_plots(res)[[1]] ac tibble::as_tibble(ac)res <- spice_run("rc\nvin 1 0 dc 0 ac 1\nr1 1 2 1k\nc1 2 0 1u\n.ac dec 5 10 10k\n.end") ac <- spice_plots(res)[[1]] ac tibble::as_tibble(ac)
Plots of a simulation result
spice_plots(result)spice_plots(result)
result |
A |
A named list of spice_plot objects in rawfile order.
res <- spice_run("divider\nv1 1 0 dc 2\nr1 1 2 1k\nr2 2 0 1k\n.op\n.dc v1 0 2 1\n.end") names(spice_plots(res))res <- spice_run("divider\nv1 1 0 dc 2\nr1 1 2 1k\nr2 2 0 1k\n.op\n.dc v1 0 2 1\n.end") names(spice_plots(res))
Runs the periodic steady state (.pss) of the circuit in deck, by
shooting–Newton: Newton on the period map x(t0) -> x(t0 + T) with
matrix-free GMRES, the Jacobian products by directional differences
over a frozen-grid replay of the period transient. A linear circuit
converges in one Newton step. The arguments are those of the card
.pss FREQ TSTAB OSCNODE POINTS HARMS SCITER STEADYCOEFF UIC, and
the plots are, value for value, what that card gives in
spice_run() – the same engine call. The deck supplies the circuit
and its .options; its own analysis cards are not run.
spice_pss( deck, freq = 0, tstab = 0, osc_node = NULL, points = 128L, harmonics = 10L, max_iter = 50L, steady_coeff = 1, uic = FALSE, includes = NULL, options = NULL, tmax_divisor = NULL )spice_pss( deck, freq = 0, tstab = 0, osc_node = NULL, points = 128L, harmonics = 10L, max_iter = 50L, steady_coeff = 1, uic = FALSE, includes = NULL, options = NULL, tmax_divisor = NULL )
deck |
Either the path to a deck file, or the netlist itself as
a character vector: a single string containing newlines, or one
element per line. A length-one string without a newline is taken
as a path. As in SPICE3, the first line of a netlist is its title.
A |
freq |
The fundamental in Hz; |
tstab |
Stabilization time (s): a plain transient runs to the
first multiple of the period at or after |
osc_node |
|
points |
Samples per period, 4 to 10 000 000: the time plot has
|
harmonics |
Rows of the spectrum, the DC included (ngspice's
count), 1 to |
max_iter |
Most shooting iterations (at least 1). |
steady_coeff |
Scale of the convergence tolerance, |
uic |
Start the stabilization transient from the initial
conditions, as |
includes |
For a netlist given as text only: the files its
|
options |
|
tmax_divisor |
As in |
The method is Dune's: ngspice-47's .pss is a free-running
oscillator search that detunes from a driving source. points is the
accuracy knob: the error left is the integrator's phase error,
(2 * pi / points)^2 / 12 of the amplitude with the trapezoidal
rule (method = "trap", or compat = "spice3") and about half of
that with the default, TR-BDF2.
A circuit without a periodic source (freq = 0 finds none) is an
autonomous oscillator: the period becomes a Newton unknown, with the
phase pinned where v(osc_node) rises through its mid-range, and is
first estimated by counting the crossings of osc_node over the
second half of tstab (both are required then; a freq given is
only a fallback for fewer than three crossings). The deck must start
the oscillation itself (.ic with uic = TRUE, or a ramp): there is
no automatic kick. The result's periods follows the period per
iteration. A deck with a transient-noise source or with devnoise
on is refused: a random stimulus has no periodic steady state.
Transmission lines take part: the lossless ones (T, and
O in its LC regime) as they are, the lossy RLC/RC lines of O with
options = list(ltrafit = TRUE).
A spice_pss, which is also a spice_result (so
spice_plots(), spice_tidy() and spice_measure() on its plots
work as for spice_run()): a list with
title, notes, diagnostics, measurements (always zero rows:
a deck's .measure cards do not apply to .pss plots) and
plots – the two spice_plots, "Time Domain Periodic Steady State Analysis" and "Frequency Domain Periodic Steady State Analysis" (ngspice's plot names) – as in spice_run();
time: one period as a long tibble, points + 1 equispaced
instants from t0 to t0 + period per variable: time,
variable, type ("voltage", "current"), value;
spectrum: the complex harmonics as a long tibble: harmonic
(int, 0 is the DC), frequency, variable, type, re, im
and the derived mag (Mod()) and phase (Arg(), radians).
The convention is .ac's phasor: x(t) = X_0 + sum Re(X_k exp(1i * k * w * t)), phases referred to t = 0; mag is
ngspice's (magnitude-only) plot;
period (s: the drive's for a driven circuit, the shooting's
result for an oscillator), t0 (s, the start of the reported
period), residuals: the period mismatch
max_i |x_i(t0+T) - x_i(t0)| / tol_i of each shooting iteration
(the last one <= steady_coeff; Inf for an iteration whose
transient failed), and periods: the period of each iteration
(constant for a driven circuit, the Newton iterate of an
oscillator; the last one is period).
As spice_run(); a shooting that does not converge in max_iter
iterations is a condition of class spice_error_pss (and
spice_error) whose fields iterations (int) and residuals (dbl)
hold the history, and period (dbl) the last period iterate of an
oscillator (NULL for a driven circuit) – the same condition a
.pss card raises from spice_run(), spice_rerun() and a run of
spice_sweep(). Other failures (an unknown osc_node, an
oscillator without osc_node or tstab, a shooting that settles
on the equilibrium, a transmission line) are spice_error_analysis;
an argument out of range is spice_error_input.
This is spice.pss(), whose PssConvergenceError is the
spice_error_pss condition here.
spice_run() (a .pss card), spice_measure().
rc <- "rc low-pass v1 1 0 sin(0 1 1k) r1 1 2 1k c1 2 0 1u .end" res <- spice_pss(rc, freq = 1e3, tstab = 2e-3) res res$period # First harmonic of v(2): |H| = 1 / sqrt(1 + (2 * pi)^2) subset(res$spectrum, variable == "v(2)" & harmonic == 1) # The period measures as a transient spice_measure(res$plots[[1]], "pp v(2)") # A shooting cut short keeps its history on the condition e <- tryCatch(spice_pss(rc, freq = 1e3, max_iter = 1), spice_error_pss = identity) e$residualsrc <- "rc low-pass v1 1 0 sin(0 1 1k) r1 1 2 1k c1 2 0 1u .end" res <- spice_pss(rc, freq = 1e3, tstab = 2e-3) res res$period # First harmonic of v(2): |H| = 1 / sqrt(1 + (2 * pi)^2) subset(res$spectrum, variable == "v(2)" & harmonic == 1) # The period measures as a transient spice_measure(res$plots[[1]], "pp v(2)") # A shooting cut short keeps its history on the condition e <- tryCatch(spice_pss(rc, freq = 1e3, max_iter = 1), spice_error_pss = identity) e$residuals
spice_read_raw() reads a SPICE3 rawfile (ASCII or binary, as
written by spice3 -r, ngspice -r or spice_write_raw()) into a
spice_result. spice_write_raw() writes a result's plots, or a
single plot, back to back as the SPICE3 raw_write does.
spice_read_raw(path) spice_write_raw(x, path, format = c("binary", "ascii"))spice_read_raw(path) spice_write_raw(x, path, format = c("binary", "ascii"))
path |
Path of the rawfile. |
x |
A |
format |
|
A rawfile does not record which vector is the scale: like the 3f5
reader, spice_read_raw() takes the first vector of each plot as
its scale, so an operating-point plot read back has its first
variable as scale while the one from spice_run() has none. All
else (names, types, values, header fields) round-trips exactly
through the binary format; the ASCII format keeps 15 significant
digits, like SPICE3.
spice_read_raw(): a spice_result whose notes hold the
reader's warnings and whose title is the first plot's title.
spice_write_raw(): path, invisibly.
res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") f <- tempfile(fileext = ".raw") spice_write_raw(res, f) spice_read_raw(f)res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") f <- tempfile(fileext = ".raw") spice_write_raw(res, f) spice_read_raw(f)
Run a session's analyses again
spice_rerun(session)spice_rerun(session)
session |
A spice_result, as from spice_run() – the deck's
.measure cards evaluated on the new plots included: with
warm_start = FALSE, the result spice_run() gives for the altered
deck.
As spice_run(): an analysis failure is a spice_error_analysis.
s <- spice_session("rc\nv1 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") tau <- vapply(c(1e3, 2e3), function(r) { tr <- spice_plots(spice_rerun(spice_alter(s, "r1", r)))[[1]]$values tr$time[which.max(tr[["v(2)"]] > 1 - exp(-1))] }, numeric(1)) taus <- spice_session("rc\nv1 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") tau <- vapply(c(1e3, 2e3), function(r) { tr <- spice_plots(spice_rerun(spice_alter(s, "r1", r)))[[1]]$values tr$time[which.max(tr[["v(2)"]] > 1 - exp(-1))] }, numeric(1)) tau
Parses a SPICE3 netlist, builds the circuit and runs every analysis
card in deck order, exactly as spice3 -b (and dune -b) would.
spice_run(deck, includes = NULL, options = NULL, tmax_divisor = NULL)spice_run(deck, includes = NULL, options = NULL, tmax_divisor = NULL)
deck |
Either the path to a deck file, or the netlist itself as
a character vector: a single string containing newlines, or one
element per line. A length-one string without a newline is taken
as a path. As in SPICE3, the first line of a netlist is its title.
A |
includes |
For a netlist given as text only: the files its
|
options |
|
tmax_divisor |
|
A spice_result: a list with
title: the deck's title line;
plots: a named list of spice_plot objects, one per rawfile
plot, in the order spice3 -b -r writes them (one for most
analyses; .noise adds an integrated-noise plot when the band has
more than one frequency; .disto gives two or three). Names are
the plot names ("Transient Analysis", ...) made unique with
make.unique() when an analysis appears twice;
notes: non-fatal remarks from the engine;
diagnostics: a tibble (severity, message) of the parser's
warnings, each message prefixed with its file:line:col;
measurements: the deck's .measure cards (ngspice grammar),
each evaluated on every plot of its analysis, as the tibble
spice_measure() returns (zero rows without .measure cards).
Failed measurements are rows with error set.
Failures are signalled with cli::cli_abort() as conditions of class
spice_error_<kind> and spice_error, where kind is the stage
that failed: "options", "io" (unreadable deck file), "parse",
"elaborate" (building the circuit), "analysis" or "pss" (a
.pss card whose shooting did not converge; see spice_pss() for
the condition's iterations and residuals fields) (and, from
spice_alter(), "alter"; for a spice_pic with extraction errors,
"pic"). Parse errors
carry the file:line:col of the offending card in the message; the
condition's diagnostics field holds every diagnostic seen so far.
This is the R face of spice.simulate() in the Python package of
the same name. Both run the same engine with the same semantics;
the R side returns S3 objects and long tibbles where Python returns
polars frames.
A long simulation cannot be interrupted from R: the call returns when the engine finishes.
spice_plots(), spice_tidy(), spice_write_raw().
deck <- "rc low-pass vin 1 0 pulse(0 1) r1 1 2 1k c1 2 0 1u .tran 0.1m 5m .end" res <- spice_run(deck) res head(spice_tidy(res)) # Options override the deck's .options card spice_run(deck, options = list(reltol = 1e-4, method = "gear")) # Finer transient steps: trtol = 1 and a tenth of the maximum step spice_run(deck, options = list(trtol = 1), tmax_divisor = 10)deck <- "rc low-pass vin 1 0 pulse(0 1) r1 1 2 1k c1 2 0 1u .tran 0.1m 5m .end" res <- spice_run(deck) res head(spice_tidy(res)) # Options override the deck's .options card spice_run(deck, options = list(reltol = 1e-4, method = "gear")) # Finer transient steps: trtol = 1 and a tenth of the maximum step spice_run(deck, options = list(trtol = 1), tmax_divisor = 10)
spice_session() parses and builds a deck once; spice_alter() then
changes element values in place and spice_rerun() runs every analysis
card again without re-parsing – for interactive exploration and for
fitting loops that evaluate the same circuit many times.
spice_session( deck, includes = NULL, options = NULL, warm_start = FALSE, tmax_divisor = NULL )spice_session( deck, includes = NULL, options = NULL, warm_start = FALSE, tmax_divisor = NULL )
deck |
Either the path to a deck file, or the netlist itself as
a character vector: a single string containing newlines, or one
element per line. A length-one string without a newline is taken
as a path. As in SPICE3, the first line of a netlist is its title.
A |
includes |
For a netlist given as text only: the files its
|
options |
|
warm_start |
Continue each operating point from the previous run's (see Details). |
tmax_divisor |
|
With warm_start = FALSE (the default), spice_rerun() returns exactly
what spice_run() returns for the altered deck: the same plots, value
for value, and the same notes and diagnostics. With warm_start = TRUE
each operating point (.op, and the bias point of .ac, .noise,
.tf, .sens, .pz, .disto) continues from the previous one: faster
for nonlinear circuits, and equal to a fresh run to the Newton
tolerances (reltol, vntol, abstol) rather than bit for bit.
Transient operating points and decks with .nodeset are never
warm-started.
A session is a reference object: spice_alter(),
spice_set_temp() and spice_set_tmax_divisor() modify it in place (every copy of it sees the
change) and return it invisibly, so calls can be piped.
A spice_session.
This is spice.Session in Python: spice_alter() is Session.alter(),
spice_rerun() is Session.run(), spice_set_temp() sets
Session.temp, spice_set_tmax_divisor() sets Session.tmax_divisor.
spice_alter(), spice_rerun(), spice_param().
s <- spice_session("divider v1 1 0 dc 10 r1 1 2 1k r2 2 0 1k .op .end") spice_plots(spice_rerun(s))[[1]]$values[["v(2)"]] s |> spice_alter("r2", 3e3) spice_plots(spice_rerun(s))[[1]]$values[["v(2)"]]s <- spice_session("divider v1 1 0 dc 10 r1 1 2 1k r2 2 0 1k .op .end") spice_plots(spice_rerun(s))[[1]]$values[["v(2)"]] s |> spice_alter("r2", 3e3) spice_plots(spice_rerun(s))[[1]]$values[["v(2)"]]
The .options temp= of the deck, in degrees Celsius. Instance temp
values (see spice_alter()) still win, as in SPICE3.
spice_set_temp(session, celsius) spice_temp(session)spice_set_temp(session, celsius) spice_temp(session)
session |
|
celsius |
The temperature, degrees C. |
spice_set_temp(): session, invisibly (modified in place).
spice_temp(): the temperature, degrees C.
s <- spice_session("t\nv1 1 0 dc 1\nd1 1 0 dm\n.model dm d\n.op\n.end") spice_set_temp(s, 85) spice_temp(s)s <- spice_session("t\nv1 1 0 dc 1\nd1 1 0 dm\n.model dm d\n.op\n.end") spice_set_temp(s, 85) spice_temp(s)
The tmax_divisor of spice_run() on a live session: from the next
spice_rerun() on, every .tran card runs with its maximum step
divided by tmax_divisor (NULL restores the cards' own), without
re-building the circuit – a "fine steps" toggle.
spice_set_tmax_divisor(session, tmax_divisor) spice_tmax_divisor(session)spice_set_tmax_divisor(session, tmax_divisor) spice_tmax_divisor(session)
session |
|
tmax_divisor |
|
spice_set_tmax_divisor(): session, invisibly (modified in
place). spice_tmax_divisor(): the divisor, or NULL.
s <- spice_session("rc\nv1 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") nrow(spice_tidy(spice_rerun(s))) spice_set_tmax_divisor(s, 10) nrow(spice_tidy(spice_rerun(s))) spice_tmax_divisor(s)s <- spice_session("rc\nv1 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") nrow(spice_tidy(spice_rerun(s))) spice_set_tmax_divisor(s, 10) nrow(spice_tidy(spice_rerun(s))) spice_tmax_divisor(s)
Runs a SPICE3 deck once per assignment of the swept parameters. The
deck stays pure SPICE3 (there is no .step card): it is parsed once,
and each run writes its values into the parsed deck, builds the
circuit afresh and runs every analysis card, exactly as spice_run()
would on the deck edited by hand – bit for bit.
spice_sweep( deck, ..., .mode = c("grid", "zip"), .includes = NULL, .options = NULL, .threads = 1L, .tmax_divisor = NULL )spice_sweep( deck, ..., .mode = c("grid", "zip"), .includes = NULL, .options = NULL, .threads = 1L, .tmax_divisor = NULL )
deck |
The deck, as in |
... |
Named numeric vectors: swept parameter = its values. A
data frame or list of draws can be spliced with |
.mode |
|
.includes, .options
|
As |
.threads |
Worker threads: |
.tmax_divisor |
As |
The simulator holds no random generator: a Monte Carlo is a "zip"
sweep over draws you make with stats::rnorm() and friends, so it is
reproducible from your own set.seed().
A spice_sweep: a list with
title: the deck's title line;
params: a tibble with run (the run index, from 1) and one
double column per swept parameter, named in canonical form
("r1", "@m1[w]", "temp");
runs: a list of spice_result, one per run (each with the
deck's .measure cards evaluated in its measurements);
diagnostics: the deck's parser warnings, as in spice_run().
spice_tidy() turns it into one long tibble.
Matched case-insensitively:
temp: circuit temperature in degrees Celsius (as .options temp=);
an element name: r1, c1, l1 for its value, vin, iin for a
source's DC level;
the ngspice form @name[param]: @r1[resistance],
@c1[capacitance], @l1[inductance], @vin[dc], @vin[acmag],
@vin[acphase] (degrees), @m1[w], @m1[l] (MOSFET width and
length, m). Non-syntactic names need backticks:
spice_sweep(deck, `@m1[w]` = c(2e-6, 4e-6)).
Elements inside subcircuits go by their expanded names (r.x1.r1).
Model parameters are not sweepable yet.
An unknown element or parameter, a parameter given twice or a
non-finite value is a spice_error_sweep. A run that fails to build
or simulate stops the sweep with the error class of spice_run()
(spice_error_elaborate, spice_error_analysis, or
spice_error_pss with the shooting history for a .pss that did
not converge), naming the run and its values.
This is the R face of spice.sweep() in Python. Run indices are
1-based here and 0-based in Python.
deck <- "rc low-pass vin 1 0 dc 0 ac 1 r1 1 2 1k c1 2 0 1u .ac dec 5 10 10k .end" sw <- spice_sweep(deck, r1 = c(500, 1000, 2000)) sw head(spice_tidy(sw)) # Monte Carlo: 5% resistor and capacitor, reproducible from the seed set.seed(1) mc <- spice_sweep(deck, r1 = rnorm(20, 1000, 50), c1 = rnorm(20, 1e-6, 5e-8), .mode = "zip" ) mc$paramsdeck <- "rc low-pass vin 1 0 dc 0 ac 1 r1 1 2 1k c1 2 0 1u .ac dec 5 10 10k .end" sw <- spice_sweep(deck, r1 = c(500, 1000, 2000)) sw head(spice_tidy(sw)) # Monte Carlo: 5% resistor and capacitor, reproducible from the seed set.seed(1) mc <- spice_sweep(deck, r1 = rnorm(20, 1000, 50), c1 = rnorm(20, 1e-6, 5e-8), .mode = "zip" ) mc$params
Binds tibble::as_tibble() of every plot of a result. For a
spice_sweep from spice_sweep(), binds the tidy tibble of every
run, with the sweep's run index and swept parameters as the first
columns (one column per parameter, constant within a run): group by
run for one curve per run. When the
result mixes real and complex plots (e.g. a deck with .tran and
.ac), the tibble has value and the complex columns (re, im,
mag, db, phase), with NA where a column does not apply;
otherwise only the columns of its kind. See spice_plot for the
columns.
spice_tidy(result, plots = NULL, vars = NULL)spice_tidy(result, plots = NULL, vars = NULL)
result |
A |
plots |
Optional: labels, short names (see below) or indices of the plots to keep. |
vars |
Optional: names of the variables to keep. |
A tibble.
plots takes the labels of spice_plots(), their positions, or a
short name of the analysis, which selects every plot of that kind:
| short name | plot |
"op" |
Operating Point |
"dc" |
DC transfer characteristic |
"tran" |
Transient Analysis |
"ac" |
AC Analysis |
"noise" |
Noise Spectral Density Curves |
"inoise" |
Integrated Noise |
"tf" |
Transfer Function |
"pz" |
Pole-Zero Analysis |
"sens" |
Sensitivity Analysis |
"sp" |
SP Analysis |
"pss" |
Time Domain Periodic Steady State Analysis |
"pss_spectrum" |
Frequency Domain Periodic Steady State Analysis |
vars keeps the named variables, matched without regard to case; a
bare node name stands for its voltage ("out" is "v(out)").
spice_wide() for one column per variable, spice_op()
for the operating point as a named vector.
res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") spice_tidy(res) res |> spice_tidy("tran", "v(2)")res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") spice_tidy(res) res |> spice_tidy("tran", "v(2)")
The wide layout: one row per point, the plot's scale first (time,
frequency, the swept source, ...) and then one column per
variable, named as the variable. Columns of a complex plot (.ac)
are complex vectors, so Mod(), Arg() and arithmetic between
signals work directly. Use it when the computation is across
variables (`v(out)` - `v(in)`); spice_tidy() is the layout
'ggplot2' wants.
spice_wide(result, plot = NULL, vars = NULL)spice_wide(result, plot = NULL, vars = NULL)
result |
A |
plot |
The plot: a label, short name (see |
vars |
Optional: names of the variables to keep, as in
|
A tibble with nrow = the plot's points.
res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") w <- res |> spice_wide("tran") w # The voltage across r1 w$`v(1)` - w$`v(2)`res <- spice_run("rc\nvin 1 0 pulse(0 1)\nr1 1 2 1k\nc1 2 0 1u\n.tran 0.1m 5m\n.end") w <- res |> spice_wide("tran") w # The voltage across r1 w$`v(1)` - w$`v(2)`