R/asc_paired.R

Defines functions .fric_rarefied asc_paired

Documented in asc_paired

#' Paired Functional Restructuring (Reference vs Comparison State)
#'
#' @description
#' Measures, at each site, the change between a reference state and a
#' comparison state (e.g. before and after an event) in three layers of the
#' functional space: position (shift of the abundance-weighted centroid,
#' \eqn{\Delta C}), dispersion (\eqn{\Delta}FDis) and volume
#' (\eqn{\Delta}FRic). Pass the result to \code{\link{asc_null}} to test each
#' layer, and to \code{\link{asc_transitions}} to see which species moved the
#' centroid.
#'
#' @param traits A data frame or matrix of functional traits, one row per
#'   species (row names = species). Categorical traits should be factors.
#' @param abund A data frame or matrix of abundances, one row per sample and
#'   one column per species (matched to \code{traits} by name). Use counts of
#'   individuals (whole numbers): null model A needs them. Several samples of
#'   the same site and state are replicates.
#' @param sites A vector, one value per row of \code{abund}, naming the site
#'   (one contrast is made per site).
#' @param time A vector, one value per row of \code{abund}, naming the state
#'   of each sample.
#' @param ref_time The value of \code{time} that is the reference state; all
#'   other samples of a site form the comparison state.
#' @param blocks Optional vector, one value per row of \code{abund}, naming the
#'   unit in which each sample was taken when the samples of both states were
#'   taken in matched units: the same months, plots or survey rounds. With
#'   \code{blocks}, null model A exchanges samples between the two states only
#'   within each block (see \code{\link{asc_null}}, section "Choosing the
#'   permutation for A"). Leave \code{NULL} when samples are not matched.
#'   Blocks are used only when both states of a contrast have replicates.
#'   They remove effects shared by the samples of a block, but not the
#'   temporal autocorrelation of consecutive samples of the same state.
#' @param dist_method Distance metric for the trait matrix. Default is "gower".
#' @param dim_retention Character. How many PCoA axes to keep: \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"} (axes needed
#'   to reach \code{var_tol} of the positive variance; the default up to
#'   0.5.0, use it to reproduce earlier results) or \code{"broken_stick"}
#'   (axes explaining more than the broken-stick expectation).
#'   \code{\link{assess_functional_space}} shows the fidelity for each number
#'   of axes.
#' @param var_tol Numeric. Proportion of cumulative variance to retain when
#'   \code{dim_retention = "variance"}. Default is 0.80.
#' @param na.rm Logical. Remove missing values? Default is TRUE.
#' @param correction Character. \code{"none"} (default) builds the PCoA on the
#'   Gower dissimilarity, as in 0.1.1. \code{"sqrt"} uses its square root, which
#'   Gower (1971) showed to be Euclidean for complete data with constant
#'   weights (no negative eigenvalues). It changes the distances
#'   between species (and the shape of the space), so results with and without
#'   it are not comparable; its effect on the tests has not been evaluated by
#'   simulation. An option when the space quality is low, not a default
#'   recommendation.
#' @param type,weights Optional; passed unchanged to \code{\link[cluster]{daisy}}
#'   (e.g. to declare asymmetric binary traits or to down-weight traits coded
#'   in several columns). Default: not used.
#'
#' @note
#' **Normalization:** Delta FDis and Delta FRic are absolute differences, not
#' normalized by the regional pool. Values are not directly comparable across
#' studies with different species pools or trait scales. Only rDelta_C (position)
#' is normalized by Dmax_regional.
#'
#' **FRic = NA:** When a community has fewer species than retained PCoA axes,
#' the convex hull is geometrically undefined and FRic is set to \code{NA},
#' which propagates to Delta_FRic.
#'
#' **FRic and unequal replicates:** with replicates, a species counts as
#' present in a state if it appears in any of its samples, so FRic grows with
#' the number of samples. When the two states of a contrast have different
#' numbers of samples, \code{Delta_FRic_rarefied} gives Delta FRic with the
#' same number of samples in both states: FRic of the state with more samples
#' is averaged over all subsets of the size of the other state (or over 200
#' random subsets, with a fixed internal seed, when there are more). Use it to
#' read the size of the volume change; the tests of \code{\link{asc_null}}
#' keep the numbers of samples and remain valid.
#'
#' **Replicates:** When several rows share the same site and state (e.g. five
#' surveys before an event), their relative abundances are averaged (column
#' means) to describe the state, so the three layers compare the mean
#' community of each state. The variation among replicates is used by null
#' model A, which then permutes whole samples between the states (see
#' \code{\link{asc_null}}).
#'
#' @return An S3 object of class \code{ascent_paired} (it also carries the
#'   class \code{ascfcd} of ascent 0.5.0, which will be dropped in 0.6.0), a
#'   list whose main elements are \code{rDelta_C} (centroid shift per contrast,
#'   as a percentage of the largest distance between species in the functional
#'   space), \code{site_results} (per contrast: \code{abs_dist} =
#'   \eqn{||\Delta C||}, \code{Delta_FDis}, \code{Delta_FRic},
#'   \code{Delta_FRic_rarefied}, \code{n_samples} and the share of the shift
#'   along each axis), \code{F_space} (species coordinates), \code{k_retained}
#'   and \code{dim_retention} (number of axes and the rule used),
#'   \code{quality} of the PCoA and the inputs needed by \code{asc_null()}.
#'   \code{summary()} gives a reading; \code{plot()} draws the shift.
#'
#' @examples
#' # birds_sim: two sites surveyed 5 times before and 5 times after an event.
#' # At "Logged" the bird community changes; at "Control" nothing changes.
#' # Check the functional space first (see ?assess_functional_space)
#' assess_functional_space(birds_sim$traits)
#'
#' res <- asc_paired(birds_sim$traits, birds_sim$counts,
#'                   sites = birds_sim$samples$site,
#'                   time = birds_sim$samples$time, ref_time = "Before")
#'
#' # Layer1_rDeltaC is the centroid shift (% of the functional space): it is
#' # large at "Logged" and small at "Control". The last section ("Top Functional
#' # Drivers") lists the species that moved the centroid most (see ?asc_transitions).
#' summary(res)
#'
#' \donttest{
#' # Is each shift larger than sampling noise (A) and organised by traits (B)?
#' res <- asc_null(res, n_perm = 199, seed = 1)
#' summary(res)
#' }
#'
#' @export
asc_paired <- function(traits, abund, sites, time, ref_time, dist_method = "gower",
                       dim_retention = c("msd", "variance", "broken_stick"), var_tol = 0.80, na.rm = TRUE,
                       correction = c("none", "sqrt"), type = NULL, weights = NULL,
                       blocks = NULL) {

  dim_retention <- match.arg(dim_retention)
  correction <- match.arg(correction)
  if (!is.null(blocks)) {
    if (length(blocks) != nrow(abund)) {
      stop(sprintf("'blocks' must have one value per row of 'abund' (%d), not %d.",
                   nrow(abund), length(blocks)))
    }
    if (anyNA(blocks)) stop("'blocks' must not contain missing values.")
    blocks <- as.character(blocks)
  }

  abund <- .align_species(traits, abund)
  counts <- .keep_counts(abund)
  abund_rel <- as.matrix(sweep(abund, 1, rowSums(abund, na.rm = na.rm), "/"))

  fs <- .build_functional_space(traits, dist_method, dim_retention, var_tol,
                                correction, type, weights)
  .check_fric_richness(abund, fs$k_retained)
  F_mat <- fs$F_mat

  cwm_global <- abund_rel %*% F_mat
  Dmax_regional <- max(stats::dist(F_mat))
  if(Dmax_regional == 0) Dmax_regional <- 1

  unique_sites <- unique(sites)
  res_list <- list()
  rDelta_C <- numeric(length(unique_sites))
  names(rDelta_C) <- unique_sites
  directional_vectors <- list(); p_ref_list <- list(); p_comp_list <- list()
  cwm_ref_list <- list(); cwm_comp_list <- list()

  for (s in unique_sites) {
    idx <- which(sites == s)
    abund_site <- abund_rel[idx, , drop = FALSE]
    time_site <- time[idx]

    idx_ref <- which(time_site == ref_time)
    idx_comp <- which(time_site != ref_time)

    if(length(idx_ref) == 0 || length(idx_comp) == 0) { rDelta_C[s] <- NA; next }

    p_ref_mat <- if(nrow(abund_site[idx_ref, , drop=FALSE]) > 1) t(as.matrix(colMeans(abund_site[idx_ref, , drop=FALSE]))) else abund_site[idx_ref, , drop=FALSE]
    p_comp_mat <- if(nrow(abund_site[idx_comp, , drop=FALSE]) > 1) t(as.matrix(colMeans(abund_site[idx_comp, , drop=FALSE]))) else abund_site[idx_comp, , drop=FALSE]

    p_ref_list[[s]] <- p_ref_mat; p_comp_list[[s]] <- p_comp_mat
    cwm_ref <- p_ref_mat %*% F_mat; cwm_comp <- p_comp_mat %*% F_mat
    cwm_ref_list[[s]] <- cwm_ref; cwm_comp_list[[s]] <- cwm_comp

    v_dir <- cwm_comp - cwm_ref
    directional_vectors[[s]] <- v_dir
    dist_abs <- sqrt(sum(v_dir^2))
    rDelta_C[s] <- (dist_abs / Dmax_regional) * 100

    # Guard: zero displacement
    ss_vdir <- sum(v_dir^2)
    if (ss_vdir < 1e-12) {
      asc_contrib <- rep(0, length(v_dir))
      crit_axis <- NA_integer_
    } else {
      asc_contrib <- (v_dir^2 / ss_vdir) * 100
      crit_axis <- which.max(asc_contrib)
    }

    topo_ref <- .calc_core_topology(as.numeric(p_ref_mat), F_mat)
    topo_comp <- .calc_core_topology(as.numeric(p_comp_mat), F_mat)
    fric_r <- .fric_rarefied(abund_site[idx_ref, , drop = FALSE], length(idx_comp), F_mat, topo_ref$FRic)
    fric_c <- .fric_rarefied(abund_site[idx_comp, , drop = FALSE], length(idx_ref), F_mat, topo_comp$FRic)

    res_list[[s]] <- list(
      abs_dist = dist_abs,
      asc = asc_contrib,
      critical_axis = crit_axis,
      Delta_FDis = topo_comp$FDis - topo_ref$FDis,
      Delta_FRic = topo_comp$FRic - topo_ref$FRic,
      Delta_FRic_rarefied = fric_c - fric_r,
      n_samples = c(reference = length(idx_ref), comparison = length(idx_comp))
    )
  }

  valid_sites <- !is.na(rDelta_C)
  output <- list(
    rDelta_C = rDelta_C[valid_sites],
    Dmax_regional = Dmax_regional,
    directional_vectors = directional_vectors,
    p_ref = p_ref_list, p_comp = p_comp_list,
    cwm_ref = cwm_ref_list, cwm_comp = cwm_comp_list,
    site_results = res_list[valid_sites],
    F_space = F_mat, k_retained = fs$k_retained, dim_retention = dim_retention,
    var_retained = fs$var_retained, axis_var = fs$axis_var,
    quality = fs$quality,
    original_traits = traits, original_abund = abund_rel,
    counts = counts, sites = sites, time = time, ref_time = ref_time,
    blocks = blocks, correction = correction
  )
  class(output) <- c("ascent_paired", "ascfcd")
  return(output)
}
# FRic of a state with its number of samples reduced to n_other (internal).
# Returns fric_all unchanged when the state has at most n_other samples.
.fric_rarefied <- function(A, n_other, F_mat, fric_all) {
  m <- nrow(A)
  if (m <= n_other || n_other < 1) return(fric_all)
  n_sub <- choose(m, n_other)
  subs <- if (n_sub <= 200) utils::combn(m, n_other, simplify = FALSE)
          else withr::with_seed(1, replicate(200, sort(sample.int(m, n_other)), simplify = FALSE))
  f <- vapply(subs, function(i) .calc_core_topology(colMeans(A[i, , drop = FALSE]), F_mat)$FRic, numeric(1))
  if (all(is.na(f))) NA_real_ else mean(f, na.rm = TRUE)
}

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.