R/assess_functional_space.R

Defines functions summary.ascent_space print.ascent_space assess_functional_space

Documented in assess_functional_space

#' Assess Functional Space Quality
#'
#' @description
#' Diagnostic tool to evaluate the quality of the PCoA-based functional space
#' constructed from a trait matrix. Intended for use before running core
#' analyses (\code{asc_paired}, \code{asc_pairwise}, etc.) to identify
#' potential distortion from negative eigenvalues or excessive dimensionality
#' reduction.
#'
#' @param traits A data frame or matrix of functional traits.
#' @param dist_method Distance metric for the trait matrix. Default is \code{"gower"}.
#' @param dim_retention Character. Method for choosing the number of axes:
#'   \code{"msd"} (default since 0.5.1: the number of axes, 2 to 10, whose
#'   Euclidean distances best reproduce the trait distances, i.e. the minimum
#'   mean squared deviation of Maire et al. 2015), \code{"variance"} (the axes
#'   needed to reach \code{var_tol} of the positive variance; the default up
#'   to 0.5.0) or \code{"broken_stick"} (axes that explain more variance than
#'   the broken-stick expectation).
#' @param var_tol Numeric. Proportion of cumulative variance to retain (used
#'   when \code{dim_retention = "variance"}). Default is 0.80.
#' @param correction Character. \code{"none"} (default) or \code{"sqrt"}
#'   (square root of the Gower dissimilarity; Euclidean for complete data,
#'   Gower 1971). Use it to compare the quality of both spaces.
#' @param type,weights Optional; passed unchanged to \code{\link[cluster]{daisy}}.
#'
#' @return A list of class \code{ascent_space} (it also carries the class
#'   \code{ascfcd_space} of ascent 0.5.0, which will be dropped in 0.6.0) with:
#' \describe{
#'   \item{quality}{Numeric. PCoA quality index (\code{sum(positive_eig) / sum(abs(all_eig))}). Values above 0.80 are generally acceptable.}
#'   \item{n_species}{Integer. Number of species in the trait matrix.}
#'   \item{n_traits}{Integer. Number of traits.}
#'   \item{k_retained}{Integer. Number of PCoA axes retained.}
#'   \item{dim_retention}{Character. Rule used to choose them.}
#'   \item{var_retained}{Numeric. Cumulative variance explained by retained axes.}
#'   \item{axis_var}{Numeric vector. Relative variance per retained axis.}
#'   \item{n_neg_eigenvalues}{Integer. Count of negative eigenvalues.}
#'   \item{neg_eigenvalue_pct}{Numeric. Percentage of total absolute eigenvalue represented by negative eigenvalues.}
#'   \item{eigenvalues}{Numeric vector. All raw eigenvalues from PCoA.}
#'   \item{msd}{Data frame. For k = 1 to 10 axes, the mean squared deviation
#'     (mSD) between the trait distances and the Euclidean distances in the
#'     first k axes (both scaled to a maximum of 1) and their Pearson
#'     correlation (Maire et al. 2015). Lower mSD = more faithful space.}
#' }
#'
#' @details
#' All functions of the package build the same functional space: a PCoA of
#' the distances between species traits (Gower by default), keeping the
#' number of axes given by \code{dim_retention}. This function shows that
#' space before any analysis, with two diagnostics:
#' \itemize{
#'   \item \strong{Number of axes.} By default (\code{"msd"}) the number of
#'     axes, from 2 to 10, whose Euclidean distances best reproduce the trait
#'     distances (lowest mSD, Maire et al. 2015). The table \code{msd} shows
#'     the fidelity for each number of axes. More axes describe the traits
#'     better, but FRic can only be computed in communities with more species
#'     than axes.
#'   \item \strong{Quality.} The Gower distance is not strictly Euclidean, so
#'     the PCoA can give negative eigenvalues. The quality index is the share
#'     of positive eigenvalues; below 0.80, negative eigenvalues represent more
#'     than 20\% of the total variation. Then review the trait data first
#'     (traits with many missing values, redundant or badly coded traits).
#'     \code{correction = "sqrt"} (square root of the Gower dissimilarity,
#'     Euclidean for complete data with constant weights, Gower 1971) removes
#'     the negative eigenvalues, but it changes the distances between species,
#'     so results with and without it are not comparable, and its effect on
#'     the null-model tests has not been evaluated by simulation.
#' }
#'
#' @references
#' Maire, E., Grenouillet, G., Brosse, S., & Villeger, S. (2015). How many
#' dimensions are needed to accurately assess functional diversity? A
#' pragmatic approach for assessing the quality of functional spaces. Global
#' Ecology and Biogeography, 24, 728-740.
#'
#' @examples
#' # Check the functional space before any analysis
#' q <- assess_functional_space(birds_sim$traits)
#'
#' # Number of axes kept (rule: mSD) and quality (>= 0.8 is adequate). FRic can
#' # only be computed in samples with more species than retained axes.
#' q
#'
#' # Fidelity of the space for 1 to 10 axes (lower mSD = more faithful)
#' summary(q)
#'
#' @export
assess_functional_space <- function(traits, dist_method = "gower",
                                     dim_retention = c("msd", "variance", "broken_stick"),
                                     var_tol = 0.80, correction = c("none", "sqrt"),
                                     type = NULL, weights = NULL) {

  dim_retention <- match.arg(dim_retention)
  correction <- match.arg(correction)

  # Compute distance and PCoA (same engine as all ASC-CFD functions)
  d_mat <- .trait_distance(traits, dist_method, correction, type, weights)
  pcoa_res <- .pcoa(d_mat, nrow(traits) - 1)

  eig_raw <- pcoa_res$eig
  eig_pos <- eig_raw[eig_raw > 1e-8]
  n_neg <- sum(eig_raw < -1e-8)
  neg_pct <- if (sum(abs(eig_raw)) > 0) {
    sum(abs(eig_raw[eig_raw < -1e-8])) / sum(abs(eig_raw)) * 100
  } else {
    0
  }

  quality <- sum(eig_pos) / sum(abs(eig_raw))

  # Axis retention (same rule as the analysis functions)
  rel_var <- eig_pos / sum(eig_pos)
  cum_var <- cumsum(rel_var)
  k_valid <- .retain_axes(eig_pos, pcoa_res$points, d_mat, dim_retention, var_tol)

  # Fidelity of the reduced space for 1 to 10 axes (Maire et al. 2015)
  k_max <- min(10L, ncol(pcoa_res$points))
  dv <- as.vector(stats::as.dist(as.matrix(d_mat)))
  msd_tab <- data.frame(
    k = seq_len(k_max),
    mSD = .msd_by_k(d_mat, pcoa_res$points, k_max),
    r = vapply(seq_len(k_max), function(k)
      stats::cor(dv, as.vector(stats::dist(pcoa_res$points[, seq_len(k), drop = FALSE]))), numeric(1)))

  output <- list(
    quality            = quality,
    n_species          = nrow(traits),
    n_traits           = ncol(traits),
    k_retained         = k_valid,
    var_retained       = cum_var[k_valid],
    axis_var           = rel_var[1:k_valid],
    n_neg_eigenvalues  = n_neg,
    neg_eigenvalue_pct = neg_pct,
    eigenvalues        = eig_raw,
    msd                = msd_tab,
    dim_retention      = dim_retention,
    correction         = correction
  )
  class(output) <- c("ascent_space", "ascfcd_space")
  return(output)
}


#' @export
print.ascent_space <- function(x, ...) {
  cat("==================================================\n")
  cat(" Functional Space Diagnostic (ascent)\n")
  cat("==================================================\n\n")
  cat(sprintf("  Species:           %d\n", x$n_species))
  cat(sprintf("  Traits:            %d\n", x$n_traits))
  cat(sprintf("  PCoA Quality:      %.1f%%\n", x$quality * 100))
  cat(sprintf("  Axes Retained:     %d (%.1f%% variance%s)\n",
              x$k_retained, x$var_retained * 100,
              if (is.null(x$dim_retention)) "" else paste0("; rule: ", x$dim_retention)))
  cat(sprintf("  Negative Eigenvalues: %d (%.1f%% of total)\n",
              x$n_neg_eigenvalues, x$neg_eigenvalue_pct))

  if (x$quality < 0.80) {
    cat("\n  [!] WARNING: Quality < 80%. Consider correction = \"sqrt\" (Gower 1971)\n")
    cat("      in all functions, or reviewing trait data.\n")
  } else {
    cat("\n  Quality is adequate for analysis.\n")
  }
  invisible(x)
}


#' @export
summary.ascent_space <- function(object, ...) {
  print.ascent_space(object, ...)
  cat("\n--- Per-Axis Variance ---\n")
  axis_df <- data.frame(
    Axis     = paste0("Axis_", seq_along(object$axis_var)),
    Variance = round(object$axis_var * 100, 2),
    Cumul    = round(cumsum(object$axis_var) / sum(object$axis_var) * object$var_retained * 100, 2)
  )
  print(axis_df, row.names = FALSE)
  if (!is.null(object$msd)) {
    cat("\n--- Fidelity of the reduced space (Maire et al. 2015) ---\n")
    m <- object$msd
    m$mSD <- signif(m$mSD, 3); m$r <- round(m$r, 3)
    m$Best <- ifelse(seq_len(nrow(m)) == which.min(replace(object$msd$mSD, 1, Inf)), "<- min mSD (k >= 2)", "")
    print(m, row.names = FALSE)
  }
  cat("\n--- Full Eigenvalue Spectrum ---\n")
  eig <- object$eigenvalues
  cat(sprintf("  Positive: %d | Negative: %d | Total: %d\n",
              sum(eig > 1e-8), sum(eig < -1e-8), length(eig)))
  invisible(object)
}

Try the ascent package in your browser

Any scripts or data that you put into this service are public.

ascent documentation built on Nov. 30, 2026, 1:07 a.m.