R/summary.R

Defines functions .print_drivers .null_reading_guide .print_trait_shifts .b_position_note .print_permutation .null_p_note .fmt_p .read_null_tests summary.ascent_transitions summary.ascent_entities summary.ascent_baseline summary.ascent_pairwise summary.ascent_paired

Documented in summary.ascent_baseline summary.ascent_entities summary.ascent_paired summary.ascent_pairwise summary.ascent_transitions

#' Summary for Paired Functional Centroid Displacement
#'
#' @description
#' Provides a concise, multi-layer overview of the paired ASC-CFD analysis,
#' including null models and top functional drivers.
#'
#' @param object An object of class \code{ascent_paired}.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return Invisibly returns a data frame with the displacement metrics.
#' @export
summary.ascent_paired <- function(object, ...) {
  cat("==================================================\n")
  cat(" ASC-CFD: Multidimensional Functional Restructuring \n")
  cat("==================================================\n\n")

  cat(sprintf("Number of Contrasts: %d\n", length(object$rDelta_C)))
  cat(sprintf("Functional Dimensionality (k): %d (rule: %s; explaining %.1f%% of variance)\n",
              object$k_retained, .rule_text(object), object$var_retained * 100))
  cat(sprintf("PCoA Quality: %.1f%%\n", object$quality * 100))

  df_dist <- data.frame(
    Contrast = names(object$rDelta_C),
    Layer1_rDeltaC = round(object$rDelta_C, 2),
    Layer2_DeltaFDis = round(sapply(object$site_results, function(x) x$Delta_FDis), 4),
    Layer3_DeltaFRic = round(sapply(object$site_results, function(x) x$Delta_FRic), 4)
  )
  rar <- sapply(object$site_results, function(x) if (is.null(x$Delta_FRic_rarefied)) NA_real_ else x$Delta_FRic_rarefied)
  raw <- sapply(object$site_results, function(x) x$Delta_FRic)
  dif <- !is.na(rar) & !is.na(raw) & abs(rar - raw) > 1e-12
  if (any(dif)) df_dist$Layer3_DeltaFRic_rarefied <- round(rar, 4)

  cat("\n--- Functional Shift Overview ---\n")
  print(df_dist, row.names = FALSE)
  if (!is.null(df_dist$Layer3_DeltaFRic_rarefied)) {
    cat("Layer3_DeltaFRic_rarefied: Delta FRic with the same number of samples in both states\n",
        "(FRic grows with the number of samples; see ?asc_paired).\n", sep = "")
  }
  cat("\n")

  if (!is.null(object$null_models)) {
    method <- if (!is.null(object$null_models$P_adj)) object$null_settings$p_adjust
    cat("--- Null Models (A: sampling | B: traits, stratified) ---\n")
    print(.read_null_tests(object$null_models, global = FALSE, method = method), row.names = FALSE)
    cat("\n")
    .null_p_note(global = FALSE, method = method,
                 two_sided = if (is.null(object$null_settings$two_sided)) "centred" else object$null_settings$two_sided)
    .b_position_note(object$null_settings, global = FALSE)
    .print_trait_shifts(object$trait_shifts, global = FALSE)
    .print_permutation(object$null_settings$permutation)
    .null_reading_guide(global = FALSE)
  } else {
    cat("Null models not evaluated. Run asc_null() to test each layer against sampling (A) and traits (B).\n\n")
  }

  # TOP 5 DRIVERS (Leverage Preview)
  cat("--- Top Functional Drivers (Leverage, midpoint reference) ---\n")
  trans <- asc_transitions(object)
  .print_drivers(trans, names(trans))

  invisible(df_dist)
}


#' Summary for Pairwise Functional Spatial Divergence
#'
#' @description
#' Provides a comprehensive overview of the spatial network ASC-CFD analysis.
#'
#' @param object An object of class \code{ascent_pairwise}.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return Invisibly returns the pairwise results data frame.
#' @export
summary.ascent_pairwise <- function(object, ...) {
  cat("==================================================\n")
  cat(" ASC-CFD: Pairwise Spatial Functional Network \n")
  cat("==================================================\n\n")

  n_com <- nrow(object$cwm_global)
  n_pairs <- nrow(object$pairwise_results)

  cat(sprintf("Communities Analyzed: %d | Spatial Contrasts: %d\n", n_com, n_pairs))
  cat(sprintf("Functional Dimensionality (k): %d (rule: %s; explaining %.1f%% of variance)\n",
              object$k_retained, .rule_text(object), object$var_retained * 100))
  cat(sprintf("PCoA Quality: %.1f%%\n\n", object$quality * 100))

  cat("--- Global Divergence Summary ---\n")
  rdelta <- object$pairwise_results$rDelta_C_pct
  fdis_shifts <- object$pairwise_results$Delta_FDis
  fric_shifts <- object$pairwise_results$Delta_FRic

  cat(sprintf(" Mean Position Shift (rDelta_C): %6.2f%%\n", mean(rdelta, na.rm = TRUE)))
  cat(sprintf(" Mean Dispersion Shift (Delta_FDis): %6.4f\n", mean(fdis_shifts, na.rm = TRUE)))
  cat(sprintf(" Mean Volume Shift (Delta_FRic): %s\n\n",
              if(all(is.na(fric_shifts))) "NA" else sprintf("%6.4f", mean(fric_shifts, na.rm = TRUE))))

  if (!is.null(object$null_models)) {
    method <- if (!is.null(object$null_models$P_adj)) object$null_settings$p_adjust
    cat("--- Global Test Over All Communities (A: sampling | B: traits, stratified) ---\n")
    print(.read_null_tests(object$null_models, global = TRUE, method = method), row.names = FALSE)
    cat("\n")
    .null_p_note(global = TRUE, method = method)
    .b_position_note(object$null_settings, global = TRUE)
    .print_trait_shifts(object$trait_shifts, global = TRUE)
    if (!is.null(object$site_contribution)) {
      cat("--- Distance of Each Community to the Common Centroid ---\n")
      sc <- object$site_contribution[order(-object$site_contribution$Distance_to_common_centroid), ]
      sc[, -1] <- round(sc[, -1], 4)
      print(utils::head(sc, 10), row.names = FALSE)
      cat("\n")
    }
    .null_reading_guide(global = TRUE)
  }

  # TOP 5 DRIVERS ESPACIALES (Leverage Preview)
  cat("--- Top Functional Drivers (Leverage, midpoint reference - Head) ---\n")
  trans <- asc_transitions(object)
  .print_drivers(trans, utils::head(names(trans), 5))
  if (length(trans) > 5) cat(sprintf("(first 5 of %d pairs; see asc_transitions())\n\n", length(trans)))

  invisible(object$pairwise_results)
}


#' Summary for Baseline Functional Entities
#'
#' @description
#' Provides an overview of the baseline functional topology of the evaluated entities.
#'
#' @param object An object of class \code{ascent_baseline}.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return Invisibly returns the entities results data frame.
#' @export
summary.ascent_baseline <- function(object, ...) {
  cat("==================================================\n")
  cat(" ASC-CFD: Baseline Functional Topology \n")
  cat("==================================================\n\n")

  cat(sprintf("Entities Analyzed: %d\n", nrow(object$entities_results)))
  cat(sprintf("Functional Dimensionality (k): %d (rule: %s; explaining %.1f%% of variance)\n",
              object$k_retained, .rule_text(object), object$var_retained * 100))
  cat(sprintf("PCoA Quality: %.1f%%\n\n", object$quality * 100))

  cat("--- Absolute Entity Metrics ---\n")

  # Redondeo para limpieza visual en consola
  print_df <- object$entities_results
  num_cols <- sapply(print_df, is.numeric)
  print_df[, num_cols] <- round(print_df[, num_cols], 4)

  print(print_df, row.names = FALSE)
  cat("\n")

  invisible(object$entities_results)
}

#' Summary for Functional Entities Classification
#'
#' @description
#' Provides an overview of the species clustering into functional entities.
#'
#' @param object An object of class \code{ascent_entities}.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return Invisibly returns the classification data frame.
#' @export
summary.ascent_entities <- function(object, ...) {
  cat("==================================================\n")
  cat(" ASC-CFD: Functional Entities Classification \n")
  cat("==================================================\n\n")

  df <- object$entity_classification
  cat(sprintf("Total Species: %d | Functional Entities: %d\n", nrow(df), length(unique(df$Entity_ID))))
  cat(sprintf("Distance Metric: %s | Clustering Method: %s\n",
              tools::toTitleCase(object$metric), object$method))
  if (!is.null(object$suggestions)) {
    cat(sprintf("Suggested k -> silhouette: %d (max. mean silhouette %.2f) | Mojena: %d | gap: %d\n",
                object$suggestions[["silhouette"]], object$silhouette_max,
                object$suggestions[["mojena"]], object$suggestions[["gap"]]))
    cat("Silhouette guide: > 0.5 clear groups; 0.25-0.5 weak; < 0.25 no clear groups. Gap = 1: no natural groups.\n")
  }
  cat("\n--- Species per Entity ---\n")
  print(table(df$Entity_ID))
  cat("\n--- Classification Preview (Head) ---\n")
  print(utils::head(df, 5), row.names = FALSE)
  cat("\n")

  invisible(df)
}

#' Summary for Functional Transitions
#'
#' @description
#' For each contrast, shows the species with the largest leverage, the
#' partition of the centroid displacement among shared, gained and lost
#' species (with its range across reference points) and, if entities were
#' given, the split between and within entities.
#'
#' @param object An object of class \code{ascent_transitions}.
#' @param n_sp Integer. Number of top species to display per contrast. Default is 5.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return Invisibly returns the object.
#' @export
summary.ascent_transitions <- function(object, n_sp = 5, ...) {
  cat("==================================================\n")
  cat(" ASC-CFD: Functional Transitions \n")
  cat("==================================================\n\n")
  cat(sprintf("Contrasts Analyzed: %d\n\n", length(object)))

  for (s in names(object)) {
    o <- object[[s]]
    cat(sprintf("--- %s (shift = %.4f, reference point: %s) ---\n", s, o$shift, o$ref))
    df <- utils::head(o$species_leverage, n_sp)
    num_cols <- vapply(df, is.numeric, logical(1))
    df[, num_cols] <- round(df[, num_cols], 4)
    print(df, row.names = FALSE)
    cat("Partition of the shift:\n")
    pt <- o$partition
    pt[, -1] <- round(pt[, -1], 3)
    print(pt, row.names = FALSE)
    if (!is.null(o$entities)) {
      cat(sprintf("Entities: between = %.4f | within = %.4f | within fraction = %.2f\n",
                  o$entities[["Between"]], o$entities[["Within"]], o$entities[["Within_fraction"]]))
    }
    cat("\n")
  }
  cat("A wide Min-Max range across reference points means the partition depends on the reference: interpret with caution.\n\n")
  invisible(object)
}

# ==============================================================================
# READING OF NULL MODEL TESTS (internal)
# ==============================================================================
# The reading uses the adjusted p-value (P_adj) when it exists; objects from
# ascent 0.5.0 have no P_adj and are read with the unadjusted value.
#' @noRd
.read_null_tests <- function(tab, global = FALSE, alpha = 0.05, method = NULL) {
  isA <- grepl("^A", tab$Test)
  pos <- tab$Layer == "Position"
  p_used <- if (global) tab$P_upper else ifelse(pos, tab$P_upper, tab$P_two)
  p_read <- if (!is.null(tab$P_adj)) tab$P_adj else p_used
  # The lower tail of B is not read (as compensation or otherwise): it had
  # little power in the validation (see ?asc_null)
  if (global) {
    reading <- ifelse(is.na(p_read) | p_read > alpha, "no evidence",
               ifelse(isA, "more variation than sampling", "variation organised by traits"))
  } else {
    reading <- ifelse(is.na(p_read) | p_read > alpha, "no evidence",
               ifelse(isA, ifelse(pos, "larger than sampling",
                                  ifelse(tab$SES > 0, "increase beyond sampling", "decrease beyond sampling")),
                      ifelse(pos, "directed by traits",
                             ifelse(tab$SES > 0, "increase linked to traits", "decrease linked to traits"))))
  }
  out <- data.frame(Contrast = tab$Contrast, Test = tab$Test, Layer = tab$Layer,
                    Observed = signif(tab$Observed, 4), SES = round(tab$SES, 2),
                    P_upper = .fmt_p(tab$P_upper), P_lower = .fmt_p(tab$P_lower),
                    stringsAsFactors = FALSE)
  if (!global) out$P_two <- .fmt_p(ifelse(pos, NA, tab$P_two))
  if (!is.null(tab$P_adj)) out[[paste0("P_", if (is.null(method)) "adj" else method)]] <- .fmt_p(tab$P_adj)
  out$Reading <- reading
  out
}

# p-values as text with three significant digits; "-" when not applicable
#' @noRd
.fmt_p <- function(p) {
  vapply(p, function(v) if (is.na(v)) "-" else format(signif(v, 3), scientific = FALSE,
                                                         drop0trailing = TRUE), character(1))
}

#' @noRd
.null_p_note <- function(global = FALSE, method = NULL, two_sided = "centred") {
  if (global) {
    cat("P_upper, P_lower: one-tailed p-values (not adjusted). The upper tail is used for all layers.\n")
  } else {
    cat("P_upper, P_lower: one-tailed p-values (not adjusted). P_two: two-tailed (not adjusted), ",
        if (two_sided == "doubled") "twice the smaller tail" else "centred on the null mean", ".\n",
        "P used: P_upper for position; P_two for dispersion and volume.\n", sep = "")
  }
  if (is.null(method)) {
    cat("Reading: based on the P used, not adjusted.\n")
  } else if (method == "none") {
    cat("P_none: the P used, not adjusted (p_adjust = \"none\"). Reading: based on it.\n")
  } else {
    cat(sprintf(paste0("P_%s: the P used, adjusted (%s) across the three layers of each test and contrast.\n",
                       "Reading: based on the adjusted p-value (P_%s).\n"), method, method, method))
  }
  if (!global) {
    cat(if (two_sided == "doubled") "Other two-tailed convention: asc_null(..., two_sided = \"centred\").\n"
        else "Other two-tailed convention: 2 x min(P_upper, P_lower), or asc_null(..., two_sided = \"doubled\").\n")
  }
  cat("\n")
  invisible(NULL)
}

# How the samples were permuted for A in each contrast (internal)
#' @noRd
.print_permutation <- function(perm) {
  if (is.null(perm) || !nrow(perm)) return(invisible(NULL))
  perm <- perm[grepl("^A", perm$Test), , drop = FALSE]
  if (!nrow(perm)) return(invisible(NULL))
  cat("--- Permutation used for A ---\n")
  for (i in seq_len(nrow(perm))) {
    r <- perm[i, ]
    txt <- switch(r$Design,
      individuals = "one sample per state: individuals reassigned (multinomial sampling error only).",
      free = sprintf("whole samples permuted freely: %s allocations (%s).",
                     format(r$Allocations, big.mark = ",", scientific = FALSE),
                     if (r$Exact) "all enumerated" else "random sample"),
      blocks = sprintf("samples exchanged within %d blocks: %s allocations (%s); smallest attainable P for position = %.3g.",
                       r$Blocks, format(r$Allocations, big.mark = ",", scientific = FALSE),
                       if (r$Exact) "all enumerated" else "random sample", r$Min_P_position))
    cat(sprintf("  %s, %s: %s\n", r$Contrast, r$Test, txt))
  }
  if (any(perm$Design == "individuals")) {
    cat("  Without replicates, ordinary variation between samples (e.g. two months of the same\n",
        "  community) can look like a change in A. Replicates are recommended.\n", sep = "")
  }
  if (any(perm$Design == "free")) {
    cat("  Free permutation assumes that samples are exchangeable between states. If both states\n",
        "  were sampled in matched units (same months, plots), give them as 'blocks' in asc_paired().\n",
        "  Consecutive samples of a before/after design are not exchangeable: A is then liberal.\n", sep = "")
  }
  cat("\n")
  invisible(NULL)
}

# What the statistic of B for position is (internal). Objects from ascent
# 0.5.0 used the norm and have no "b_position" setting.
#' @noRd
.b_position_note <- function(settings, global = FALSE) {
  if (is.null(settings$b_position)) return(invisible(NULL))
  if (global) {
    cat("B, position: sum over axes of the variance of the community centroids along each axis,\n",
        "divided by its mean under the null (about the number of axes when there is no change).\n",
        "Each axis counts in units of its own chance variation, so changes along minor axes are\n",
        "detected as well as along the first axis. The mean distance to the common centroid is in\n",
        "row A; B with that statistic (as in 0.5.0) is kept in $b_position_norm.\n\n", sep = "")
  } else {
    cat("B, position: sum over axes of the squared shift of the centroid in units of its null\n",
        "standard deviation (about the number of axes when there is no change). Each axis counts\n",
        "in units of its own chance variation, so changes along minor axes are detected as well as\n",
        "along the first axis. ||Delta C|| is in row A; B with ||Delta C|| (as in 0.5.0) is kept in\n",
        "$b_position_norm.\n\n", sep = "")
  }
  invisible(NULL)
}

# Trait whose abundance-weighted mean moved most, in null standard deviations
# (descriptive; no p-value) (internal)
#' @noRd
.print_trait_shifts <- function(ts, global = FALSE) {
  if (is.null(ts) || !nrow(ts)) return(invisible(NULL))
  cat("--- Trait with the largest standardised shift (descriptive) ---\n")
  for (s in unique(ts$Contrast)) {
    d <- ts[ts$Contrast == s, , drop = FALSE]
    d <- d[order(-abs(d$Std_shift)), , drop = FALSE]
    lvl <- !is.null(d$Type) && identical(d$Type[1], "level")
    if (global) {
      what <- if (lvl) "sd among communities of its share of abundance" else "sd among communities of its weighted mean"
      cat(sprintf("  %s: %s (%s = %.3g; %.1f times its null value)\n",
                  s, d$Trait[1], what, d$Delta[1], d$Std_shift[1]))
    } else {
      what <- if (lvl) "change of its share of abundance" else "change of its weighted mean"
      cat(sprintf("  %s: %s (%s = %+.3g; %.1f null SD)\n",
                  s, d$Trait[1], what, d$Delta[1], abs(d$Std_shift[1])))
    }
  }
  cat(if (global) "About 1 times its null value is chance level; it is a description, not a test.\n"
      else "About 1 null SD or less is chance level; it is a description, not a test.\n",
      "Correlated traits move together: read it as the group of traits that changed.\n",
      "Categorical traits are shown by level (\"trait = level\"). All traits: $trait_shifts.\n\n", sep = "")
  invisible(NULL)
}

#' @noRd
.null_reading_guide <- function(global = FALSE) {
  if (global) {
    cat("Guide: A no -> the communities do not differ more than samples of one community |\n",
        "A yes + B yes -> variation among communities organised by traits |\n",
        "A yes + B no -> variation beyond sampling without detectable trait structure.\n",
        "The lower tail of B is shown for description only.\n\n", sep = "")
  } else {
    cat("Guide: A no -> no evidence of change beyond sampling | A yes + B upper -> directed by traits |\n",
        "A yes + B no -> change beyond sampling without detectable trait structure.\n",
        "Entities (exploratory): many within-entity shifts (asc_transitions) with A_entities no are\n",
        "consistent with replacement among similar species within entities; replacement between species of\n",
        "different entities looks like a change between entities, so a 'no' does not rule out redundancy.\n",
        "The lower tail of B is shown for description only (little power for compensation).\n",
        "B is slightly liberal for dispersion, for evenness changes and for individuals captured in groups:\n",
        "treat P close to 0.05 with caution.\n\n",
        sep = "")
  }
  invisible(NULL)
}

# Up to five species with the largest leverage per contrast; leverages that
# round to zero are not shown (internal)
#' @noRd
.print_drivers <- function(trans, contrasts) {
  for (s in contrasts) {
    lev <- trans[[s]]$species_leverage
    lev <- utils::head(lev[round(lev$Leverage, 2) != 0, , drop = FALSE], 5)
    txt <- if (nrow(lev)) paste(sprintf("%s (%+.2f)", lev$Species, lev$Leverage), collapse = ", ")
           else "no species with leverage >= 0.005"
    cat(sprintf("  %s: %s\n", s, txt))
  }
  cat("\n")
  invisible(NULL)
}

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.