#' Root mean squared error
#'
#' Computes the root mean squared error between actual and predicted values.
#'
#' @param actual Numeric vector or matrix of observed values.
#' @param predicted Numeric vector or matrix of predicted values.
#'
#' @return A numeric scalar.
rmse_vec <- function(actual, predicted) {
  actual <- as.numeric(actual)
  predicted <- as.numeric(predicted)
  sqrt(mean((actual - predicted)^2))
}

#' Mean absolute error
#'
#' Computes the mean absolute error between actual and predicted values.
#'
#' @param actual Numeric vector or matrix of observed values.
#' @param predicted Numeric vector or matrix of predicted values.
#'
#' @return A numeric scalar.
mae_vec <- function(actual, predicted) {
  actual <- as.numeric(actual)
  predicted <- as.numeric(predicted)
  mean(abs(actual - predicted))
}

#' Mean absolute percentage error
#'
#' Computes the mean absolute percentage error between actual and predicted values.
#'
#' @param actual Numeric vector or matrix of observed values.
#' @param predicted Numeric vector or matrix of predicted values.
#' @param eps Small constant to avoid division by zero.
#'
#' @return A numeric scalar.
mape_vec <- function(actual, predicted, eps = 1e-8) {
  actual <- as.numeric(actual)
  predicted <- as.numeric(predicted)
  mean(abs((actual - predicted) / pmax(abs(actual), eps))) * 100
}

#' R-squared
#'
#' Computes the coefficient of determination.
#'
#' @param actual Numeric vector or matrix of observed values.
#' @param predicted Numeric vector or matrix of predicted values.
#'
#' @return A numeric scalar.
rsq_vec <- function(actual, predicted) {
  actual <- as.numeric(actual)
  predicted <- as.numeric(predicted)

  ss_res <- sum((actual - predicted)^2)
  ss_tot <- sum((actual - mean(actual))^2)

  1 - ss_res / ss_tot
}
