## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5,
  dpi = 96
)

build_gif <- requireNamespace("gifski", quietly = TRUE) &&
  identical(tolower(Sys.getenv("QVIVID_BUILD_GIF")), "true")

## ----attach-------------------------------------------------------------------
library(qvivid)

## ----bell-circuit-------------------------------------------------------------
bell <- quantum_circuit(2, name = "Bell state") |>
  gate_h(1) |>
  gate_cx(control = 1, target = 2) |>
  measure_all()

bell

## ----bell-simulation----------------------------------------------------------
result <- simulate_quantum(
  bell,
  shots = 256,
  seed = 2026,
  record = TRUE
)

result
result$counts

## ----lsb-order----------------------------------------------------------------
lsb_result <- quantum_circuit(2, name = "LSB example") |>
  gate_x(1) |>
  simulate_quantum()

state_data(lsb_result, include_zero = FALSE)

## ----state-schema-------------------------------------------------------------
state_data(result, include_zero = FALSE)

## ----trajectory-schema--------------------------------------------------------
trajectory <- trajectory_data(result, include_zero = FALSE)
trajectory[, c("step", "label", "basis", "probability")]

trajectory_bloch(result, qubit = 1)

## ----state-plot, fig.cap="Exact Bell-state probabilities and phases."---------
plot(result, theme = "npj", engine = "base")

## ----execution-plot, fig.height=5.3, fig.cap="Circuit and exact state after the controlled-X gate."----
plot_execution(result, step = 2, theme = "nature")

## ----export-------------------------------------------------------------------
figure_file <- tempfile(fileext = ".pdf")
artifact <- save_quantum_plot(
  result,
  figure_file,
  view = "execution",
  step = 2,
  size = "single",
  theme = "nature"
)

file.exists(artifact$path)
unlink(artifact$path)

## ----optional-gif, eval=build_gif---------------------------------------------
# gif_file <- tempfile(fileext = ".gif")
# animation <- animate_state(
#   result,
#   gif_file,
#   fps = 2,
#   width = 640,
#   height = 480,
#   theme = "npj",
#   progress = FALSE
# )
# 
# animation
# unlink(animation$path)

