## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
has_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)

## ----setup--------------------------------------------------------------------
library(spice)

## ----deck---------------------------------------------------------------------
deck <- "RLC low-pass
vin in 0 pulse(0 1 0 1u) ac 1
r1 in mid 50
l1 mid out 1m
c1 out 0 1u
.tran 2u 1m
.ac dec 50 100 100k
.end"

## ----run----------------------------------------------------------------------
res <- spice_run(deck)
res

## ----options------------------------------------------------------------------
tight <- spice_run(deck, options = list(reltol = 1e-5, method = "gear"))

## ----tidy---------------------------------------------------------------------
tran <- spice_tidy(res, "tran")
tran

## ----ac-----------------------------------------------------------------------
ac <- res |> spice_tidy("ac", "out")
ac[, c("scale", "db", "phase")]

## ----wide---------------------------------------------------------------------
w <- res |> spice_wide("tran")
w
# The largest voltage across the inductor
max(abs(w$`v(mid)` - w$`v(out)`))

## ----plot, eval = has_ggplot2, fig.width = 6.5, fig.height = 3.5--------------
library(ggplot2)
volts <- res |> spice_tidy("tran", c("in", "out"))
ggplot(volts, aes(scale * 1e3, value, colour = variable)) +
  geom_line() +
  labs(x = "time (ms)", y = "voltage (V)", colour = NULL,
       title = "Step response of the RLC low-pass")

## ----autoplot, eval = has_ggplot2, fig.width = 6.5, fig.height = 3.5----------
autoplot(spice_plots(res)[["AC Analysis"]])

## ----divider-plot, eval = has_ggplot2, fig.width = 6.5, fig.height = 3--------
autoplot(spice_plots(divider)[[1]])

## ----pic----------------------------------------------------------------------
fig <- ".PS
spice = 1
In: (0,1); Out: (2,1)
V1: vsource(In, (0,0), DC 5)
R1: resistor(In, Out, 1k)
R2: resistor(Out, (2,0), 3k)
line from R2.N to V1.N; ground(V1.N)
.op
.PE"
p <- spice_pic(fig)
cat(p$netlist)
spice_run(p) |> spice_op("out")
p$map$pins

## ----raw----------------------------------------------------------------------
f <- tempfile(fileext = ".raw")
spice_write_raw(res, f)
back <- spice_read_raw(f)
identical(spice_tidy(back), spice_tidy(res))

