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

## ----setup, message = FALSE---------------------------------------------------
library(shewhartr)
library(ggplot2)
library(dplyr)

## -----------------------------------------------------------------------------
fit <- shewhart_regression(
  temperature_drift,
  value = temp_c,
  index = minute,
  model = "linear"
)
broom::glance(fit)

## -----------------------------------------------------------------------------
autoplot(fit)

## ----eval = FALSE-------------------------------------------------------------
# shewhart_diagnostics(fit)    # residuals~fitted, Q-Q, ACF, MR, histogram

## -----------------------------------------------------------------------------
set.seed(1)
trended <- tibble::tibble(
  t = 1:120,
  y = c( 1:60 * 0.5  + rnorm(60, sd = 0.5),     # phase 1
         30 + 1:60 * 0.1 + rnorm(60, sd = 0.5)) # phase 2: shift + slowdown
)

fit <- shewhart_regression(trended, value = y, index = t,
                           model = "linear",
                           phase_rule = "nelson_2_nine_same")
broom::glance(fit)
length(fit$fits)    # number of phases detected

## -----------------------------------------------------------------------------
fit_legacy <- shewhart_regression(trended, value = y, index = t,
                                  model = "linear",
                                  phase_rule = "we_seven_same")
length(fit_legacy$fits)

## -----------------------------------------------------------------------------
autoplot(fit)            # Nelson 2 — usually 1–2 phases
autoplot(fit_legacy)     # WE 7 — typically more phases on the same data

## ----fig.height = 4.6---------------------------------------------------------
fit_recife <- shewhart_regression(
  cvd_recife,
  value      = new_deaths,
  index      = .t,
  model      = "loglog",
  phase_rule = "we_seven_same",
  rules      = c("nelson_1_beyond_3s", "we_seven_same"),
  lower_bound = 0          # death counts can't go negative
)

length(fit_recife$fits)              # phases detected
nrow(fit_recife$violations)          # individual flagged observations
autoplot(fit_recife)

## -----------------------------------------------------------------------------
head(fit_recife$violations, 8)

## ----eval = FALSE-------------------------------------------------------------
# shewhart_regression(temperature_drift, value = temp_c, index = minute,
#                     formula = temp_c ~ poly(minute, 3))

## -----------------------------------------------------------------------------
fit_gomp <- shewhart_regression(
  bacterial_growth,
  value = od,
  index = hour,
  model = "gompertz"
)
broom::glance(fit_gomp)

## -----------------------------------------------------------------------------
autoplot(fit_gomp)

