# Reproduce "What does a neural network add once every group has a slope?"
# Requires cmdstanr, a configured CmdStan installation, and scoringRules.
library(cmdstanr)
library(scoringRules)

stan <- "
functions {
  vector shared_curve(vector x, vector w, vector b, vector v) {
    vector[num_elements(x)] r = rep_vector(0, num_elements(x));
    for (h in 1:num_elements(w))
      r += v[h] * (tanh(w[h] * x + b[h]) - tanh(b[h]));
    return r;
  }
}
data {
  int<lower=1> N;
  int<lower=1> T;
  int<lower=1> J;
  int<lower=0> H;
  vector[N] x;
  vector[N] y;
  array[N] int<lower=1,upper=J> g;
  vector[T] xt;
  array[T] int<lower=1,upper=J> gt;
}
parameters {
  real a0;
  real b0;
  real<lower=0> sa;
  real<lower=0> sb;
  vector[J] za;
  vector[J] zb;
  real<lower=0> sigma;
  vector[H] w;
  vector[H] b;
  vector[H] v;
}
transformed parameters {
  vector[J] alpha = a0 + sa * za;
  vector[J] beta = b0 + sb * zb;
}
model {
  a0 ~ normal(0, 2);
  b0 ~ normal(0, 2);
  sa ~ std_normal();
  sb ~ std_normal();
  sigma ~ std_normal();
  za ~ std_normal();
  zb ~ std_normal();
  w ~ std_normal();
  b ~ std_normal();
  v ~ normal(0, 1 / sqrt(max(1, H)));
  y ~ normal(alpha[g] + beta[g] .* x + shared_curve(x, w, b, v), sigma);
}
generated quantities {
  vector[T] mu_test = alpha[gt] + beta[gt] .* xt + shared_curve(xt, w, b, v);
  array[T] real y_test = normal_rng(mu_test, sigma);
}
"
model <- cmdstan_model(write_stan_file(stan))
set.seed(42)
J <- 10
group_intercept <- rnorm(J, 0, 1.5)
group_slope <- rnorm(J, 2, 0.8)
g <- rep(seq_len(J), each = 30)
x <- runif(length(g), -2, 2)
straight <- rnorm(length(g), group_intercept[g] + group_slope[g] * x, 0.5)
outcomes <- list(straight = straight, curved = straight + 2 * sin(1.5 * x) + 0.5 * cos(3 * x))
train <- rep(seq_len(30) <= 20, J)
for (scenario in names(outcomes)) {
  y <- outcomes[[scenario]]
  for (H in c(0L, 8L)) {
    data <- list(N = sum(train), T = sum(!train), J = J, H = H, x = x[train],
                 g = g[train], y = y[train], xt = x[!train], gt = g[!train])
    fit <- model$sample(data, seed = 4201, chains = 4, parallel_chains = 4,
                        iter_warmup = 600, iter_sampling = 600, adapt_delta = 0.95,
                        max_treedepth = 13,
                        refresh = 0)
    pred <- t(fit$draws("y_test", format = "matrix"))
    score <- mean(crps_sample(y[!train], pred))
    means <- fit$summary("mu_test")
    diag <- fit$diagnostic_summary()
    cat(sprintf("%s H=%d CRPS=%.5f max predictive-mean Rhat=%.4f min bulk ESS=%.0f divergences=%d depth hits=%d\n",
                scenario, H, score, max(means$rhat), min(means$ess_bulk),
                sum(diag$num_divergent), sum(diag$num_max_treedepth)))
  }
}
