# ============================================================================
# IA-DeepIV v8 - Revision Script
# Journal: Applied Artificial Intelligence
# Changes vs v7:
#   1. Output to ~/Downloads/ia_deepiv_outputs
#   2. Card 1995 uses small network + stronger regularization
#   3. train_additive: new args weight_decay / hidden1 / hidden2 / dropout
# ============================================================================

# ---------------------------------------------------------------------------
# 0. ENVIRONMENT
# ---------------------------------------------------------------------------
if (getRversion() < "4.1.0") stop("torch requires R >= 4.1.0")

pkgs <- c("torch", "AER", "ggplot2", "Metrics", "randomForest",
          "reshape2", "gridExtra", "wooldridge")
for (p in pkgs) {
  if (!requireNamespace(p, quietly = TRUE)) {
    install.packages(p, repos = "https://cloud.r-project.org")
  }
  library(p, character.only = TRUE)
}
if (!torch::torch_is_installed()) {
  torch::install_torch(); stop("Restart R and rerun.")
}
cat("PyTorch OK.\n")

OUT <- file.path(Sys.getenv("HOME"), "Downloads", "ia_deepiv_outputs")
if (!dir.exists(OUT)) dir.create(OUT, recursive = TRUE)
cat("Output folder:", OUT, "\n")

# ============================================================================
# 1. DATA GENERATORS
# ============================================================================
generate_dgp1 <- function(n = 8000, dim_x = 8, dim_z = 10, seed = 2026) {
  set.seed(seed)
  X <- matrix(rnorm(n * dim_x), ncol = dim_x)
  Z <- matrix(rnorm(n * dim_z), ncol = dim_z)
  beta_z <- numeric(dim_z); beta_z[1:3] <- c(1.5, 2.0, 2.5)
  f_x <- 2.0*sin(X[,1]*X[,2]) + 1.5*cos(X[,3])*X[,4] +
    0.8*X[,5]^3 + 0.6*exp(-X[,1]^2)*X[,2]
  h_x <- 0.5*X[,1] + 0.3*X[,2]
  T <- 2.5*(Z %*% beta_z) + 0.02*X[,1] + rnorm(n, sd = 0.3)
  theta_true <- f_x + T*h_x
  Y <- T*(f_x + 0.5*T*h_x) + 0.1*X[,1] - 0.05*X[,2] + rnorm(n, sd = 0.1)
  idx <- sample(1:n, floor(0.7*n))
  list(train = list(X=X[idx,], Z=Z[idx,], T=T[idx], Y=Y[idx], theta=theta_true[idx]),
       valid = list(X=X[-idx,], Z=Z[-idx,], T=T[-idx], Y=Y[-idx], theta=theta_true[-idx]))
}

generate_dgp2_noXT <- function(n = 8000, dim_x = 8, dim_z = 10, seed = 2026) {
  set.seed(seed)
  X <- matrix(rnorm(n * dim_x), ncol = dim_x)
  Z <- matrix(rnorm(n * dim_z), ncol = dim_z)
  beta_z <- numeric(dim_z); beta_z[1:3] <- c(1.5, 2.0, 2.5)
  theta_true <- sin(X[,1]) + 0.5 * X[,2]^2 + X[,3] * X[,4]
  T <- 2.5*(Z %*% beta_z) + 0.02*X[,1] + rnorm(n, sd = 0.3)
  Y <- T * theta_true + 0.1*X[,1] - 0.05*X[,2] + rnorm(n, sd = 0.1)
  idx <- sample(1:n, floor(0.7*n))
  list(train = list(X=X[idx,], Z=Z[idx,], T=T[idx], Y=Y[idx], theta=theta_true[idx]),
       valid = list(X=X[-idx,], Z=Z[-idx,], T=T[-idx], Y=Y[-idx], theta=theta_true[-idx]))
}

generate_interaction_strength <- function(n = 8000, dim_x = 8, dim_z = 10,
                                          c = 0.5, seed = 2026) {
  set.seed(seed)
  X <- matrix(rnorm(n * dim_x), ncol = dim_x)
  Z <- matrix(rnorm(n * dim_z), ncol = dim_z)
  beta_z <- numeric(dim_z); beta_z[1:3] <- c(1.5, 2.0, 2.5)
  f_x <- 2.0*sin(X[,1]*X[,2]) + 1.5*cos(X[,3])*X[,4] +
    0.8*X[,5]^3 + 0.6*exp(-X[,1]^2)*X[,2]
  h_x <- 0.5*X[,1] + 0.3*X[,2]
  T <- 2.5*(Z %*% beta_z) + 0.02*X[,1] + rnorm(n, sd = 0.3)
  theta_true <- f_x + c * T * h_x
  Y <- T*(f_x + 0.5*c*T*h_x) + 0.1*X[,1] - 0.05*X[,2] + rnorm(n, sd = 0.1)
  idx <- sample(1:n, floor(0.7*n))
  list(train = list(X=X[idx,], Z=Z[idx,], T=T[idx], Y=Y[idx], theta=theta_true[idx]),
       valid = list(X=X[-idx,], Z=Z[-idx,], T=T[-idx], Y=Y[-idx], theta=theta_true[-idx]))
}

generate_weak_iv <- function(n = 8000, dim_x = 8, dim_z = 10,
                             kappa = 1.0, seed = 2026) {
  set.seed(seed)
  X <- matrix(rnorm(n * dim_x), ncol = dim_x)
  Z <- matrix(rnorm(n * dim_z), ncol = dim_z)
  beta_z <- numeric(dim_z); beta_z[1:3] <- c(1.5, 2.0, 2.5)
  z_signal <- as.numeric(Z %*% beta_z); z_signal <- z_signal / sd(z_signal)
  T <- kappa * z_signal + sqrt(1 - kappa^2) * rnorm(n)
  T <- T + 0.05 * X[,1]; T <- T / sd(T)
  f_x <- 2.0*sin(X[,1]*X[,2]) + 1.5*cos(X[,3])*X[,4] +
    0.8*X[,5]^3 + 0.6*exp(-X[,1]^2)*X[,2]
  h_x <- 0.5*X[,1] + 0.3*X[,2]
  theta_true <- f_x + T*h_x
  Y <- T*(f_x + 0.5*T*h_x) + 0.1*X[,1] - 0.05*X[,2] + rnorm(n, sd = 0.1)
  idx <- sample(1:n, floor(0.7*n))
  list(train = list(X=X[idx,], Z=Z[idx,], T=T[idx], Y=Y[idx], theta=theta_true[idx]),
       valid = list(X=X[-idx,], Z=Z[-idx,], T=T[-idx], Y=Y[-idx], theta=theta_true[-idx]))
}

# ============================================================================
# 2. FEATURES
# ============================================================================
build_features <- function(X, T_vec, include_xt = TRUE) {
  X_poly <- cbind(X, X^2)
  if (include_xt) cbind(X_poly, X * T_vec) else X_poly
}

# ============================================================================
# 3. NETWORKS
# ============================================================================
Stage1MLP <- nn_module(
  initialize = function(dim_z) {
    self$fc1 <- nn_linear(dim_z, 64); self$fc2 <- nn_linear(64, 64); self$fc3 <- nn_linear(64, 1)
  },
  forward = function(z) { x <- nnf_relu(self$fc1(z)); x <- nnf_relu(self$fc2(x)); self$fc3(x) }
)

Stage1MDN <- nn_module(
  initialize = function(dim_z, n_components = 5) {
    self$K <- n_components
    self$shared <- nn_sequential(nn_linear(dim_z, 64), nn_relu(),
                                 nn_linear(64, 64), nn_relu())
    self$pi_head <- nn_linear(64, n_components)
    self$mu_head <- nn_linear(64, n_components)
    self$logvar_head <- nn_linear(64, n_components)
  },
  forward = function(z) {
    h <- self$shared(z)
    list(pi_logits = self$pi_head(h), mu = self$mu_head(h), logvar = self$logvar_head(h))
  }
)

# --- v8: parameterized hidden sizes + dropout ------------------------------
Stage2_additive <- nn_module(
  initialize = function(dim_x_features, hidden1 = 64, hidden2 = 32, dropout = 0.2) {
    self$g_fc1 <- nn_linear(dim_x_features, hidden1); self$g_bn1 <- nn_batch_norm1d(hidden1)
    self$g_drop <- nn_dropout(dropout); self$g_fc2 <- nn_linear(hidden1, hidden2)
    self$g_ln <- nn_layer_norm(hidden2); self$g_out <- nn_linear(hidden2, 1)
    self$theta_fc1 <- nn_linear(dim_x_features, hidden1); self$theta_bn1 <- nn_batch_norm1d(hidden1)
    self$theta_drop <- nn_dropout(dropout); self$theta_fc2 <- nn_linear(hidden1, hidden2)
    self$theta_ln <- nn_layer_norm(hidden2); self$theta_out <- nn_linear(hidden2, 1)
  },
  forward = function(t_hat, x_features) {
    gx <- self$g_fc1(x_features); gx <- nnf_relu(gx); gx <- self$g_bn1(gx); gx <- self$g_drop(gx)
    gx <- self$g_fc2(gx); gx <- nnf_relu(gx); gx <- self$g_ln(gx); gx <- self$g_out(gx)
    thx <- self$theta_fc1(x_features); thx <- nnf_relu(thx); thx <- self$theta_bn1(thx)
    thx <- self$theta_drop(thx); thx <- self$theta_fc2(thx); thx <- nnf_relu(thx)
    thx <- self$theta_ln(thx); thx <- self$theta_out(thx)
    list(gx + t_hat * thx, thx)
  }
)

Stage2_plain <- nn_module(
  initialize = function(dim_x_features) {
    self$fc1 <- nn_linear(1 + dim_x_features, 128); self$fc2 <- nn_linear(128, 128); self$out <- nn_linear(128, 1)
  },
  forward = function(t_hat, x_features) {
    combined <- torch_cat(list(t_hat, x_features), dim = 2)
    x <- nnf_relu(self$fc1(combined)); x <- nnf_relu(self$fc2(x)); self$out(x)
  }
)

# ============================================================================
# 4. LOSSES
# ============================================================================
orthogonal_loss <- function(model, lambda_reg) {
  loss <- torch_zeros(1, dtype = torch_float())
  for (param in model$parameters) {
    if (length(param$shape) == 2) {
      W <- param; eye <- torch_eye(W$shape[2], dtype = W$dtype)
      loss <- loss + torch_sum((torch_matmul(W$t(), W) - eye)^2)
    }
  }
  lambda_reg * loss
}
gating_loss <- function(g, lambda_l1) lambda_l1 * torch_sum(torch_abs(g))

mdn_nll_loss <- function(outputs, T) {
  pi_logits <- outputs$pi_logits; mu <- outputs$mu; logvar <- outputs$logvar
  log_sigma <- 0.5 * logvar; sigma <- torch_exp(log_sigma)
  log_prob <- -0.5 * ((T - mu) / sigma)^2 - log_sigma - 0.5 * log(2 * pi)
  log_pi <- nnf_log_softmax(pi_logits, dim = 2)
  log_mix <- torch_logsumexp(log_pi + log_prob, dim = 2)
  -torch_mean(log_mix)
}
mdn_predict <- function(model, Z) {
  out <- model(Z); pi <- nnf_softmax(out$pi_logits, dim = 2)
  torch_sum(pi * out$mu, dim = 2, keepdim = TRUE)
}
gmm_style_loss <- function(pred_Y, Y, Z) {
  residual <- (Y - pred_Y)$view(c(-1, 1))
  moments <- torch_mean(Z * residual, dim = 1)
  torch_sum(moments^2)
}

# ============================================================================
# 5. TRAINING
# ============================================================================
# --- v8: add weight_decay / hidden1 / hidden2 / dropout ---
train_additive <- function(data_list,
                           epochs_stage1 = 200, epochs_stage2 = 300,
                           lr = 4e-4, patience = 50,
                           start_reg_epoch = 80, lambda_max_init = 0.0,
                           use_gating = FALSE, lambda_l1 = 0.04,
                           include_xt = TRUE, use_orth = FALSE,
                           hidden1 = 64, hidden2 = 32, dropout = 0.2,
                           weight_decay = 0) {
  dim_z <- ncol(data_list$train$Z)
  train_Z <- torch_tensor(data_list$train$Z, dtype = torch_float())
  train_T <- torch_tensor(data_list$train$T, dtype = torch_float())$view(c(-1, 1))
  train_Y <- torch_tensor(data_list$train$Y, dtype = torch_float())$view(c(-1, 1))
  valid_Z <- torch_tensor(data_list$valid$Z, dtype = torch_float())
  valid_Y <- torch_tensor(data_list$valid$Y, dtype = torch_float())$view(c(-1, 1))
  
  train_feat <- build_features(data_list$train$X, data_list$train$T, include_xt)
  valid_feat <- build_features(data_list$valid$X, data_list$valid$T, include_xt)
  train_feat_t <- torch_tensor(train_feat, dtype = torch_float())
  valid_feat_t <- torch_tensor(valid_feat, dtype = torch_float())
  
  stage1 <- Stage1MLP(dim_z)
  if (use_gating) {
    gating <- torch_ones(dim_z, 1, requires_grad = TRUE)
    optim1 <- optim_adam(c(stage1$parameters, list(gating)), lr = lr, weight_decay = weight_decay)
  } else {
    gating <- NULL
    optim1 <- optim_adam(stage1$parameters, lr = lr, weight_decay = weight_decay)
  }
  for (ep in 1:epochs_stage1) {
    optim1$zero_grad()
    if (use_gating) {
      pred_T <- stage1(train_Z * gating$t())
      loss1 <- nnf_mse_loss(pred_T, train_T) + gating_loss(gating, lambda_l1)
    } else {
      pred_T <- stage1(train_Z); loss1 <- nnf_mse_loss(pred_T, train_T)
    }
    loss1$backward(); optim1$step()
  }
  stage1$eval()
  with_no_grad({
    if (use_gating) {
      T_hat_tr <- stage1(train_Z * gating$t()); T_hat_va <- stage1(valid_Z * gating$t())
    } else {
      T_hat_tr <- stage1(train_Z); T_hat_va <- stage1(valid_Z)
    }
  })
  
  stage2 <- Stage2_additive(dim_x_features = ncol(train_feat),
                            hidden1 = hidden1, hidden2 = hidden2, dropout = dropout)
  optim2 <- optim_adam(stage2$parameters, lr = lr, weight_decay = weight_decay)
  best <- Inf; wait <- 0; lambda <- lambda_max_init; vmse <- c()
  for (ep in 1:epochs_stage2) {
    pred_Y <- stage2(T_hat_tr, train_feat_t)[[1]]
    mse <- nnf_mse_loss(pred_Y, train_Y)
    lc <- if (ep < start_reg_epoch) 0 else max(0, lambda)
    ortho <- if (use_orth) orthogonal_loss(stage2, lc) else torch_zeros(1, dtype = mse$dtype)
    loss <- mse + ortho
    optim2$zero_grad(); loss$backward(); optim2$step()
    stage2$eval()
    with_no_grad({ v <- nnf_mse_loss(stage2(T_hat_va, valid_feat_t)[[1]], valid_Y)$item() })
    stage2$train()
    if (use_orth && ep >= start_reg_epoch && ep %% 10 == 0 && length(vmse) >= 2) {
      d <- v - tail(vmse, 1)
      if (!is.na(d)) {
        if (d > 1e-4) lambda <- lambda * 0.97 else if (d < -1e-4) lambda <- lambda * 1.03
        lambda <- max(0, min(lambda, lambda_max_init))
      }
    }
    if (v < best) { best <- v; wait <- 0 } else { wait <- wait + 1; if (wait >= patience) break }
    vmse <- c(vmse, v)
  }
  list(stage1 = stage1, stage2 = stage2, gating = gating, valid_mse = best)
}

train_deepiv <- function(data_list, epochs_stage1 = 200, epochs_stage2 = 300,
                         lr = 4e-4, patience = 50, n_components = 5) {
  dim_z <- ncol(data_list$train$Z)
  train_Z <- torch_tensor(data_list$train$Z, dtype = torch_float())
  train_T <- torch_tensor(data_list$train$T, dtype = torch_float())$view(c(-1, 1))
  train_Y <- torch_tensor(data_list$train$Y, dtype = torch_float())$view(c(-1, 1))
  valid_Z <- torch_tensor(data_list$valid$Z, dtype = torch_float())
  valid_Y <- torch_tensor(data_list$valid$Y, dtype = torch_float())$view(c(-1, 1))
  train_feat <- build_features(data_list$train$X, data_list$train$T, TRUE)
  valid_feat <- build_features(data_list$valid$X, data_list$valid$T, TRUE)
  train_feat_t <- torch_tensor(train_feat, dtype = torch_float())
  valid_feat_t <- torch_tensor(valid_feat, dtype = torch_float())
  
  s1 <- Stage1MDN(dim_z, n_components)
  o1 <- optim_adam(s1$parameters, lr = lr)
  for (ep in 1:epochs_stage1) {
    o1$zero_grad(); l <- mdn_nll_loss(s1(train_Z), train_T); l$backward(); o1$step()
  }
  s1$eval()
  with_no_grad({ T_hat_tr <- mdn_predict(s1, train_Z); T_hat_va <- mdn_predict(s1, valid_Z) })
  
  s2 <- Stage2_plain(dim_x_features = ncol(train_feat))
  o2 <- optim_adam(s2$parameters, lr = lr)
  best <- Inf; wait <- 0
  for (ep in 1:epochs_stage2) {
    o2$zero_grad()
    l <- nnf_mse_loss(s2(T_hat_tr, train_feat_t), train_Y); l$backward(); o2$step()
    s2$eval()
    with_no_grad({ v <- nnf_mse_loss(s2(T_hat_va, valid_feat_t), valid_Y)$item() })
    s2$train()
    if (v < best) { best <- v; wait <- 0 } else { wait <- wait + 1; if (wait >= patience) break }
  }
  list(stage1 = s1, stage2 = s2, valid_mse = best)
}

train_gmm_style <- function(data_list, epochs_stage1 = 200, epochs_stage2 = 300,
                            lr = 4e-4, patience = 50, n_components = 5) {
  dim_z <- ncol(data_list$train$Z)
  train_Z <- torch_tensor(data_list$train$Z, dtype = torch_float())
  train_T <- torch_tensor(data_list$train$T, dtype = torch_float())$view(c(-1, 1))
  train_Y <- torch_tensor(data_list$train$Y, dtype = torch_float())$view(c(-1, 1))
  valid_Z <- torch_tensor(data_list$valid$Z, dtype = torch_float())
  valid_Y <- torch_tensor(data_list$valid$Y, dtype = torch_float())$view(c(-1, 1))
  train_feat <- build_features(data_list$train$X, data_list$train$T, TRUE)
  valid_feat <- build_features(data_list$valid$X, data_list$valid$T, TRUE)
  train_feat_t <- torch_tensor(train_feat, dtype = torch_float())
  valid_feat_t <- torch_tensor(valid_feat, dtype = torch_float())
  
  s1 <- Stage1MDN(dim_z, n_components)
  o1 <- optim_adam(s1$parameters, lr = lr)
  for (ep in 1:epochs_stage1) {
    o1$zero_grad(); l <- mdn_nll_loss(s1(train_Z), train_T); l$backward(); o1$step()
  }
  s1$eval()
  with_no_grad({ T_hat_tr <- mdn_predict(s1, train_Z); T_hat_va <- mdn_predict(s1, valid_Z) })
  
  s2 <- Stage2_plain(dim_x_features = ncol(train_feat))
  o2 <- optim_adam(s2$parameters, lr = lr)
  best <- Inf; wait <- 0
  for (ep in 1:epochs_stage2) {
    o2$zero_grad()
    pred <- s2(T_hat_tr, train_feat_t)
    l <- gmm_style_loss(pred, train_Y, train_Z); l$backward(); o2$step()
    s2$eval()
    with_no_grad({ v <- nnf_mse_loss(s2(T_hat_va, valid_feat_t), valid_Y)$item() })
    s2$train()
    if (v < best) { best <- v; wait <- 0 } else { wait <- wait + 1; if (wait >= patience) break }
  }
  list(stage1 = s1, stage2 = s2, valid_mse = best)
}

# ============================================================================
# 6. CATE
# ============================================================================
cate_additive <- function(m1, m2, data_list, gating = NULL, include_xt = TRUE) {
  vf <- build_features(data_list$valid$X, data_list$valid$T, include_xt)
  vf_t <- torch_tensor(vf, dtype = torch_float())
  vz_t <- torch_tensor(data_list$valid$Z, dtype = torch_float())
  m1$eval(); m2$eval()
  with_no_grad({ T_hat <- if (!is.null(gating)) m1(vz_t * gating$t()) else m1(vz_t) })
  T_hat$requires_grad_(TRUE)
  Ypred <- m2(T_hat, vf_t)[[1]]
  g <- torch::autograd_grad(outputs = Ypred, inputs = T_hat,
                            grad_outputs = torch_ones_like(Ypred))[[1]]
  list(cate = as.numeric(g$squeeze()), true = data_list$valid$theta)
}

cate_plain <- function(m1, m2, data_list) {
  vf <- build_features(data_list$valid$X, data_list$valid$T, TRUE)
  vf_t <- torch_tensor(vf, dtype = torch_float())
  vz_t <- torch_tensor(data_list$valid$Z, dtype = torch_float())
  m1$eval(); m2$eval()
  with_no_grad({ T_hat <- mdn_predict(m1, vz_t) })
  T_hat$requires_grad_(TRUE)
  Ypred <- m2(T_hat, vf_t)
  g <- torch::autograd_grad(outputs = Ypred, inputs = T_hat,
                            grad_outputs = torch_ones_like(Ypred))[[1]]
  list(cate = as.numeric(g$squeeze()), true = data_list$valid$theta)
}

# ============================================================================
# 7. 2SLS + F
# ============================================================================
run_2sls <- function(data) {
  df_tr <- as.data.frame(cbind(data$train$Y, data$train$T, data$train$X))
  colnames(df_tr) <- c("Y", "T", paste0("X", 1:ncol(data$train$X)))
  df_z <- as.data.frame(data$train$Z); colnames(df_z) <- paste0("Z", 1:ncol(df_z))
  df <- cbind(df_tr, df_z)
  f <- as.formula(paste0("Y ~ T + ",
                         paste0("X", 1:ncol(data$train$X), collapse = "+"),
                         " | ",
                         paste0("X", 1:ncol(data$train$X), collapse = "+"),
                         " + ", paste0(colnames(df_z), collapse = "+")))
  m <- AER::ivreg(f, data = df)
  list(model = m, coef_T = coef(m)["T"])
}

compute_F <- function(data_list, gating = NULL) {
  Z <- data_list$train$Z
  if (!is.null(gating)) Z <- sweep(Z, 2, as.numeric(gating$abs()), "*")
  summary(lm(data_list$train$T ~ Z))$fstatistic[1]
}

# ============================================================================
# 8. ABLATION
# ============================================================================
run_ablation <- function(data_all, n_repeats = 3, tag = "DGP1") {
  cat(sprintf("\n========== Ablation on %s ==========\n", tag))
  variants <- list(
    Main     = list(type="additive", gating=FALSE, orth=FALSE, xt=TRUE,  label="IA-DeepIV (main)"),
    Gating   = list(type="additive", gating=TRUE,  orth=FALSE, xt=TRUE,  label="+ Gating"),
    Orth     = list(type="additive", gating=FALSE, orth=TRUE,  xt=TRUE,  label="+ Orthogonal"),
    NoXT     = list(type="additive", gating=FALSE, orth=FALSE, xt=FALSE, label="No X*T"),
    DeepIV   = list(type="deepiv",   label="DeepIV (MDN)"),
    GMMstyle = list(type="gmm",      label="GMM-style")
  )
  res <- data.frame(); all_rmse <- list()
  for (nm in names(variants)) {
    cfg <- variants[[nm]]
    cat(sprintf("  %s\n", cfg$label))
    rmse <- c(); mse <- c()
    for (rep in 1:n_repeats) {
      set.seed(123 + rep*10 + which(names(variants) == nm))
      torch_manual_seed(123 + rep)
      if (cfg$type == "additive") {
        m <- train_additive(data_all, 200, 300, 4e-4, 50, 80,
                            lambda_max_init = if (cfg$orth) 0.025 else 0.0,
                            use_gating = cfg$gating, lambda_l1 = 0.04,
                            include_xt = cfg$xt, use_orth = cfg$orth)
        r <- cate_additive(m$stage1, m$stage2, data_all, gating = m$gating, include_xt = cfg$xt)
      } else if (cfg$type == "deepiv") {
        m <- train_deepiv(data_all, 200, 300, 4e-4, 50, 5)
        r <- cate_plain(m$stage1, m$stage2, data_all)
      } else {
        m <- train_gmm_style(data_all, 200, 300, 4e-4, 50, 5)
        r <- cate_plain(m$stage1, m$stage2, data_all)
      }
      rmse <- c(rmse, Metrics::rmse(r$true, r$cate))
      mse <- c(mse, Metrics::mse(r$true, r$cate))
    }
    res <- rbind(res, data.frame(Variant=cfg$label,
                                 RMSE_mean=mean(rmse), RMSE_sd=sd(rmse),
                                 MSE_mean=mean(mse), MSE_sd=sd(mse)))
    all_rmse[[nm]] <- rmse
  }
  twosls_rmse <- c(); n <- nrow(data_all$train$X)
  for (b in 1:5) {
    set.seed(5000 + b); idx <- sample(1:n, n, replace = TRUE)
    bd <- list(train = lapply(data_all$train, function(x)
      if (is.matrix(x)) x[idx, , drop = FALSE] else x[idx]),
      valid = data_all$valid)
    tw <- tryCatch(run_2sls(bd), error = function(e) NULL)
    if (!is.null(tw)) {
      cs <- rep(tw$coef_T, nrow(data_all$valid$X))
      twosls_rmse <- c(twosls_rmse, Metrics::rmse(data_all$valid$theta, cs))
    }
  }
  res <- rbind(res, data.frame(Variant="2SLS",
                               RMSE_mean=mean(twosls_rmse), RMSE_sd=sd(twosls_rmse),
                               MSE_mean=NA, MSE_sd=NA))
  if (length(all_rmse$Main) == length(all_rmse$NoXT)) {
    imp_noxt <- (mean(all_rmse$NoXT) - mean(all_rmse$Main)) / mean(all_rmse$NoXT) * 100
    imp_dv <- (mean(all_rmse$DeepIV) - mean(all_rmse$Main)) / mean(all_rmse$DeepIV) * 100
    imp_gmm <- (mean(all_rmse$GMMstyle) - mean(all_rmse$Main)) / mean(all_rmse$GMMstyle) * 100
    imp_2sls <- (mean(twosls_rmse) - mean(all_rmse$Main)) / mean(twosls_rmse) * 100
    p_noxt <- tryCatch(t.test(all_rmse$Main, all_rmse$NoXT, paired=TRUE)$p.value, error=function(e) NA)
    p_dv <- tryCatch(t.test(all_rmse$Main, all_rmse$DeepIV, paired=TRUE)$p.value, error=function(e) NA)
    cat(sprintf("\n  Main vs No X*T : %.2f%% (p=%.4f)\n", imp_noxt, p_noxt))
    cat(sprintf("  Main vs DeepIV: %.2f%% (p=%.4f)\n", imp_dv, p_dv))
    cat(sprintf("  Main vs GMM   : %.2f%%\n", imp_gmm))
    cat(sprintf("  Main vs 2SLS  : %.2f%%\n", imp_2sls))
  }
  print(res)
  write.csv(res, file.path(OUT, sprintf("ablation_%s.csv", tag)), row.names = FALSE)
  res
}

# ============================================================================
# 9. INTERACTION STRENGTH
# ============================================================================
run_interaction_strength <- function(c_levels = c(0, 0.25, 0.5, 0.75, 1), n_repeats = 3) {
  cat("\n========== Interaction-strength sensitivity ==========\n")
  out <- data.frame()
  for (cc in c_levels) {
    cat(sprintf("  c = %.2f\n", cc))
    rmse_ia <- c(); rmse_dv <- c(); rmse_2sls <- c()
    for (rep in 1:n_repeats) {
      seed <- 6000 + which(c_levels == cc) * 10 + rep
      torch_manual_seed(seed)
      d <- generate_interaction_strength(n = 8000, c = cc, seed = seed)
      m <- train_additive(d, 200, 300, 4e-4, 50)
      r <- cate_additive(m$stage1, m$stage2, d, gating = m$gating, include_xt = TRUE)
      rmse_ia <- c(rmse_ia, Metrics::rmse(r$true, r$cate))
      md <- train_deepiv(d, 200, 300, 4e-4, 50, 5)
      rd <- cate_plain(md$stage1, md$stage2, d)
      rmse_dv <- c(rmse_dv, Metrics::rmse(rd$true, rd$cate))
      tw <- run_2sls(d); cs <- rep(tw$coef_T, nrow(d$valid$X))
      rmse_2sls <- c(rmse_2sls, Metrics::rmse(d$valid$theta, cs))
    }
    out <- rbind(out, data.frame(
      c = cc,
      IA_mean = mean(rmse_ia), IA_sd = sd(rmse_ia),
      DeepIV_mean = mean(rmse_dv), DeepIV_sd = sd(rmse_dv),
      TSLS_mean = mean(rmse_2sls), TSLS_sd = sd(rmse_2sls)))
  }
  print(out)
  write.csv(out, file.path(OUT, "interaction_strength.csv"), row.names = FALSE)
  df <- rbind(
    data.frame(c=out$c, Method="IA-DeepIV", RMSE=out$IA_mean),
    data.frame(c=out$c, Method="DeepIV (MDN)", RMSE=out$DeepIV_mean),
    data.frame(c=out$c, Method="2SLS", RMSE=out$TSLS_mean))
  p <- ggplot(df, aes(x=c, y=RMSE, color=Method)) +
    geom_point(size=3.5) + geom_line(linewidth=0.8) +
    labs(x="Interaction strength c", y="CATE RMSE",
         title="RMSE vs Interaction Strength") + theme_minimal(base_size=12)
  print(p)
  ggsave(file.path(OUT, "interaction_strength.png"), p, width=8, height=5, dpi=150)
  out
}

# ============================================================================
# 10. WEAK IV
# ============================================================================
run_weak_iv <- function(n_repeats = 5) {
  cat("\n========== Weak-IV sensitivity ==========\n")
  ks <- c(0.05, 0.10, 0.20, 0.35, 0.50, 0.70, 0.90)
  out <- data.frame()
  for (k in ks) {
    cat(sprintf("  kappa = %.2f\n", k))
    rmse_ia <- c(); rmse_dv <- c(); rmse_2sls <- c(); fs <- c()
    for (rep in 1:n_repeats) {
      seed <- 7000 + which(ks == k) * 10 + rep
      torch_manual_seed(seed)
      d <- generate_weak_iv(n = 8000, kappa = k, seed = seed)
      m <- train_additive(d, 150, 200, 4e-4, 25, 60, 0.025,
                          use_gating = TRUE, lambda_l1 = 0.04,
                          include_xt = TRUE, use_orth = TRUE)
      r <- cate_additive(m$stage1, m$stage2, d, gating = m$gating, include_xt = TRUE)
      rmse_ia <- c(rmse_ia, Metrics::rmse(r$true, r$cate))
      fs <- c(fs, compute_F(d, m$gating))
      md <- train_deepiv(d, 150, 200, 4e-4, 25, 5)
      rd <- cate_plain(md$stage1, md$stage2, d)
      rmse_dv <- c(rmse_dv, Metrics::rmse(rd$true, rd$cate))
      tw <- run_2sls(d); cs <- rep(tw$coef_T, nrow(d$valid$X))
      rmse_2sls <- c(rmse_2sls, Metrics::rmse(d$valid$theta, cs))
    }
    out <- rbind(out, data.frame(
      kappa = k, F = mean(fs),
      IA = mean(rmse_ia), IA_sd = sd(rmse_ia),
      DeepIV = mean(rmse_dv), DeepIV_sd = sd(rmse_dv),
      TSLS = mean(rmse_2sls), TSLS_sd = sd(rmse_2sls)))
  }
  print(out)
  write.csv(out, file.path(OUT, "weak_iv_sensitivity.csv"), row.names = FALSE)
  out
}

# ============================================================================
# 11. BOOTSTRAP
# ============================================================================
run_bootstrap <- function(data_all, B = 500) {
  cat(sprintf("\n========== Bootstrap (B=%d) ==========\n", B))
  n <- nrow(data_all$train$X); ia <- c(); sl <- c()
  for (b in 1:B) {
    if (b %% 100 == 0) cat(sprintf("  %d/%d\n", b, B))
    set.seed(9000 + b); torch_manual_seed(9000 + b)
    idx <- sample(1:n, n, replace = TRUE)
    bd <- list(train = lapply(data_all$train, function(x)
      if (is.matrix(x)) x[idx, , drop = FALSE] else x[idx]),
      valid = data_all$valid)
    m <- tryCatch(train_additive(bd, 60, 80, 6e-4, 15, 30, 0.025,
                                 use_gating = TRUE, lambda_l1 = 0.04,
                                 include_xt = TRUE, use_orth = TRUE),
                  error = function(e) NULL)
    if (!is.null(m)) {
      r <- cate_additive(m$stage1, m$stage2, bd, gating = m$gating, include_xt = TRUE)
      ia <- c(ia, Metrics::rmse(r$true, r$cate))
    }
    tw <- tryCatch(run_2sls(bd), error = function(e) NULL)
    if (!is.null(tw)) {
      cs <- rep(tw$coef_T, nrow(bd$valid$X))
      sl <- c(sl, Metrics::rmse(bd$valid$theta, cs))
    }
  }
  res <- data.frame(
    Method = c("IA-DeepIV","2SLS"),
    Mean = c(mean(ia), mean(sl)),
    SD = c(sd(ia), sd(sl)),
    CI_low = c(quantile(ia, 0.025), quantile(sl, 0.025)),
    CI_high = c(quantile(ia, 0.975), quantile(sl, 0.975)),
    B = B)
  print(res)
  write.csv(res, file.path(OUT, "bootstrap_ci.csv"), row.names = FALSE)
  res
}

# ============================================================================
# 12. CARD 1995 (v8: small network + weight decay)
# ============================================================================
run_card_1995 <- function() {
  cat("\n========== Card (1995) ==========\n")
  if (!requireNamespace("wooldridge", quietly = TRUE)) {
    install.packages("wooldridge", repos = "https://cloud.r-project.org")
  }
  data("card", package = "wooldridge")
  card <- na.omit(card)
  
  y <- card$lwage; T <- card$educ
  Z <- as.matrix(card[, c("nearc4")])
  X <- as.matrix(card[, c("exper","expersq","black","smsa","south","married")])
  
  # --- Standardize X and y (helps small networks) ---
  X <- scale(X); y <- scale(y)[,1]
  
  n <- nrow(card); idx <- sample(1:n, floor(0.7*n))
  
  # --- 2SLS ---
  df <- data.frame(Y = y, T = T, X)
  colnames(df) <- c("Y","T", paste0("V", 1:ncol(X)))
  df$nearc4 <- Z[, 1]
  f <- as.formula(paste0("Y ~ T + ", paste0("V", 1:ncol(X), collapse = "+"),
                         " | ", paste0("V", 1:ncol(X), collapse = "+"), " + nearc4"))
  m_2sls <- AER::ivreg(f, data = df[idx, ])
  pred_2sls <- predict(m_2sls, newdata = df[-idx, ])
  rmse_2sls <- Metrics::rmse(y[-idx], pred_2sls)
  
  # --- IA-DeepIV with small network + strong regularization ---
  data_card <- list(
    train = list(X = X[idx, ], Z = Z[idx, , drop=FALSE],
                 T = T[idx], Y = y[idx], theta = y[idx]*0),
    valid = list(X = X[-idx, ], Z = Z[-idx, , drop=FALSE],
                 T = T[-idx], Y = y[-idx], theta = y[-idx]*0))
  
  m <- train_additive(data_card,
                      epochs_stage1 = 100, epochs_stage2 = 200,
                      lr = 1e-4, patience = 20,
                      include_xt = TRUE, use_gating = FALSE, use_orth = FALSE,
                      hidden1 = 16, hidden2 = 8, dropout = 0.3,
                      weight_decay = 1e-3)
  
  vf <- build_features(X[-idx, ], T[-idx], TRUE)
  vf_t <- torch_tensor(vf, dtype = torch_float())
  vz_t <- torch_tensor(Z[-idx, , drop=FALSE], dtype = torch_float())
  m$stage1$eval(); m$stage2$eval()
  with_no_grad({
    T_hat <- m$stage1(vz_t)
    pred_ia <- as.numeric(m$stage2(T_hat, vf_t)[[1]])
  })
  rmse_ia <- Metrics::rmse(y[-idx], pred_ia)
  
  res <- data.frame(Model = c("IA-DeepIV","2SLS"),
                    RMSE = c(rmse_ia, rmse_2sls))
  print(res)
  write.csv(res, file.path(OUT, "card_1995.csv"), row.names = FALSE)
  res
}

# ============================================================================
# 13. PLOTTING
# ============================================================================
plot_ablation_bars <- function(res, tag = "DGP1") {
  res$lo <- res$RMSE_mean - ifelse(is.na(res$RMSE_sd), 0, res$RMSE_sd)
  res$hi <- res$RMSE_mean + ifelse(is.na(res$RMSE_sd), 0, res$RMSE_sd)
  p <- ggplot(res, aes(x = Variant, y = RMSE_mean, fill = Variant)) +
    geom_col(width = 0.65) +
    geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.2) +
    geom_text(aes(label = sprintf("%.3f", RMSE_mean)), vjust = -0.6, size = 3.2) +
    labs(title = sprintf("CATE RMSE (%s)", tag), y = "RMSE", x = "") +
    theme_minimal(base_size = 12) +
    theme(legend.position = "none", axis.text.x = element_text(angle = 20, hjust = 1))
  print(p)
  ggsave(file.path(OUT, sprintf("ablation_rmse_%s.png", tag)), p, width = 9, height = 5, dpi = 150)
}

plot_cate_curves <- function(data_all, n_plot = 200) {
  set.seed(123); torch_manual_seed(123)
  m_main <- train_additive(data_all, 200, 300, 4e-4, 50)
  r_main <- cate_additive(m_main$stage1, m_main$stage2, data_all, gating = m_main$gating, include_xt = TRUE)
  m_noxt <- train_additive(data_all, 200, 300, 4e-4, 50, use_gating = FALSE, include_xt = FALSE)
  r_noxt <- cate_additive(m_noxt$stage1, m_noxt$stage2, data_all, gating = m_noxt$gating, include_xt = FALSE)
  m_dv <- train_deepiv(data_all, 200, 300, 4e-4, 50, 5)
  r_dv <- cate_plain(m_dv$stage1, m_dv$stage2, data_all)
  tw <- run_2sls(data_all); c2sls <- rep(tw$coef_T, length(data_all$valid$theta))
  df <- data.frame(Index = 1:n_plot,
                   True = data_all$valid$theta[1:n_plot],
                   Main = r_main$cate[1:n_plot],
                   NoXT = r_noxt$cate[1:n_plot],
                   DeepIV = r_dv$cate[1:n_plot],
                   TSLS = c2sls[1:n_plot])
  dl <- melt(df, id.vars = "Index", variable.name = "Model", value.name = "CATE")
  p <- ggplot(dl, aes(x = Index, y = CATE, color = Model)) +
    geom_line(alpha = 0.8, linewidth = 0.7) +
    labs(title = "CATE curves (first 200 validation samples)",
         y = expression(theta(x)), x = "Sample index") +
    theme_minimal(base_size = 12) + theme(legend.position = "bottom")
  print(p)
  ggsave(file.path(OUT, "cate_curves.png"), p, width = 10, height = 6, dpi = 150)
}

# ============================================================================
# 14. MAIN
# ============================================================================
cat("\n==================== v8 EXECUTION ====================\n")

cat("\n[1/7] Generating DGP1 & DGP2 ...\n")
d1 <- generate_dgp1(n = 8000, seed = 2026)
d2 <- generate_dgp2_noXT(n = 8000, seed = 2026)

cat("\n[2/7] Ablation DGP1 ...\n")
res1 <- run_ablation(d1, 3, "DGP1"); plot_ablation_bars(res1, "DGP1")

cat("\n[3/7] Ablation DGP2 ...\n")
res2 <- run_ablation(d2, 3, "DGP2"); plot_ablation_bars(res2, "DGP2")

cat("\n[4/7] Interaction strength ...\n")
res_is <- run_interaction_strength(c(0, 0.25, 0.5, 0.75, 1), 3)

cat("\n[5/7] Weak-IV ...\n")
res_wiv <- run_weak_iv(5)

cat("\n[6/7] Bootstrap ...\n")
res_boot <- run_bootstrap(d1, B = 500)

cat("\n[7/7] CATE curves + Card 1995 ...\n")
plot_cate_curves(d1, 200)
res_card <- tryCatch(run_card_1995(), error = function(e) { cat("Card skipped:", e$message, "\n"); NULL })

cat("\n==================== DONE ====================\n")
cat("Outputs in:", OUT, "\n")
print(list.files(OUT, pattern = "\\.(csv|png)$"))