# Phenology in R: day of year and event timing
# https://tidyecology.com/posts/phenology-and-day-of-year/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-14

## ---- setup ----
library(ggplot2)

forest <- "#275139"; gold <- "#cda23f"; terra <- "#b5534e"; mown <- "#2f8f63"
theme_te <- function(base = 13) {
  theme_minimal(base_size = base) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6da", linewidth = 0.3),
          axis.title = element_text(colour = "#46604a"),
          axis.text  = element_text(colour = "#2c3a31"),
          plot.title = element_text(colour = "#16241d", face = "bold"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          legend.position = "none")
}
theme_set(theme_te())

## ---- doy ----
d   <- as.Date(c("2023-03-01", "2024-03-01"))
doy <- as.integer(format(d, "%j"))
doy

## ---- doy-store ----
doy23 <- doy[1]; doy24 <- doy[2]

## ---- season ----
set.seed(101)
onset <- 105
flow  <- round(onset + rgamma(400, shape = 4.5, scale = 5.5))   # first-flower day per plant

first_d  <- min(flow)
last_d   <- max(flow)
mean_d   <- mean(flow)
median_d <- median(flow)
tab      <- table(flow)
peak_d   <- as.integer(names(tab)[which.max(tab)])              # busiest single day
span     <- last_d - first_d
iqr80    <- as.numeric(quantile(flow, 0.9) - quantile(flow, 0.1))
c(first = first_d, peak = peak_d, median = median_d,
  mean = round(mean_d, 1), last = last_d)

## ---- fig-season ----
marks <- data.frame(
  day = c(first_d, peak_d, median_d, mean_d, last_d),
  lab = c("first", "peak", "median", "mean", "last"),
  col = c(terra, gold, forest, "#16241d", terra))
ggplot(data.frame(flow), aes(flow)) +
  geom_histogram(binwidth = 2, fill = "#c9d3c2", colour = "white") +
  geom_vline(data = marks, aes(xintercept = day, colour = col), linewidth = 0.8) +
  geom_text(data = marks, aes(x = day, y = 34, label = lab, colour = col),
            angle = 90, vjust = -0.3, hjust = 1, size = 3.4) +
  scale_colour_identity() +
  labs(x = "day of year", y = "plants flowering") +
  coord_cartesian(clip = "off") +
  theme(plot.margin = margin(12, 14, 6, 6))

## ---- fig-cumulative ----
qs   <- quantile(flow, c(0.1, 0.5, 0.9))
ecdf_df <- data.frame(day = sort(unique(flow)))
ecdf_df$cum <- ecdf(flow)(ecdf_df$day)
ggplot(ecdf_df, aes(day, cum)) +
  geom_step(colour = forest, linewidth = 0.9) +
  geom_hline(yintercept = c(0.1, 0.5, 0.9), colour = "#b9c2b0", linetype = 2) +
  geom_vline(xintercept = qs, colour = gold, linetype = 3) +
  annotate("text", x = qs, y = 0.97,
           label = c("10%", "50% (median)", "90%"), hjust = -0.05, size = 3.3,
           colour = "#46604a") +
  labs(x = "day of year", y = "fraction flowered") +
  scale_y_continuous(limits = c(0, 1))

## ---- winter ----
winter   <- c(350, 355, 358, 360, 3, 6, 10, 12)   # days of year, spanning the boundary
lin_mean <- mean(winter)
ang       <- winter / 365 * 2 * pi
circ_mean <- (atan2(mean(sin(ang)), mean(cos(ang))) / (2 * pi) * 365) %% 365
c(linear_mean = round(lin_mean, 1), circular_mean = round(circ_mean, 1))

## ---- imprecise-dates ----
herb_adv <- -1.5                                  # true advance, days per decade
one_century <- function(n_year = 20) {
  yr <- rep(1921:2020, each = n_year)
  doy_true <- round(onset + herb_adv * (yr - 1921) / 10 + rgamma(length(yr), 4.5, scale = 5.5))
  w <- plogis((yr - 1960) / 12)                   # recording improves around 1960
  p_year <- 0.2 * (1 - w); p_month <- 0.5 * (1 - w) + 0.03 * w; u <- runif(length(yr))
  n_char <- ifelse(u < p_year, 4, ifelse(u < p_year + p_month, 7, 10))
  when <- format(as.Date(paste0(yr, "-01-01")) + doy_true - 1)   # "yyyy-mm-dd"
  data.frame(year = yr, doy_true, event_date = substr(when, 1, n_char))
}
fit_codings <- function(rec) {                    # reads only year and event_date
  len <- nchar(rec$event_date); kept <- len > 4; dec <- (rec$year - 1921) / 10
  jday <- function(x) as.integer(format(x, "%j"))
  m_first <- as.Date(paste0(substr(rec$event_date, 1, 7), "-01"), format = "%Y-%m-%d")
  m_last <- as.Date(format(m_first + 31, "%Y-%m-01")) - 1
  first <- ifelse(len == 10, jday(as.Date(rec$event_date, format = "%Y-%m-%d")), jday(m_first))
  jan1 <- ifelse(len == 4, 1, first); mid <- ifelse(len == 7, first + 14, first)
  lo <- ifelse(len == 4, 1, first) - 0.5; hi <- ifelse(len == 7, jday(m_last), first) + 0.5
  hi[len == 4] <- jday(as.Date(paste0(rec$year[len == 4], "-12-31"))) + 0.5
  sl <- function(y, s = TRUE) unname(coef(lm(y[s] ~ dec[s]))[2])
  ic <- survival::survreg(survival::Surv(lo, hi, type = "interval2") ~ dec, dist = "gaussian")
  z_lo <- (lo - ic$linear.predictors) / ic$scale; z_hi <- (hi - ic$linear.predictors) / ic$scale
  p_in <- ifelse(z_lo > 0, pnorm(-z_lo) - pnorm(-z_hi), pnorm(z_hi) - pnorm(z_lo))
  stopifnot(abs(sum(log(p_in)) - ic$loglik[2]) < 1e-6)   # P(true day in its interval)
  off <- function(y, k) mean((y - rec$doy_true)[len == k])
  c(exact = sl(rec$doy_true), drop = sl(first, len == 10), first = sl(first, kept),
    jan1 = sl(jan1), mid = sl(mid, kept), interval = unname(coef(ic)[2]),
    off_m = off(first, 7), off_y = off(jan1, 4), off_mid = off(mid, 7),
    s_m = sl(1 * (len == 7), kept), s_m_all = sl(1 * (len == 7)), s_y_all = sl(1 * (len == 4)),
    day1_fill = mean(len[kept] == 7 | substr(rec$event_date[kept], 9, 10) == "01"),
    day1_exact = mean(substr(rec$event_date[len == 10], 9, 10) == "01"))
}
set.seed(27092601); cent <- as.data.frame(t(replicate(200, fit_codings(one_century()))))
cf <- with(cent, c(first = mean(off_m * s_m), jan1 = mean(off_m * s_m_all + off_y * s_y_all),
                   mid = mean(off_mid * s_m)))               # mean offset x change in share
shift <- sapply(cent[2:6], function(v) mean(v - cent$exact)); gap <- cf[c("first", "mid")] - shift[c("first", "mid")]
shift_se <- sapply(cent[2:6], function(v) sd(v - cent$exact) / sqrt(nrow(cent))); stopifnot(isTRUE(all.equal(gap[[1]], gap[[2]])))

## ---- fig-imprecise-dates ----
lev <- c(exact = "true dates", drop = "day-precise only",
         first = "first of month, year-only dropped", jan1 = "first of month + 1 January",
         mid = "15th of month, year-only dropped", interval = "interval-censored")
slopes <- data.frame(coding = factor(rep(lev, each = nrow(cent)), levels = rev(lev)),
                     slope = unlist(cent[names(lev)]))
pred <- data.frame(coding = factor(lev[names(cf)], levels = rev(lev)), slope = mean(cent$exact) + cf)
ggplot(slopes, aes(slope, coding, colour = coding %in% lev[c("first", "jan1")])) +
  geom_vline(xintercept = herb_adv, colour = "#16241d", linetype = 2, linewidth = 0.5) +
  geom_point(alpha = 0.25, size = 1, position = position_jitter(width = 0, height = 0.18, seed = 1)) +
  geom_point(data = aggregate(slope ~ coding, data = slopes, FUN = mean), size = 3.2) +
  geom_point(data = pred, shape = 5, colour = gold, size = 3.6, stroke = 1.1) +
  scale_colour_manual(values = c("FALSE" = forest, "TRUE" = terra)) +
  labs(x = "fitted trend in first-flowering day (days per decade)", y = NULL)
