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

## ----libraries, message = FALSE, warning = FALSE------------------------------
library(actiRhythm)
library(ggplot2)

## ----read---------------------------------------------------------------------
agd <- agd.counts(read.agd(example_agd(1), verbose = FALSE))
head(agd[, c("timestamp", "axis1")])

## ----actogram, fig.height = 5, fig.cap = "Double-plotted actogram: each row is one day shown twice across 48 hours, so a stable rhythm forms a vertical band of activity at the same clock time each day; scattered fill marks a fragmented or shifting rhythm."----
plot_actogram(agd$axis1, agd$timestamp)

## ----rhythm-------------------------------------------------------------------
rhythm <- circadian.rhythm(agd$axis1, agd$timestamp)
rhythm

## ----cosinor------------------------------------------------------------------
cos <- cosinor.analysis(agd$axis1, agd$timestamp, period = 24)
c(mesor = unname(cos$mesor), amplitude = unname(cos$amplitude),
  acrophase = unname(cos$acrophase))

## ----rhythmicity--------------------------------------------------------------
rhythmicity.test(agd$axis1, agd$timestamp, cosinor_result = cos)

## ----cosinor-plot, fig.cap = "Hourly activity with the fitted 24-hour cosine overlaid; the peak of the curve is the acrophase and its height above the MESOR line is the amplitude. Systematic departures from the curve are where a single cosine is too smooth for real rest-activity data."----
plot_extended_cosinor(agd$axis1, agd$timestamp)

## ----period-------------------------------------------------------------------
per <- circadian.period(agd$axis1, agd$timestamp)
c(tau = per$tau, p_value = per$p_value)

## ----period-ci----------------------------------------------------------------
period.ci(agd$axis1, agd$timestamp, n_boot = 50, seed = 1)

## ----periodogram, fig.cap = "Lomb-Scargle spectral power across candidate periods; the tallest peak is the dominant rhythm, and a peak rising above the significance line rejects the no-rhythm null."----
plot_periodogram(agd$axis1, agd$timestamp)

## ----chisq, fig.cap = "Chi-square (Sokolove-Bushell) periodogram: the Qp statistic against trial period, with the significance threshold. The peak should fall at the period the Lomb-Scargle periodogram found."----
plot_chisq(agd$axis1, agd$timestamp)

## ----spectrogram, fig.height = 4, fig.cap = "Period (vertical) against time (horizontal), coloured by spectral power. A horizontal band of colour is a stable period; a band that bends upward or downward is a rhythm lengthening or shortening across the recording."----
circadian.spectrogram(agd$axis1, agd$timestamp, step_hours = 24)$plot

## ----dfa----------------------------------------------------------------------
fractal.dfa(agd$axis1)$alpha

## ----dfa-plot, fig.cap = "Detrended fluctuation on log-log axes; the slope is the DFA exponent alpha. One straight line is monofractal scaling, a visible kink is a crossover between short- and long-range dynamics."----
plot_dfa(agd$axis1)

## ----transitions--------------------------------------------------------------
st <- state.transitions(agd$axis1)
c(kRA = st$kRA, kAR = st$kAR)

## ----changepoints-------------------------------------------------------------
cp <- sleep.changepoints(agd$axis1, agd$timestamp)
cp

## ----cp-plot, fig.height = 3.5, fig.cap = "Each detected sleep onset (blue) and wake onset (orange) by date and clock time. The detector reads the per-night sleep and wake timing directly from the counts."----
cps <- cp$changepoints
cps$clock <- as.numeric(format(cps$time, "%H")) + as.numeric(format(cps$time, "%M")) / 60
ggplot(cps, aes(time, clock, colour = type)) +
  geom_point(size = 3) +
  scale_colour_manual(values = c("sleep onset" = "#236192", "wake onset" = "#E69F00")) +
  labs(x = "Date", y = "Clock hour", colour = NULL) +
  theme_actiRhythm()

## ----restperiods--------------------------------------------------------------
rp <- rest.periods(agd$axis1, agd$timestamp)
rp

## ----restperiods-plot, fig.height = 3, fig.cap = "Each consolidated rest bout as a bar from onset to offset. Detecting more than one bout a day, including naps, is what separates this from the one-per-cycle change-point detector."----
ggplot(rp$rest_periods, aes(onset, bout, xend = offset, yend = bout, colour = type)) +
  geom_segment(linewidth = 3) +
  scale_colour_manual(values = c(main = "#236192", nap = "#E69F00")) +
  labs(x = "Time", y = "Rest bout", colour = NULL) +
  theme_actiRhythm()

## ----scoring------------------------------------------------------------------
state <- sleep.cole.kripke(agd$axis1)
table(state)

## ----sri----------------------------------------------------------------------
sleep.regularity.index(state, agd$timestamp)

## ----consensus----------------------------------------------------------------
consensus.rhythmicity(agd$axis1, agd$timestamp)

## ----summary------------------------------------------------------------------
data.frame(
  IS        = rhythm$IS,
  IV        = rhythm$IV,
  RA        = rhythm$RA,
  tau       = per$tau,
  amplitude = cos$amplitude,
  acrophase = cos$acrophase,
  dfa_alpha = fractal.dfa(agd$axis1)$alpha
)

## ----batch--------------------------------------------------------------------
batch <- circadian.batch(
  system.file("extdata", package = "actiRhythm"),
  verbose = FALSE
)
batch[, c("file", "IS", "IV", "RA", "period_tau", "rhythm_p_value")]

## ----workbook, eval = FALSE---------------------------------------------------
# circadian.workbook(agd$axis1, agd$timestamp, file = "subject01.xlsx")

