# EESC 301, Lab 8: subsampling a high-frequency record (Nyquist and aliasing)
# Code from the Lab 8 deck (slides 35 and 36), assembled into one runnable file
# and set up for the L8 file on datasets.okanaganwatersupply.com.
# Base R only.

## Part 1. The synthetic demonstration (slide 35)
i  <- 0:(365 * 96 - 1)                            # 15-min steps, 1 year
d  <- i / 96; hr <- (i %% 96) / 4                 # day, hour of day
temp <- 10 + 7 * sin(2 * pi * (d - 110) / 365) +  # seasonal cycle
        2 * cos(2 * pi * (hr - 15) / 24)          # diel cycle, peak 15:00
wk <- function(h) temp[hr == h][seq(1, 365, by = 7)]   # weekly, fixed hour
print(round(c(true = mean(temp), wk14 = mean(wk(14)), wk06 = mean(wk(6)),
              diel = diff(range(temp[1:96]))), 2))
stopifnot(length(temp) == 35040, length(wk(14)) == 53)  # SYNTHETIC
# Prints true 10.00, wk14 11.82, wk06 8.48, diel 3.98

## Part 2. The Mission Creek record (slide 36)
# Download L8 from the data site and put it beside this script.
f         <- "L8_mission_creek_tw_15min_2025_20261015.csv"
TIME_COL  <- "timestamp"   # the file's time column, in UTC
VALUE_COL <- "value"       # water temperature, degrees C
VISIT     <- "14:00"       # the visit hour, LOCAL time in Kelowna. Try "06:00" too.
x <- read.csv(f)
x$t <- as.POSIXct(x[[TIME_COL]], tz = "UTC", format = "%Y-%m-%d %H:%M")
stopifnot(!anyNA(x$t), !anyNA(x[[VALUE_COL]]))
x <- x[order(x$t), ]
# The file is UTC; a 14:00 visit in Kelowna is 21:00 UTC in summer. Pick the
# visit hour in local time, or the "14:00" sample is really a 07:00 visit.
x$local <- format(x$t, "%Y-%m-%d %H:%M", tz = "America/Vancouver")
days    <- seq(as.Date(min(x$local)), as.Date(max(x$local)), by = 7)  # every 7th day
want    <- paste(days, VISIT)
w       <- x[match(want, x$local, nomatch = 0), ]
cat(sprintf("Weekly visits planned %d, found %d (the rest fall in data gaps)\n",
            length(want), nrow(w)))
print(round(c(all = mean(x[[VALUE_COL]]), weekly = mean(w[[VALUE_COL]])), 2))
stopifnot(nrow(w) >= 0.9 * length(want),
          all(diff(as.numeric(w$t)) %% 86400 %in% c(0, 3600, 82800)))  # whole weeks, give or take a DST hour
plot(x$t, x[[VALUE_COL]], type = "l", col = "grey60",
     xlab = "Date", ylab = "Water temperature (C)")
points(w$t, w[[VALUE_COL]], pch = 19, col = "red")
