## ----echo: false,message=FALSE, warning=FALSE---------------------------------
library(dplyr)
library(ggplot2)
library(glmnet)
library(stringr)
library(tidyr)
library(ranger)
library(broom)

data("sports_features_missing", package = "sportsfeatures")

df_sports <- sports_features_missing %>%
type.convert(as.is = TRUE)



## -----------------------------------------------------------------------------
df_ml1 <- df_sports %>%
  mutate(pace_min_km = round(duration_min / distance_km, 2)) %>%
  group_by(athlete_id) %>%
  mutate(
    athlete_mean_distance = round(mean(distance_km, na.rm = TRUE), 2),
    distance_centered     = round(distance_km - athlete_mean_distance, 2),
    athlete_mean_pace     = round(mean(pace_min_km, na.rm = TRUE), 2),
    pace_centered         = round(pace_min_km - athlete_mean_pace, 2),
    athlete_mean_fatigue  = round(mean(fatigue_score, na.rm = TRUE), 2),
    fatigue_deviation     = round(fatigue_score - athlete_mean_fatigue, 2)
  ) %>%
  ungroup() %>%
  mutate(
    activity_group = factor(case_when(
      str_detect(activity_type, regex("cycle|bike", ignore_case = TRUE)) ~ "Cycling",
      str_detect(activity_type, regex("walk", ignore_case = TRUE)) ~ "Walking",
      str_detect(activity_type, regex("hiking", ignore_case = TRUE)) ~ "Hiking",
      str_detect(activity_type, regex("run|jog", ignore_case = TRUE)) ~ "Running",
      TRUE ~ "Other"
    )),
    weather_group = factor(case_when(
      str_detect(weather_type, regex("cloud", ignore_case = TRUE)) ~ "Cloudy",
      str_detect(weather_type, regex("overcast", ignore_case = TRUE)) ~ "Overcast",
      str_detect(weather_type, regex("rain|shower", ignore_case = TRUE)) ~ "Rain",
      str_detect(weather_type, regex("sun|clear", ignore_case = TRUE)) ~ "Sunny",
      TRUE ~ "Other"
    )),
    personal_status = factor(str_replace_all(str_to_title(personal_status), "_", " "))
  ) %>%
  filter(!is.na(vo2_utilisation))


## -----------------------------------------------------------------------------
# Dummy-code categorical factors automatically
X_matrix <- model.matrix(
  vo2_utilisation ~ distance_centered + athlete_mean_distance +
                    pace_centered + athlete_mean_pace +
                    fatigue_deviation + athlete_mean_fatigue +
                    age + calories_per_min +
                    activity_group + weather_group + personal_status,
  data = df_ml1
)[, -1] # Remove intercept column

Y_vector <- df_ml1$vo2_utilisation


## ----results = 'hide'---------------------------------------------------------
set.seed(42)
cv_lasso <- cv.glmnet(X_matrix, Y_vector, alpha = 1, nfolds = 10, standardize = TRUE)

cat("--- LASSO FEATURE SELECTION (lambda.1se) ---\n")
cat("Optimal Lambda (min):", round(cv_lasso$lambda.min, 5), "\n")
cat("Parsimonious Lambda (1se):", round(cv_lasso$lambda.1se, 5), "\n\n")

# Robust extraction using broom::tidy
lasso_coefs <- tidy(cv_lasso$glmnet.fit) %>%
  filter(lambda == cv_lasso$lambda.1se & estimate != 0) %>%
  select(term, estimate) %>%
  rename(Feature = term, Coefficient = estimate) %>%
  mutate(Coefficient = round(Coefficient, 5))

print(lasso_coefs)



## ----results = 'hide'---------------------------------------------------------

set.seed(42)
cv_enet <- cv.glmnet(X_matrix, Y_vector, alpha = 0.5, nfolds = 10, standardize = TRUE)

cat("\n--- ELASTIC NET FEATURE SELECTION (alpha = 0.5, lambda.1se) ---\n")
cat("Optimal Lambda (min):", round(cv_enet$lambda.min, 5), "\n")
cat("Parsimonious Lambda (1se):", round(cv_enet$lambda.1se, 5), "\n\n")

enet_coefs <- tidy(cv_enet$glmnet.fit) %>%
  filter(lambda == cv_enet$lambda.1se & estimate != 0) %>%
  select(term, estimate) %>%
  rename(Feature = term, Coefficient = estimate) %>%
  mutate(Coefficient = round(Coefficient, 5))

 print(enet_coefs)


## -----------------------------------------------------------------------------
#| fig-cap: "Figure 4.1. Cross-validation error profiles across the LASSO and Elastic Net penalty paths."
#| fig-align: center
# Cross-Validation Profiles for LASSO and Elastic Net
par(mfrow = c(1, 2))
plot(cv_lasso, main = "LASSO (alpha = 1)")
plot(cv_enet, main = "Elastic Net (alpha = 0.5)")
par(mfrow = c(1, 1))


## -----------------------------------------------------------------------------


# Create only variables that can be calculated independently for each row.
# Athlete means and centred predictors are intentionally not calculated here.

df_ml_base <- df_sports %>%
  mutate(
    pace_min_km = round(duration_min / distance_km, 2),

    activity_group = factor(
      case_when(
        str_detect(
          activity_type,
          regex("cycle|bike", ignore_case = TRUE)
        ) ~ "Cycling",

        str_detect(
          activity_type,
          regex("walk", ignore_case = TRUE)
        ) ~ "Walking",

        str_detect(
          activity_type,
          regex("hiking", ignore_case = TRUE)
        ) ~ "Hiking",

        str_detect(
          activity_type,
          regex("run|jog", ignore_case = TRUE)
        ) ~ "Running",

        TRUE ~ "Other"
      )
    ),

    weather_group = factor(
      case_when(
        str_detect(
          weather_type,
          regex("cloud", ignore_case = TRUE)
        ) ~ "Cloudy",

        str_detect(
          weather_type,
          regex("overcast", ignore_case = TRUE)
        ) ~ "Overcast",

        str_detect(
          weather_type,
          regex("rain|shower", ignore_case = TRUE)
        ) ~ "Rain",

        str_detect(
          weather_type,
          regex("sun|clear", ignore_case = TRUE)
        ) ~ "Sunny",

        TRUE ~ "Other"
      )
    ),

    personal_status = factor(
      str_replace_all(
        str_to_title(personal_status),
        "_",
        " "
      )
    )
  ) %>%
  filter(
    !is.na(vo2_utilisation),
    !is.na(athlete_id),
    !is.na(distance_km),
    !is.na(pace_min_km),
    !is.na(fatigue_score),
    !is.na(calories_per_min),
    !is.na(activity_group),
    !is.na(weather_group),
    !is.na(personal_status)
  )



## -----------------------------------------------------------------------------
set.seed(123)

train_indices <- sample(
  seq_len(nrow(df_ml_base)),
  size = floor(0.8 * nrow(df_ml_base))
)

train_base <- df_ml_base[train_indices, , drop = FALSE]
test_base  <- df_ml_base[-train_indices, , drop = FALSE]

cat("--- DATA SPLIT SUMMARY ---\n")
cat("Training Set Rows:", nrow(train_base), "\n")
cat("Testing Set Rows :", nrow(test_base), "\n\n")


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Calculate athlete summaries from training data only

athlete_training_means <- train_base %>%
  group_by(athlete_id) %>%
  summarise(
    athlete_mean_distance = round(
      mean(distance_km, na.rm = TRUE),
      2
    ),

    athlete_mean_pace = round(
      mean(pace_min_km, na.rm = TRUE),
      2
    ),

    athlete_mean_fatigue = round(
      mean(fatigue_score, na.rm = TRUE),
      2
    ),

    .groups = "drop"
  )

# print(athlete_training_means)


## -----------------------------------------------------------------------------
#| echo: true
#| output: true
#| warning: false
#| message: false

# Construct Training and Test Predictors

train_data <- train_base %>%
  select(
    -any_of(c(
      "athlete_mean_distance",
      "athlete_mean_pace",
      "athlete_mean_fatigue",
      "distance_centered",
      "pace_centered",
      "fatigue_deviation"
    ))
  ) %>%
  left_join(
    athlete_training_means,
    by = "athlete_id"
  ) %>%
  mutate(
    distance_centered = round(
      distance_km - athlete_mean_distance,
      2
    ),

    pace_centered = round(
      pace_min_km - athlete_mean_pace,
      2
    ),

    fatigue_deviation = round(
      fatigue_score - athlete_mean_fatigue,
      2
    )
  )

test_data <- test_base %>%
  select(
    -any_of(c(
      "athlete_mean_distance",
      "athlete_mean_pace",
      "athlete_mean_fatigue",
      "distance_centered",
      "pace_centered",
      "fatigue_deviation"
    ))
  ) %>%
  left_join(
    athlete_training_means,
    by = "athlete_id"
  ) %>%
  mutate(
    distance_centered = round(
      distance_km - athlete_mean_distance,
      2
    ),

    pace_centered = round(
      pace_min_km - athlete_mean_pace,
      2
    ),

    fatigue_deviation = round(
      fatigue_score - athlete_mean_fatigue,
      2
    )
  )



## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Verify ncols in datasets
ncol(df_sports)
ncol(df_ml_base)
ncol(train_base)
ncol(train_data)

setdiff(
  names(train_data),
  names(train_base)
)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Verify data dimensions
dim(train_data)
dim(test_data)

identical(
  names(train_data),
  names(test_data)
)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Verify that every test athlete has training-derived means

missing_test_means <- test_data %>%
  filter(
    is.na(athlete_mean_distance) |
      is.na(athlete_mean_pace) |
      is.na(athlete_mean_fatigue)
  ) %>%
  distinct(athlete_id)

if (nrow(missing_test_means) > 0) {
  stop(
    paste0(
      "The test subset contains athlete IDs with no training observations: ",
      paste(missing_test_means$athlete_id, collapse = ", "),
      ". A different split or an explicit new-athlete preprocessing rule is required."
    )
  )
}

cat(
  "All test observations received athlete means calculated from training data only.\n"
)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Optional diagnostic verification (Verify the Revised Preprocessing)

cat("\n--- TRAINING-DERIVED ATHLETE MEANS ---\n")
print(athlete_training_means)

cat("\n--- TRAINING SUBSET SUMMARY ---\n")
print(
  train_data %>%
    summarise(
      rows = n(),
      athletes = n_distinct(athlete_id),
      mean_distance_centered = mean(distance_centered),
      mean_pace_centered = mean(pace_centered),
      mean_fatigue_deviation = mean(fatigue_deviation)
    )
)

cat("\n--- TEST SUBSET SUMMARY ---\n")
print(
  test_data %>%
    summarise(
      rows = n(),
      athletes = n_distinct(athlete_id),
      missing_athlete_means = sum(
        is.na(athlete_mean_distance) |
          is.na(athlete_mean_pace) |
          is.na(athlete_mean_fatigue)
      )
    )
)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Revised benchmark-model block (Fit the Benchmark Models)

f_model <- vo2_utilisation ~
  distance_centered +
  athlete_mean_distance +
  pace_centered +
  athlete_mean_pace +
  fatigue_deviation +
  athlete_mean_fatigue +
  calories_per_min +
  activity_group +
  weather_group +
  personal_status


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# MODEL 1: Ordinary Least Squares
m_ols <- lm(
  f_model,
  data = train_data
)

pred_ols <- predict(
  m_ols,
  newdata = test_data
)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# MODEL 2: Elastic Net

X_train <- model.matrix(
  f_model,
  data = train_data
)[, -1, drop = FALSE]

Y_train <- train_data$vo2_utilisation

X_test <- model.matrix(
  f_model,
  data = test_data
)[, -1, drop = FALSE]

# Confirm identical predictor columns and ordering.
if (!identical(colnames(X_train), colnames(X_test))) {
  stop(
    paste0(
      "Training and test model matrices do not have identical columns. ",
      "Check factor levels before fitting Elastic Net."
    )
  )
}

set.seed(123)

m_enet <- cv.glmnet(
  x = X_train,
  y = Y_train,
  alpha = 0.5,
  nfolds = 10,
  standardize = TRUE
)

pred_enet <- as.vector(
  predict(
    m_enet,
    newx = X_test,
    s = "lambda.1se"
  )
)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false

# MODEL 3: Random Forest

set.seed(123)

m_rf <- ranger(
  formula = f_model,
  data = train_data,
  num.trees = 500,
  importance = "impurity"
)

pred_rf <- predict(
  m_rf,
  data = test_data
)$predictions


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Prediction-length check
stopifnot(
  length(pred_ols) == nrow(test_data),
  length(pred_enet) == nrow(test_data),
  length(pred_rf) == nrow(test_data)
)

cat("\n--- PREDICTION VECTOR CHECK ---\n")
cat("Test rows          :", nrow(test_data), "\n")
cat("OLS predictions    :", length(pred_ols), "\n")
cat("Elastic Net        :", length(pred_enet), "\n")
cat("Random Forest      :", length(pred_rf), "\n")


## ----results = 'hide'---------------------------------------------------------
calc_metrics <- function(actual, predicted) {

  complete_predictions <- complete.cases(
    actual,
    predicted
  )

  actual_complete <- actual[complete_predictions]
  predicted_complete <- predicted[complete_predictions]

  rmse_val <- sqrt(
    mean(
      (actual_complete - predicted_complete)^2
    )
  )

  mae_val <- mean(
    abs(
      actual_complete - predicted_complete
    )
  )

  test_sse <- sum(
    (actual_complete - predicted_complete)^2
  )

  test_sst <- sum(
    (actual_complete - mean(actual_complete))^2
  )

  r2_val <- 1 - (test_sse / test_sst)

  c(
    RMSE = rmse_val,
    MAE = mae_val,
    R2_OutSample = r2_val
  )
}

results_ols <- calc_metrics(
  test_data$vo2_utilisation,
  pred_ols
)

results_enet <- calc_metrics(
  test_data$vo2_utilisation,
  pred_enet
)

results_rf <- calc_metrics(
  test_data$vo2_utilisation,
  pred_rf
)

benchmark_table <- tibble(
  Model = c(
    "Linear Regression (OLS)",
    "Elastic Net (GLMNET)",
    "Random Forest (Ranger)"
  ),

  RMSE = c(
    results_ols["RMSE"],
    results_enet["RMSE"],
    results_rf["RMSE"]
  ),

  MAE = c(
    results_ols["MAE"],
    results_enet["MAE"],
    results_rf["MAE"]
  ),

  `R2 Out-of-Sample` = c(
    results_ols["R2_OutSample"],
    results_enet["R2_OutSample"],
    results_rf["R2_OutSample"]
  )
) %>%
  mutate(
    across(
      c(RMSE, MAE, `R2 Out-of-Sample`),
      ~ round(.x, 4)
    )
  )

cat(
  "--- OUT-OF-SAMPLE PREDICTIVE BENCHMARKING RESULTS ---\n"
)

print(benchmark_table)


## -----------------------------------------------------------------------------
#| fig-cap: "Figure 5.1. Observed and predicted VO₂ utilisation for the three models in the held-out test subset."
#| fig-align: center
#| warning: false
#| message: false

df_preds <- test_data %>%
  transmute(
    vo2_utilisation,
    activity_group,
    OLS = pred_ols,
    ElasticNet = pred_enet,
    RandomForest = pred_rf
  ) %>%
  pivot_longer(
    cols = c(
      OLS,
      ElasticNet,
      RandomForest
    ),
    names_to = "Model",
    values_to = "Predicted"
  ) %>%
  mutate(
    Model = factor(
      Model,
      levels = c(
        "OLS",
        "ElasticNet",
        "RandomForest"
      ),
      labels = c(
        "OLS",
        "Elastic Net",
        "Random Forest"
      )
    )
  )

p_predictive <- ggplot(
  df_preds,
  aes(
    x = vo2_utilisation,
    y = Predicted,
    colour = Model
  )
) +
  geom_point(
    alpha = 0.6
  ) +
  geom_abline(
    intercept = 0,
    slope = 1,
    linetype = "dashed",
    colour = "black"
  ) +
  facet_wrap(
    ~ Model
  ) +
  coord_equal() +
  theme_minimal() +
labs(
  title = "Out-of-Sample Predictions by Model",
  subtitle = paste0(
    "Observed and predicted VO2 utilisation in the held-out test subset, ",
    "n = ",
    nrow(test_data)
  ),
  x = "Observed VO2 Utilisation",
  y = "Predicted VO2 Utilisation",
  colour = "Model"
)

print(p_predictive)


## -----------------------------------------------------------------------------
#| echo: false
#| output: false
#| warning: false
#| message: false
# Rank Models by Test Performance

benchmark_ranking <- benchmark_table %>%
  arrange(
    RMSE,
    MAE
  ) %>%
  mutate(
    RMSE_Rank = row_number()
  )

cat("\n--- MODEL RANKING BY TEST RMSE ---\n")
print(benchmark_ranking)

