---
title: "Tests Kats"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Tests Kats}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(FrailtyCompRisk)
library(tibble)
library(dplyr)
library(knitr)
library(kableExtra)
```

Multi_tests with simulate_data()


fonctions annexes

```{r}
compute_mean_mse <- function(df, true_values) {
  if (!is.data.frame(df)) stop("L'entrée doit être un data.frame.")
  if (!is.numeric(true_values)) stop("true_values doit être un vecteur numérique.")
  if (ncol(df) != length(true_values)) {
    stop("Le nombre de colonnes du data.frame doit correspondre à la longueur de true_values.")
  }

  means <- colMeans(df, na.rm = TRUE)
  
  true_mat <- matrix(rep(true_values, each = nrow(df)), nrow = nrow(df), byrow = FALSE)
  mse <- colMeans((df - true_mat)^2, na.rm = TRUE)
  
  result <- data.frame(
    variable = colnames(df),
    true_value = true_values,
    mean = means,
    mse = mse
  )
  
  return(result)
}
```


Ml_Cox()

```{r}
Multi_tests = function(N_test,
                       n_cov,
                       n_cluster,
                       n_per_cluster,
                       a1,
                       b1)
{
  n = n_cluster * n_per_cluster
  results <- data.frame(matrix(NA, nrow = N_test, ncol = (n_cov)))
  if (n_cov > 0) {
    colnames(results) <- paste0("beta", 1:n_cov)
  } else{
    stop("Covariables missing")
  }
  for (i in 1:N_test)
  {
    G <- rep(1:n_cluster, each = n_per_cluster)
    if (n_cov == 0) {
      Z <- matrix(0, n, 0)
    } else {
      Z <- matrix(runif(n * n_cov, a1, b1), ncol = n_cov)
    }
    df = simulate_data(
      G,
      Z,
      prop = 0.6,
      beta = c(0, 0.25, 0.12, 0.33, 0.24, 1, -0.2, -0.35),
      theta = 0,
      cens = TRUE,
      pcens = 0.25,
      tau = 0.5
    )
    df = data.frame(times = df$times, status = df$status,clusters = rep(1,length(G)),as.matrix(df[,4:(n_cov + 3)]))
    ind <- which(df$status > 1)
    df$status[ind] <- 1
    res <- tryCatch(
      Ml_Cox(df),
      error = function(e) {
        message("Erreur à l’itération ", i, " : ", e$message)
        return(NULL)
      }
    )
    
    if (!is.null(res)) {
      if (n_cov > 0) {
        results[i, 1:n_cov] <- res$beta
      }
    }
  }
  return(results)
}

M = Multi_tests(N_test = 100,n_cov = 8,n_cluster = 20,n_per_cluster = 25,a1 = 0,b1=1)
m = compute_mean_mse(M, c(0, 0.25, 0.12, 0.33, 0.24, 1, -0.2, -0.35))
m

```


Reml_Cox_frailty()

```{r}
Multi_tests = function(N_test,
                       n_cov,
                       n_cluster,
                       n_per_cluster,
                       a1,
                       b1)
{
  suppressMessages({
  n = n_cluster * n_per_cluster
  results <- data.frame(matrix(NA, nrow = N_test, ncol = (n_cov + 1)))
  if (n_cov > 0) {
    colnames(results) <- c(paste0("beta", 1:n_cov), "theta_hat")
  } else{
    colnames(results) <- "theta_hat"
  }
  for (i in 1:N_test)
  {
    G <- rep(1:n_cluster, each = n_per_cluster)
    if (n_cov == 0) {
      Z <- matrix(0, n, 0)
    } else {
      Z <- matrix(runif(n * n_cov, a1, b1), ncol = n_cov)
    }
    df = simulate_data(
      G,
      Z,
      prop = 0.6,
      beta = c(0, 0.25, 0.12, 0.33, 0.24, 1, -0.2, -0.35),
      theta = 0,
      cens = TRUE,
      pcens = 0.25,
      tau = 0.5
    )
    check_data_format(df)
    res <- tryCatch(
      Reml_Cox_frailty(df, max_iter = 100),
      error = function(e) {
        message("Erreur à l’itération ", i, " : ", e$message)
        return(NULL)
      }
    )
   if (is.null(res)) {
     res_bis <- tryCatch(
      Ml_Cox(df, max_iter = 100),
      error = function(e) {
        message("Erreur à l’itération ", i, " : ", e$message)
        return(NULL)})
     res <- list(beta = res_bis$beta,theta = 0)
   }
    if (!is.null(res)) {
      if (n_cov > 0) {
        results[i, 1:n_cov] <- res$beta
        results[i, "theta_hat"] <- res$theta
      } else{
        results[i, "theta_hat"] <- res$theta
      }
    }
  }
  })
  return(results)
}

M = Multi_tests(N_test = 100,n_cov = 8,n_cluster = 15, n_per_cluster = 20,a1 = 0,b1 = 1)
m = compute_mean_mse(M,c(0,0.25,0.12,0.33,0.24,1,-0.2,-0.35,0))
m
```


Ml_CompRisk()

```{r}
Multi_tests = function(N_test,
                       n_cov,
                       n_cluster,
                       n_per_cluster,
                       a1,
                       b1)
{
  n = n_cluster * n_per_cluster
  results <- data.frame(matrix(NA, nrow = N_test, ncol = (n_cov)))
  if (n_cov > 0) {
    colnames(results) <- paste0("beta", 1:n_cov)
  } else{
    stop("Covariables missing")
  }
  for (i in 1:N_test)
  {
    G <- rep(1:n_cluster, each = n_per_cluster)
    if (n_cov == 0) {
      Z <- matrix(0, n, 0)
    } else {
      Z <- matrix(runif(n * n_cov, a1, b1), ncol = n_cov)
    }
    df = simulate_data(
      G,
      Z,
      prop = 0.6,
      beta = c(0, 0.25, 0.12, 0.33, 0.24, 1, -0.2, -0.35),
      theta = 0,
      cens = TRUE,
      pcens = 0.25,
      tau = 0.5
    )
    df = data.frame(times = df$times, status = df$status, clusters = rep(1,length(G)), as.matrix(df[,4:(n_cov + 3)]))
    res <- tryCatch(
      Ml_CompRisk(df),
      error = function(e) {
        message("Erreur à l’itération ", i, " : ", e$message)
        return(NULL)
      }
    )
    
    if (!is.null(res)) {
      if (n_cov > 0) {
        results[i, 1:n_cov] <- res$beta
      }
    }
  }
  return(results)
}

M = Multi_tests(N_test = 100,n_cov = 8,n_cluster = 20,n_per_cluster = 25,a1 = 0,b1 = 1)
m = compute_mean_mse(M, c(0, 0.25, 0.12, 0.33, 0.24, 1, -0.2, -0.35))
m
```


Reml_CompRisk_frailty()

```{r}
Multi_tests = function(N_test,
                       n_cov,
                       n_cluster,
                       n_per_cluster,
                       a1,
                       b1)
{
  suppressMessages({
  n = n_cluster * n_per_cluster
  results <- data.frame(matrix(NA, nrow = N_test, ncol = (n_cov + 1)))
  if (n_cov > 0) {
    colnames(results) <- c(paste0("beta", 1:n_cov), "theta_hat")
  } else{
    colnames(results) <- "theta_hat"
  }
  for (i in 1:N_test)
  {
    G <- rep(1:n_cluster, each = n_per_cluster)
    if (n_cov == 0) {
      Z <- matrix(0, n, 0)
    } else {
      Z <- matrix(runif(n * n_cov, a1, b1), ncol = n_cov)
    }
    df = simulate_data(
      G,
      Z,
      prop = 0.6,
      beta = c(0, 0.25, 0.12, 0.33, 0.24, 1, -0.2, -0.35),
      theta = 0,
      cens = TRUE,
      pcens = 0.25,
      tau = 0.5
    )
    check_data_format(df)
    res <- tryCatch(
      Reml_CompRisk_frailty(df, max_iter = 100),
      error = function(e) {
        message("Erreur à l’itération ", i, " : ", e$message)
        return(NULL)
      }
    )
   if (is.null(res)) {
     res_bis <- tryCatch(
      Ml_CompRisk(df, max_iter = 100),
      error = function(e) {
        message("Erreur à l’itération ", i, " : ", e$message)
        return(NULL)})
     res <- list(beta = res_bis$beta,theta = 0)
   }
    if (!is.null(res)) {
      if (n_cov > 0) {
        results[i, 1:n_cov] <- res$beta
        results[i, "theta_hat"] <- res$theta
      } else{
        results[i, "theta_hat"] <- res$theta
      }
    }
  }
  })
  return(results)
}

M = Multi_tests(N_test = 100,n_cov = 8,n_cluster = 15, n_per_cluster = 20,a1 = 0,b1 = 1)
m = compute_mean_mse(M,c(0,0.25,0.12,0.33,0.24,1,-0.2,-0.35,0))
m
```



Creation of huge data sets with numerous variables

```{r}
generate_full_table <- function(
  beta_vec,
  theta_vec,
  N_vec,
  K_vec,
  n_sim = 100,
  pcens = 0.25
) {
  iter <- 1
  n_iter <- n_sim * length(N_vec) * length(K_vec) * length(theta_vec) * length(beta_vec)
  full_results <- list()
  idx <- 1

  suppressWarnings(suppressMessages({
    for (theta in theta_vec) {
      for (beta in beta_vec) {
        beta_clean <- as.numeric(beta)
        n_cov <- length(beta_clean)

        for (N in N_vec) {
          for (K in K_vec) {
            n_per_cluster <- N / K
            config_id <- paste0("gamma=", paste(beta_clean, collapse = ","),
                                "  theta=", theta,
                                "  N=", N,
                                "  K=", K)
            cat("Starting :", config_id, "\n")

            results_1 <- matrix(NA, nrow = n_sim, ncol = n_cov)
            results_2 <- rep(NA, n_sim)

            for (i in 1:n_sim) {
              cat("iteration", iter, "out of", n_iter, "\n")
              G <- rep(1:K, each = n_per_cluster)
              Z <- if (n_cov == 0) matrix(0, N, 0) else matrix(runif(N * n_cov, 0, 1), ncol = n_cov)

              df <- simulate_data(G, Z, prop = 0.6, beta = beta_clean, theta = theta,
                                  cens = TRUE, pcens = pcens, tau = 0.5)
              check_data_format(df)
              res <- tryCatch(
                Reml_CompRisk_frailty(df),
                error = function(e) return(NULL)
              )
              if (!is.null(res)) {
                if (n_cov > 0) {
                  results_1[i, ] <- res$beta
                }
                results_2[i] <- res$theta
              }
              iter <- iter + 1
            }
            mean_gamma_hat <- c()
            mse_gamma_hat <- c()
            gamma_vals <- c()

            if (n_cov > 0) {
              mean_gamma_hat <- colMeans(results_1, na.rm = TRUE)
              mse_gamma_hat <- colMeans((results_1 - matrix(rep(beta, each = n_sim), nrow = n_sim))^2, na.rm = TRUE)
            }
            
            mean_theta_hat <- mean(results_2, na.rm = TRUE)
            mse_theta_hat <- mean((results_2 - rep(theta, n_sim))^2, na.rm = TRUE)
            
            gamma_data <- tibble(
              gamma = list(beta),
              mean_gamma_hat = list(mean_gamma_hat),
              mse_gamma_hat = list(mse_gamma_hat)
            )
            
            full_results[[idx]] <- bind_cols(
              tibble(
                N = N,
                K = K,
                theta = theta,
                mean_theta_hat = mean_theta_hat,
                mse_theta_hat = mse_theta_hat
              ),
              gamma_data
            )
            idx <- idx + 1
            cat("Finished :", config_id, "\n")
          }
        }
      }
    }
  }))

  final_df <- do.call(rbind, full_results)
  return(list(final_df = final_df,beta_vec = beta_vec))
}

#big_table <- generate_full_table(beta_vec = list(a=c(0),b=c(0.375)), theta_vec = c(0, 0.1, 0.6), N_vec = c(200, 500), K_vec = c(5, 20), n_sim = 100, pcens = 0.25)

#big_table$final_df
```

```{r}
export_to_latex <- function(final_df, file = "simulation_results.tex") {
  # On applique une ligne par simulation avec une cellule contenant les vecteurs formatés
  formatted_df <- final_df %>%
    mutate(
      gamma = sapply(gamma, function(x) paste0("(", paste(round(x, 3), collapse = ", "), ")")),
      mean_gamma_hat = sapply(mean_gamma_hat, function(x) paste0("(", paste(round(x, 3), collapse = ", "), ")")),
      mse_gamma_hat = sapply(mse_gamma_hat, function(x) paste0("(", paste(round(x, 5), collapse = ", "), ")")),
      mean_theta_hat = round(mean_theta_hat, 3),
      mse_theta_hat = round(mse_theta_hat, 5)
    )

  # Affichage en LaTeX
  tex_table <- kable(formatted_df, format = "latex", booktabs = TRUE, escape = FALSE,
                     col.names = c("N", "K", "$\\theta$", "$\\widehat{\\theta}$", "MSE($\\theta$)",
                                   "$\\gamma$", "$\\widehat{\\gamma}$", "MSE($\\gamma$)")) %>%
    kable_styling(latex_options = c("striped", "hold_position"), full_width = FALSE)

  # Sauvegarde dans un fichier
  writeLines(tex_table, file)
}
```
```{r}
#export_to_latex(big_table$final_df,"tableau_Sandrine.tex")
```





