## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse   = TRUE,
  comment    = "#>",
  fig.width  = 6,
  fig.height = 3.5,
  fig.align  = "center",
  out.width  = "90%"
)

## ----setup-example, message = FALSE-------------------------------------------
library(BTWAR)

set.seed(123)

fs <- 12000   # sampling frequency (Hz)

## ----simulate-----------------------------------------------------------------
phi_obs <- c(0.34, -0.22, 0.16)

sim_data <- simulate_ar_split(
  phi_real   = phi_obs,
  n          = 1000,
  burn       = 200,
  prop_train = 0.7
)

dados <- list(
  train = as.numeric(sim_data$train),
  test  = as.numeric(sim_data$test)
)

## ----true-params--------------------------------------------------------------
cat("True AR coefficients:\n")
print(phi_obs)

cat("\nTrue Z-plane poles:\n")
print(sim_data$poles)

## ----pacf, fig.cap = "PACF of the training series. Significant spikes at lags 1, 2, and 3 suggest AR order 3, which fixes the filter order N = 3."----
pacf(dados$train, main = "PACF – Training Series")

## ----fit, message = FALSE-----------------------------------------------------
p <- 3

res <- btwar_fit(
  y_tr_raw = dados$train,
  y_te_raw = dados$test,
  fs       = fs,
  method   = "ls",
  N_vec    = p:p
)

cat("BTW-AR Performance:\n")
print(res$performance)

## ----plot-train, fig.cap = "Training set: observed series vs. BTW-AR predictions."----
plot(res, dataset = "train", fs = fs,
     colour_observed = "goldenrod",
     colour_btwar    = "blue",
     lwd_observed    = 1.2,
     lwd_btwar       = 1.2)

## ----plot-test, fig.cap = "Test set: observed series vs. BTW-AR predictions."----
plot(res, dataset = "test", fs = fs,
     colour_observed = "goldenrod",
     colour_btwar    = "blue",
     lwd_observed    = 1.2,
     lwd_btwar       = 1.2)

## ----bode, fig.cap = "Butterworth magnitude response for the selected BTW-AR model.", fig.width = 10, fig.height = 5, out.width = "100%"----
plot_bode(res, fs = fs)

## ----amplitude, fig.cap = "Amplitude spectrum of the training series. The cutoff frequency fc separates the dominant signal energy from the high-frequency components.", fig.width = 10, fig.height = 4, out.width = "100%"----
plot_freq_amplitude(
  dados$train,
  fs = fs,
  fc = res$parameters$fc_opt
)

## ----zpoles, fig.cap = "Z-plane poles: BTW-AR (selected) vs. true signal.", fig.height = 5----
df_true <- data.frame(
  Re = Re(sim_data$poles),
  Im = Im(sim_data$poles)
)

plot_zpoles(
  res,
  external_list = list(
    "True Signal Z-Poles" = df_true
  )
)

## ----robust, eval = FALSE-----------------------------------------------------
#  fit_huber <- btwar_fit(
#    y_tr_raw = dados$train,
#    y_te_raw = dados$test,
#    fs       = fs,
#    method   = "huber",
#    N_vec    = p:p
#  )
#  summary(fit_huber)

## ----session------------------------------------------------------------------
sessionInfo()

