#-------------------------
## Load required libraries
#-------------------------

library(tidyverse)
library(vroom)
library(caret)
library(glmnet)
library(pROC)


#------------------------
## Load data and metadata
#------------------------
# Normalized counts
ntd <- vroom("reports/ntd_merged_corrected.tsv")

# Metadata
meta_validation <-
  vroom("data/validation_set_metadata.tsv") %>%
  rename(
    Sample = `id sample`, Group = `grado de enfermedad`
  ) %>%
  mutate(
    Group = factor(Group),
    Sample = as.character(Sample),
    #etnia = as.factor(etnia),
    #sexo = as.factor(sexo)
  ) %>%
  select(
    Sample, edad, sexo, imc, Group
  ) %>%
  drop_na()

meta_original <-
  vroom("../Metadata_Marató_94samples_1.tsv") %>%
  rename(
    Sample = `ID complet`, Group = `Grado enfermedad coronaria`
  ) %>%
  mutate(
    Sample=as.character(Sample),
    Group=as.factor(Group),
    #sexo=as.factor(sexo)
    #etnia=as.factor(etnia),
  ) %>%
  select(
    Sample, edad, sexo, imc, Group
  ) %>%
  drop_na()

meta <-
  meta_validation %>%
  bind_rows(meta_original)

degs <- vroom("reports/degs/final/degs_CADvsHealthy.tsv")

#annotation <- vroom(
#  "../raw_data_processing/new_samples_2025/mapping_quantification/grape_pipeline/gene_annotation_v48.tsv",
#  col_names = c(
#    "Chrom","Start","End", "Strand",
#    "GeneID", "GeneType","GeneName"
#  )
#)


#------------------
## Pre-process Data
#------------------
# Make Patient vs Healthy Group variable
meta <-
  meta %>%
  filter(Sample %in% colnames(ntd)) %>%
  rename(
    Age = edad,
    Sex = sexo,
    BMI = imc
  ) %>%
  mutate(
    group = Group,
    Group = case_when(
      Group == "1" ~ "Healthy",
      Group %in% c("2", "3") ~ "Patient",
      .default = NA
    ),
    Group = factor(Group, levels = c("Patient", "Healthy"))
  )

# Is there an covariance imbalance in the data?
meta %>%
  group_by(Group, Sex) %>%
  summarise(
    N = n(),
    Age = mean(Age),
    BMI = mean(BMI)
    #group_1 = sum(group == 1),
    #group_2 = sum(group == 2),
    #group_3 = sum(group == 3)
  )

# Subsample dataset to make it balanced
set.seed(345)
meta_balanced <-
  meta %>%
  mutate(
    age_bin = cut(
      Age,
      breaks = quantile(Age, seq(0, 1, 0.1)),
      include.lowest = TRUE
    )
  ) %>%
  group_by(Sex, age_bin) %>%
  mutate(n_min = min(table(Group))) %>%
  group_by(Sex, age_bin, Group) %>%
  slice_sample(prop = 1) %>%
  filter(row_number() <= unique(n_min)) %>%
  ungroup() %>%
  select(-n_min)


# reorder metadata to match gene counts matrix
meta <-
  meta %>%
  #meta_balanced %>%
  column_to_rownames("Sample")

# transpose gene counts matrix
data <-
  ntd %>%
  #mutate(GeneID = str_sub(GeneID, 1, 15)) %>%
  filter(GeneID %in% degs$GeneID) %>%
  column_to_rownames("GeneID") %>%
  select(which(colnames(.) %in% rownames(meta))) %>%
  as.matrix() %>%
  t()

meta <- meta[rownames(data), , drop = FALSE]
all(rownames(meta) == rownames(data))

# Calculate split index
set.seed(345)
trainIndex <- createDataPartition(
  meta$Group,
  p = 0.6,
  list = FALSE,
  times = 1
)

covars <- c("BMI", "Age", "Sex")              # explicit; add/remove as appropriate
stopifnot(!anyNA(meta[, covars]))       # glmnet can't handle NAs

x_train <- cbind(data[trainIndex, ],  meta[trainIndex,  covars, drop = FALSE])
x_test  <- cbind(data[-trainIndex, ],  meta[-trainIndex, covars, drop = FALSE])
y_train <- meta$Group[trainIndex]
y_test  <- meta$Group[-trainIndex]



#-------------------------------------
## Model training and parameter tuning
#-------------------------------------
fitControl <- trainControl(
  method = "repeatedcv", number = 5, repeats = 10,
  classProbs = TRUE,
  summaryFunction = twoClassSummary,    # ROC, Sens, Spec
  savePredictions = "final"             # keep out-of-fold predictions
)

# Data-driven lambda grid for pure LASSO
x_scaled <- scale(as.matrix(x_train))
fit0 <- glmnet(x_scaled, y_train, family = "binomial",
               alpha = 0.25, standardize = FALSE)
lmax <- max(fit0$lambda)

grid <- expand.grid(
  #alpha  = 1,
  alpha  = c(0.25, 0.5, 0.75, 1),
  lambda = 10^seq(log10(lmax), log10(lmax * 1e-3), length.out = 80)
)

set.seed(345)
model <- train(
  x = x_train, y = y_train,
  method = "glmnet", family = "binomial",
  metric = "ROC",
  preProcess = c("center", "scale"),    # learned inside each fold, reused at predict()
  standardize = FALSE,
  trControl = fitControl, tuneGrid = grid
)

saveRDS(model, "RData/final/model_glmnet.rds")

# Model that uses only covariates
# How much does expression add to the predictions
base <- train(
  x = x_train[, covars], y = y_train, method = "glm",
  family = "binomial", metric = "ROC", trControl = fitControl
)
auc(roc(
  y_test, predict(base, x_test[, covars], type = "prob")$Patient,
  levels = c("Healthy", "Patient"), direction = "<"
))

#--------------------------------------------------------
## Choose threshold from OUT-OF-FOLD training predictions
#--------------------------------------------------------
target_sens <- 0.95                     # set by your clinical requirement

oof <- model$pred %>%
  group_by(rowIndex, obs) %>%           # average over the 10 repeats
  summarise(p = mean(Patient), .groups = "drop")

ths  <- sort(unique(oof$p))
sens <- sapply(ths, function(t) mean(oof$p[oof$obs == "Patient"] >= t))
thr  <- max(ths[sens >= target_sens])   # highest threshold meeting target sensitivity

cat("Threshold:", round(thr, 3),
    "| OOF specificity:", round(mean(oof$p[oof$obs == "Healthy"] < thr), 3), "\n")


#-------------------------
## Evaluation of the model
#-------------------------
thr <- 0.5
p_test    <- predict(model, newdata = x_test, type = "prob")$Patient
pred_test <- factor(ifelse(p_test >= thr, "Patient", "Healthy"),
                    levels = levels(y_test))

confMatrix <- confusionMatrix(pred_test, y_test, positive = "Patient")
# Add prevalence = <your intended-use prevalence> to get NPV/PPV for that population

confusion_matrix <- as.data.frame(confMatrix$table)
metrics <- tibble(
  Sensitivity = confMatrix$byClass["Sensitivity"],
  Specificity = confMatrix$byClass["Specificity"],
  PPV         = confMatrix$byClass["Pos Pred Value"],
  NPV         = confMatrix$byClass["Neg Pred Value"],
  Accuracy    = confMatrix$overall["Accuracy"]
) %>% mutate(across(everything(), ~ round(.x, 3)))
metrics

roc_test <- roc(y_test, p_test, levels = c("Healthy", "Patient"), direction = "<")
auc(roc_test); ci.auc(roc_test)
ci_val <- as.numeric(ci.auc(roc_test))

# Exact CI on sensitivity (will be wide with a small test set)
n_pat <- sum(y_test == "Patient")
binom.test(sum(pred_test == "Patient" & y_test == "Patient"), n_pat)$conf.int


#------------
## Importance
#------------
#coefs <- coef(model$finalModel, s = model$bestTune$lambda)
#
#importance <-
#  tibble(Variable = rownames(coefs), Coefficient = as.numeric(coefs)) %>%
#  filter(Variable != "(Intercept)", Coefficient != 0) %>%
#  mutate(Importance = abs(Coefficient)) %>%   # coefficients are on the scaled features
#  arrange(desc(Importance))

importance <-
  model %>%
  varImp

importance <-
  importance$importance %>%
  rownames_to_column('Variable') %>%
  as_tibble() %>%
  arrange(desc(Overall)) %>%
  rename(Importance=Overall) %>%
  left_join(
    degs %>%
      select(GeneID, GeneName),
      by=c("Variable" = "GeneID")
  )

importance$GeneName[which(is.na(importance$GeneName))] <-
  importance$Variable[which(is.na(importance$GeneName))]

importance <-
  importance %>%
  select(-Variable) %>%
  rename(Variable = GeneName)


#-------------------------------------------------
## Plot evaluation metrics and variable importance
#-------------------------------------------------
library(gridExtra)
library(grid)
library(gtable)
#source("~/bin/theme_publication.R")
pdf('plots/final/classification_glmnet.pdf')
ggplot(data =  confusion_matrix,
       mapping = aes(x = Reference, y = Prediction)) +
  geom_tile(aes(fill = Freq), colour = "white") +
  geom_text(aes(label = sprintf("%1.0f", Freq)), vjust = 1) +
  theme_bw() + theme(legend.position = "none")

plot(
  roc_test,
  print.thres = thr,
  legacy.axes = TRUE
)
text(0.4, 0.2, sprintf("AUC = %.2f (%.2f-%.2f)", ci_val[2], ci_val[1], ci_val[3]))

g <- tableGrob(metrics, rows = NULL)
g <- gtable_add_grob(g,
        grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
        t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
        grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
        t = 1, l = 1, r = ncol(g))
#g1 <- tableGrob(as.data.frame(accuracy_overall), rows = NULL)
#grid.arrange(g, g1, nrow=2)
grid.arrange(g, nrow=1)

importance %>%
  head(n=50) %>%
  mutate(Variable=fct_reorder(Variable, Importance)) %>%
  ggplot(aes(x=Variable, y=Importance)) +
  geom_segment(aes(x=Variable,
                   xend=Variable,
                   y=0, yend=Importance),
               color="skyblue") +
  geom_point(color="blue", size=4, alpha=0.6) +
  theme_light() +
  coord_flip() +
  #theme_publication() +
  theme(
    panel.grid.major.y = element_blank(),
    panel.border = element_blank(),
    axis.ticks.y = element_blank()
  )

dev.off()
