# ============================================================
# KRONX :: init.R
# Random initialisation of HMM parameters for EM restarts.
# ============================================================

# Create initial HMM parameters.
#
# Strategy
#   * means   : sample quantiles of x, jittered by 10 % of sd(x)
#   * sigmas  : sd(x) scaled by U(0.7, 1.3) uniform noise
#   * A       : persistent (0.95 diagonal), row-normalised
#   * delta   : uniform
#   * nu      : sampled from {4,5,6,8,10,12,15} (Student-t only)
init_hmm_params <- function(x, K, model = c("gaussian", "student")) {
  model <- match.arg(model)

  qs       <- stats::quantile(x, probs = seq(0, 1, length.out = K + 2L))
  mu_init  <- as.numeric(qs[2:(K + 1L)])
  mu_init  <- mu_init + stats::rnorm(K, sd = stats::sd(x) / 10)
  s0       <- max(stats::sd(x), 1e-4)
  sigma_init <- rep(s0, K) * stats::runif(K, 0.7, 1.3)

  A        <- matrix(0.05 / (K - 1), nrow = K, ncol = K)
  diag(A)  <- 0.95
  A        <- row_normalize(A)
  delta    <- safe_normalize(rep(1 / K, K))

  params <- list(
    mu    = mu_init,
    sigma = pmax(sigma_init, 1e-4)
  )
  if (model == "student") {
    params$nu <- sample(c(4, 5, 6, 8, 10, 12, 15), K, replace = TRUE)
  }

  list(A = A, delta = delta, params = params)
}
