INTRO
This entry analyzes the resazurin assay data from the 20261120 Magallana gigas (Pacific oyster) life stage comparison at 36°C. In that experiment, ~10mm, ~40mm, and ~70mm oysters were assayed to compare metabolism across life stages.
Markdown below was knitted from 02.00-resazurin-lifestage-comparisons.Rmd (GitHub).
1 Background
On 20261120, three size classes of Magallana gigas, representing different life stages (~10mm, ~40mm and ~70mm; ten oysters each), were exposed to 36°C for 4hrs in resazurin working solution, with fluorescence measured every 30mins (0.0hr-4.0hr). Each size class was analysed on its own in:
01.00-resazurin-20261120-mgig-10mm-36C.Rmd01.00-resazurin-20261120-mgig-40mm-36C.Rmd01.00-resazurin-20261120-mgig-70mm-36C.Rmd
This script runs the same analysis on all three experiments together and compares the size classes (size_class.group): 10mm vs 40mm vs 70mm. Sections, chunk names, figures and output files follow the 01.00 scripts, with size class taking the place of family/treatment as the grouping factor. Each oyster’s processing (blank correction, fold-change, metabolism, AUC) is identical to its 01.00 script, so per-oyster values match those outputs.
See each experiment’s data/UW/raw/resazurin/<experiment>/README.md for full experimental notes.
\[!IMPORTANT\] Size class is confounded with assay setup. The 10mm oysters were held in 4mL of resazurin in a 12-well plate read directly every 30mins; the 40mm and 70mm oysters were held in ~100mL cups, with 200uL aliquots transferred to 96-well plates and read at the end of the experiment. Each size class also has its own plates and blanks. Raw fluorescence (RFU) is therefore not comparable between size classes. Fold-change (relative to each oyster’s own T0 read) and size-normalised metabolism are the comparable quantities, but differences between size classes may still partly reflect solution volume per oyster and read method, not life stage alone.
1.1 How the experiments are combined
Each experiment directory is loaded exactly as in the 01.00 scripts: its own plate exports, its own layout.csv and its own timepoint source (filename or layout; see the 01.00 scripts). The experiments are then stacked, keyed by experiment so that sample IDs (1-10 in every experiment) and plates never collide.
T0 and blank fold-change are computed within each experiment: each experiment’s blank fold-change is relative to its own T0 blank, and pooled across plates only within that experiment.
1.2 Expected inputs
| Path | Description |
|---|---|
<data_dirs>/*.txt |
Plate reader fluorescence exports for each experiment (files without a Results block are reported and skipped) |
<data_dirs>/layout.csv |
Well metadata for each experiment, as in the 01.00 scripts. Every layout must carry the comparison column (compare_col, here size_class.group) |
data_dirs, out_dir and compare_col are set in the configuration block at the top of Load Data.
1.3 Expected outputs
All outputs are written to out_dir (outputs/02.00-resazurin-lifestage-comparisons/).
| File | Description |
|---|---|
figures/ |
All plots generated by this script |
auc_all_metrics.csv |
Per-individual AUC values for every active measurement metric |
auc_summary.csv |
Size-class AUC summary statistics (mean, SD, SE, median) |
metabolism.csv |
Full per-well per-timepoint metabolism data frame |
pairwise_stats.csv |
Tukey-adjusted pairwise size-class comparisons from AUC linear models |
auc_sensitivity_overall.csv |
Overall size-class tests under each sensitivity method, with and without the most extreme individual |
auc_sensitivity_pairwise.csv |
Pairwise size-class comparisons under each sensitivity method, with and without the most extreme individual |
2 Setup
2.1 Knitr options
knitr::opts_chunk$set(
echo = TRUE, # Display code chunks
eval = TRUE, # Evaluate code chunks
warning = FALSE, # Hide warnings
message = FALSE, # Hide messages
comment = "", # Prevents appending '##' to beginning of lines in code output
results = 'hold' # Holds output so it's all printed together after code chunk
)2.2 Load libraries
library(tidyverse)
library(pracma) # trapz()
library(lme4)
library(lmerTest)
library(emmeans)
library(multcompView)
library(cowplot)
library(colorspace) # qualitative_hcl() for large palettes3 Helper Functions
normalize_well_id <- function(x) {
x <- toupper(trimws(x))
valid <- str_detect(x, "^[A-Z]+[0-9]+$")
out <- rep(NA_character_, length(x))
if (!any(valid)) return(out)
m <- str_match(x[valid], "^([A-Z]+)([0-9]+)$")
out[valid] <- paste0(m[, 2], as.integer(m[, 3]))
out
}
# Timepoint encoded in the plate export FILENAME, e.g. "..._T3.txt" -> 3.
# A trailing ".0" is tolerated: "..._T0.0.txt" -> 0, "..._T18.75.0.txt" -> 18.75.
# Returns NA when the filename carries no timepoint token, in which case the
# timepoint is taken from the layout file instead (see `timepoint_source`).
parse_time_hr <- function(path) {
hit <- str_match(basename(path),
"(?i)[_-]T([0-9]+(?:\\.[0-9]+)?)(?:\\.0)?\\.[^.]+$")
as.numeric(hit[, 2])
}
# Plate ID from the plate export FILENAME. Must resolve to the same value as
# `plate_id` in layout.csv, which is lower-cased and has any "plate-"/"plate_"
# prefix stripped. Handles both file naming conventions:
# "20260624_round1_T3.txt" -> "round1" (date_plate_timepoint)
# "plate-D.txt" -> "d" (one file per plate)
# "plate-C-T0.25.txt" -> "c" (plate_timepoint)
# "plate-A-96well.txt" -> "a" (plate type suffix)
parse_plate_id <- function(path) {
base <- str_remove(basename(path), "\\.[^.]+$")
has_time <- !is.na(parse_time_hr(path))
dated <- str_match(
base, "(?i)^[0-9]{8}[_-](.+?)[_-]T[0-9]+(?:\\.[0-9]+)*$")[, 2]
id <- if (!is.na(dated)) {
dated
} else if (has_time) {
str_remove(base, "(?i)[_-]T[0-9]+(?:\\.[0-9]+)*$")
} else {
base
}
id <- str_remove(str_to_lower(trimws(id)), "^plate[_-]")
id <- str_remove(id, "[_-][0-9]+[_-]?wells?$")
if (is.na(id) || id == "") "unknown" else id
}
# Timepoint encoded in the LAYOUT, converted to numeric hours. Accepts bare
# numbers ("0", "1.5"), T-prefixed labels ("T0", "t3") and unit suffixes
# ("4h", "90min" -> 1.5). Returns NA when no number can be recovered.
parse_timepoint_hr <- function(x) {
x <- trimws(as.character(x))
num <- suppressWarnings(as.numeric(str_extract(x, "[0-9]+(?:\\.[0-9]+)?")))
is_min <- str_detect(str_to_lower(replace_na(x, "")), "min")
if_else(is_min & !is.na(num), num / 60, num)
}
extract_results_block <- function(lines) {
results_idx <- which(trimws(lines) == "Results")
if (length(results_idx) == 0) stop("No Results section found")
idx <- results_idx[1]
header_tokens <- str_split(lines[idx + 1], "\\t")[[1]] |> trimws()
col_ids <- header_tokens[
header_tokens != "" & str_detect(header_tokens, "^[0-9]+$")]
j <- idx + 2
data_lines <- character()
while (j <= length(lines)) {
line <- lines[j]
if (trimws(line) == "") break
if (!str_detect(line, "^[A-Za-z]\\t")) break
data_lines <- c(data_lines, line)
j <- j + 1
}
list(col_ids = col_ids, data_lines = data_lines)
}
parse_plate_export <- function(path) {
lines <- readLines(path, warn = FALSE)
res <- extract_results_block(lines)
map_dfr(res$data_lines, function(line) {
tokens <- str_split(line, "\\t")[[1]] |> trimws()
tokens <- tokens[tokens != ""]
row_letter <- tokens[1]
nums <- suppressWarnings(as.numeric(tokens[-1]))
valid_idx <- which(!is.na(nums))
if (length(valid_idx) == 0) return(tibble())
vals <- nums[valid_idx]
n <- min(length(vals), length(res$col_ids))
tibble(
row_id = toupper(row_letter),
col_id = as.integer(res$col_ids[seq_len(n)]),
well_id = normalize_well_id(
paste0(toupper(row_letter), res$col_ids[seq_len(n)])),
value = vals[seq_len(n)]
)
}) %>%
mutate(
plate_id = str_to_lower(parse_plate_id(path)),
time_hr = parse_time_hr(path)
)
}
# Stable identity of one individual across timepoints. Used for line traces,
# fold-change baselines, repeated-measures random effects and AUC grouping.
#
# The correct fallback depends on where the timepoint comes from:
# * FILENAME - the same well is re-read at every timepoint, so plate + well
# already identifies the individual.
# * LAYOUT - a well holds a single read, so plate + well cannot span time
# and `sample_ID.group` is required (validated when the layout is loaded).
# Blanks are keyed separately so they never merge with sample traces.
trace_key <- function(df, timepoint_source = "filename") {
well_key <- paste(df$plate_id, df$well_id, sep = "_")
fallback <- if (identical(timepoint_source, "layout")) df$plate_id else well_key
sid <- if ("sample_id_group" %in% names(df))
as.character(df$sample_id_group) else rep(NA_character_, nrow(df))
has_sid <- !is.na(sid) & trimws(sid) != ""
blank <- if ("is_blank" %in% names(df))
replace_na(df$is_blank, FALSE) else rep(FALSE, nrow(df))
# Blanks without a sample ID: with filename timepoints the same blank well is
# re-read, so plate + well tracks it. With layout timepoints a blank well
# holds a single read and the blank series can span plates, so all of the
# experiment's blank reads form one trace instead of one per plate.
blank_fallback <- if (identical(timepoint_source, "layout")) "all" else well_key
if_else(blank,
paste0("blank_", if_else(has_sid, sid, blank_fallback)),
if_else(has_sid, sid, fallback))
}
# Distinct non-empty values of a column, or character(0) if it is absent.
# Keeps figure code from failing on layouts that omit a grouping column.
col_values <- function(df, col) {
if (!col %in% names(df)) return(character(0))
v <- as.character(df[[col]])
unique(v[!is.na(v) & trimws(v) != ""])
}
trapezoid_auc <- function(time_hr, value) {
ok <- is.finite(time_hr) & is.finite(value)
t <- time_hr[ok]
v <- value[ok]
if (length(t) < 2) return(NA_real_)
ord <- order(t)
t <- t[ord]; v <- v[ord]
sum(diff(t) * (head(v, -1) + tail(v, -1)) / 2)
}
# Shared helper: extract display unit string from a measurement column name.
# e.g. "area_mm2_measurement" -> "mm²", "weight_mg_measurement" -> "mg"
parse_meas_unit <- function(col_name) {
unit_raw <- col_name |>
str_remove("^metabolism_per_") |>
str_remove("_measurement$") |>
str_extract("[^_]+$")
case_when(
unit_raw == "mm2" ~ "mm²",
unit_raw == "cm2" ~ "cm²",
unit_raw == "mm3" ~ "mm³",
unit_raw == "cm3" ~ "cm³",
TRUE ~ unit_raw
)
}
# y-axis label for metabolism line plots: "fold change/mm²"
metabolism_y_label <- function(col_name) {
paste0("Metabolism (fold change/", parse_meas_unit(col_name), ")")
}
# y-axis label for AUC box plots: "Metabolism (AUC; mm²)"
auc_y_label <- function(metric_name) {
paste0("Metabolism (AUC; ", parse_meas_unit(metric_name), ")")
}
# Mean ± SE time series of `value_col`, one coloured line per level of
# `colour_col`, optionally split into linetypes by a second grouping column.
mean_ts_plot <- function(df, value_col, colour_col, colours, legend_name,
y_lab, linetype_col = NULL, linetypes = NULL) {
if (!is.null(linetype_col) && !linetype_col %in% names(df))
linetype_col <- NULL
grp <- c(colour_col, linetype_col, "time_hr")
summ <- df %>%
filter(!is.na(.data[[colour_col]]), !exclude_from_analysis) %>%
group_by(across(all_of(grp))) %>%
summarise(
mean_val = mean(.data[[value_col]], na.rm = TRUE),
se_val = sd(.data[[value_col]], na.rm = TRUE) /
sqrt(sum(!is.na(.data[[value_col]]))),
n = sum(!is.na(.data[[value_col]])),
.groups = "drop"
) %>%
mutate(group_var = if (is.null(linetype_col))
as.character(.data[[colour_col]])
else
paste(.data[[colour_col]], .data[[linetype_col]], sep = "."))
p <- ggplot(summ, aes(x = time_hr, y = mean_val,
colour = .data[[colour_col]], group = group_var)) +
geom_ribbon(aes(ymin = mean_val - se_val, ymax = mean_val + se_val,
fill = .data[[colour_col]]),
alpha = 0.15, colour = NA) +
geom_line(mapping = if (!is.null(linetype_col))
aes(linetype = .data[[linetype_col]]) else NULL,
linewidth = 1) +
geom_point(size = 2) +
scale_colour_manual(values = colours, name = legend_name,
breaks = names(colours)) +
scale_fill_manual(values = colours, name = legend_name,
breaks = names(colours)) +
labs(x = "Time (h)", y = y_lab,
caption = "Points and lines: group mean. Shaded band: \u00b1 1 standard error (SE).") +
theme_classic(base_size = 13) +
theme(plot.caption = element_text(hjust = 0, size = 10, colour = "grey30"))
if (!is.null(linetype_col))
p <- p + scale_linetype_manual(values = linetypes, name = "Treatment")
p
}
# One line per individual (`trace_id`), faceted by `facet_col` and coloured
# by `colour_col`.
individual_ts_plot <- function(df, value_col, facet_col, colour_col,
colours, legend_name, y_lab) {
df %>%
filter(!is.na(.data[[facet_col]])) %>%
ggplot(aes(x = time_hr, y = .data[[value_col]], group = trace_id,
colour = .data[[colour_col]])) +
geom_line(alpha = 0.6) +
geom_point(size = 1.2, alpha = 0.7) +
facet_wrap(vars(.data[[facet_col]])) +
scale_colour_manual(values = colours, name = legend_name,
breaks = names(colours)) +
labs(x = "Time (h)", y = y_lab) +
theme_classic(base_size = 12) +
theme(strip.background = element_blank(),
strip.text = element_text(face = "bold"))
}4 Load Data
4.1 Plate export files
# ---------------------------------------------------------------------------
# CONFIGURATION - normally the only lines that change between comparisons.
# ---------------------------------------------------------------------------
proj_root <- rprojroot::find_root(
rprojroot::is_rstudio_project | rprojroot::is_git_root)
data_root <- file.path(proj_root, "data", "UW", "raw", "resazurin")
# One entry per experiment; names are the experiment labels used throughout.
data_dirs <- c(
"10mm" = file.path(data_root, "20261120-mgig-10mm-36C"),
"40mm" = file.path(data_root, "20261120-mgig-40mm-36C"),
"70mm" = file.path(data_root, "20261120-mgig-70mm-36C")
)
out_dir <- file.path(proj_root, "outputs",
"02.00-resazurin-lifestage-comparisons")
# Layout `*.group` column (snake_case) whose levels are compared.
compare_col <- "size_class_group"
compare_label <- "Size class"
# Which files in each data directory are plate reader exports. The default
# accepts any .txt; anything without a "Results" block is reported and skipped.
plate_file_pattern <- "(?i)\\.txt$"
# ---------------------------------------------------------------------------
fig_dir <- file.path(out_dir, "figures")
dir.create(fig_dir, recursive = TRUE, showWarnings = FALSE)
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
experiments <- names(data_dirs)
plate_raw <- imap_dfr(data_dirs, function(data_dir, ex) {
plate_files <- list.files(data_dir, pattern = plate_file_pattern,
full.names = TRUE)
if (length(plate_files) == 0)
stop("No files matching '", plate_file_pattern, "' found in ", data_dir)
map_dfr(plate_files, function(path) {
tryCatch(parse_plate_export(path),
error = function(e) {
message("Parse error in ", basename(path), ": ", e$message)
tibble()
})
}) %>%
mutate(experiment = ex)
})
str(plate_raw)tibble [492 × 7] (S3: tbl_df/tbl/data.frame)
$ row_id : chr [1:492] "A" "A" "A" "A" ...
$ col_id : int [1:492] 1 2 3 4 1 2 3 4 1 2 ...
$ well_id : chr [1:492] "A1" "A2" "A3" "A4" ...
$ value : num [1:492] 160 163 204 152 193 202 276 180 197 330 ...
$ plate_id : chr [1:492] "f" "f" "f" "f" ...
$ time_hr : num [1:492] 0 0 0 0 0 0 0 0 0 0 ...
$ experiment: chr [1:492] "10mm" "10mm" "10mm" "10mm" ...
4.2 Layout files
Each experiment’s layout.csv is cleaned exactly as in the 01.00 scripts, and its timepoint source (layout column or plate filename) is determined separately.
load_layout <- function(data_dir, plate_raw_ex) {
layout_path <- file.path(data_dir, "layout.csv")
layout_raw <- read_csv(layout_path,
col_types = cols(.default = "c"),
show_col_types = FALSE)
# Standardise column names to snake_case
names(layout_raw) <- names(layout_raw) |>
str_to_lower() |>
str_replace_all("[^a-z0-9]+", "_") |>
str_replace_all("_+", "_") |>
str_replace("_$", "")
# Normalise plate_id to match plate file ids (strip "plate-" prefix)
layout_clean <- layout_raw %>%
mutate(
plate_id = str_remove(str_to_lower(plate_id), "^plate-"),
well_id = normalize_well_id(plate_well),
is_blank = if ("is_blank" %in% names(layout_raw))
toupper(trimws(is_blank)) %in% c("TRUE", "T", "1", "YES", "Y")
else
FALSE
)
# Trailing blank rows are common in hand-edited layout CSVs; drop anything
# without a resolvable plate + well.
layout_clean <- layout_clean %>%
filter(!is.na(plate_id), plate_id != "", !is.na(well_id))
found_exclude_col <- intersect(
c("exclude_from_analysis", "exclude", "omit", "not_analyzed"),
names(layout_clean)
)[1]
layout_clean <- layout_clean %>%
mutate(
exclude_from_analysis = if (!is.na(found_exclude_col))
toupper(trimws(.data[[found_exclude_col]])) %in%
c("TRUE", "T", "1", "YES", "Y")
else
FALSE
)
# Identify measurement columns and group columns
measurement_cols <- names(layout_clean)[
str_detect(names(layout_clean), "_measurement$")]
group_cols <- names(layout_clean)[
str_detect(names(layout_clean), "_group$")]
# Cast measurement columns to numeric
layout_clean <- layout_clean %>%
mutate(across(all_of(measurement_cols),
~ suppressWarnings(as.numeric(.x))))
# Normalise group values to lowercase so they match colour scale definitions
layout_clean <- layout_clean %>%
mutate(across(all_of(group_cols),
~ str_to_lower(trimws(as.character(.x)))))
# --- Timepoint source ----------------------------------------------------
# Prefer a timepoint column in the layout (per-well, so one plate file may
# hold several timepoints); fall back to the timepoint parsed from the
# filename.
timepoint_col <- intersect(
c("timepoint", "time_point", "timepoint_hr", "time_hr", "time_hrs",
"time_h", "hours", "hour", "time"),
names(layout_clean)
)[1]
layout_time_ok <- !is.na(timepoint_col) &&
any(is.finite(parse_timepoint_hr(layout_clean[[timepoint_col]])))
filename_time_ok <- any(is.finite(plate_raw_ex$time_hr))
timepoint_source <- if (layout_time_ok) "layout" else
if (filename_time_ok) "filename" else NA_character_
if (is.na(timepoint_source))
stop("Could not determine a timepoint for any read in ", data_dir,
". Either name plate export files '<...>_T<hr>.txt' or add a ",
"`timepoint` column to layout.csv.")
if (timepoint_source == "layout") {
layout_clean <- layout_clean %>%
mutate(
timepoint_label = as.character(.data[[timepoint_col]]),
time_hr = parse_timepoint_hr(.data[[timepoint_col]])
)
# With layout-supplied timepoints a well is read once, so plate + well
# cannot follow an individual through the time series - sample IDs are
# the only link.
sample_ids_present <- "sample_id_group" %in% names(layout_clean) &&
any(!is.na(layout_clean$sample_id_group) &
trimws(layout_clean$sample_id_group) != "")
if (!sample_ids_present)
stop("Timepoints come from ", layout_path, ", so each well holds a ",
"single read and plate + well cannot identify an individual ",
"across timepoints. Populate a `sample_ID.group` column.")
}
list(layout = layout_clean,
timepoint_source = timepoint_source,
timepoint_col = timepoint_col,
measurement_cols = measurement_cols,
group_cols = group_cols)
}
layouts <- imap(data_dirs, function(data_dir, ex)
load_layout(data_dir, plate_raw %>% filter(experiment == ex)))
timepoint_sources <- map_chr(layouts, "timepoint_source")
measurement_cols <- unique(unlist(map(layouts, "measurement_cols")))
group_cols <- unique(unlist(map(layouts, "group_cols")))
if (!compare_col %in% group_cols)
stop("Comparison column `", compare_col, "` not found in any layout.csv.")
# Determine which measurement columns contain finite data in EVERY experiment;
# a metric missing from one experiment cannot be compared across them.
active_meas_cols <- measurement_cols[
sapply(measurement_cols, function(col)
all(map_lgl(layouts, ~ col %in% names(.x$layout) &&
any(is.finite(.x$layout[[col]])))))]
for (ex in experiments)
message(ex, ": timepoint source = ", timepoint_sources[[ex]],
if (timepoint_sources[[ex]] == "layout")
paste0(" (layout column `", layouts[[ex]]$timepoint_col, "`)")
else "")
message("Group columns: ", paste(group_cols, collapse = ", "))
message("Active measurement columns: ",
paste(active_meas_cols, collapse = ", "))
str(map(layouts, "layout"))List of 3
$ 10mm: tibble [12 × 15] (S3: tbl_df/tbl/data.frame)
..$ plate_id : chr [1:12] "f" "f" "f" "f" ...
..$ plate_well : chr [1:12] "A01" "A02" "A03" "A04" ...
..$ timepoint_hr : chr [1:12] NA NA NA NA ...
..$ is_blank : logi [1:12] FALSE FALSE FALSE FALSE FALSE FALSE ...
..$ size_class_group : chr [1:12] "10mm" "10mm" "10mm" "10mm" ...
..$ treatment_group : chr [1:12] "36c" "36c" "36c" "36c" ...
..$ sample_id_group : chr [1:12] "1" "2" "3" "4" ...
..$ exclude_from_analysis: logi [1:12] FALSE FALSE FALSE FALSE FALSE FALSE ...
..$ exclude_reason : chr [1:12] NA NA NA NA ...
..$ width_mm_measurement : num [1:12] NA NA NA NA NA NA NA NA NA NA ...
..$ length_mm_measurement: num [1:12] NA NA NA NA NA NA NA NA NA NA ...
..$ weight_mg_measurement: num [1:12] NA NA NA NA NA NA NA NA NA NA ...
..$ area_mm2_measurement : num [1:12] 130 150 194 145 114 ...
..$ imagej_id : chr [1:12] "4" "2" "1" "3" ...
..$ well_id : chr [1:12] "A1" "A2" "A3" "A4" ...
$ 40mm: tibble [108 × 17] (S3: tbl_df/tbl/data.frame)
..$ plate_id : chr [1:108] "a" "a" "a" "a" ...
..$ plate_well : chr [1:108] "A01" "A02" "A03" "A04" ...
..$ timepoint_hr : chr [1:108] "0.0" "0.0" "0.0" "0.0" ...
..$ is_blank : logi [1:108] FALSE FALSE FALSE FALSE FALSE FALSE ...
..$ size_class_group : chr [1:108] "40mm" "40mm" "40mm" "40mm" ...
..$ treatment_group : chr [1:108] "36c" "36c" "36c" "36c" ...
..$ sample_id_group : chr [1:108] "1" "2" "3" "4" ...
..$ exclude_from_analysis: logi [1:108] FALSE FALSE FALSE FALSE FALSE FALSE ...
..$ exclude_reason : chr [1:108] NA NA NA NA ...
..$ width_mm_measurement : num [1:108] NA NA NA NA NA NA NA NA NA NA ...
..$ length_mm_measurement: num [1:108] NA NA NA NA NA NA NA NA NA NA ...
..$ weight_mg_measurement: num [1:108] NA NA NA NA NA NA NA NA NA NA ...
..$ area_mm2_measurement : num [1:108] 602 766 783 634 603 ...
..$ imagej_id : chr [1:108] "5" "4" "3" "2" ...
..$ well_id : chr [1:108] "A1" "A2" "A3" "A4" ...
..$ timepoint_label : chr [1:108] "0.0" "0.0" "0.0" "0.0" ...
..$ time_hr : num [1:108] 0 0 0 0 0 0 0 0 0 0 ...
$ 70mm: tibble [108 × 17] (S3: tbl_df/tbl/data.frame)
..$ plate_id : chr [1:108] "c" "c" "c" "c" ...
..$ plate_well : chr [1:108] "A01" "A02" "A03" "A04" ...
..$ timepoint_hr : chr [1:108] "0.0" "0.0" "0.0" "0.0" ...
..$ is_blank : logi [1:108] FALSE FALSE FALSE FALSE FALSE FALSE ...
..$ size_class_group : chr [1:108] "70mm" "70mm" "70mm" "70mm" ...
..$ treatment_group : chr [1:108] "36c" "36c" "36c" "36c" ...
..$ sample_id_group : chr [1:108] "1" "2" "3" "4" ...
..$ exclude_from_analysis: logi [1:108] FALSE FALSE FALSE FALSE FALSE FALSE ...
..$ exclude_reason : chr [1:108] NA NA NA NA ...
..$ width_mm_measurement : num [1:108] NA NA NA NA NA NA NA NA NA NA ...
..$ length_mm_measurement: num [1:108] NA NA NA NA NA NA NA NA NA NA ...
..$ weight_mg_measurement: num [1:108] NA NA NA NA NA NA NA NA NA NA ...
..$ area_mm2_measurement : num [1:108] 1911 1570 1962 1612 1594 ...
..$ imagej_id : chr [1:108] "1" "2" "3" "4" ...
..$ well_id : chr [1:108] "A1" "A2" "A3" "A4" ...
..$ timepoint_label : chr [1:108] "0.0" "0.0" "0.0" "0.0" ...
..$ time_hr : num [1:108] 0 0 0 0 0 0 0 0 0 0 ...
5 Merge Plate Data with Layout
dat <- map_dfr(experiments, function(ex) {
src <- timepoint_sources[[ex]]
d <- plate_raw %>%
filter(experiment == ex) %>%
# When the layout supplies the timepoint, drop the (all-NA) filename-
# derived column so the layout is the single source of truth for `time_hr`.
select(-any_of(if (src == "layout") "time_hr" else character(0))) %>%
left_join(
layouts[[ex]]$layout %>%
select(plate_id, well_id, is_blank, exclude_from_analysis,
any_of(c("exclude_reason", "timepoint_label", "time_hr")),
any_of(group_cols), any_of(measurement_cols)),
by = c("plate_id", "well_id")
) %>%
mutate(
is_blank = replace_na(is_blank, FALSE),
exclude_from_analysis = replace_na(exclude_from_analysis, FALSE)
)
# Single definition of individual identity (see `trace_key()`), prefixed
# with the experiment so sample IDs shared between experiments stay apart.
d$trace_id <- paste(ex, trace_key(d, src), sep = "_")
d
})
# Wells present in the plate export but with no usable timepoint cannot be
# placed in the time series: unused wells, or wells missing from layout.csv.
unassigned <- dat %>% filter(!is.finite(time_hr))
if (nrow(unassigned) > 0) {
message(nrow(unassigned), " well read(s) dropped for having no layout ",
"timepoint (e.g. ",
paste(head(paste(unassigned$experiment, unassigned$plate_id,
unassigned$well_id, sep = ":"), 5),
collapse = ", "), ")")
dat <- dat %>% filter(is.finite(time_hr))
}
# Drop unassigned (empty) wells: not a resazurin blank and no group values.
# Covers wells missing from the layout and wells listed with empty groups;
# with filename timepoints these still carry a time and are not caught above.
if (length(group_cols) > 0) {
n_before <- nrow(dat)
dat <- dat %>%
filter(is_blank | if_any(all_of(group_cols), ~ !is.na(.) & . != ""))
message("Dropped ", n_before - nrow(dat), " unassigned well read(s).")
}
time_levels <- sort(unique(dat$time_hr))
message("Timepoints (h): ", paste(time_levels, collapse = ", "))
# AUC is only comparable between size classes measured over the same
# timepoints; report any differences.
times_by_ex <- dat %>%
group_by(experiment) %>%
summarise(times = paste(sort(unique(time_hr)), collapse = ", "),
.groups = "drop")
if (n_distinct(times_by_ex$times) > 1)
warning("Experiments were read at different timepoints; AUCs are not ",
"directly comparable:\n",
paste(times_by_ex$experiment, times_by_ex$times, sep = ": ",
collapse = "\n"))
str(dat)tibble [297 × 19] (S3: tbl_df/tbl/data.frame)
$ row_id : chr [1:297] "A" "A" "A" "A" ...
$ col_id : int [1:297] 1 2 3 4 1 2 3 4 1 2 ...
$ well_id : chr [1:297] "A1" "A2" "A3" "A4" ...
$ value : num [1:297] 160 163 204 152 193 202 276 180 197 330 ...
$ plate_id : chr [1:297] "f" "f" "f" "f" ...
$ time_hr : num [1:297] 0 0 0 0 0 0 0 0 0 0 ...
$ experiment : chr [1:297] "10mm" "10mm" "10mm" "10mm" ...
$ is_blank : logi [1:297] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_from_analysis: logi [1:297] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_reason : chr [1:297] NA NA NA NA ...
$ size_class_group : chr [1:297] "10mm" "10mm" "10mm" "10mm" ...
$ treatment_group : chr [1:297] "36c" "36c" "36c" "36c" ...
$ sample_id_group : chr [1:297] "1" "2" "3" "4" ...
$ width_mm_measurement : num [1:297] NA NA NA NA NA NA NA NA NA NA ...
$ length_mm_measurement: num [1:297] NA NA NA NA NA NA NA NA NA NA ...
$ weight_mg_measurement: num [1:297] NA NA NA NA NA NA NA NA NA NA ...
$ area_mm2_measurement : num [1:297] 130 150 194 145 114 ...
$ trace_id : chr [1:297] "10mm_1" "10mm_2" "10mm_3" "10mm_4" ...
$ timepoint_label : chr [1:297] NA NA NA NA ...
5.1 Plate consistency check
Checks, within each experiment, that every plate x timepoint read covers the same number of wells. The expected well count is the mode across that experiment’s reads. Any plate with at least one deviating read is flagged and dropped entirely before any further analysis — removing only the aberrant read would break the fold-change baseline calculation.
well_counts <- dat %>%
group_by(experiment, plate_id, time_hr) %>%
summarise(n_wells = n_distinct(well_id), .groups = "drop") %>%
group_by(experiment) %>%
mutate(expected_n_wells = as.integer(
names(which.max(table(n_wells))))) %>%
ungroup()
inconsistent_reads <- well_counts %>%
filter(n_wells != expected_n_wells) %>%
arrange(experiment, plate_id, time_hr)
inconsistent_plates <- inconsistent_reads %>% distinct(experiment, plate_id)
if (nrow(inconsistent_reads) > 0) {
cat("**Plate consistency check FAILED.**",
nrow(inconsistent_plates),
"plate(s) have at least one deviating read and are excluded",
"from all analyses:\n\n")
cat(knitr::kable(
inconsistent_reads,
col.names = c("Experiment", "Plate", "Time (h)", "Wells read",
"Expected")
), sep = "\n")
cat("\n")
dat <- dat %>% anti_join(inconsistent_plates, by = c("experiment", "plate_id"))
message(nrow(inconsistent_plates), " plate(s) removed from `dat`.")
} else {
cat("Plate consistency check passed: every plate read the expected",
"number of wells at every timepoint (",
paste(distinct(well_counts, experiment, expected_n_wells) %>%
with(paste0(experiment, ": ", expected_n_wells)),
collapse = "; "), ").\n")
}Plate consistency check passed: every plate read the expected number of wells at every timepoint ( 10mm: 11; 40mm: 11; 70mm: 11 ).
6 Raw Fluorescence
Raw fluorescence is shown for QC only: because assay setup differs between size classes (see Background), RFU values are not comparable across them.
6.1 Data frame
# Wells in the plate reader output that have no layout entry get all-NA group
# columns after the join. Keep only wells assigned to at least one group.
active_gc <- intersect(group_cols, names(dat))
raw_df <- dat %>%
filter(
!is_blank,
if (length(active_gc) > 0)
if_any(all_of(active_gc), ~ !is.na(.))
else
TRUE
)
compare_levels <- str_sort(col_values(raw_df, compare_col), numeric = TRUE)
n_cmp <- length(compare_levels)
if (n_cmp < 2)
stop("Fewer than two levels of `", compare_col, "` found; nothing to compare.")
# Palette strategy:
# <= 7 groups : Okabe-Ito (gold standard for colorblind-safe figures).
# > 7 groups : colorspace::qualitative_hcl("Dynamic") scales to any N
# using perceptually uniform HCL space — no colour collisions.
# Black (#000000) is excluded from both and reserved for blank wells.
okabe_ito_7 <- c(
"#E69F00", "#56B4E9", "#009E73", "#F0E442",
"#0072B2", "#D55E00", "#CC79A7"
)
make_palette <- function(n) {
if (n == 0L) return(character(0))
if (n <= length(okabe_ito_7)) return(okabe_ito_7[seq_len(n)])
colorspace::qualitative_hcl(n, palette = "Dynamic")
}
cmp_colours <- setNames(make_palette(n_cmp), compare_levels)
# QC plot colours: comparison groups plus black blanks.
plate_well_colours <- c(blank = "black", cmp_colours)
# File-name stem for figures, e.g. "size_class"
compare_name <- str_remove(compare_col, "_group$")
str(raw_df)tibble [270 × 19] (S3: tbl_df/tbl/data.frame)
$ row_id : chr [1:270] "A" "A" "A" "A" ...
$ col_id : int [1:270] 1 2 3 4 1 2 3 4 1 2 ...
$ well_id : chr [1:270] "A1" "A2" "A3" "A4" ...
$ value : num [1:270] 160 163 204 152 193 202 276 180 197 330 ...
$ plate_id : chr [1:270] "f" "f" "f" "f" ...
$ time_hr : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
$ experiment : chr [1:270] "10mm" "10mm" "10mm" "10mm" ...
$ is_blank : logi [1:270] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_from_analysis: logi [1:270] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_reason : chr [1:270] NA NA NA NA ...
$ size_class_group : chr [1:270] "10mm" "10mm" "10mm" "10mm" ...
$ treatment_group : chr [1:270] "36c" "36c" "36c" "36c" ...
$ sample_id_group : chr [1:270] "1" "2" "3" "4" ...
$ width_mm_measurement : num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ length_mm_measurement: num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ weight_mg_measurement: num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ area_mm2_measurement : num [1:270] 130 150 194 145 114 ...
$ trace_id : chr [1:270] "10mm_1" "10mm_2" "10mm_3" "10mm_4" ...
$ timepoint_label : chr [1:270] NA NA NA NA ...
6.2 Raw fluorescence, all wells (including blanks)
Faceted by experiment, with independent y-axes.
p_raw_plates <- dat %>%
filter(is.finite(time_hr), is.finite(value)) %>%
mutate(colour_group = if_else(is_blank, "blank", .data[[compare_col]])) %>%
ggplot(aes(x = time_hr, y = value,
group = trace_id, colour = colour_group)) +
geom_line(alpha = 0.6) +
geom_point(size = 1, alpha = 0.7) +
facet_wrap(~ experiment, scales = "free_y") +
scale_colour_manual(
values = plate_well_colours,
name = "Group",
breaks = names(plate_well_colours),
na.value = "grey80"
) +
labs(x = "Time (h)", y = "Raw fluorescence (RFU)") +
theme_classic(base_size = 12) +
theme(strip.background = element_blank(),
strip.text = element_text(face = "bold"))
p_raw_plates
ggsave(file.path(fig_dir, "raw_fluor_by_plate.png"),
p_raw_plates, width = 10, height = 8)6.3 Mean raw fluorescence by group
p <- mean_ts_plot(raw_df, "value", compare_col, cmp_colours, compare_label,
"Mean raw fluorescence (RFU ± SE)")
print(p)
ggsave(file.path(fig_dir, paste0("raw_mean_by_", compare_name, ".png")),
p, width = 8, height = 5)6.4 Individual raw fluorescence traces
p <- individual_ts_plot(
raw_df, "value", facet_col = compare_col,
colour_col = compare_col, colours = cmp_colours,
legend_name = compare_label,
y_lab = "Raw fluorescence (RFU)")
print(p)
ggsave(file.path(fig_dir, paste0("raw_individual_by_", compare_name, ".png")),
p, width = 10, height = 5)6.5 Excluded samples
Wells flagged exclude_from_analysis = TRUE appear in the raw fluorescence plots above but are omitted from all analyses that follow.
excluded_wells <- dat %>%
filter(!is_blank, exclude_from_analysis) %>%
select(experiment, plate_id, well_id, sample = trace_id,
any_of(c(compare_col, "exclude_reason"))) %>%
distinct() %>%
arrange(experiment, plate_id, well_id)
if (nrow(excluded_wells) > 0) {
cat(knitr::kable(excluded_wells), sep = "\n")
} else {
cat("No wells are excluded from analysis.\n")
}No wells are excluded from analysis.
7 Blank Correction via Fold-Change Normalization
Identical to the 01.00 scripts, applied within each experiment. T0 is the earliest timepoint in each experiment. Sample fold-change is expressed relative to each individual’s T0 reading, where the individual is identified by trace_id (experiment + sample_ID.group, or + plate/well when sample IDs are absent). Blank fold-change is the per-plate mean blank RFU at each timepoint divided by that experiment’s pooled mean blank RFU at T0. Subtracting blank fold-change from sample fold-change removes background fluorescence drift; all samples start at exactly 0 at T0 by construction.
When an experiment contains no blank wells, its blank fold-change is set to 0 (no correction), so corrected_fc is simply the fold-change relative to T0 and its samples start at 1 rather than 0.
7.1 Step 1 – Identify T0 and compute per-sample fold-change
# T0 = earliest timepoint present in each experiment
t0_times <- dat %>%
filter(is.finite(time_hr)) %>%
group_by(experiment) %>%
summarise(t0_time = min(time_hr), .groups = "drop")
message("T0 timepoint(s): ",
paste(t0_times$experiment, t0_times$t0_time, sep = " = ",
collapse = ", "), " hr")
dat <- dat %>% left_join(t0_times, by = "experiment")
# T0 reference value per individual.
t0_all <- dat %>%
filter(time_hr == t0_time, !is_blank, is.finite(value)) %>%
group_by(trace_id) %>%
summarise(value_t0 = mean(value, na.rm = TRUE), .groups = "drop")
n_missing_t0 <- dat %>%
filter(!is_blank, !trace_id %in% t0_all$trace_id) %>%
pull(trace_id) %>%
n_distinct()
if (n_missing_t0 > 0)
message(n_missing_t0, " individual(s) have no T0 reading; ",
"their fold-change will be NA.")
dat_fc <- dat %>%
left_join(t0_all, by = "trace_id") %>%
mutate(fold_change = if_else(
!is_blank & is.finite(value_t0) & value_t0 > 0,
value / value_t0,
NA_real_
))
str(dat_fc)tibble [297 × 22] (S3: tbl_df/tbl/data.frame)
$ row_id : chr [1:297] "A" "A" "A" "A" ...
$ col_id : int [1:297] 1 2 3 4 1 2 3 4 1 2 ...
$ well_id : chr [1:297] "A1" "A2" "A3" "A4" ...
$ value : num [1:297] 160 163 204 152 193 202 276 180 197 330 ...
$ plate_id : chr [1:297] "f" "f" "f" "f" ...
$ time_hr : num [1:297] 0 0 0 0 0 0 0 0 0 0 ...
$ experiment : chr [1:297] "10mm" "10mm" "10mm" "10mm" ...
$ is_blank : logi [1:297] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_from_analysis: logi [1:297] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_reason : chr [1:297] NA NA NA NA ...
$ size_class_group : chr [1:297] "10mm" "10mm" "10mm" "10mm" ...
$ treatment_group : chr [1:297] "36c" "36c" "36c" "36c" ...
$ sample_id_group : chr [1:297] "1" "2" "3" "4" ...
$ width_mm_measurement : num [1:297] NA NA NA NA NA NA NA NA NA NA ...
$ length_mm_measurement: num [1:297] NA NA NA NA NA NA NA NA NA NA ...
$ weight_mg_measurement: num [1:297] NA NA NA NA NA NA NA NA NA NA ...
$ area_mm2_measurement : num [1:297] 130 150 194 145 114 ...
$ trace_id : chr [1:297] "10mm_1" "10mm_2" "10mm_3" "10mm_4" ...
$ timepoint_label : chr [1:297] NA NA NA NA ...
$ t0_time : num [1:297] 0 0 0 0 0 0 0 0 0 0 ...
$ value_t0 : num [1:297] 160 163 204 152 193 202 276 180 197 330 ...
$ fold_change : num [1:297] 1 1 1 1 1 1 1 1 1 1 ...
7.2 Step 2 – Blank fold-change reference per plate per timepoint
# Pooled mean blank RFU at T0 across each experiment's T0 plates
mean_blank_t0 <- dat %>%
filter(is_blank, time_hr == t0_time, is.finite(value)) %>%
group_by(experiment) %>%
summarise(mean_blank_t0 = mean(value, na.rm = TRUE), .groups = "drop")
blank_experiments <- dat %>%
filter(is_blank, is.finite(value)) %>%
distinct(experiment) %>%
pull(experiment)
missing_t0_blank <- setdiff(blank_experiments, mean_blank_t0$experiment)
if (length(missing_t0_blank) > 0)
message("No blank readings at T0 for: ",
paste(missing_t0_blank, collapse = ", "),
"; blank correction will produce NA.")
no_blank_experiments <- setdiff(experiments, blank_experiments)
if (length(no_blank_experiments) > 0)
message("No blank wells in: ", paste(no_blank_experiments, collapse = ", "),
"; skipping blank correction for these.")
# Per-plate per-timepoint mean blank expressed as fold-change relative to the
# experiment's T0 blank. Experiments with no blank wells get 0 (no correction).
blank_fc_ref <- bind_rows(
dat %>%
filter(is_blank, is.finite(value)) %>%
group_by(experiment, plate_id, time_hr) %>%
summarise(mean_blank_rfu = mean(value, na.rm = TRUE), .groups = "drop") %>%
left_join(mean_blank_t0, by = "experiment") %>%
mutate(mean_blank_fc = mean_blank_rfu / mean_blank_t0) %>%
select(-mean_blank_t0),
dat %>%
filter(experiment %in% no_blank_experiments) %>%
distinct(experiment, plate_id, time_hr) %>%
mutate(mean_blank_rfu = NA_real_, mean_blank_fc = 0)
)
str(blank_fc_ref)tibble [27 × 5] (S3: tbl_df/tbl/data.frame)
$ experiment : chr [1:27] "10mm" "10mm" "10mm" "10mm" ...
$ plate_id : chr [1:27] "f" "f" "f" "f" ...
$ time_hr : num [1:27] 0 0.5 1 1.5 2 2.5 3 3.5 4 0 ...
$ mean_blank_rfu: num [1:27] 117 117 118 117 118 120 120 119 119 219 ...
$ mean_blank_fc : num [1:27] 1 1 1.01 1 1.01 ...
7.3 Step 3 – Subtract blank fold-change from sample fold-change
samples <- dat_fc %>%
filter(!is_blank, !exclude_from_analysis) %>%
left_join(blank_fc_ref, by = c("experiment", "plate_id", "time_hr")) %>%
mutate(corrected_fc = fold_change - mean_blank_fc)
str(samples)tibble [270 × 25] (S3: tbl_df/tbl/data.frame)
$ row_id : chr [1:270] "A" "A" "A" "A" ...
$ col_id : int [1:270] 1 2 3 4 1 2 3 4 1 2 ...
$ well_id : chr [1:270] "A1" "A2" "A3" "A4" ...
$ value : num [1:270] 160 163 204 152 193 202 276 180 197 330 ...
$ plate_id : chr [1:270] "f" "f" "f" "f" ...
$ time_hr : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
$ experiment : chr [1:270] "10mm" "10mm" "10mm" "10mm" ...
$ is_blank : logi [1:270] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_from_analysis: logi [1:270] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_reason : chr [1:270] NA NA NA NA ...
$ size_class_group : chr [1:270] "10mm" "10mm" "10mm" "10mm" ...
$ treatment_group : chr [1:270] "36c" "36c" "36c" "36c" ...
$ sample_id_group : chr [1:270] "1" "2" "3" "4" ...
$ width_mm_measurement : num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ length_mm_measurement: num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ weight_mg_measurement: num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ area_mm2_measurement : num [1:270] 130 150 194 145 114 ...
$ trace_id : chr [1:270] "10mm_1" "10mm_2" "10mm_3" "10mm_4" ...
$ timepoint_label : chr [1:270] NA NA NA NA ...
$ t0_time : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
$ value_t0 : num [1:270] 160 163 204 152 193 202 276 180 197 330 ...
$ fold_change : num [1:270] 1 1 1 1 1 1 1 1 1 1 ...
$ mean_blank_rfu : num [1:270] 117 117 117 117 117 117 117 117 117 117 ...
$ mean_blank_fc : num [1:270] 1 1 1 1 1 1 1 1 1 1 ...
$ corrected_fc : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
8 Blank-Corrected Fold-Change
8.1 Mean by group
p <- mean_ts_plot(samples, "corrected_fc", compare_col, cmp_colours,
compare_label, "Mean blank-corrected fold-change (± SE)")
print(p)
ggsave(file.path(fig_dir,
paste0("blank_corrected_fc_mean_by_", compare_name, ".png")),
p, width = 8, height = 5)8.2 Individual traces
p <- individual_ts_plot(
samples, "corrected_fc", facet_col = compare_col,
colour_col = compare_col, colours = cmp_colours,
legend_name = compare_label,
y_lab = "Blank-corrected fold-change")
print(p)
ggsave(file.path(fig_dir,
paste0("blank_corrected_fc_by_", compare_name, ".png")),
p, width = 10, height = 5)9 Metabolism (Size-Normalised Fold-Change)
Blank-corrected fold-change divided by each active measurement column. This is “metabolism” as defined in Huffmyer et al.
metab_cols <- paste0("metabolism_per_", active_meas_cols)
if (length(active_meas_cols) == 0) {
message("No active measurement columns: skipping metabolism calculation.")
metabolism_df <- tibble()
} else {
metabolism_df <- samples
for (mc in active_meas_cols) {
out_col <- paste0("metabolism_per_", mc)
metabolism_df <- metabolism_df %>%
mutate(!!out_col := if_else(
is.finite(.data[[mc]]) & .data[[mc]] > 0 &
is.finite(corrected_fc),
corrected_fc / .data[[mc]],
NA_real_
))
}
}
str(metabolism_df)tibble [270 × 26] (S3: tbl_df/tbl/data.frame)
$ row_id : chr [1:270] "A" "A" "A" "A" ...
$ col_id : int [1:270] 1 2 3 4 1 2 3 4 1 2 ...
$ well_id : chr [1:270] "A1" "A2" "A3" "A4" ...
$ value : num [1:270] 160 163 204 152 193 202 276 180 197 330 ...
$ plate_id : chr [1:270] "f" "f" "f" "f" ...
$ time_hr : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
$ experiment : chr [1:270] "10mm" "10mm" "10mm" "10mm" ...
$ is_blank : logi [1:270] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_from_analysis : logi [1:270] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ exclude_reason : chr [1:270] NA NA NA NA ...
$ size_class_group : chr [1:270] "10mm" "10mm" "10mm" "10mm" ...
$ treatment_group : chr [1:270] "36c" "36c" "36c" "36c" ...
$ sample_id_group : chr [1:270] "1" "2" "3" "4" ...
$ width_mm_measurement : num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ length_mm_measurement : num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ weight_mg_measurement : num [1:270] NA NA NA NA NA NA NA NA NA NA ...
$ area_mm2_measurement : num [1:270] 130 150 194 145 114 ...
$ trace_id : chr [1:270] "10mm_1" "10mm_2" "10mm_3" "10mm_4" ...
$ timepoint_label : chr [1:270] NA NA NA NA ...
$ t0_time : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
$ value_t0 : num [1:270] 160 163 204 152 193 202 276 180 197 330 ...
$ fold_change : num [1:270] 1 1 1 1 1 1 1 1 1 1 ...
$ mean_blank_rfu : num [1:270] 117 117 117 117 117 117 117 117 117 117 ...
$ mean_blank_fc : num [1:270] 1 1 1 1 1 1 1 1 1 1 ...
$ corrected_fc : num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
$ metabolism_per_area_mm2_measurement: num [1:270] 0 0 0 0 0 0 0 0 0 0 ...
9.1 Mean metabolism by group
if (nrow(metabolism_df) > 0) {
for (col in metab_cols) {
if (!col %in% names(metabolism_df)) next
mc_label <- str_remove(col, "^metabolism_per_")
y_lab <- paste0(metabolism_y_label(col), " (± SE)")
p <- mean_ts_plot(metabolism_df, col, compare_col, cmp_colours,
compare_label, y_lab)
print(p)
ggsave(file.path(fig_dir,
paste0("metabolism_mean_", mc_label, "_by_",
compare_name, ".png")),
p, width = 8, height = 5)
}
}
9.2 Individual metabolism traces
if (nrow(metabolism_df) > 0) {
for (col in metab_cols) {
if (!col %in% names(metabolism_df)) next
mc_label <- str_remove(col, "^metabolism_per_")
p <- individual_ts_plot(
metabolism_df, col, facet_col = compare_col,
colour_col = compare_col, colours = cmp_colours,
legend_name = compare_label, y_lab = metabolism_y_label(col))
print(p)
ggsave(file.path(fig_dir,
paste0("metabolism_individual_", mc_label, "_by_",
compare_name, ".png")),
p, width = 10, height = 5)
}
}
10 Time-Series Statistical Analysis
Linear mixed effects models test the effect of size class on metabolism over time (metabolism ~ time * size class). Individual (trace_id) is included as a random intercept to account for repeated measures across timepoints. Type III ANOVA with Satterthwaite’s approximation (lmerTest) assesses significance; post-hoc pairwise comparisons use estimated marginal means (emmeans, Tukey adjustment).
run_ts_stats <- function(df, value_col, group_col) {
df <- df %>%
filter(is.finite(.data[[value_col]]), is.finite(time_hr),
!is.na(.data[[group_col]])) %>%
mutate(
time_f = factor(time_hr),
individual = factor(trace_id),
group = factor(.data[[group_col]], levels = compare_levels)
) %>%
mutate(group = droplevels(group))
if (nrow(df) == 0 || nlevels(df$group) < 2) return(NULL)
model <- lmer(
as.formula(paste0(value_col, " ~ time_f * group + (1 | individual)")),
data = df
)
anova_res <- anova(model, type = 3, ddf = "Satterthwaite")
# Pairwise comparisons of groups at each timepoint
emm <- emmeans(model, ~ group | time_f)
pairs_res <- as.data.frame(pairs(emm, adjust = "tukey"))
# Main-effect marginal means (collapsed across time)
pairs_main <- as.data.frame(pairs(emmeans(model, ~ group), adjust = "tukey"))
list(
model = model,
anova = anova_res,
pairs_by_time = pairs_res,
pairs_main = pairs_main
)
}
ts_stats <- list()
if (nrow(metabolism_df) > 0) {
for (mc in active_meas_cols) {
col <- paste0("metabolism_per_", mc)
if (col %in% names(metabolism_df))
ts_stats[[col]] <- run_ts_stats(metabolism_df, col, compare_col)
}
}10.1 Results
for (col in names(ts_stats)) {
res <- ts_stats[[col]]
if (is.null(res)) next
cat("\n\n### Metric:", col, "\n\n")
cat("**Type III ANOVA (Satterthwaite approximation):**\n\n")
cat(knitr::kable(as.data.frame(res$anova), digits = 4, format = "pipe"), sep = "\n")
cat("\n")
cat("**Marginal means – main effects (collapsed across time):**\n\n")
cat(knitr::kable(as.data.frame(res$pairs_main), digits = 4, format = "pipe"), sep = "\n")
cat("\n")
cat("**Pairwise comparisons by timepoint (Tukey):**\n\n")
cat(knitr::kable(as.data.frame(res$pairs_by_time), digits = 4, format = "pipe"), sep = "\n")
cat("\n")
}10.1.1 Metric: metabolism_per_area_mm2_measurement
Type III ANOVA (Satterthwaite approximation):
| Sum Sq | Mean Sq | NumDF | DenDF | F value | Pr(>F) | |
|---|---|---|---|---|---|---|
| time_f | 0.0150 | 0.0019 | 8 | 216 | 52.6471 | 0 |
| group | 0.0015 | 0.0007 | 2 | 27 | 20.5498 | 0 |
| time_f:group | 0.0081 | 0.0005 | 16 | 216 | 14.1483 | 0 |
Marginal means – main effects (collapsed across time):
| contrast | estimate | SE | df | t.ratio | p.value |
|---|---|---|---|---|---|
| 10mm - 40mm | 0.0203 | 0.0041 | 27 | 4.9292 | 0.0001 |
| 10mm - 70mm | 0.0248 | 0.0041 | 27 | 6.0145 | 0.0000 |
| 40mm - 70mm | 0.0045 | 0.0041 | 27 | 1.0854 | 0.5311 |
Pairwise comparisons by timepoint (Tukey):
| contrast | time_f | estimate | SE | df | t.ratio | p.value |
|---|---|---|---|---|---|---|
| 10mm - 40mm | 0 | 0.0000 | 0.0048 | 49.9303 | 0.0000 | 1.0000 |
| 10mm - 70mm | 0 | 0.0000 | 0.0048 | 49.9303 | 0.0000 | 1.0000 |
| 40mm - 70mm | 0 | 0.0000 | 0.0048 | 49.9303 | 0.0000 | 1.0000 |
| 10mm - 40mm | 0.5 | 0.0103 | 0.0048 | 49.9303 | 2.1400 | 0.0921 |
| 10mm - 70mm | 0.5 | 0.0106 | 0.0048 | 49.9303 | 2.1970 | 0.0815 |
| 40mm - 70mm | 0.5 | 0.0003 | 0.0048 | 49.9303 | 0.0570 | 0.9982 |
| 10mm - 40mm | 1 | 0.0166 | 0.0048 | 49.9303 | 3.4380 | 0.0034 |
| 10mm - 70mm | 1 | 0.0181 | 0.0048 | 49.9303 | 3.7480 | 0.0013 |
| 40mm - 70mm | 1 | 0.0015 | 0.0048 | 49.9303 | 0.3100 | 0.9485 |
| 10mm - 40mm | 1.5 | 0.0180 | 0.0048 | 49.9303 | 3.7289 | 0.0014 |
| 10mm - 70mm | 1.5 | 0.0216 | 0.0048 | 49.9303 | 4.4657 | 0.0001 |
| 40mm - 70mm | 1.5 | 0.0036 | 0.0048 | 49.9303 | 0.7369 | 0.7429 |
| 10mm - 40mm | 2 | 0.0221 | 0.0048 | 49.9303 | 4.5826 | 0.0001 |
| 10mm - 70mm | 2 | 0.0277 | 0.0048 | 49.9303 | 5.7331 | 0.0000 |
| 40mm - 70mm | 2 | 0.0056 | 0.0048 | 49.9303 | 1.1505 | 0.4880 |
| 10mm - 40mm | 2.5 | 0.0251 | 0.0048 | 49.9303 | 5.1862 | 0.0000 |
| 10mm - 70mm | 2.5 | 0.0313 | 0.0048 | 49.9303 | 6.4717 | 0.0000 |
| 40mm - 70mm | 2.5 | 0.0062 | 0.0048 | 49.9303 | 1.2855 | 0.4099 |
| 10mm - 40mm | 3 | 0.0291 | 0.0048 | 49.9303 | 6.0210 | 0.0000 |
| 10mm - 70mm | 3 | 0.0346 | 0.0048 | 49.9303 | 7.1705 | 0.0000 |
| 40mm - 70mm | 3 | 0.0056 | 0.0048 | 49.9303 | 1.1494 | 0.4887 |
| 10mm - 40mm | 3.5 | 0.0310 | 0.0048 | 49.9303 | 6.4118 | 0.0000 |
| 10mm - 70mm | 3.5 | 0.0386 | 0.0048 | 49.9303 | 7.9927 | 0.0000 |
| 40mm - 70mm | 3.5 | 0.0076 | 0.0048 | 49.9303 | 1.5809 | 0.2632 |
| 10mm - 40mm | 4 | 0.0308 | 0.0048 | 49.9303 | 6.3714 | 0.0000 |
| 10mm - 70mm | 4 | 0.0408 | 0.0048 | 49.9303 | 8.4420 | 0.0000 |
| 40mm - 70mm | 4 | 0.0100 | 0.0048 | 49.9303 | 2.0705 | 0.1064 |
11 Area Under the Curve (AUC)
AUC computed per individual via the trapezoid rule across all timepoints. metabolism_per_* is the primary metric matching the paper.
compute_auc <- function(df, value_col, group_vars) {
df %>%
filter(is.finite(time_hr), is.finite(.data[[value_col]])) %>%
group_by(across(all_of(group_vars))) %>%
summarise(
AUC = trapezoid_auc(time_hr, .data[[value_col]]),
n_timepoints = n(),
.groups = "drop"
) %>%
filter(is.finite(AUC))
}
# Plate is not a grouping column: within an experiment an individual's time
# series may span plates, and plates are nested in (confounded with) size
# class, so plate effects cannot be separated from the comparison.
individual_vars <- intersect(
c("trace_id", "experiment", compare_col),
names(metabolism_df)
)
auc_metab_list <- list()
if (nrow(metabolism_df) > 0) {
for (mc in active_meas_cols) {
col <- paste0("metabolism_per_", mc)
if (col %in% names(metabolism_df)) {
auc_metab_list[[col]] <-
compute_auc(metabolism_df, col, individual_vars) %>%
mutate(metric = col)
}
}
}
auc_all <- bind_rows(auc_metab_list)
str(auc_all)tibble [30 × 6] (S3: tbl_df/tbl/data.frame)
$ trace_id : chr [1:30] "10mm_1" "10mm_10" "10mm_2" "10mm_3" ...
$ experiment : chr [1:30] "10mm" "10mm" "10mm" "10mm" ...
$ size_class_group: chr [1:30] "10mm" "10mm" "10mm" "10mm" ...
$ AUC : num [1:30] 0.0753 0.122 0.1092 0.1976 0.0672 ...
$ n_timepoints : int [1:30] 9 9 9 9 9 9 9 9 9 9 ...
$ metric : chr [1:30] "metabolism_per_area_mm2_measurement" "metabolism_per_area_mm2_measurement" "metabolism_per_area_mm2_measurement" "metabolism_per_area_mm2_measurement" ...
11.1 AUC summary tables
sum_vars <- intersect(c("metric", compare_col), names(auc_all))
auc_summary <- auc_all %>%
group_by(across(all_of(sum_vars))) %>%
summarise(
n = n(),
mean = mean(AUC, na.rm = TRUE),
sd = sd(AUC, na.rm = TRUE),
se = sd / sqrt(n),
median = median(AUC, na.rm = TRUE),
.groups = "drop"
)
print(auc_summary)# A tibble: 3 × 7
metric size_class_group n mean sd se median
<chr> <chr> <int> <dbl> <dbl> <dbl> <dbl>
1 metabolism_per_area_mm2_m… 10mm 10 0.117 0.0602 0.0190 0.0959
2 metabolism_per_area_mm2_m… 40mm 10 0.0331 0.0231 0.00731 0.0299
3 metabolism_per_area_mm2_m… 70mm 10 0.0155 0.0101 0.00319 0.0123
12 Statistical Analysis
Each individual oyster is the observational unit. A one-way linear model (AUC ~ size class) tests for differences between size classes, followed by Tukey-adjusted pairwise comparisons. Each size class was run as a separate experiment with its own plates, blanks and assay setup, so size class is confounded with experiment; interpret accordingly (see Background).
run_auc_stats <- function(auc_df, group_col) {
auc_df <- auc_df %>%
filter(!is.na(.data[[group_col]])) %>%
mutate(group = droplevels(factor(.data[[group_col]],
levels = compare_levels)))
if (nlevels(auc_df$group) < 2)
return(list(model = NULL, anova = NULL, pairs = tibble()))
model <- lm(AUC ~ group, data = auc_df)
anova_res <- anova(model)
pairs_res <- as.data.frame(pairs(emmeans(model, ~ group), adjust = "tukey"))
list(model = model, anova = anova_res, pairs = pairs_res)
}
metrics_to_test <- unique(auc_all$metric)
stats_results <- map(
set_names(metrics_to_test),
~ run_auc_stats(auc_all %>% filter(metric == .x), compare_col)
)12.1 Results by metric
for (met in metrics_to_test) {
stats <- stats_results[[met]]
if (is.null(stats$model)) next
cat("\n\n### Metric:", met, "\n\n")
cat("**ANOVA:**\n\n")
cat(knitr::kable(as.data.frame(stats$anova), digits = 4, format = "pipe"), sep = "\n")
cat("\n")
cat("**Pairwise:", str_to_lower(compare_label), "(Tukey):**\n\n")
cat(knitr::kable(as.data.frame(stats$pairs), digits = 4, format = "pipe"), sep = "\n")
cat("\n")
}12.1.1 Metric: metabolism_per_area_mm2_measurement
ANOVA:
| Df | Sum Sq | Mean Sq | F value | Pr(>F) | |
|---|---|---|---|---|---|
| group | 2 | 0.0588 | 0.0294 | 20.7041 | 0 |
| Residuals | 27 | 0.0383 | 0.0014 | NA | NA |
Pairwise: size class (Tukey):
| contrast | estimate | SE | df | t.ratio | p.value |
|---|---|---|---|---|---|
| 10mm - 40mm | 0.0838 | 0.0168 | 27 | 4.9747 | 0.0001 |
| 10mm - 70mm | 0.1014 | 0.0168 | 27 | 6.0222 | 0.0000 |
| 40mm - 70mm | 0.0176 | 0.0168 | 27 | 1.0475 | 0.5541 |
12.2 Sensitivity analysis
The equal-variance ANOVA above assumes similar AUC spread in every size class and normally distributed residuals. Two alternatives are run next to it, not instead of it, to show which conclusions depend on those assumptions:
- Welch ANOVA (
oneway.test, unequal variances), with pairwise Welch t-tests (Holm-adjusted). Estimates are differences in mean AUC. - Log-transformed AUC (
lm(log(AUC) ~ size class), Tukey). Estimates are ratios of geometric mean AUC. Skipped if any AUC is <=
Every test is also repeated without the most extreme individual: the oyster with the largest absolute studentized residual in the log-AUC model (raw-AUC model if logs cannot be taken). This shows how much a single oyster drives each result; it is not an exclusion. To exclude an oyster, flag it with exclude_from_analysis in its experiment’s layout.csv.
run_sensitivity <- function(auc_df, group_col) {
auc_df <- auc_df %>%
filter(!is.na(.data[[group_col]]), is.finite(AUC)) %>%
mutate(group = droplevels(factor(.data[[group_col]],
levels = compare_levels)))
if (nlevels(auc_df$group) < 2) return(NULL)
can_log <- all(auc_df$AUC > 0)
grp_mean <- c(tapply(auc_df$AUC, auc_df$group, mean)) # plain named vector
overall <- list()
pairs_l <- list()
# 1. Equal-variance ANOVA (as in the main analysis)
m <- lm(AUC ~ group, data = auc_df)
an <- anova(m)
overall$equal <- tibble(
method = "Equal-variance ANOVA", F = an$`F value`[1],
df1 = an$Df[1], df2 = an$Df[2], p.value = an$`Pr(>F)`[1],
resid_shapiro_p = shapiro.test(resid(m))$p.value)
pairs_l$equal <- as.data.frame(pairs(emmeans(m, ~ group), adjust = "tukey")) %>%
transmute(contrast = as.character(contrast),
method = "Equal-variance (Tukey)",
estimate, p.value)
# 2. Welch ANOVA + pairwise Welch t-tests
w <- oneway.test(AUC ~ group, data = auc_df, var.equal = FALSE)
overall$welch <- tibble(
method = "Welch ANOVA", F = unname(w$statistic),
df1 = unname(w$parameter[1]), df2 = unname(w$parameter[2]),
p.value = w$p.value, resid_shapiro_p = NA_real_)
pw <- pairwise.t.test(auc_df$AUC, auc_df$group, pool.sd = FALSE,
p.adjust.method = "holm")$p.value
pairs_l$welch <- as.data.frame(as.table(pw)) %>%
filter(!is.na(Freq)) %>%
transmute(contrast = paste(Var2, "-", Var1),
method = "Welch t-tests (Holm)",
estimate = grp_mean[as.character(Var2)] -
grp_mean[as.character(Var1)],
p.value = Freq)
# 3. Log-transformed AUC
if (can_log) {
ml <- lm(log(AUC) ~ group, data = auc_df)
anl <- anova(ml)
overall$log <- tibble(
method = "Log-AUC ANOVA", F = anl$`F value`[1],
df1 = anl$Df[1], df2 = anl$Df[2], p.value = anl$`Pr(>F)`[1],
resid_shapiro_p = shapiro.test(resid(ml))$p.value)
pairs_l$log <- as.data.frame(pairs(emmeans(ml, ~ group, type = "response"),
adjust = "tukey")) %>%
transmute(contrast = str_replace(as.character(contrast), " / ", " - "),
method = "Log-AUC (Tukey; estimate = ratio)",
estimate = ratio, p.value)
} else {
message("Some AUC values are <= 0; log-transformed analysis skipped.")
}
list(overall = bind_rows(overall), pairs = bind_rows(pairs_l),
can_log = can_log)
}
# Individual with the largest absolute studentized residual.
most_extreme <- function(auc_df, group_col) {
auc_df <- auc_df %>%
filter(!is.na(.data[[group_col]]), is.finite(AUC)) %>%
mutate(group = factor(.data[[group_col]]))
m <- if (all(auc_df$AUC > 0)) lm(log(AUC) ~ group, data = auc_df)
else lm(AUC ~ group, data = auc_df)
r <- rstudent(m)
i <- which.max(abs(r))
grp <- as.character(auc_df$group[i])
tibble(trace_id = auc_df$trace_id[i],
group = grp,
AUC = auc_df$AUC[i],
group_median = median(auc_df$AUC[auc_df$group == grp]),
rstudent = unname(r[i]))
}
sensitivity_results <- map(set_names(metrics_to_test), function(met) {
df <- auc_all %>% filter(metric == met)
ext <- most_extreme(df, compare_col)
all_ind <- run_sensitivity(df, compare_col)
no_ext <- run_sensitivity(df %>% filter(trace_id != ext$trace_id),
compare_col)
if (is.null(all_ind) || is.null(no_ext)) return(NULL)
list(
extreme = ext,
overall = full_join(
all_ind$overall,
no_ext$overall %>% rename_with(~ paste0(.x, "_without_extreme"), -method),
by = "method"),
pairs = full_join(
all_ind$pairs,
no_ext$pairs %>% rename(estimate_without_extreme = estimate,
p.value_without_extreme = p.value),
by = c("contrast", "method")) %>%
arrange(contrast, method)
)
})12.2.1 Sensitivity results by metric
for (met in names(sensitivity_results)) {
res <- sensitivity_results[[met]]
if (is.null(res)) next
ext <- res$extreme
cat("\n\n#### Metric:", met, "\n\n")
cat("**Most extreme individual:** `", ext$trace_id, "` (",
ext$group, "; AUC = ", signif(ext$AUC, 3), ", group median = ",
signif(ext$group_median, 3), ", ~",
round(ext$group_median / ext$AUC, 1),
"x below the median; studentized residual = ",
round(ext$rstudent, 2), ").\n\n", sep = "")
cat("**Overall tests:**\n\n")
cat(knitr::kable(res$overall %>%
select(method, p.value, resid_shapiro_p,
p.value_without_extreme,
resid_shapiro_p_without_extreme) %>%
mutate(across(where(is.numeric), ~ signif(.x, 3))),
format = "pipe",
col.names = c("Method", "p", "Residual Shapiro p",
"p (without extreme)",
"Residual Shapiro p (without extreme)")),
sep = "\n")
cat("\n\n**Pairwise comparisons:**\n\n")
cat(knitr::kable(res$pairs %>%
mutate(across(where(is.numeric), ~ signif(.x, 3))),
format = "pipe",
col.names = c("Contrast", "Method", "Estimate", "p",
"Estimate (without extreme)",
"p (without extreme)")),
sep = "\n")
cat("\n")
}12.2.1.1 Metric: metabolism_per_area_mm2_measurement
Most extreme individual: 40mm_10 (40mm; AUC = 0.00147, group median = 0.0299, ~20.3x below the median; studentized residual = -4.9).
Overall tests:
| Method | p | Residual Shapiro p | p (without extreme) | Residual Shapiro p (without extreme) |
|---|---|---|---|---|
| Equal-variance ANOVA | 3.50e-06 | 0.00684 | 5.80e-06 | 0.00616 |
| Welch ANOVA | 3.34e-04 | NA | 2.92e-04 | NA |
| Log-AUC ANOVA | 9.90e-06 | 0.00697 | 1.00e-07 | 0.19900 |
Pairwise comparisons:
| Contrast | Method | Estimate | p | Estimate (without extreme) | p (without extreme) |
|---|---|---|---|---|---|
| 10mm - 40mm | Equal-variance (Tukey) | 0.0838 | 9.41e-05 | 0.0803 | 2.62e-04 |
| 10mm - 40mm | Log-AUC (Tukey; estimate = ratio) | 4.4400 | 9.45e-04 | 3.2600 | 5.80e-04 |
| 10mm - 40mm | Welch t-tests (Holm) | 0.0838 | 3.09e-03 | 0.0803 | 4.20e-03 |
| 10mm - 70mm | Equal-variance (Tukey) | 0.1010 | 5.80e-06 | 0.1010 | 7.20e-06 |
| 10mm - 70mm | Log-AUC (Tukey; estimate = ratio) | 8.4600 | 8.50e-06 | 8.4600 | 1.00e-07 |
| 10mm - 70mm | Welch t-tests (Holm) | 0.1010 | 1.31e-03 | 0.1010 | 1.31e-03 |
| 40mm - 70mm | Equal-variance (Tukey) | 0.0176 | 5.54e-01 | 0.0212 | 4.54e-01 |
| 40mm - 70mm | Log-AUC (Tukey; estimate = ratio) | 1.9100 | 1.97e-01 | 2.5900 | 4.94e-03 |
| 40mm - 70mm | Welch t-tests (Holm) | 0.0176 | 4.66e-02 | 0.0212 | 2.06e-02 |
13 AUC Box Plots with Statistical Annotations
Significance labels: *** p < 0.001, ** p < 0.01, * p < 0.05. Brackets are drawn only for significant pairs (p < 0.05).
sig_label <- function(p) {
case_when(p < 0.001 ~ "***", p < 0.01 ~ "**", p < 0.05 ~ "*",
TRUE ~ "ns")
}
# Add significance brackets to an existing ggplot.
# pairs_df : data frame with $contrast and $p.value columns
# group_levels: ordered character vector matching x-axis factor levels
# y_vals : numeric vector of AUC values used to set bracket heights
add_sig_brackets <- function(p, pairs_df, group_levels, y_vals) {
sig_pairs <- pairs_df %>%
mutate(label = sig_label(p.value)) %>%
filter(label != "ns")
if (nrow(sig_pairs) == 0) return(p)
y_max <- max(y_vals, na.rm = TRUE)
y_range <- diff(range(y_vals, na.rm = TRUE))
step <- y_range * 0.12
for (i in seq_len(nrow(sig_pairs))) {
parts <- str_split(as.character(sig_pairs$contrast[i]), " - ", 2)[[1]]
# emmeans wraps level names containing "-" in parentheses, e.g.
# "(heat_mech_no-water)"; strip them so labels match the x-axis levels.
g1 <- str_remove_all(trimws(parts[1]), "^\\(|\\)$")
g2 <- str_remove_all(trimws(parts[2]), "^\\(|\\)$")
x1 <- match(g1, group_levels)
x2 <- match(g2, group_levels)
if (is.na(x1) || is.na(x2)) next
bar_y <- y_max + i * step
p <- p +
annotate("segment", x = x1, xend = x2,
y = bar_y, yend = bar_y,
colour = "black", linewidth = 0.6) +
annotate("segment", x = x1, xend = x1,
y = bar_y, yend = bar_y - step * 0.3,
colour = "black", linewidth = 0.6) +
annotate("segment", x = x2, xend = x2,
y = bar_y, yend = bar_y - step * 0.3,
colour = "black", linewidth = 0.6) +
annotate("text", x = (x1 + x2) / 2,
y = bar_y + step * 0.15,
label = sig_pairs$label[i], size = 4.5)
}
p
}for (met in metrics_to_test) {
df <- auc_all %>% filter(metric == met)
stats <- stats_results[[met]]
y_lab <- auc_y_label(met)
df_p <- df %>%
mutate(x = factor(.data[[compare_col]], levels = compare_levels))
grps <- levels(droplevels(df_p$x))
p <- ggplot(df_p, aes(x = x, y = AUC, fill = x)) +
geom_boxplot(alpha = 0.6, outlier.shape = NA) +
geom_jitter(width = 0.15, alpha = 0.4, size = 1.5) +
scale_fill_manual(values = cmp_colours[grps], guide = "none") +
labs(x = compare_label, y = y_lab) +
theme_classic(base_size = 13)
p <- add_sig_brackets(p, stats$pairs, grps, df_p$AUC)
print(p)
ggsave(file.path(fig_dir, paste0("auc_", compare_name, "_", met, ".png")),
p, width = 5, height = 5)
}
14 Save Output Data
write_csv(auc_all, file.path(out_dir, "auc_all_metrics.csv"))
write_csv(auc_summary, file.path(out_dir, "auc_summary.csv"))
if (nrow(metabolism_df) > 0)
write_csv(metabolism_df,
file.path(out_dir, "metabolism.csv"))
stats_compiled <- map_dfr(metrics_to_test, function(met) {
stats_results[[met]]$pairs %>%
mutate(comparison = compare_name, metric = met)
})
write_csv(stats_compiled,
file.path(out_dir, "pairwise_stats.csv"))
write_csv(map_dfr(sensitivity_results, "overall", .id = "metric"),
file.path(out_dir, "auc_sensitivity_overall.csv"))
write_csv(map_dfr(sensitivity_results, "pairs", .id = "metric"),
file.path(out_dir, "auc_sensitivity_pairwise.csv"))
message("Output files written to: ", out_dir)15 Conclusions
These conclusions describe metric metabolism_per_area_mm2_measurement.
- 10mm oysters had much higher size-normalised metabolism than 40mm and 70mm oysters: about 4.4x and 8.5x higher (ratio of geometric mean AUC). This holds under all three tests, with or without the most extreme oyster (all p ≤ 0.0042).
- 40mm vs 70mm is not resolved. 40mm was about 1.9x higher, but significance depends on the test: p = 0.55 (equal-variance), p = 0.047 (Welch), p = 0.2 (log-AUC).
- Outlier:
40mm_10(AUC = 0.0015, about 20x below the 40mm median) is the most extreme oyster. Without it, the 40mm vs 70mm p-values become p = 0.45 (equal-variance), p = 0.021 (Welch) and p = 0.0049 (log-AUC), and the log-AUC residuals go from non-normal (Shapiro p = 0.007) to consistent with normal (Shapiro p = 0.2). Its raw reads should be checked; if a handling problem is confirmed, flag it withexclude_from_analysisin its experiment’slayout.csv. - Caveat: size class is confounded with assay setup (solution volume per oyster, read method, plates and blanks), so these differences cannot be attributed to life stage alone.