# SENSIBILIDADE NORMALIZAÇÃO | LINEAR

fit_linear_dias <- function(x, y1, y2) {
  m1 <- lm(y1 ~ x)
  m2 <- lm(y2 ~ x)
  p1 <- coef(m1); p2 <- coef(m2)
  
  denom <- p1[2] - p2[2]
  if (abs(denom) < 1e-12) return(NULL)
  dias_x <- (p2[1] - p1[1]) / denom
  dias_y <- p1[1] + p1[2] * dias_x
  return(c(dias_x = dias_x, dias_y = dias_y))
}

normalize_minmax <- function(y) {
  (y - min(y)) / (max(y) - min(y)) * 100
}

normalize_zscore <- function(y) {
  (y - mean(y)) / sd(y)
}


a1 <- 20; b1 <- 2
a2 <- 60; b2 <- -1
n <- 10
x <- seq(0, 20, length.out = n)
sigma <- 2
n_sim <- 1000

results <- data.frame()

set.seed(123)
for (i in 1:n_sim) {
  y1 <- a1 + b1 * x + rnorm(n, 0, sigma)
  y2 <- a2 + b2 * x + rnorm(n, 0, sigma)
  
  res_none <- fit_linear_dias(x, y1, y2)
  res_minmax <- fit_linear_dias(x, normalize_minmax(y1), normalize_minmax(y2))
  res_zscore <- fit_linear_dias(x, normalize_zscore(y1), normalize_zscore(y2))
  
  results <- rbind(results, data.frame(
    norm = c("none", "minmax", "zscore"),
    dias_x = c(res_none[1], res_minmax[1], res_zscore[1]),
    dias_y = c(res_none[2], res_minmax[2], res_zscore[2])
  ))
}

summary_stats <- aggregate(cbind(dias_x, dias_y) ~ norm, data = results,
                           FUN = function(z) c(mean = mean(z), sd = sd(z)))
print(summary_stats)
write.csv(results, "sensitivity_normalisation_results.csv", row.names = FALSE)