## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----setup--------------------------------------------------------------------
library(nof1kit)

## -----------------------------------------------------------------------------
sched <- design_schedule(n_days = 70, max_run = 2, seed = 20260218)
head(sched, 12)

## -----------------------------------------------------------------------------
check_schedule(sched)

## -----------------------------------------------------------------------------
sim_power(n_days = 70, effect = 0.5, phi = 0.4, n_sims = 200, seed = 2)

## -----------------------------------------------------------------------------
sim_power(n_days = 70, effect = 0, phi = 0.7, n_sims = 200, seed = 4,
          schedule = rep(c(0, 1), each = 35))

## -----------------------------------------------------------------------------
f <- tempfile(fileext = ".json")
write_schedule(sched, f)
cat(substr(readLines(f), 1, 90))

## ----error = TRUE-------------------------------------------------------------
try({
path <- system.file("extdata", "melatonin_ema.csv", package = "nof1kit")
ema <- read_ema(path, start_date = "2026-02-18", timestamp_col = "datetime")
})

## -----------------------------------------------------------------------------
ema <- read_ema(path, timestamp_col = "datetime")

v <- validate_ema(
  ema,
  ranges = list(mood = c(0, 100), agency = c(0, 100),
                metacognition = c(0, 100), melatonin = c(0, 1)),
  n_days = 70
)
v
subset(v$issues, check == "inconsistent_study_day")

## ----error = TRUE-------------------------------------------------------------
try({
stopifnot(v$n_issues == 0)
})

## -----------------------------------------------------------------------------
records <- nrow(ema)
prompts <- 70 * 3
round(100 * records / prompts, 1)

## -----------------------------------------------------------------------------
cp <- compliance(
  ema,
  start_date = "2026-02-18",
  n_days = 70,
  times = c("10:00", "16:00", "22:00"),
  window = 3
)
cp

## -----------------------------------------------------------------------------
tapply(cp$prompts$answered, cp$prompts$time, mean)

## ----eval = FALSE-------------------------------------------------------------
# library(lme4)
# lmer(mood ~ melatonin + (1 | study_day), data = ema)

## ----eval = FALSE-------------------------------------------------------------
# sched <- design_schedule(n_days = 70, max_run = 2, seed = 20260218)
# write_schedule(sched, "schedule.json")     # onto the phone
# 
# ema <- read_ema("export.csv", start_date = "2026-02-18")
# validate_ema(ema, ranges = list(mood = c(0, 100)), n_days = 70)
# compliance(ema, start_date = "2026-02-18", n_days = 70,
#            times = c("09:00", "15:00", "21:00"))

