## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  fig.alt = "ggplot2 chart showing the result of this windcut workflow step."
)

## ----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 |>
  derive_vpd(daily_mean_temp, daily_mean_rh, name = "daily_vpd")
assessments <- window_pane_demo_data$assessments

windows <- make_windows(min_offset = -18, max_offset = -1, width = 5, reference_col = "assessment_time")

daily_weather_cols <- c(
  "daily_mean_temp",
  "daily_mean_rh",
  "daily_vpd",
  "daily_sum_rain",
  "daily_sum_leaf_wetness"
)

summary_statistics <- list(
  daily_mean_temp = list(mean = "mean", days_18_26 = count_between(18, 26)),
  daily_mean_rh = list(mean = "mean", humid_days = humid_hours(90)),
  daily_vpd = list(mean = "mean", dry_days = count_above(1.2)),
  daily_sum_rain = list(total = "sum", rain_events = rain_events(0.2)),
  daily_sum_leaf_wetness = list(wet_days = wet_days(0)),
  .conditions = list(
    favorable_days = count_when(
      daily_mean_temp >= 18 & daily_mean_temp <= 26 & daily_mean_rh >= 90
    )
  )
)

features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = windows,
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = daily_weather_cols,
  statistics = summary_statistics
)

feature_cols <- features %>%
  select(contains("_window_")) %>%
  names()

feature_table_overview <- data.frame(
  rows = nrow(features),
  candidate_feature_columns = length(feature_cols)
)

knitr::kable(feature_table_overview)
knitr::kable(data.frame(feature = head(feature_cols, 8)))

## -----------------------------------------------------------------------------
screened <- screen_window_features(
  data = features,
  response_col = "disease_intensity",
  feature_cols = feature_cols,
  method = "spearman"
)

knitr::kable(screened %>% slice_head(n = 10))

## -----------------------------------------------------------------------------
top10 <- screened %>%
  mutate(abs_estimate = abs(estimate)) %>%
  arrange(desc(abs_estimate)) %>%
  slice_head(n = 10) %>%
  mutate(feature = factor(feature, levels = rev(feature)))

ggplot(top10, aes(estimate, feature, fill = estimate > 0)) +
  geom_col(show.legend = FALSE) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "gray50") +
  scale_fill_manual(values = c("#c47f2c", "#5f8f63")) +
  labs(
    title = "Top feature-screening results",
    x = "Correlation estimate",
    y = NULL
  ) +
  cowplot::theme_half_open()

## -----------------------------------------------------------------------------
correlation_screen <- screen_feature_correlations(
  data = features,
  feature_cols = feature_cols,
  method = "spearman",
  threshold = 0.8
)

knitr::kable(correlation_screen$high_correlations %>% slice_head(n = 10))
knitr::kable(
  data.frame(suggested_feature = correlation_screen$suggested_features) %>%
    slice_head(n = 12)
)

## -----------------------------------------------------------------------------
feature_reduction <- data.frame(
  status = c("Original features", "Suggested features", "Removed features"),
  count = c(
    length(feature_cols),
    length(correlation_screen$suggested_features),
    length(correlation_screen$removed_features)
  )
)

knitr::kable(feature_reduction)

ggplot(feature_reduction, aes(count, status, fill = status)) +
  geom_col(show.legend = FALSE, width = 0.65) +
  geom_text(aes(label = count), hjust = -0.25, size = 3.8) +
  scale_fill_manual(values = c(
    "Original features" = "#3f7d58",
    "Suggested features" = "#6ea87d",
    "Removed features" = "#c47f2c"
  )) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.12))) +
  labs(
    title = "Feature count after correlation screening",
    x = "Number of feature columns",
    y = NULL
  ) +
  cowplot::theme_half_open()

## ----fig.height = 9-----------------------------------------------------------
summary_plot <- correlation_screen$feature_summary %>%
  arrange(desc(mean_abs_correlation)) %>%
  slice_head(n = 30) %>%
  mutate(feature = factor(feature, levels = rev(feature)))

ggplot(summary_plot, aes(mean_abs_correlation, feature, fill = suggested)) +
  geom_col() +
  scale_fill_manual(values = c("#c47f2c", "#5f8f63")) +
  labs(
    title = "Feature redundancy ranking",
    x = "Mean absolute correlation with other features",
    y = NULL,
    fill = "Suggested"
  ) +
  cowplot::theme_half_open()

## ----fig.width = 8, fig.height = 8--------------------------------------------
heatmap_features <- head(correlation_screen$suggested_features, 12)
heatmap_matrix <- correlation_screen$correlation_matrix[
  heatmap_features,
  heatmap_features,
  drop = FALSE
]

heatmap_data <- as.data.frame(as.table(heatmap_matrix)) %>%
  rename(feature_x = Var1, feature_y = Var2, correlation = Freq) %>%
  mutate(
    label = sprintf("%.2f", correlation),
    feature_x = factor(feature_x, levels = heatmap_features),
    feature_y = factor(feature_y, levels = rev(heatmap_features))
  )

ggplot(heatmap_data, aes(feature_x, feature_y, fill = correlation)) +
  geom_tile(color = "white", linewidth = 0.4) +
  geom_text(aes(label = label), size = 2.6) +
  scale_fill_gradient2(
    low = "#4b79a8",
    mid = "white",
    high = "#b13a32",
    midpoint = 0,
    limits = c(-1, 1),
    name = "Correlation"
  ) +
  labs(
    title = "Correlation matrix for suggested features",
    x = NULL,
    y = NULL
  ) +
  coord_fixed() +
  cowplot::theme_half_open() +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
    panel.grid = element_blank()
  )

