R/utils_topology.R

Defines functions .pcoa .msd_by_k .retain_axes .check_fric_richness .keep_counts .align_species .calc_core_topology .build_functional_space .trait_distance

# ==============================================================================
# INTERNAL UTILITY FUNCTIONS — SHARED ENGINES
# ==============================================================================
# These are hidden (.dot) functions that serve as the single source of truth
# for the core mathematical engines used across the package.

#' Distance Matrix Between Species (Gower by Default)
#'
#' @description
#' Internal function. Computes the species-by-species dissimilarity used by all
#' ASC-CFD functions. With \code{correction = "sqrt"} the square root of the
#' dissimilarity is returned: for Gower's coefficient without missing values
#' and with constant non-negative weights, \eqn{\sqrt{1 - S}} is Euclidean
#' (Gower 1971, Biometrics 27: 857-871), so the PCoA has no negative
#' eigenvalues. \code{type} and \code{weights} are passed unchanged to
#' \code{cluster::daisy}.
#'
#' @noRd
.trait_distance <- function(traits, dist_method = "gower", correction = c("none", "sqrt"),
                            type = NULL, weights = NULL) {
  correction <- match.arg(correction)
  args <- list(traits, metric = dist_method)
  if (!is.null(type)) args$type <- type
  if (!is.null(weights)) args$weights <- weights
  d_mat <- do.call(cluster::daisy, args)
  if (correction == "sqrt") {
    if (anyNA(traits)) {
      warning("correction = 'sqrt': the Euclidean property shown by Gower (1971) ",
              "requires complete trait data; the trait matrix contains missing values.")
    }
    d_mat <- sqrt(d_mat)
  }
  d_mat
}

#' Build the Functional PCoA Space from a Trait Matrix
#'
#' @description
#' Internal function. Computes Gower (or other) distance, runs PCoA,
#' selects axes via variance threshold or broken stick, and reports quality.
#'
#' @param traits Data frame or matrix of functional traits.
#' @param dist_method Distance metric (default \code{"gower"}).
#' @param dim_retention Method for axis selection (\code{"msd"}, the
#'   default, \code{"variance"} or \code{"broken_stick"}).
#' @param var_tol Proportion of cumulative variance to retain.
#' @param correction \code{"none"} (default) or \code{"sqrt"}; see \code{.trait_distance}.
#' @param type,weights Passed to \code{cluster::daisy} (default: not used).
#'
#' @return A list with: \code{F_mat}, \code{k_retained}, \code{var_retained},
#'   \code{axis_var}, \code{quality}, \code{correction}.
#'
#' @details
#' **Negative eigenvalues:** Gower distance is not strictly Euclidean, so
#' \code{cmdscale} may produce negative eigenvalues. This function filters
#' them out and reports a quality metric (\code{quality = sum(positive_eig) /
#' sum(abs(all_eig))}). If quality falls below 0.80, a warning is issued
#' recommending \code{correction = "sqrt"}.
#'
#' @noRd
.build_functional_space <- function(traits, dist_method = "gower",
                                     dim_retention = "msd", var_tol = 0.80,
                                     correction = "none", type = NULL, weights = NULL) {

  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]
  rel_var <- eig_pos / sum(eig_pos)
  cum_var <- cumsum(rel_var)

  # PCoA quality: proportion of total absolute eigenvalue explained by positive axes

  quality <- sum(eig_pos) / sum(abs(eig_raw))
  if (quality < 0.80) {
    warning(sprintf(
      paste0("PCoA quality is low (%.1f%%). Negative eigenvalues represent ",
             "%.1f%% of total variation. Consider correction = \"sqrt\" ",
             "(Gower 1971) or reviewing the trait data."),
      quality * 100, (1 - quality) * 100
    ))
  }

  k_valid <- .retain_axes(eig_pos, pcoa_res$points, d_mat, dim_retention, var_tol)

  axis_var <- rel_var[1:k_valid]
  total_var_retained <- cum_var[k_valid]
  F_mat <- pcoa_res$points[, 1:k_valid, drop = FALSE]
  colnames(F_mat) <- paste0("Axis_", 1:k_valid)

  list(
    F_mat = F_mat,
    k_retained = k_valid,
    dim_retention = dim_retention,
    var_retained = total_var_retained,
    axis_var = axis_var,
    quality = quality,
    correction = correction
  )
}


#' Compute Core Topology (FDis, FRic) for a Single Community
#'
#' @description
#' Internal function. Calculates abundance-weighted functional dispersion
#' (Laliberte & Legendre 2010) and convex hull volume for a single
#' community vector in the retained functional space.
#'
#' @param abund_vec Numeric vector of (relative) abundances.
#' @param F_space Matrix of species coordinates in PCoA space.
#'
#' @return A list with \code{FDis} and \code{FRic}.
#'   \code{FRic} is \code{NA_real_} when the convex hull is not computable.
#' @noRd
.calc_core_topology <- function(abund_vec, F_space) {
  idx <- abund_vec > 0
  n_pres <- sum(idx)

  if (n_pres < 2) return(list(FDis = 0, FRic = NA_real_))

  p_pres <- abund_vec[idx] / sum(abund_vec[idx])
  F_pres <- F_space[idx, , drop = FALSE]

  centroid <- colSums(p_pres * F_pres)
  dist_to_c <- sqrt(rowSums(sweep(F_pres, 2, centroid, "-")^2))
  fdis <- sum(p_pres * dist_to_c)

  fric <- NA_real_
  if (n_pres > ncol(F_space)) {
    fric <- tryCatch(
      geometry::convhulln(F_pres, options = "FA")$vol,
      error = function(e) NA_real_
    )
  }

  list(FDis = fdis, FRic = fric)
}


#' Match Species Between Traits and Abundances by Name
#'
#' @description
#' Internal. Reorders the columns of \code{abund} to the row order of
#' \code{traits}. Stops if species are missing in either table. If
#' \code{abund} has no column names, the 0.1.1 behaviour is kept (same order
#' assumed) and the trait names are assigned.
#'
#' @noRd
.align_species <- function(traits, abund) {
  abund <- as.matrix(abund)
  if (nrow(traits) != ncol(abund)) {
    stop("Number of species in traits and abundances does not match.")
  }
  sp <- rownames(traits); cn <- colnames(abund)
  if (is.null(cn) || is.null(sp)) {
    if (!is.null(sp)) colnames(abund) <- sp
    return(abund)
  }
  missing_ab <- setdiff(sp, cn); missing_tr <- setdiff(cn, sp)
  if (length(missing_ab) || length(missing_tr)) {
    stop("Species do not match between traits and abundances. ",
         "Without abundances: ", paste(missing_ab, collapse = ", "),
         " | Without traits: ", paste(missing_tr, collapse = ", "))
  }
  abund[, sp, drop = FALSE]
}

#' Keep Raw Counts When Abundances Are Integers
#'
#' @description Internal. Null model A needs counts of individuals. Returns
#' the matrix when all values are whole numbers, otherwise \code{NULL}.
#' @noRd
.keep_counts <- function(abund) {
  a <- as.matrix(abund)
  if (all(is.finite(a)) && all(abs(a - round(a)) < 1e-8) && all(a >= 0)) a else NULL
}

#' Warn When FRic Will Often Be Undefined
#' @noRd
.check_fric_richness <- function(abund, k_retained) {
  rich <- rowSums(as.matrix(abund) > 0)
  if (stats::median(rich) <= k_retained) {
    warning(sprintf(paste0("Median richness per sample (%g) does not exceed the number of ",
                           "retained axes (%d): FRic (convex hull volume) will often be NA."),
                    stats::median(rich), k_retained))
  }
  invisible(NULL)
}

# PCoA without cmdscale's warning about non-positive eigenvalues: negative
# eigenvalues are already reported through the quality index (internal)
# Number of PCoA axes to retain (internal). "variance": smallest k reaching
# var_tol of the positive variance; "broken_stick": axes explaining more than
# the broken-stick expectation; "msd": k (2-10) minimising the mean squared
# deviation between the trait distances and the Euclidean distances in the
# first k axes, both scaled to a maximum of 1 (Maire et al. 2015). At least 2.
.retain_axes <- function(eig_pos, points, d_mat, method, var_tol = 0.80) {
  rel_var <- eig_pos / sum(eig_pos)
  k <- switch(method,
    variance = min(which(cumsum(rel_var) >= var_tol)),
    broken_stick = {
      n_eig <- length(eig_pos)
      sum(rel_var > sapply(seq_len(n_eig), function(j) sum(1 / (j:n_eig)) / n_eig))
    },
    msd = {
      m <- .msd_by_k(d_mat, points, min(10L, ncol(points)))
      m[1] <- Inf
      which.min(m)
    },
    stop("Unknown dim_retention: ", method))
  max(2L, as.integer(k))
}

# mSD of Maire et al. (2015) for k = 1..k_max retained axes (internal)
.msd_by_k <- function(d_mat, points, k_max) {
  dv <- as.vector(stats::as.dist(as.matrix(d_mat)))
  dv <- dv / max(dv)
  vapply(seq_len(k_max), function(k) {
    e <- as.vector(stats::dist(points[, seq_len(k), drop = FALSE]))
    mean((e / max(e) - dv)^2)
  }, numeric(1))
}

.pcoa <- function(d_mat, k) {
  withCallingHandlers(
    stats::cmdscale(d_mat, k = k, eig = TRUE),
    warning = function(w) {
      if (grepl("eigenvalues are > 0", conditionMessage(w), fixed = TRUE)) invokeRestart("muffleWarning")
    })
}

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.