## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  fig.width = 7,
  fig.height = 4.8,
  dev.args = list(bg = "white"),
  fig.alt = "ggplot2 chart showing reference dates, candidate windows, or generated weather features."
)

## ----packages, message=FALSE, warning=FALSE-----------------------------------
library(windcut)
library(dplyr)
library(ggplot2)
library(tidyr)
library(cowplot)

## -----------------------------------------------------------------------------
data(window_pane_demo_data)

weather <- window_pane_demo_data$weather
assessments <- window_pane_demo_data$assessments

nrow(weather)
knitr::kable(assessments)

## -----------------------------------------------------------------------------
example_site <- assessments$site_id[1]
example_assessment <- assessments %>% filter(site_id == example_site)
example_weather <- weather %>% filter(site_id == example_site)

plot_start <- example_assessment$planting_time - 7 * 86400
plot_end <- example_assessment$assessment_time + 1 * 86400
plot_weather <- example_weather %>%
  filter(time >= plot_start, time <= plot_end)

reference_dates <- data.frame(
  reference_col = c("planting_time", "assessment_time"),
  reference_time = c(
    example_assessment$planting_time,
    example_assessment$assessment_time
  )
)

ggplot(plot_weather, aes(time, daily_mean_temp)) +
  geom_line(color = "#3f7d58", linewidth = 0.7) +
  geom_vline(
    data = reference_dates,
    aes(xintercept = reference_time, color = reference_col),
    linetype = "dashed",
    linewidth = 0.8
  ) +
  scale_color_manual(values = c(planting_time = "#c47f2c", assessment_time = "#20262e")) +
  labs(
    title = "Two possible reference dates for one site",
    x = "Calendar time",
    y = "Daily mean temperature (deg C)",
    color = "Reference column"
  ) +
  cowplot::theme_half_open()

## -----------------------------------------------------------------------------
fixed_windows <- make_windows(
  min_offset = -49,
  max_offset = 0,
  width = 7
)

knitr::kable(head(fixed_windows, 10))
nrow(fixed_windows)

## -----------------------------------------------------------------------------
coarser_windows <- make_windows(
  min_offset = -49,
  max_offset = 0,
  width = 7,
  slide_by = 2
)

knitr::kable(head(coarser_windows, 10))
nrow(coarser_windows)

## -----------------------------------------------------------------------------
slide_comparison <- data.frame(
  slide_by = c("slide_by = 1", "slide_by = 2"),
  candidate_windows = c(nrow(fixed_windows), nrow(coarser_windows))
)

knitr::kable(slide_comparison)

## ----dense-fixed-window-plot, fig.height=9------------------------------------
plot_window_pane(
  fixed_windows,
  max_windows = Inf,
  color_by = "none",
  title = "Dense fixed-width window-pane grid",
  subtitle = "slide_by = 1 moves the 7-day window one relative-time unit at a time",
  xlab = "Time relative to reference date (days)"
)

## ----coarser-fixed-window-plot, fig.height=6.5--------------------------------
plot_window_pane(
  coarser_windows,
  max_windows = Inf,
  color_by = "none",
  title = "Coarser fixed-width window-pane grid",
  subtitle = "slide_by = 2 moves the 7-day window two relative-time units at a time",
  xlab = "Time relative to reference date (days)"
)

## -----------------------------------------------------------------------------
variable_windows <- make_windows(
  min_offset = -49,
  max_offset = 0,
  width = c(3, 5, 7),
  slide_by = 2
)

knitr::kable(head(variable_windows, 10))
nrow(variable_windows)

## ----variable-window-plot, fig.height=12--------------------------------------
plot_window_pane(
  variable_windows,
  max_windows = Inf,
  color_by = "width",
  title = "Variable-width window-pane grid",
  subtitle = "The dashed line at relative-time 0 marks the reference date",
  xlab = "Time relative to reference date (days)"
)

## -----------------------------------------------------------------------------
daily_weather_cols <- c(
  "daily_mean_temp",
  "daily_mean_rh",
  "daily_sum_rain",
  "daily_sum_leaf_wetness"
)

summary_statistics <- list(
  daily_mean_temp = c("mean", "min", "max"),
  daily_mean_rh = list(mean = "mean", median = "median", days_at_or_above_90 = count_at_or_above(90)),
  daily_sum_rain = c("sum", "max"),
  daily_sum_leaf_wetness = "sum"
)

assessment_features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = fixed_windows,
  reference_col = "assessment_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

assessment_feature_overview <- data.frame(
  rows = nrow(assessment_features),
  columns = ncol(assessment_features)
)
assessment_feature_names <- data.frame(
  feature = names(assessment_features %>% select(1:12))
)

knitr::kable(assessment_feature_overview)
knitr::kable(assessment_feature_names)

## -----------------------------------------------------------------------------
assessment_features %>%
  select(1:12) %>%
  slice_head(n = 6) %>%
  knitr::kable()

## -----------------------------------------------------------------------------
planting_windows <- make_windows(
  min_offset = -14,
  max_offset = 35,
  width = 7,
  slide_by = 7,
  reference_col = "planting_time"
)

knitr::kable(planting_windows)

## -----------------------------------------------------------------------------
plot_window_pane(
  planting_windows,
  max_windows = Inf,
  color_by = "timing",
  title = "Planting-centered windows can cross both sides of the reference date",
  subtitle = "Negative offsets are before planting; positive offsets are after planting",
  xlab = "Time relative to planting date (days)"
)

## -----------------------------------------------------------------------------
planting_features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = planting_windows,
  reference_col = "planting_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

knitr::kable(
  planting_features %>%
    select(site_id, planting_time, disease_intensity) %>%
    slice_head(n = 5)
)

## -----------------------------------------------------------------------------
comparison_sparse_windows <- make_windows(
  min_offset = -49,
  max_offset = 0,
  width = 7,
  slide_by = 7
)

comparison_dense_features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = fixed_windows,
  reference_col = "assessment_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

comparison_coarser_features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = coarser_windows,
  reference_col = "assessment_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

comparison_variable_features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = variable_windows,
  reference_col = "assessment_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

comparison_sparse_features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = comparison_sparse_windows,
  reference_col = "assessment_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

feature_table_sizes <- data.frame(
  window_strategy = c(
    "7-day windows, slide_by = 1",
    "7-day windows, slide_by = 2",
    "3-, 5-, and 7-day windows, slide_by = 2",
    "7-day windows, slide_by = 7"
  ),
  relative_range = rep("-49 to 0 days", 4),
  total_length_days = rep(49, 4),
  candidate_windows = c(
    nrow(fixed_windows),
    nrow(coarser_windows),
    nrow(variable_windows),
    nrow(comparison_sparse_windows)
  ),
  generated_features = c(
    sum(grepl("_window_", names(comparison_dense_features))),
    sum(grepl("_window_", names(comparison_coarser_features))),
    sum(grepl("_window_", names(comparison_variable_features))),
    sum(grepl("_window_", names(comparison_sparse_features)))
  )
)

knitr::kable(feature_table_sizes)

## ----feature-table-size-plot, fig.width=8, fig.height=4.8---------------------
feature_table_sizes <- feature_table_sizes %>%
  mutate(window_strategy = factor(window_strategy, levels = window_strategy))

ggplot(feature_table_sizes, aes(generated_features, window_strategy, fill = window_strategy)) +
  geom_col(show.legend = FALSE, width = 0.65) +
  geom_text(aes(label = generated_features), hjust = -0.25, size = 3.8) +
  scale_fill_manual(values = c(
    "7-day windows, slide_by = 1" = "#3f7d58",
    "7-day windows, slide_by = 2" = "#6ea87d",
    "3-, 5-, and 7-day windows, slide_by = 2" = "#c47f2c",
    "7-day windows, slide_by = 7" = "#7f5539"
  )) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.12))) +
  labs(
    title = "Feature-table size by window strategy",
    subtitle = "Same 49-day range; different duration and slide_by",
    x = "Generated feature columns",
    y = NULL
  ) +
  cowplot::theme_half_open()

## -----------------------------------------------------------------------------
features <- assessment_features
temp_cols <- features %>%
  select(starts_with("daily_mean_temp_mean_")) %>%
  names()
knitr::kable(data.frame(feature = head(temp_cols)))

## -----------------------------------------------------------------------------
plot_ids <- features %>%
  slice_head(n = min(4, nrow(features))) %>%
  pull(site_id)
plot_cols <- temp_cols[1:min(8, length(temp_cols))]
temp_long <- features %>%
  filter(site_id %in% plot_ids) %>%
  select(site_id, all_of(plot_cols)) %>%
  pivot_longer(
    cols = -site_id,
    names_to = "feature",
    values_to = "value"
  ) %>%
  mutate(feature_index = match(feature, plot_cols))

ggplot(temp_long, aes(feature_index, value, color = site_id, group = site_id)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.8) +
  scale_color_manual(values = c("#2b6c4f", "#8aa05a", "#c47f2c", "#7f5539")) +
  scale_x_continuous(
    breaks = seq_along(plot_cols),
    labels = sub("daily_mean_temp_mean_", "", plot_cols)
  ) +
  labs(
    title = "Temperature summaries across candidate windows",
    x = "Relative-time window",
    y = "Feature value",
    color = "Site"
  ) +
  cowplot::theme_half_open() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

