Package {spice}


Title: Circuit Simulation with a 'SPICE3f5'-Derived Engine
Version: 0.1.0
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.
License: BSD_3_clause + file LICENSE
URL: https://milkway.github.io/dune/r/, https://github.com/milkway/dune
BugReports: https://github.com/milkway/dune/issues
Encoding: UTF-8
RoxygenNote: 8.0.0
SystemRequirements: Cargo (Rust's package manager), rustc (>= 1.88.0)
Depends: R (≥ 4.2)
Imports: cli, rlang (≥ 1.1.0), tibble
Suggests: ggplot2, knitr, rmarkdown, testthat (≥ 3.0.0)
VignetteBuilder: knitr
Config/testthat/edition: 3
Config/rextendr/version: 0.5.0
NeedsCompilation: yes
Packaged: 2026-11-12 20:38:45 UTC; leite
Author: 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 <leite@castlab.org>
Repository: CRAN
Date/Publication: 2026-12-05 14:40:02 UTC

spice: Circuit Simulation with a SPICE3f5-Derived Engine

Description

Runs SPICE3 netlists (.op, .dc, .tran, .ac, .pz, .noise, .disto, .tf, .sens) on Dune, a circuit simulator written in Rust and derived from Berkeley SPICE3f5, and returns the results as tidy data.

Details

The main entry points are:

Author(s)

Maintainer: André Leite leite@castlab.org

Authors:

Other contributors:

See Also

Useful links:


Quick look at a plot with ggplot2

Description

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.

Usage

## S3 method for class 'spice_plot'
autoplot(object, ...)

Arguments

object

A spice_plot.

...

Unused.

Value

A ggplot object.

Examples


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]])


Change element values of a session

Description

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.

Usage

spice_alter(session, refdes, ...)

Arguments

session

A spice_session().

refdes

The element name, a string.

...

The new value(s): one unnamed number, or name = value pairs.

Details

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).

Value

session, invisibly (modified in place).

Errors

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.

Examples

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")

A knitr engine for SPICE3 decks

Description

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:

Details

```{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.

Chunk options

Errors

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.

Examples


# The engine knitr calls for a ```{spice} chunk:
"spice" %in% names(knitr::knit_engines$get())


Measure a simulated plot

Description

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.

Usage

spice_measure(plot, spec)

Arguments

plot

A spice_plot of a .tran, .ac, .dc or .sp analysis, from spice_run() or spice_read_raw().

spec

A character vector of measurements, e.g. "trig v(out) val=0.1 rise=1 targ v(out) val=0.9 rise=1", "when v(out)=0.5 cross=last", "max v(out) from=1n to=5n". Its names, when given, name the results; unnamed ones are called measure (or measure1, measure2, ... for several).

Details

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.

Value

A tibble with one row per measurement:

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.

Mirror of the Python package

This is spice.measure(); the deck's measurements are Result.measurements there.

See Also

spice_run() (its measurements field).

Examples

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 operating point as a named vector

Description

The values of a result's operating-point plot (.op), named by variable: node voltages and source currents.

Usage

spice_op(result, vars = NULL)

Arguments

result

A spice_result with an operating point.

vars

Optional: names of the variables to keep, as in spice_tidy(), in the order of the plot.

Value

A named double vector.

Examples

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)")

Read a session's element values

Description

spice_param() reads the current value of an alterable parameter (names and units as spice_alter()); spice_alterable() lists the parameters an element has.

Usage

spice_param(session, refdes, param = "")

spice_alterable(session, refdes)

Arguments

session

A spice_session().

refdes

The element name.

param

The parameter name; "" for the principal value.

Value

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.

Examples

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")

Extract the netlist of a pic figure

Description

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().

Usage

spice_pic(src, snap = NULL, includes = NULL)

Arguments

src

The figure: the path to a .pic file, or the figure text 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 spice_run().

snap

NULL (the default, 0.001 inch) or the distance, in pic inches, under which two terminals are the same point. A positive finite number.

includes

For a figure given as text only: the files its netlist's .include cards read, as in spice_run() – a named list (or named character vector) mapping the path written on the card to the file's text. A figure given as a path reads its .include files from disk, relative to the figure's own directory (as ⁠dune pic --run⁠ does), at extraction time, and must leave includes as NULL.

Details

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.

Value

A spice_pic: a list with

Errors

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.

Mirror of the Python package

This is spice.pic.extract() in Python; spice_run(spice_pic(...)) is spice.simulate(spice.pic.extract(...)).

See Also

spice_pic_svg() to draw the figure, spice_run() to simulate it.

Examples

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)

Draw a pic figure as SVG

Description

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.

Usage

spice_pic_svg(x)

spice_pic_texlabels()

Arguments

x

The figure: a spice_pic (its source is drawn), a path to a .pic file or the figure text, as in spice_pic().

Details

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.

Value

The SVG document, a single string.

spice_pic_texlabels(): TRUE when this build typesets ⁠$...$⁠ labels.

Errors

A figure rpic rejects is a spice_error_pic condition with its line and column, as for spice_pic().

Mirror of the Python package

This is spice.pic.render() in Python; spice_pic_texlabels() is spice.pic.TEXLABELS.

Examples

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()

Simulation plots

Description

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

Usage

## S3 method for class 'spice_plot'
as_tibble(x, ...)

Arguments

x

A spice_plot.

...

Unused.

Value

A tibble in the long format described above.

Long format

as_tibble() returns one row per point and non-scale variable, with the scale repeated on every row:

This is the long ("tidy") layout ggplot2 expects: ggplot(df, aes(scale, value, colour = variable)) + geom_line().

Examples

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

Description

Plots of a simulation result

Usage

spice_plots(result)

Arguments

result

A spice_result from spice_run() or spice_read_raw().

Value

A named list of spice_plot objects in rawfile order.

Examples

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))

Periodic steady state of a driven circuit or an oscillator

Description

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.

Usage

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
)

Arguments

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 spice_pic (the extraction of a pic figure, spice_pic()) runs as its netlist, with the .include files that came with the figure; one whose diagnostics include an error is refused (spice_error_pic).

freq

The fundamental in Hz; 0 (the default) takes it from the periodic sources – the greatest common divisor of their frequencies (SIN/SFFM with an explicit frequency, PULSE 1/PER).

tstab

Stabilization time (s): a plain transient runs to the first multiple of the period at or after tstab (at least one period) before the shooting starts there.

osc_node

NULL or ngspice's oscillation node. Required for an autonomous oscillator: its phase condition and period estimate (see Details). A driven circuit only checks that it exists.

points

Samples per period, 4 to 10 000 000: the time plot has points + 1 rows, and the period transient steps at most period / points.

harmonics

Rows of the spectrum, the DC included (ngspice's count), 1 to points %/% 2.

max_iter

Most shooting iterations (at least 1).

steady_coeff

Scale of the convergence tolerance, ⁠> 0⁠: 1 (the default) is the SPICE tolerances (reltol, vntol, abstol) on the period mismatch.

uic

Start the stabilization transient from the initial conditions, as ⁠.tran ... uic⁠.

includes

For a netlist given as text only: the files its .include cards may read, as a named list (or named character vector) mapping the path exactly as written on the card to the file's text. Nothing is read from disk for a text deck. A deck given as a path resolves .include on the file system, relative to the deck's own directory, and must leave includes as NULL; so must a spice_pic.

options

NULL or a named list of simulator options that override the deck's .options card, with the card's names and units (temperatures temp/tnom in degrees Celsius): reltol, abstol, vntol, gmin, itl1, itl2, itl4, gminsteps, srcsteps, temp, tnom, pivtol, pivrel, noopiter, trtol, chgtol, method ("trap", "gear" or "trbdf2"; unset, a .tran integrates with "trbdf2"), compat ("dune" or "spice3", the 'SPICE3f5' defaults: a trapezoidal .tran, switches flipping on the time grid, ltrabkrate 0), ltrabkrate, ltrafit, maxord, nopage, defl, defw, defad, defas, seed (the transient-noise seed, a whole number ⁠>= 1⁠; no "random"), notrnoise, devnoise, devnt (the device-noise grid step, seconds, ⁠> 0⁠), keepopinfo and trytocompact. The flags noopiter, nopage, ltrafit, notrnoise, devnoise and keepopinfo take TRUE/FALSE (FALSE clears a flag the deck's card set). Unlike a .options card, which only warns, an unknown name or a value of the wrong type is an error.

tmax_divisor

As in spice_run() (it divides the maximum step of the stabilization transient).

Details

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).

Value

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

Errors

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.

Mirror of the Python package

This is spice.pss(), whose PssConvergenceError is the spice_error_pss condition here.

See Also

spice_run() (a .pss card), spice_measure().

Examples

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$residuals

Read and write SPICE3 rawfiles

Description

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.

Usage

spice_read_raw(path)

spice_write_raw(x, path, format = c("binary", "ascii"))

Arguments

path

Path of the rawfile.

x

A spice_result or a spice_plot.

format

"binary" (the default, as spice3 -r writes) or "ascii".

Details

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.

Value

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.

Examples

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

Description

Run a session's analyses again

Usage

spice_rerun(session)

Arguments

session

A spice_session().

Value

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.

Errors

As spice_run(): an analysis failure is a spice_error_analysis.

Examples

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))
tau

Run a SPICE3 deck

Description

Parses a SPICE3 netlist, builds the circuit and runs every analysis card in deck order, exactly as spice3 -b (and dune -b) would.

Usage

spice_run(deck, includes = NULL, options = NULL, tmax_divisor = NULL)

Arguments

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 spice_pic (the extraction of a pic figure, spice_pic()) runs as its netlist, with the .include files that came with the figure; one whose diagnostics include an error is refused (spice_error_pic).

includes

For a netlist given as text only: the files its .include cards may read, as a named list (or named character vector) mapping the path exactly as written on the card to the file's text. Nothing is read from disk for a text deck. A deck given as a path resolves .include on the file system, relative to the deck's own directory, and must leave includes as NULL; so must a spice_pic.

options

NULL or a named list of simulator options that override the deck's .options card, with the card's names and units (temperatures temp/tnom in degrees Celsius): reltol, abstol, vntol, gmin, itl1, itl2, itl4, gminsteps, srcsteps, temp, tnom, pivtol, pivrel, noopiter, trtol, chgtol, method ("trap", "gear" or "trbdf2"; unset, a .tran integrates with "trbdf2"), compat ("dune" or "spice3", the 'SPICE3f5' defaults: a trapezoidal .tran, switches flipping on the time grid, ltrabkrate 0), ltrabkrate, ltrafit, maxord, nopage, defl, defw, defad, defas, seed (the transient-noise seed, a whole number ⁠>= 1⁠; no "random"), notrnoise, devnoise, devnt (the device-noise grid step, seconds, ⁠> 0⁠), keepopinfo and trytocompact. The flags noopiter, nopage, ltrafit, notrnoise, devnoise and keepopinfo take TRUE/FALSE (FALSE clears a flag the deck's card set). Unlike a .options card, which only warns, an unknown name or a value of the wrong type is an error.

tmax_divisor

NULL (the default) or a finite number ⁠>= 1⁠ that divides the maximum step of every .tran card – its TMAX argument, else the default min(TSTEP, (TSTOP - TSTART) / 50). The run is, bit for bit, that of the deck with the card's TMAX edited to TMAX / tmax_divisor; with options = list(trtol = 1) it gives the "fine steps" view of a waveform. It is an argument rather than an options name because TMAX is a parameter of the analysis card, not an engine option.

Value

A spice_result: a list with

Errors

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.

Mirror of the Python package

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.

See Also

spice_plots(), spice_tidy(), spice_write_raw().

Examples

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)

Keep a circuit alive to alter and re-run it

Description

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.

Usage

spice_session(
  deck,
  includes = NULL,
  options = NULL,
  warm_start = FALSE,
  tmax_divisor = NULL
)

Arguments

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 spice_pic (the extraction of a pic figure, spice_pic()) runs as its netlist, with the .include files that came with the figure; one whose diagnostics include an error is refused (spice_error_pic).

includes

For a netlist given as text only: the files its .include cards may read, as a named list (or named character vector) mapping the path exactly as written on the card to the file's text. Nothing is read from disk for a text deck. A deck given as a path resolves .include on the file system, relative to the deck's own directory, and must leave includes as NULL; so must a spice_pic.

options

NULL or a named list of simulator options that override the deck's .options card, with the card's names and units (temperatures temp/tnom in degrees Celsius): reltol, abstol, vntol, gmin, itl1, itl2, itl4, gminsteps, srcsteps, temp, tnom, pivtol, pivrel, noopiter, trtol, chgtol, method ("trap", "gear" or "trbdf2"; unset, a .tran integrates with "trbdf2"), compat ("dune" or "spice3", the 'SPICE3f5' defaults: a trapezoidal .tran, switches flipping on the time grid, ltrabkrate 0), ltrabkrate, ltrafit, maxord, nopage, defl, defw, defad, defas, seed (the transient-noise seed, a whole number ⁠>= 1⁠; no "random"), notrnoise, devnoise, devnt (the device-noise grid step, seconds, ⁠> 0⁠), keepopinfo and trytocompact. The flags noopiter, nopage, ltrafit, notrnoise, devnoise and keepopinfo take TRUE/FALSE (FALSE clears a flag the deck's card set). Unlike a .options card, which only warns, an unknown name or a value of the wrong type is an error.

warm_start

Continue each operating point from the previous run's (see Details).

tmax_divisor

NULL (the default) or a finite number ⁠>= 1⁠ that divides the maximum step of every .tran card – its TMAX argument, else the default min(TSTEP, (TSTOP - TSTART) / 50). The run is, bit for bit, that of the deck with the card's TMAX edited to TMAX / tmax_divisor; with options = list(trtol = 1) it gives the "fine steps" view of a waveform. It is an argument rather than an options name because TMAX is a parameter of the analysis card, not an engine option.

Details

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.

Value

A spice_session.

Mirror of the Python package

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.

See Also

spice_alter(), spice_rerun(), spice_param().

Examples

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)"]]

Set a session's circuit temperature

Description

The ⁠.options temp=⁠ of the deck, in degrees Celsius. Instance temp values (see spice_alter()) still win, as in SPICE3.

Usage

spice_set_temp(session, celsius)

spice_temp(session)

Arguments

session

A spice_session().

celsius

The temperature, degrees C.

Value

spice_set_temp(): session, invisibly (modified in place). spice_temp(): the temperature, degrees C.

Examples

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)

Set a session's transient step divisor

Description

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.

Usage

spice_set_tmax_divisor(session, tmax_divisor)

spice_tmax_divisor(session)

Arguments

session

A spice_session().

tmax_divisor

NULL or a finite number ⁠>= 1⁠.

Value

spice_set_tmax_divisor(): session, invisibly (modified in place). spice_tmax_divisor(): the divisor, or NULL.

Examples

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)

Run a deck over a set of parameter values (sweeps and Monte Carlo)

Description

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.

Usage

spice_sweep(
  deck,
  ...,
  .mode = c("grid", "zip"),
  .includes = NULL,
  .options = NULL,
  .threads = 1L,
  .tmax_divisor = NULL
)

Arguments

deck

The deck, as in spice_run().

...

Named numeric vectors: swept parameter = its values. A data frame or list of draws can be spliced with ⁠!!!⁠.

.mode

"grid" runs every combination, the first parameter varying slowest (as tidyr::expand_grid()); "zip" runs row by row and needs equal lengths (length-one values are recycled).

.includes, .options

As includes and options in spice_run(); the options apply to every run (a swept temp overrides options$temp).

.threads

Worker threads: 1 (the default) runs sequentially, 0 uses one per core, n uses n. Results are identical either way: every run is an independent circuit.

.tmax_divisor

As tmax_divisor in spice_run(), for every run.

Details

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().

Value

A spice_sweep: a list with

spice_tidy() turns it into one long tibble.

Parameter names

Matched case-insensitively:

Elements inside subcircuits go by their expanded names (r.x1.r1). Model parameters are not sweepable yet.

Errors

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.

Mirror of the Python package

This is the R face of spice.sweep() in Python. Run indices are 1-based here and 0-based in Python.

See Also

spice_tidy(), spice_run().

Examples

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$params

Results as one long tibble

Description

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.

Usage

spice_tidy(result, plots = NULL, vars = NULL)

Arguments

result

A spice_result, or a spice_sweep.

plots

Optional: labels, short names (see below) or indices of the plots to keep.

vars

Optional: names of the variables to keep.

Value

A tibble.

Selecting plots and variables

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)").

See Also

spice_wide() for one column per variable, spice_op() for the operating point as a named vector.

Examples

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)")

One plot with a column per variable

Description

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.

Usage

spice_wide(result, plot = NULL, vars = NULL)

Arguments

result

A spice_result, or a spice_plot.

plot

The plot: a label, short name (see spice_tidy()) or position. Optional when the result has a single plot.

vars

Optional: names of the variables to keep, as in spice_tidy().

Value

A tibble with nrow = the plot's points.

Examples

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)`