# ==============================================================================
# Course:       [CONS7008] Sampling Design & Analysis in Conservation Science
# Assignment:   Scientific webpage to inform National Park management
# Purpose:      Document the analysis workflow behind an R Markdown science 
#               communications webpage in a standalone, reproducible document 
#               - from raw data, to model evaluation, to final graphical figures.
#               This analysis examines previously collected data from Queensland
#               Parks and Wildlife Service (QPWS) on recorded Amphibians with visible chytrid signs of 
#               chytrid fungus in three species of amphibian during one summer
#               in Queensland's Wet Tropics Bioregion. It forms the foundation
#               of the accompanying R Markdown webpage, which together aims to 
#               provide clear, evidence-based, management recommendations to QPWS on 
#               managing chytrid in the national parks of the Wet Tropics.
#
# Caveat:       Amphibians with visible chytrid signs are not laboratory-confirmed infections.
#
# Author name:  Gemma Monique Freeman
# Student ID:   49479557
# Date:         2026-11-19
# ==============================================================================

## ------------------------------------------------------------
## 1. PACKAGES & SETTINGS
## ------------------------------------------------------------

# 1.1 Install packages

# Remove # and run manually to install packages required
# install.packages("ggplot2")
# install.packages("dplyr")
# install.packages("tidyverse")
# install.packages("patchwork")
# install.packages("here")
# install.packages("knitr")
# install.packages("broom")
# install.packages("DHARMa")
# install.packages("emmeans")
# install.packages("performance")
# install.packages("sjPlot")
# install.packages("glmmTMB")
# install.packages("ggeffects")
# install.packages("ggtext")
# install.packages("viridis")
# install.packages("ggimage")

# 1.2 Load packages:
library(ggplot2)
library(dplyr)
library(tidyverse)
library(patchwork)
library(DHARMa)
library(emmeans)
library(performance)
library(glmmTMB)
library(ggeffects)
library(ggtext)
library(viridis)
library(patchwork) 
library(ggimage)
  

## ------------------------------------------------------------
## 2. IMPORT RAW DATA, MERGE & VALIDATE
## ------------------------------------------------------------

# 2.1 Import raw data --------------------
chytrid_amphibian_data <- read.csv("data/chytrid_amphibian_data.csv")
national_park_data <- read.csv("data/national_park_data.csv")

## 2.1.1 Check imported raw data --------------------
names(chytrid_amphibian_data)        ## Check variables (column headings)
head(chytrid_amphibian_data, n = 5)  ## Check the first 5 rows of the data
tail(chytrid_amphibian_data, n = 5)  ## Check the last 5 rows of the data
dim(chytrid_amphibian_data)          ## Check number of rows and columns

names(national_park_data)            ## Check variables (column headings)
head(national_park_data, n = 5)      ## Check the first 5 rows of the data
tail(national_park_data, n = 5)      ## Check the last 5 rows of the data
dim(national_park_data)              ## Check number of rows and columns

## 2.1.2 Check table contains all 225 records --------------------
stopifnot(
  !anyNA(chytrid_amphibian_data$NP),
  !anyNA(national_park_data$NP),
  !anyDuplicated(national_park_data$NP),
  all(chytrid_amphibian_data$NP %in% national_park_data$NP)
)

# 2.2 Merge raw datasets by National Park --------------------
merged_chytrid_data <- merge(
    chytrid_amphibian_data, 
    national_park_data, 
    by = "NP"
)

# 2.2.1 Check merge has not lost or multiplied records.
stopifnot(
  nrow(merged_chytrid_data) ==
    nrow(chytrid_amphibian_data)
)

# 2.2.2 Check merged data --------------------
names(merged_chytrid_data)              # Check variables (column headings)
head(merged_chytrid_data, n = 5)        # Check the first 5 rows of the data
tail(merged_chytrid_data, n = 5)        # Check the last 5 rows of the data
dim(merged_chytrid_data)                # Check number of rows and columns
sum(duplicated(merged_chytrid_data))    # Check duplicate rows
colSums(is.na(merged_chytrid_data))     # Check missing values per column
str(merged_chytrid_data)                # Check data types
summary(merged_chytrid_data)            # Check unusual values
unique(merged_chytrid_data$species)     # Check unique species
subset(merged_chytrid_data, n_infected < 0 | n_frogs_sampled < 0) ## Check negative counts
subset(merged_chytrid_data, n_infected > n_frogs_sampled) ## Check impossible counts
# result: 0 rows
# [1] NP                creek_id                track_density        pop_density           
# [5] species           n_frogs_sampled         n_infected           VPD                   
# [9] NP_area_1000_ha   visit_rate_1000_per_yr  frog_spp_richness    plant_spp_richness    
# [13] infected_prop    infection_percent       n_uninfected         creek_uid             
# [17] Species_name          

range(merged_chytrid_data$n_frogs_sampled)  # expected 9–45.
table(merged_chytrid_data$species)          #  expected 75 each.
nrow(merged_chytrid_data)                   # expected 225
range(merged_chytrid_data$n_frogs_sampled)      # expected 9-45


# 2.2.3 Optional export of merged data --------------------
# Remove hashtags below to save the data as a CSV:
# write.csv(merged_chytrid_data, file = "merged_chytrid_data.csv", row.names = FALSE)


## ------------------------------------------------------------
## 3. PREPARE RESPONSE, GROUPS & SPECIES LABELS
## ------------------------------------------------------------

# 3.1 Proportional data analysis --------------------

# 3.1.1 Validate counts before calculating proportions --------------------
stopifnot(
  !anyNA(merged_chytrid_data$n_infected),
  !anyNA(merged_chytrid_data$n_frogs_sampled),
  all(merged_chytrid_data$n_infected >= 0),
  all(merged_chytrid_data$n_frogs_sampled > 0),
  all(merged_chytrid_data$n_infected <=
      merged_chytrid_data$n_frogs_sampled),
  all(merged_chytrid_data$n_infected ==
      floor(merged_chytrid_data$n_infected)
  ),
  all(merged_chytrid_data$n_frogs_sampled ==
      floor(merged_chytrid_data$n_frogs_sampled)
  )
)

# 3.1.2 Calculate a proportion variable WITH Amphibians with visible chytrid signs -------------------- 
# Descriptive representation of the response variable.
# Model will use WITH- (infected) and WITHOUT- (uninfected) signs together.
# Adapted from 'Practical 8.2 An example with proportion data'
# infected = individuals examined WITH Amphibians with visible chytrid signs (not laboratory-confirmed).
merged_chytrid_data$infected_prop <-
  merged_chytrid_data$n_infected /
  merged_chytrid_data$n_frogs_sampled

# 3.1.3 Calculate the observed % WITH Amphibians with visible chytrid signs --------------------
# For descriptive figures only, not model responses.
merged_chytrid_data$infection_percent <-
  merged_chytrid_data$infected_prop * 100

# 3.1.4 Calculate the number WITHOUT Amphibians with visible chytrid signs --------------------
# uninfected = individuals examined WITHOUT Amphibians with visible chytrid signs (not lab-confirmed).
merged_chytrid_data$n_uninfected <-
  merged_chytrid_data$n_frogs_sampled -
  merged_chytrid_data$n_infected

# 3.2 Prepare grouping variables
merged_chytrid_data <- merged_chytrid_data %>%
  mutate(
    NP = factor(NP),
    species = factor(
      species,
      levels = c(
        "Litoria rheocola", 
        "Litoria nannotis", 
        "Rhinella marina")
    ),
    creek_uid = interaction(NP, creek_id, drop = TRUE)
  )

# 3.3 Common-name labels for figures, same order as species --------------------
# Species retained as the scientific-name variable for model formulas.
# Ordered by highest prevalance
merged_chytrid_data$Species_name <- factor(
  merged_chytrid_data$species,
      levels = c(
        "Litoria rheocola",
        "Litoria nannotis",
        "Rhinella marina"
   ),
      labels = c(
        "Common mistfrog",
        "Waterfall frog",
        "Cane toad"
  )
)

stopifnot(
  !anyNA(merged_chytrid_data$species),
  !anyNA(merged_chytrid_data$Species_name)
)

# 3.4 Inspect the prepared variables --------------------
head(merged_chytrid_data)
str(merged_chytrid_data)
summary(merged_chytrid_data$infected_prop)
summary(merged_chytrid_data$infection_percent)
summary(merged_chytrid_data$n_uninfected)
hist(merged_chytrid_data$infection_percent)   # how infection is spread across observations
# 3.5 Check categories & record counts --------------------
# Check scientific and common names correspond correctly
table(
  merged_chytrid_data$species,
  merged_chytrid_data$Species_name)

stopifnot(
  all(merged_chytrid_data$Species_name[merged_chytrid_data$species == "Litoria nannotis"] == "Waterfall frog"),
  all(merged_chytrid_data$Species_name[merged_chytrid_data$species == "Litoria rheocola"] == "Common mistfrog"),
  all(merged_chytrid_data$Species_name[merged_chytrid_data$species == "Rhinella marina"] == "Cane toad")
)

# Correct labels: 75 records per species pairing.

# 3.6 Check counts
table(merged_chytrid_data$NP)        # Expected: 15 per NP (5 creeks × 3 species)
table(merged_chytrid_data$species)   # Expected: 75 per species (15 NPs x 5 creeks)
table(merged_chytrid_data$creek_uid) # Expected: 3 records per creek (1 per species)

stopifnot(
  nlevels(merged_chytrid_data$NP) == 15,
  nlevels(merged_chytrid_data$creek_uid) == 75,
  all(table(merged_chytrid_data$species) == 75),
  all(table(merged_chytrid_data$creek_uid) == 3)
)

# 3.7 Display creek records - expect 75 creeks across 3 records
table(table(merged_chytrid_data$creek_uid))

# 3.8 Check duplication
stopifnot(
  !anyDuplicated(
    merged_chytrid_data[,c("NP", "creek_id", "species")]
  )
)

# 3.9 Pairs plot all data ---------------------------
pairs_all_data <- merged_chytrid_data

with(
  pairs_all_data,
  pairs(
      infection_percent ~
      VPD +
      visit_rate_1000_per_yr +
      track_density +
      pop_density +
      plant_spp_richness +
      frog_spp_richness,
    upper.panel = panel.smooth
  ))
## ------------------------------------------------------------
## 4. EXPLORATION: OBSERVED SPECIES COMPARISON
## ------------------------------------------------------------
# Draws on Practical 6 pairs plots.

# NB: Response and species labels were prepared in Section 3.

# 4.1 Decision tree preparation --------------------------- 

# DT1 response:
# counts with and without Amphibians with visible chytrid signs -> cbind(n_infected, n_uninfected)

# DT2 predictors:
# species (categorical); 
# VPD, visitation, track density, Population density (continuous)

# DT3 structure:
# 225 records in 75 creeks in 15 parks
# -> park and creek random intercepts

# Baseline: predictor slopes are shared among species on the log-odds scale.


# 4.2.1 Creek level predictor check ---------------------------
creek_predictors <- merged_chytrid_data %>%
  distinct(NP, creek_uid, VPD, visit_rate_1000_per_yr, track_density)
nrow(creek_predictors)    # expected 75

stopifnot(nrow(creek_predictors) == 75)
stopifnot(all(
    tapply(
      merged_chytrid_data$VPD, 
      merged_chytrid_data$NP, 
      function(x) length(unique(x))) == 1))

stopifnot(nrow(creek_predictors) == 75)
stopifnot(all(
  tapply(
    merged_chytrid_data$visit_rate_1000_per_yr, 
    merged_chytrid_data$NP, 
    function(x) length(unique(x))) == 1))

# 4.2.2 Park level predictor check ---------------------------
with(national_park_data, 
     pairs(~ 
       VPD + 
       visit_rate_1000_per_yr, 
       upper.panel = panel.smooth)
)     # wide scatter: VPD 0.7-2.6 kPa; visitation 0.5-15 1000/pa
# cluster at about 8 thousand visitors. 

cor(national_park_data$VPD, 
    national_park_data$visit_rate_1000_per_yr)

# 4.3 Park level summary ---------------------------
park_summary <- merged_chytrid_data %>%
  group_by(NP) %>%
  summarise(
    individuals_examined = sum(n_frogs_sampled),
    individuals_with_signs = sum(n_infected),
    pooled_percent_with_signs = 100 * sum(n_infected) / sum(n_frogs_sampled),
    .groups = "drop")
print(park_summary)

# 4.4 Species-level descriptive summary ---------------------------
species_summary <- merged_chytrid_data %>%
  group_by(species, Species_name) %>%
  summarise(
    number_of_samples = n(),
    individuals_examined = sum(n_frogs_sampled),
    individuals_with_signs = sum(n_infected),
    pooled_percent_with_signs =
      100 * sum(n_infected) / sum(n_frogs_sampled),
    median_sample_percent = median(infection_percent),
    .groups = "drop"
  )

print(species_summary, width = Inf)

# Pooled percentage weights sample individuals examined.
# Median sample percentage describes the species–creek samples.


# 4.5 Species specific pairs plots ---------------------------

# 4.5.1. Litoria rheocola ---------------------------
rheocola_data <- subset(
  merged_chytrid_data,
  species == "Litoria rheocola")

with(
  rheocola_data,
  pairs(
    infection_percent ~
      VPD +
      visit_rate_1000_per_yr +
      track_density +
      pop_density +
      plant_spp_richness,
    upper.panel = panel.smooth
  ))
# 4.5.2 Litoria nannotis - all ---------------------------
nannotis_data <- subset(
  merged_chytrid_data,
  species == "Litoria nannotis")

with(
  nannotis_data,
  pairs(
    infection_percent ~
      VPD +
      visit_rate_1000_per_yr +
      track_density +
      pop_density +
      plant_spp_richness,
    upper.panel = panel.smooth
  ))      # are plant richness & visitation confounded?
# 4.5.3. Rhinella marina ---------------------------
toad_data <- subset(
  merged_chytrid_data,
  species == "Rhinella marina")

with(
  toad_data,
  pairs(
    infection_percent ~
      VPD +
      visit_rate_1000_per_yr +
      track_density +
      pop_density +
      plant_spp_richness +
      frog_spp_richness,
    upper.panel = panel.smooth
  ))
## ------------------------------------------------------------
## 5. ANALYSIS DESIGN TO DECISION TREE MODEL EVALUATION
## ------------------------------------------------------------

# Analysis foundation questions:
# Q1. Does the probability of showing Amphibians with visible signs of chytrid differ among the three sampled species under comparable modelled conditions?
# Q2. Does the association between VPD and the probability of showing Amphibians with visible signs of chytrid differ among species?
# Q3. Does the association between annual park visitation and the probability of showing Amphibians with visible signs of chytrid differ among species?

# Response: n_infected (Amphibians with visible chytrid signs) out of n_frogs_sampled; 
# modelled as cbind(n_infected, n_uninfected).

# Predictor variables modelled: species, track_density, pop_density, VPD, visit_rate_1000_per_yr, 
# Predictor variables explored: NP_area_1000_ha, frog_spp_richness, plant_spp_richness
# Binomial denominator: n_frogs_sampled

# Data structure:
# ~ 15 national parks (NPs), each with one value of the park-level predictors.
# ~ 5 creeks per park: 75 creeks.
# ~ 3 species sampled per creek: 225 observations.
# ~ 1 row represents 1 species–creek sample: 1 observation.
# ~ 9-45 examined individuals per species, per creek.

# Modelling:
# ~ Multiple predictors estimate adjusted associations.
# ~ Random intercepts represent park and shared-creek grouping.
# ~ The response uses counts with and without Amphibians with visible chytrid signs.
# ~ Species interactions allow the focal slopes to differ.



## --------------------------------------------------------------------
## 6. MODEL EVALUATION LADDER: RESPONSE FAMILY & STRUCTURE SELECTION 
## --------------------------------------------------------------------
# Draws on Practicals 6 to 8 and Dwyer's Decision Tree.
#
# MODEL EVALUATION
#
# 1. Multiple regression principle (Prac 6):
# several predictors fitted together to estimate adjusted associations.
#
# 2. Mixed-effects principle (Prac 7):
# random intercepts for park (NP) + creek (creek_uid) as observations are grouped.
#
# 3. Generalised model principle (Prac 8):
# cbind(signs, no signs) response with a logit link.
# The beta-binomial family allows extra-binomial variation.
#
# 4. Interactions (Prac 6): # species-specific VPD and visitation slopes.
#
# 5. Plotting from a GLMM (Prac 9): predictions and confidence intervals in Section 10.


# 6.1. intercept-only binomial GLM (no predictors, no structure)
M1_binomial_glm <- glm(cbind(n_infected, n_uninfected) 
          ~ 1,
          family = binomial(link = "logit"), 
          data = merged_chytrid_data)

res_M1_binomial_glm <- simulateResiduals(
          fittedModel = M1_binomial_glm, 
          n = 1000, 
          seed = 123)

testDispersion(res_M1_binomial_glm)
# dispersion = 7.1996, p-value < 2.2e-16    
# High overdispersion


# 6.2. Add the fixed predictors (but still no structure)
M2_binomial_glm_predictors <- glm(cbind(n_infected, n_uninfected) 
          ~ VPD + 
          visit_rate_1000_per_yr +
          track_density + 
          pop_density + 
          species,
          family = binomial(link = "logit"), 
          data = merged_chytrid_data)

res_M2_binomial_glm_predictors <- simulateResiduals(
          fittedModel = M2_binomial_glm_predictors, 
          n = 1000, 
          seed = 123)

testDispersion(res_M2_binomial_glm_predictors)
# dispersion = 2.8996, p-value < 2.2e-16    
# Predictors improve fit substantially, but the model remains overdispersed.

# 6.3. Add structure (park and creek-within-park) with binomial family
# Draws on Practical 8
# Examine baseline predictors & structure, to evaluate binomial response family.
M3_binomial_glmTMB_structure <- glmmTMB(cbind(n_infected, n_uninfected) 
            ~ VPD + 
            visit_rate_1000_per_yr +
            track_density + 
            pop_density + 
            species + 
            (1 | NP) + 
            (1 | creek_uid),
            family = binomial(link = "logit"), 
            data = merged_chytrid_data)

res_M3_binomial_glmTMB_structure <- simulateResiduals(
            fittedModel = M3_binomial_glmTMB_structure, 
            n = 1000, 
            seed = 123)

testDispersion(res_M3_binomial_glmTMB_structure)
# dispersion = 1.5381, p-value < 2.2e-16
# Structure helps a lot, but still overdispersed.


# 6.4. Overdispersed, so beta-binomial without structure
M4_bb_glmTMB <- glmmTMB(cbind(n_infected, n_uninfected) 
            ~ VPD + 
            visit_rate_1000_per_yr +
            track_density + 
            pop_density + 
            species,
            family = betabinomial(link = "logit"), 
            data = merged_chytrid_data)

res_M4_bb_glmTMB <- simulateResiduals(
            fittedModel = M4_bb_glmTMB, 
            n = 1000, 
            seed = 123)

testDispersion(res_M4_bb_glmTMB)
# dispersion = 0.93672, p-value = 0.618             
# Overdispersion fixed


# 6.5. Baseline beta-binomial GLMM combined with park & creek random intercepts (structure)
M5_bb_glmTMB_structure <- glmmTMB(
    cbind(n_infected, n_uninfected) ~ 
      VPD + 
      visit_rate_1000_per_yr +
      track_density + 
      pop_density + 
      species + 
      (1 | NP) + 
      (1 | creek_uid),
      family = betabinomial(link = "logit"), 
      data = merged_chytrid_data)


# 6.5.1 Inspect baseline beta-binomial GLMM estimates --------------------------
summary(M5_bb_glmTMB_structure)


# 6.5.2 Inspect numerical fitting information ----------------------------------
M5_bb_glmTMB_structure$fit$convergence
M5_bb_glmTMB_structure$fit$message
M5_bb_glmTMB_structure$sdr$pdHess


# 6.5.3 Inspect residuals and dispersion ----------------------------------
res_M5_bb_glmTMB_structure <- simulateResiduals(
            fittedModel = M5_bb_glmTMB_structure, 
            n = 1000, 
            seed = 123)

testDispersion(res_M5_bb_glmTMB_structure)
# dispersion = 0.96025, p-value = 0.764
# Dispersion acceptable; park and creek structure now matches the sampling design


# 6.5.4. Akaike Information Criterion (AIC) comparison of the candidate models
AIC(M1_binomial_glm,
    M2_binomial_glm_predictors,
    M3_binomial_glmTMB_structure, 
    M4_bb_glmTMB,
    M5_bb_glmTMB_structure)

#                               df      AIC
# M1_binomial_glm               1     2903.462
# M2_binomial_glm_predictors    7     2423.421
# M3_binomial_glmTMB_structure  9     1802.136
# M4_bb_glmTMB                  8     1045.666
# M5_bb_glmTMB_structure       10     1041.155

# Decision: use M5. 
# The beta-binomial family fixes overdispersion (M3 vs M4/M5). 
# Park and creek random intercepts are retained because the design is hierarchical, 
# despite improving AIC by only about 4.5 over M4.


# 6.5.5 Predictor overlap
performance::check_collinearity(M5_bb_glmTMB_structure)


# 6.5.6 Residual plot
plot(res_M5_bb_glmTMB_structure, quantreg = FALSE)
# no sig deviation, over or under-dispersion,  outliers: model is adequate."

# 6.5.7 Wald 95% CIs for fixed effects (log odds ratio)
confint(M5_bb_glmTMB_structure, 
        parm = "beta_", 
        component = "cond", 
        method = "wald")


## -------------------------------------------------------------------------
## 7. SPECIES-INTERACTION MODELS: DO SLOPES DIFFER PER SPECIES?
## -------------------------------------------------------------------------
# Draws on Practical 5 and 6.

# Purpose: 
# Test whether the VPD and visitation associations differ among species (Q2, Q3).

# 7.1 Allow the VPD slope to differ among species ------------------------------
# update() = starts from an existing fitted model, then refits with a 
# specified formula change.

# Two-way interactions: VPD-by-species
M6_vpd_species <- update(
  M5_bb_glmTMB_structure,
  . ~ . + VPD:species)


# 7.2 Allow the visitation slope to differ among species -----------------------
# Two-way interactions: visitation-by-species
M7_visit_species <- update(
  M5_bb_glmTMB_structure,
  . ~ . + visit_rate_1000_per_yr:species)


# 7.3 Allow both focal slopes to differ among species --------------------------
# VPD-by-species and visitation-by-species.
# No VPD-by-visitation or three-way interaction is fitted.

M8_vpd_visit_species <- update(
  M6_vpd_species,
  . ~ . + visit_rate_1000_per_yr:species)


# 7.4 Numerical fitting checks
M6_vpd_species$fit$convergence;       M6_vpd_species$sdr$pdHess
M7_visit_species$fit$convergence;     M7_visit_species$sdr$pdHess
M8_vpd_visit_species$fit$convergence; M8_vpd_visit_species$sdr$pdHess
M8_vpd_visit_species$fit$message


# 7.5 AIC comparison of the four structures
AIC(M5_bb_glmTMB_structure, M6_vpd_species, M7_visit_species, M8_vpd_visit_species)

#                         df      AIC
# M5_bb_glmTMB_structure 10   1041.155
# M6_vpd_species         12   1029.500
# M7_visit_species       12   1030.176
# M8_vpd_visit_species   14   1008.438  


# 7.6 Likelihood ratio tests of interaction blocks (each adds 2 slopes, df = 2)
anova(M5_bb_glmTMB_structure, M6_vpd_species)   # VPD x species, alone
anova(M5_bb_glmTMB_structure, M7_visit_species) # visitation x species, alone
anova(M7_visit_species, M8_vpd_visit_species)   # Q2 null hypothesis test: VPD x species given visitation x species (Q2)
anova(M6_vpd_species, M8_vpd_visit_species)     # Q3 null hypothesis test: visitation x species given VPD x species (Q3)

# LRT results (each interaction block adds 2 species-specific slopes, df = 2):
#
# VPD x species, alone (M5 vs M6):        chi-sq(2) = 15.66, p = 0.0004
# Visitation x species, alone (M5 vs M7): chi-sq(2) = 14.98, p = 0.0006
#
# Each interaction given the other:
# Q2: VPD x species (M7 vs M8):           chi-sq(2) = 25.74, p < 0.0001
# Q3: Visitation x species (M6 vs M8):    chi-sq(2) = 25.06, p < 0.0001
#
# Q2 and Q3: the VPD and visitation associations differ among species.
# AIC supports M8 (1008.4) over M7 (1030.2), M6 (1029.5) and M5 (1041.2).
# LRTs show the slopes differ somewhere among the three species,
# not which species differ. Pairwise contrasts (Section 9) show that.

summary(M8_vpd_visit_species)

# Decision: M8 as the final model; lowest AIC and both interaction blocks supported by the LRTs.



## ------------------------------------------------------------
## 8. FINAL-MODEL DIAGNOSTICS
## ------------------------------------------------------------
# Draws on Practicals 5, 6 and 8

# 8.1 Predictor overlap
performance::check_collinearity(M8_vpd_visit_species)


# 8.2 Wald 95% CIs for fixed effects
confint(M8_vpd_visit_species, 
        parm = "beta_", 
        component = "cond", 
        method = "wald")


# 8.3 Residual diagnostics (DHARMa)
res_M8_vpd_visit_species <- DHARMa::simulateResiduals(
      M8_vpd_visit_species, 
      n = 1000, 
      seed = 123)

plot(res_M8_vpd_visit_species, quantreg = FALSE)
DHARMa::testDispersion(res_M8_vpd_visit_species)
# dispersion = 1.0297, p = 0.72: no evidence of over- or underdispersion.

DHARMa::testUniformity(res_M8_vpd_visit_species)
# KS D = 0.0671, p = 0.2624: no departure from uniformity detected.


# 8.4 Residuals by species
DHARMa::plotResiduals(res_M8_vpd_visit_species, form = merged_chytrid_data$species)
DHARMa::testCategorical(res_M8_vpd_visit_species, catPred = merged_chytrid_data$species)
# Within-species uniformity (unadjusted p): mistfrog 0.5566,
# waterfall frog 0.6112, cane toad 0.8073.
# Residual variance among species: Levene's F = 0.354, p = 0.7022.


# 8.5 Residuals against each numerical predictor -------------
DHARMa::plotResiduals(
  res_M8_vpd_visit_species,
  form = merged_chytrid_data$VPD)
DHARMa::plotResiduals(
  res_M8_vpd_visit_species,
  form = merged_chytrid_data$visit_rate_1000_per_yr)
DHARMa::plotResiduals(
  res_M8_vpd_visit_species,
  form = merged_chytrid_data$track_density)
DHARMa::plotResiduals(
  res_M8_vpd_visit_species,
  form = merged_chytrid_data$pop_density)
## ------------------------------------------------------------
## 9. SLOPES & CONTRASTS
## ------------------------------------------------------------
# Slopes are on the log-odds scale: per 1 kPa (VPD) and per 1,000 visitors/year.
# Other covariates are held at their means (emtrends default).

# 9.1 VPD slopes per species ---------------------------------------
# Estimate the association between VPD & visible chytrid signs per species.
vpd_slopes <- emmeans::emtrends(
    object = M8_vpd_visit_species, 
    specs = ~ species, 
    var = "VPD")

print(vpd_slopes)       # Display estimated slopes
print(confint(object = vpd_slopes, level = 0.95))


# 9.2 VPD slope comparisons per species (Tukey test within this set)
# Tukey adjustment accounts for pairwise comparisons
vpd_slope_contrasts <- pairs(
      x = vpd_slopes, 
      adjust = "tukey")

# Display differences, 95% confidence intervals and adjusted tests
print(summary(
    object = vpd_slope_contrasts, 
    infer = c(TRUE, TRUE), 
    level = 0.95, 
    adjust = "tukey"))


# 9.3 Visitation slopes per species
visit_slopes <- emmeans::emtrends(
      object = M8_vpd_visit_species, 
      specs = ~ species, 
      var = "visit_rate_1000_per_yr")

print(visit_slopes)
print(confint(object = visit_slopes, level = 0.95))


# 9.4 Visitation slope comparisons per species (Tukey test within this set)
visit_slope_contrasts <- pairs(
      x = visit_slopes, 
      adjust = "tukey")

# Display differences, 95% confidence intervals and adjusted tests
print(summary(
      object = visit_slope_contrasts, 
      infer = c(TRUE, TRUE), 
      level = 0.95, 
      adjust = "tukey"))


## ------------------------------------------------------------
## 10. MODEL-BASED PREDICTIONS & FINAL FIGURES
## ------------------------------------------------------------

# 10.1 Prediction values (covariates held constant)
final_data <- model.frame(M8_vpd_visit_species)

# covariates
prediction_values <- c(
  VPD = mean(final_data$VPD),
  visit_rate_1000_per_yr =
    mean(final_data$visit_rate_1000_per_yr),
  track_density = mean(final_data$track_density),
  pop_density = mean(final_data$pop_density)
)   

prediction_table <- data.frame(
  Variable = c("VPD", "Visitation (per 1,000 visitors/yr)", "Track density", "Population density"),
  Value = round(unname(prediction_values), 3),
  Units = c("kPa", "thousand visitors/year", "km/km²", "individuals/100 m"),
  Held_constant_in = c("Visitation figure", "VPD figure", "Both figures", "Both figures")
)

knitr::kable(prediction_table, caption = "Covariate values held constant in the prediction figures")

# Numerical predictors held at their means (table above); park & creek random effects set to 0.
# Confidence intervals describe the estimated mean response,
# not variation among individual future observations.
# Predictions are probabilities, shown as percentages in the final figures.
# They are not averages integrated over the random-effect distributions.


# 10.2 Predictions (park and creek random effects set to 0 - 'typical creek')
pred_vpd_smooth <- ggeffects::predict_response(
  M8_vpd_visit_species,
  terms = c("VPD [all]", "species"),
  margin = "mean_reference",
  type = "fixed",
  condition = prediction_values[c("visit_rate_1000_per_yr", "track_density", "pop_density")],
  ci_level = 0.95
)

pred_visit_smooth <- ggeffects::predict_response(
  M8_vpd_visit_species,
  terms = c("visit_rate_1000_per_yr [all]", "species"),
  margin = "mean_reference",
  type = "fixed",
  condition = prediction_values[c("VPD", "track_density", "pop_density")],
  ci_level = 0.95
)

print(pred_vpd_smooth, n = Inf)
print(pred_visit_smooth, n = Inf)


# 10.3 Q1: adjusted species probabilities (covariates at their means)
# holds other predictors at their means, with random effects at zero. 
species_emm <- emmeans::emmeans(
    object = M8_vpd_visit_species, 
    specs = ~ species, 
    type = "response")

print(species_emm)
print(pairs(species_emm, adjust = "tukey"))


## ------------------------------------------------------------
## 11. FIGURE PLOTTING
## ------------------------------------------------------------

# 11.0 Universal settings
figure_font <- "sans"

figure_theme <- theme_classic(base_size = 12, base_family = figure_font) +
  theme(
    axis.text         = element_text(colour = "grey20"),
    strip.background  = element_blank(),
    strip.text        = ggtext::element_markdown(size = 11, colour = "grey20",
                                                 lineheight = 1.1),
    plot.tag          = element_text(face = "bold", size = 14, colour = "grey20"),
    plot.margin       = margin(t = 15, r = 10, b = 5, l = 15),
    legend.position   = "bottom")

y_percent <- list(
  scale_y_continuous(breaks = seq(0, 100, 25),
                     expand = expansion(mult = c(0, 0))),
  coord_cartesian(ylim = c(0, 100)),
  guides(y = guide_axis(cap = "upper")))

theme_set(figure_theme)

panel_labels <- c(
  "Litoria rheocola" = "Common mistfrog<br>(<i>Litoria rheocola</i>)",
  "Litoria nannotis" = "Waterfall frog<br>(<i>Litoria nannotis</i>)",
  "Rhinella marina"  = "Cane toad<br>(<i>Rhinella marina</i>)")

species_colours <- c(
  "Common mistfrog" = "#440154", 
  "Waterfall frog" = "#31688e", 
  "Cane toad" = "#35b779")

prediction_colours <- setNames(unname(species_colours), names(panel_labels))

merged_chytrid_data$species <- factor(
  merged_chytrid_data$species, levels = names(panel_labels))

# Observed data: one pooled % per park per species
park_species_signs <- merged_chytrid_data %>%
  group_by(NP, species) %>%
  summarise(
    VPD = first(VPD),
    visit_rate_1000_per_yr = first(visit_rate_1000_per_yr),
    pooled_percent = 100 * sum(n_infected) / sum(n_frogs_sampled),
    .groups = "drop") 

stopifnot(nrow(park_species_signs) == 45)   # 15 parks x 3 species``

# -----------------------------------------------------------------

# 11.1 BOXPLOT OF OBSERVED SIGNS BY SPECIES
# Q1. Does the probability of showing visible signs of 4333Bd differ among the three sampled species under comparable modelled conditions?
  
# Working caption:
# Observed percentages of sampled amphibians with visible chytrid
# signs across 75 creeks for each species. Each point represents
# one species–creek sample. Boxes show the median and interquartile
# range; whiskers extend to the most extreme observations within
# 1.5 times the interquartile range. Points are displaced
# horizontally to reduce overlap, without changing their
# percentage values. These are descriptive observations, not
# adjusted model predictions or laboratory-confirmed infections.

box_stats <- merged_chytrid_data %>%
  group_by(Species_name) %>%
  summarise(q1  = quantile(infection_percent, 0.25),
            med = median(infection_percent),
            q3  = quantile(infection_percent, 0.75),
            mean = mean(infection_percent),
            .groups = "drop")

first_box <- box_stats[box_stats$Species_name == "Common mistfrog", ]

quartile_labels <- data.frame(
  Species_name = "Common mistfrog",
  y     = c(first_box$q3, first_box$med, first_box$q1, first_box$mean),
  label = c("Q3 (75%)", "Median", "Q1 (25%)", "Mean"))

p_box_species_signs <- ggplot(
  merged_chytrid_data,
  aes(x = Species_name,
      y = infection_percent,
      colour = Species_name,
      fill = Species_name)) +
  geom_boxplot(outlier.shape = NA, alpha = 0.15, width = 0.55,
               colour = "grey20", linewidth = 0.8) +
  geom_jitter(position = position_jitter(width = 0.12, height = 0, seed = 123),
              alpha = 0.65, size = 2.4) +
  stat_summary(fun = mean, geom = "point", shape = 23, size = 4.5,
               fill = "white", colour = "grey20") +
  geom_text(data = box_stats[box_stats$Species_name != "Common mistfrog", ],
            aes(x = Species_name, y = med, label = paste0(round(med), "%")),
            nudge_x = 0.35, size = 3.5, colour = "grey20", inherit.aes = FALSE) +
  geom_text(data = quartile_labels,
            aes(x = Species_name, y = y, label = label),
            nudge_x = 0.3, hjust = 0, size = 3.5, colour = "grey20",
            inherit.aes = FALSE) +
  annotate("text", x = 1:3, y = 104, label = "n = 75", size = 4) +
  scale_fill_manual(values = species_colours, guide = "none") +
  scale_colour_manual(values = species_colours, guide = "none") +
  scale_x_discrete(labels = c("Common mistfrog<br>(<i>Litoria rheocola</i>)",
                              "Waterfall frog<br>(<i>Litoria nannotis</i>)",
                              "Cane toad<br>(<i>Rhinella marina</i>)"),
                   limits = c("Common mistfrog", "Waterfall frog", "Cane toad"),
                   expand = expansion(add = 0.5)) +
  scale_y_continuous(breaks = seq(0, 100, 20),
                     expand = expansion(add = c(1.5, 0))) +
  coord_cartesian(ylim = c(0, 106)) +
  labs(x = NULL, y = "Amphibians with visible chytrid signs (%)") +
  guides(y = guide_axis(cap = "upper")) +
  theme(legend.position = "none",
        axis.text.x = ggtext::element_markdown(size = 11, lineheight = 1.1))



# View
print(p_box_species_signs)
# Diamond = mean of creek percentages; Boxes = median and interquartile range.. 

# Save
dir.create("output/figures", recursive = TRUE, showWarnings = FALSE)
ggsave("output/figures/fig_box-species-signs.png",
       plot = p_box_species_signs,
       width = 7, height = 5, dpi = 300)

# -----------------------------------------------------------------
# 11.2 Q1 ADJUSTED SPECIES PROBABILITIES & CONTRASTS

# Adjusted probability per species
species_emm_df <- as.data.frame(species_emm)

q1_table <- data.frame(
  Species = c("Common mistfrog", "Waterfall frog", "Cane toad")[
    match(species_emm_df$species, levels(merged_chytrid_data$species))],
  `Adjusted probability (%)` = round(100 * species_emm_df$prob, 1),
  `95% CI (%)` = paste0(round(100 * species_emm_df$asymp.LCL, 1), " to ",
                        round(100 * species_emm_df$asymp.UCL, 1)),
  check.names = FALSE)

knitr::kable(q1_table,
             caption = "Model-adjusted probability of visible chytrid signs for each species, with other predictors held at their means and random effects set to zero.")

# Pairwise comparisons
contrast_df <- as.data.frame(summary(pairs(species_emm, adjust = "tukey"), infer = TRUE))
names(contrast_df)    # check the column names before the next step

q1_contrasts <- data.frame(
  Comparison = contrast_df$contrast,
  `Odds ratio` = round(contrast_df$odds.ratio, 2),
  `95% CI` = paste0(round(contrast_df$asymp.LCL, 2), " to ", round(contrast_df$asymp.UCL, 2)),
  `Adjusted p` = format.pval(contrast_df$p.value, digits = 2, eps = 0.001),
  check.names = FALSE)

knitr::kable(q1_contrasts,
             caption = "Pairwise species comparisons (odds ratios, Tukey-adjusted).")

# -----------------------------------------------------------------

# 11.3 MAIN FINDINGS: PREDICTIONS + OBSERVED POINTS (VPD & VISITATION)
# Draws on Practical 9

# 11.3.1 Transform predictions into data frames
pred_vpd_df <- as.data.frame(pred_vpd_smooth) %>% mutate(
  species = factor(as.character(group),
                   levels = levels(merged_chytrid_data$species)))

pred_visit_df <- as.data.frame(pred_visit_smooth) %>% mutate(
  species = factor(as.character(group),
                   levels = levels(merged_chytrid_data$species)))

# 11.3.2 Create VPD plot
p_vpd_pred <- ggplot() +
  
  # faint points: every species-creek sample
  geom_point(data = merged_chytrid_data,
             aes(x = VPD, y = infection_percent, colour = species),
             alpha = 0.25, size = 1.4) +
  
  # shaded band: 95% confidence interval of the mean
  geom_ribbon(data = pred_vpd_df,
              aes(x = x, ymin = conf.low * 100, ymax = conf.high * 100, fill = species),
              alpha = 0.25, colour = NA) +
  
  # fitted line (probability x 100 = percent)
  geom_line(data = pred_vpd_df,
            aes(x = x, y = predicted * 100, colour = species),
            linewidth = 1.1) +
  
  # solid points: pooled percentage per park
  geom_point(data = park_species_signs,
             aes(x = VPD, y = pooled_percent, fill = species),
             shape = 21, colour = "grey20", size = 2.8) +
  facet_wrap(~ species, nrow = 1, labeller = labeller(species = panel_labels)) +
  scale_colour_manual(values = prediction_colours) +
  scale_fill_manual(values = prediction_colours) +
  y_percent + 
  labs(x = "Vapour pressure deficit (kPa)",
       y = "Amphibians with visible chytrid signs (%)") +
  theme(legend.position = "none")

# 11.3.3 Create visitation plot
p_visit_pred <- ggplot() +
  geom_point(data = merged_chytrid_data,
             aes(x = visit_rate_1000_per_yr, y = infection_percent, colour = species),
             alpha = 0.25, size = 1.4) +
  geom_ribbon(data = pred_visit_df,
              aes(x = x, ymin = conf.low * 100, ymax = conf.high * 100, fill = species),
              alpha = 0.25, colour = NA) +
  geom_line(data = pred_visit_df,
            aes(x = x, y = predicted * 100, colour = species),
            linewidth = 1.1) +
  geom_point(data = park_species_signs,
             aes(x = visit_rate_1000_per_yr, y = pooled_percent, fill = species),
             shape = 21, colour = "grey20", size = 2.8) +
  facet_wrap(~ species, nrow = 1, labeller = labeller(species = panel_labels)) +
  scale_colour_manual(values = prediction_colours) +
  scale_fill_manual(values = prediction_colours) +
  y_percent + 
  labs(x = "Visitation (per 1,000 visitors/yr)",
       y = "Amphibians with visible chytrid signs (%)") +
  theme(legend.position = "none")

# 11.3.4 Combine and save
p_pred_combined <- (p_vpd_pred / p_visit_pred) +
  plot_annotation(
    tag_levels = "A",
    caption = paste(
      "**Faint points**: individual creek samples; **outlined points**: pooled percentage per park;",
      "**line**: model prediction; **shaded band** = 95% confidence interval.",
      sep = "\n"),
    theme = theme(
      plot.caption = ggtext::element_markdown(hjust = 0, colour = "grey20", size = 10),
      plot.tag = element_text(face = "bold", size = 14, colour = "grey20")))
    
print(p_pred_combined)
ggsave("output/figures/fig_predictions-combined.png", plot = p_pred_combined,
       width = 11, height = 8, dpi = 300)

# -----------------------------------------------------------------

# 11.4 COMBINED PREDICTION MODEL: VPD, visitation, track density, pop density

# Shared slopes: track density
pred_track_smooth <- ggeffects::predict_response(
  M8_vpd_visit_species,
  terms = c("track_density [1.7:12.4 by = 0.2]", "species"),
  margin = "mean_reference", type = "fixed",
  condition = prediction_values[c("VPD", "visit_rate_1000_per_yr", "pop_density")],
  ci_level = 0.95)

# Shared slopes: population density
pred_dens_smooth <- ggeffects::predict_response(
  M8_vpd_visit_species,
  terms = c("pop_density [1:17.8 by = 0.2]", "species"),
  margin = "mean_reference", type = "fixed",
  condition = prediction_values[c("VPD", "visit_rate_1000_per_yr", "track_density")],
  ci_level = 0.95)

# Data frames: species column + panel code
final_vpd <- as.data.frame(pred_vpd_smooth)
final_vpd$species <- as.character(final_vpd$group)
final_vpd$panel   <- "p1"

final_visit <- as.data.frame(pred_visit_smooth)
final_visit$species <- as.character(final_visit$group)
final_visit$panel   <- "p2"

final_track <- as.data.frame(pred_track_smooth)
final_track$species <- as.character(final_track$group)
final_track$panel   <- "p3"

final_dens <- as.data.frame(pred_dens_smooth)
final_dens$species <- as.character(final_dens$group)
final_dens$panel   <- "p4"

# Keep species within observed Population density range
dens_range <- merged_chytrid_data %>%
  group_by(species) %>%
  summarise(min_x = min(pop_density), max_x = max(pop_density), .groups = "drop")
dens_range$species <- as.character(dens_range$species)

final_dens <- final_dens %>%
  left_join(dens_range, by = "species") %>%
  filter(x >= min_x, x <= max_x) %>%
  select(-min_x, -max_x)

# Combine
all_predictions <- bind_rows(final_vpd, final_visit, final_track, final_dens) %>%
  select(x, predicted, conf.low, conf.high, species, panel)

# Panel names and letters
panel_names <- c(p1 = "Vapour pressure deficit (kPa)",
                 p2 = "Visitation (per 1,000 visitors/yr)",
                 p3 = "Track density (km/km²)",
                 p4 = "Population density (individuals per 100 m)")

panel_letters <- data.frame(panel  = c("p1", "p2", "p3", "p4"),
                            letter = c("A", "B", "C", "D"))

# Legend order and labels
species_order  <- c("Litoria rheocola", "Litoria nannotis", "Rhinella marina")
species_labels <- expression(
  "Common mistfrog (" * italic(Litoria~rheocola) * ")",
  "Waterfall frog (" * italic(Litoria~nannotis) * ")",
  "Cane toad (" * italic(Rhinella~marina) * ")")

# Final figure
p_combined_pred_final <- ggplot(all_predictions,
                                aes(x = x, y = predicted * 100, colour = species, fill = species)) +
  geom_ribbon(aes(ymin = conf.low * 100, ymax = conf.high * 100),
              alpha = 0.15, colour = NA, show.legend = FALSE) +
  geom_line(linewidth = 0.8) +
  geom_text(data = panel_letters, aes(x = -Inf, y = Inf, label = letter),
            hjust = -0.8, vjust = 1.4, fontface = "bold", family = figure_font,
            size = 6, colour = "grey20", inherit.aes = FALSE) +
  facet_wrap(~ panel, nrow = 2, scales = "free_x", strip.position = "bottom",
             axes = "all_y", labeller = as_labeller(panel_names)) +
  scale_colour_manual(name = "Species", values = prediction_colours,
                      limits = species_order, breaks = species_order,
                      labels = species_labels, drop = FALSE) +
  scale_fill_manual(values = prediction_colours, limits = species_order, guide = "none") +
  scale_x_continuous(breaks = scales::breaks_pretty(n = 4),
                     expand = expansion(mult = c(0.03, 0.03))) +
  y_percent +
  labs(x = NULL, y = "Predicted amphibians with visible chytrid signs (%)") +
  guides(colour = guide_legend(nrow = 1, direction = "horizontal")) +
  figure_theme +
  theme(strip.placement = "outside")

# 11.6.9 View and save
print(p_combined_pred_final)
ggsave("output/figures/fig_combined-final-predictions.png", 
       plot = p_combined_pred_final,
       width = 12, height = 8, dpi = 300)

# -----------------------------------------------------------------

# 11.5 SLOPES PLOT: SUMMARY OF SPECIES DIFFERENCE

# VPD slopes table
vpd_ci <- as.data.frame(confint(vpd_slopes, level = 0.95))

vpd_table <- data.frame(
  species   = vpd_ci$species,
  slope     = vpd_ci$VPD.trend,
  lower     = vpd_ci$asymp.LCL,
  upper     = vpd_ci$asymp.UCL,
  predictor = "VPD (per 1 kPa)")

# Visitation slopes table
visit_ci <- as.data.frame(confint(visit_slopes, level = 0.95))

visit_table <- data.frame(
  species   = visit_ci$species,
  slope     = visit_ci$visit_rate_1000_per_yr.trend,
  lower     = visit_ci$asymp.LCL,
  upper     = visit_ci$asymp.UCL,
  predictor = "Visitation (per 1,000 visitors/yr)")

# Join
slopes_all <- rbind(vpd_table, visit_table)

# Plot VPD + visitation slopes
p_slopes <- ggplot(slopes_all, aes(x = slope, y = species, colour = species)) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_pointrange(aes(xmin = lower, xmax = upper), size = 0.7) +
  facet_wrap(~ predictor, scales = "free_x") +
  scale_colour_manual(values = prediction_colours, guide = "none") +
  scale_y_discrete(limits = rev,
                   labels = c("Litoria rheocola" = "Common mistfrog",
                              "Litoria nannotis" = "Waterfall frog",
                              "Rhinella marina" = "Cane toad")) +
  labs(x = "Slope (log-odds)", y = NULL)

print(p_slopes)
# Save
dir.create("output/figures", recursive = TRUE, showWarnings = FALSE)
ggsave("output/figures/p_slopes.png", plot = p_slopes,
       width = 7, height = 5, dpi = 300)

## ------------------------------------------------------------
## 12. SYNTHESIS, LIMITATIONS & MANAGEMENT IMPLICATIONS
## ------------------------------------------------------------

# 12.1 Analytical decisions
# Response: recorded Amphibians with visible chytrid signs, not confirmed infection.
# Species investigated separately during exploration.
# Formal species comparisons use the joint interaction model.
# Main questions: species, VPD and visitation.

# Track density and Population density are adjustment covariates:
# ~Track density represents a different access-related measure to annual visitation.
# ~Population density describes local abundance and can estimate associations conditional on density.
# ~These adjustments do not remove all possible confounding.

# 12.2 Main limitations
# Observational associations do not establish causation.
# Park-level predictors have 15 different park-level values.
# Amphibians with visible signs of chytrid are not diagnostic confirmation of infection.
# Some residual curvature remains across species focused density.
# Prediction interpretations depend on the support of covariates.
# Findings are applied across both sampled settings and predictor ranges.

# 12.3 Management interpretation
# Higher visitation and lower VPD identify monitoring priorities for native-frogs.
# But do not establish visitor-driven transmission or intervention effectiveness.

# RECOMMENDATION
# Additional surveillance of native frogs in higher-visitation & lower-VPD NPs.
# Justification: this statistical analysis.                                                                   |
# Maintain appropriate footwear, equipment and amphibian-handling hygiene
# Justification: Established best practise disease-management guidance.
# No evidence or information to support translocation.

# Adaptive monitoring
# 1. Repeat standardised surveys across seasons and years.
# 2. Include both priority sites & comparison sites across the predictor gradients.
# 3. Add laboratory testing to distinguish Amphibians with visible chytrid signs from confirmed infection.
# 4. Review the findings & adjust surveillance priorities or management accordingly.

Introduction

Summary

  • Drier parks, fewer signs. In both native frogs (common mistfrog and waterfall frog), visible chytrid signs became less likely as air dryness (vapour pressure deficit, VPD) increased. Predicted signs fell from 55% to 10% in mistfrogs and from 53% to 2% in waterfall frogs across the 15 parks.
  • Busier parks, more signs. Visible chytrid Signs became more likely with annual visitation (9% to 74% in mistfrogs, 3% to 65% in waterfall frogs). Only two parks exceeded about 13,000 visitors a year, so the upper end is least certain.
  • Cane toads (introduced) showed no clear pattern for either factor, so they are not a useful indicator of risk to native frogs.
  • What to do first: target surveillance at lower-VPD parks (mistfrogs first), audit and strengthen biosecurity at higher-visitation parks, and confirm with qPCR before larger interventions.
  • Caveat: these are associations in visible chytrid signs from one summer (2023/24), not laboratory-confirmed infection.

About this study

Using Queensland Parks and Wildlife Service (QPWS) survey data from 15 Wet Tropics national parks, this study asks whether visible signs of chytrid infection in three amphibians (Figure 1) differs among species, and how this changes with park dryness (VPD) and annual visitation. This data analysis answers this question and others, to point where biosecurity, conservation and surveillance should begin - not proven fixes.

Figure 1: Study species


Why chytrid still matters

Unprecedented scale

Chytridiomycosis, caused by the amphibian chytrid fungus, Batrachochytrium dendrobatidis (Bd), has contributed to the declines in at least 501 amphibian species worldwide, including 90 (18%) confirmed or presumed extinctions. Although declines peaked in the 1990s, only 12% of impacted species show recovery, while 39% remain in decline (Scheele et al., 2019; Scheele et al., 2019; Goodyear et al. 2026; Skerratt et al., 2007; Hollanders et al. 2022; IUCN 2023).

Regional relevance

In Australia, Bd has contributed to the decline or extinction of 43 of 238 amphibian species (Scheele et al. 2016). For Queensland’s Wet Tropics, mass amphibian mortalities occurred during 1990-1995, with severe declines affecting eight stream-dwelling frog species: the Green-eyed treefrog (Litoria genimaculata); Armoured mistfrog (Litoria lorica); Waterfall frog (Litoria nannotis); Mountain mistfrog (Litoria nyakalensis), Common mistfrog (Litoria rheocola), Australian lace-lid (Litoria dayi), Sharp-snouted dayfrog (Taudactylus acutirostris) and Northern tinker frog (Taudactylus rheophilus) (SOURCE).

Investigations of sick and dead montane rainforest frogs helped first identify chytridiomycosis and any vertebrate chytrid parasitism globally - a colossal conservation concern (Berger et al., 1998; Brannelly et al., 2020; Woodhams & Alford, 2005). These local losses connect an international pandemic directly to management of rainforest streams and their amphibian communities today.

Why impacts vary

Bd spreads over large geographic areas, partly enabled by the free-living, waterborne infectious stage driving transmission through stream environments (Sapsford et al. 2013), while temperature and moisture influence conditions for both pathogen and host. Wet Tropics Bd isolates grew optimally at 15°C-25°C, slowed at 26°C-28°C, then perished at 30°C (Sapsford et al. 2013).

Field research on Wet Tropics common mist frogs (Litoria rheocola) found that higher elevation (>400m) populations suffered the most severe Bd driven declines, while across elevations higher prevalences occurred during colder, winter months while summer months levels near zero - as warmer temperatures cleared infections: water connectivity at higher elevations further increased Bd prevalence (Sapsford et al 2013).

Broader multi-species modelling indicates prevalence and intensity peaks at intermediate temperatures for other species, rather than increasing alongside temperature (Grear et al., 2025). Yet, research shows recovered rainforest-frog populations can coexist with endemic Bd despite continued infections (Hollanders 2022). Environmental conditions can constrain disease impacts such as microhabitats with high connectivity to environmental or climate refugia, while increased reproductive investment (compensatory recruitment) can offset losses (Scheele et al. 2016; Bell et al., 2020; McKnight et al., 2017; Brannelly et al. 2020).


Research questions

Informed by a literature review and initial data exploration, these are the research questions this statistical analysis explores:

Questions

  • Q1: Does the probability of showing visible signs of Bd differ among the three sampled species under comparable modelled conditions?
  • Q2: Does the association between VPD and the probability of showing visible signs of Bd differ among species?
  • Q3:Does the association between annual park visitation and the probability of showing visible signs of Bd differ among species?

Hypotheses

  • H1: The adjusted probability differs between at least two species at the specified predictor values.
  • H2: The adjusted VPD slope differs between at least two species.
  • H3: The adjusted visitation slope differs between at least two species.

Null hypotheses

  • H₀1: The adjusted probability is equal among all three species at the specified predictor values.
  • H₀2:The adjusted VPD slope is equal among all three species.
  • H₀3: The adjusted visitation slope is equal among all three species.

Methods

Data and design

QPWS supplied two data sources: overarching park-level data for 15 Wet Tropics national parks and amphibian surveys from summer 2023/24. Five creeks were sampled per park, and three focal species were sampled in each creek: the common mistfrog (Litoria rheocola), waterfall frog (L. nannotis) and introduced cane toad (Rhinella marina). The two files were merged by park code in R then checked for completeness and valid counts. The response variable for this study is the number of individuals observed with or without visible signs of chytrid, not laboratory-confirmed infection.

Data structure

  • 15 de-identified national parks (NPs)
  • 5 creeks per park: 75 creeks.
  • 3 species sampled per creek: 225 observations.
  • 9-45 examined individuals per species, per creek.

Predictors

Early data exploration included species summaries, species-specific pair plots to evaluate trends, simple boxplots and other graphic representations of VPD, visitation, tracks, density and plant/amphibian richness, plus calculating Park-level VPD and visitation correlation: r = 0.247. Combined with a literature review, this informed predictor selection.

Park-level mean annual vapour pressure deficit (VPD, kPa) represents atmospheric drying, linking to research on environmental hindrance (Roznik et al. 2015). Annual visitation (thousand annual visitors per park) captures potential anthropogenic-spread (Ribas et al., 2026). Track density within a 500 m radius (km/km²) and population density (species individuals per 100 m of stream) were also included as adjustment covariates.

Model

Linear models were logically evaluated using Dwyer’s Decision Tree (2026) to find that with the least dispersion and best fit - progressing through: - intercept-only binomial GLM (no predictors, no structure) - with fixed predictors - with structure (park and creeks) in a binomial family - beta-binomial without structure - beta-binomial GLMM with park & creek random intercepts

Binomial models were strongly overdispersed, with or without structure, which led to using a beta-binomial mixed model (glmmTMB, logit link) with random intercepts for park and creek for best inference. Fixed effects were species, VPD, visitation, track density and population density. VPD×species and visitation×species terms let slopes differ among species. Four structures were compared with AIC and likelihood-ratio tests, and the model with both interactions was best supported (AIC 1008.4 against 1041.2 for shared slopes).

Checks and inference

Convergence and the Hessian were checked, and DHARMa residuals (1,000 simulations) tested dispersion, uniformity and patterns by species. Species slopes were estimated with emmeans and compared with Tukey adjustment. Predictions are percentages with 95% confidence intervals for a typical creek (random effects set to zero). The other predictors were held at their means:

  • VPD mean: 1.57
  • visit_rate_1000_per_yr mean: 6.71
  • track_density mean: 6.89
  • pop_density mean: 6.14
Table 2. Study variables.
Variable Code Role Definition and units
Individuals showing signs n_infected Response variable Number examined with visible signs attributed to chytrid
Individuals examined n_frogs_sampled Binomial denominator Total examined for signs
Species species Categorical predictor Waterfall frog, common mistfrog or cane toad
Atmospheric drying demand VPD Continuous predictor Mean annual vapour pressure deficit; kPa; higher values indicate drier air
Annual visitation visit_rate_1000_per_yr Continuous predictor Average annual visitor total; thousands/year
Walking-track density track_density Adjustment predictor Track length per area within 500 m of the sampling site; km/km²
Focal-species density pop_density Adjustment predictor Estimated density of the particular sampled species; individuals/100 m of stream
Park code NP Categorical identifier De-identified park identifier; also the dataset join key
Creek group ID creek_uid Categorical identifier Categorical identifier for creek within park

Model evaluation

Click on a model name to expand and view the DHARMa analysis:

M1 Intercept-only binomial GLM: dispersion 7.20, p <0.001

M2 Binomial GLM with fixed predictors: dispersion 2.90, p <0.001

M3 Binomial GLM with structure: dispersion 1.54, p <0.001

M4 Beta-binomial GLM without structure: dispersion 0.94, p 0.62

M5 Beta-binomial GLMM with random intercepts - selected: dispersion 0.96, p 0.86

Results and ecological interpretation

Q1: Species differences

Across 75 creeks per species, observed visible chytrid signs were recorded in: - 37.6% of common mistfrogs (548 of 1,458) - 20.2% of waterfall frogs (268 of 1,324) and - 17.1% of cane toads (326 of 1,909) (Fig. 1)

When other factors were held at their mean, the model mirrored this order: - 30% of common mistfrogs (95% Confidence Intervals 22–40), - 16% of waterfall frogs (10–24) - 9% cane toads(5–14)

Mistfrogs had 2.3 times the odds of showing chytrid signs compared with waterfall frogs (p = 0.006) and 4.6 odds compared to cane toads (p < 0.001). Waterfall frogs and cane toads could not be separated (odds ratio 2.0, p = 0.14). Because the species respond differently to VPD and visitation, this order applies to average conditions only.

Table 3. Model-adjusted probability of visible signs by species.
Species Adjusted probability (%) 95% CI (%)
Common mistfrog 30.1 22.1 to 39.6
Waterfall frog 15.9 9.9 to 24.4
Cane toad 8.6 5.2 to 14.2
Table 4. Pairwise species comparisons (odds ratios, Tukey-adjusted).
Comparison Odds ratio 95% CI Adjusted p
Litoria rheocola / Litoria nannotis 2.29 1.22 to 4.28 0.0055
Litoria rheocola / Rhinella marina 4.56 2.29 to 9.07 <0.001
Litoria nannotis / Rhinella marina 1.99 0.85 to 4.66 0.1383
Exploratory pairs plots by species
Pairs plot: common mistfrog (Litoria rheocola).

Pairs plot: common mistfrog (Litoria rheocola).

Pairs plot: waterfall frog (Litoria nannotis).

Pairs plot: waterfall frog (Litoria nannotis).

Pairs plot: cane toad (Rhinella marina).

Pairs plot: cane toad (Rhinella marina).

p_box_species_signs - TBC

Figure X: insert caption here

Q2: Dryness (VPD)

The VPD pattern differed among species (χ² = 25.7, 2 df, p < 0.001). In both native frogs, the probability of visible chytrid signs fell as VPD rose, with negative slope estimates of -1.27 per kPa (95% CI -2.13 to -0.40) for the mistfrog and -2.18 (-3.26 to -1.11) for the waterfall frog. Across the observed 0.74–2.61 kPa, predicted signs fell from 55% to 10% in mistfrogs and from 53% to 2% in waterfall frogs (Fig. 2A). Cane toads showed no clear trend (+0.53, -0.28 to 1.33; predicted 6% to 14%). Associations for the two native frogs could not be distinguished (p = 0.23), but each differed from cane toads (p < 0.001).

Q3: Visitation

The visitation trend also differed among species (χ² = 25.1, 2 df, p < 0.001). Per each 1,000 more visitors a year, log-odds of visible chytrid signs rose by 0.23 (0.13 to 0.34) in mistfrogs and 0.28 (0.17 to 0.39) in waterfall frogs, but not in cane toads (−0.02, −0.12 to 0.09). With 0.6–14.9 thousand visitors a year, predicted visible signs of chytrid increased from 9% to 74% in mistfrogs and from 3% to 65% in waterfall frogs, while cane toads maintained 8–10% (Fig. 2B). Only two parks had over 13 thousand visitors a year, so curve peaks are the least certain.

...

Figure X: insert caption here

Other predictors

Higher population density of the focal species was positively associated with more signs of chytrid (0.12 log-odds, 0.04 to 0.20). Track density as uncertain (0.09, -0.002 to 0.18). Interpretation Lower infection risk in mistfrog habitats has been linked to warmer, drier conditions after cyclone canopy loss, which aligns with this negative association of VPD with infection (Roznik et al., 2015 ). However, this is not evidence of infection mechanisms in these parks. The visitation results also align with human-driven hypotheses, but this is beyond this study. Adult cane toads are rarely infected by chytrid, fitting their flat patterns (Brannelly et al. 2018). Equally, higher prevalence of visible infection signs may not mean higher mortality risk as infected mistfrogs can survive (Sapsford et al., 2015).

## # A tibble: 45 × 5
##    NP    species            VPD visit_rate_1000_per_yr pooled_percent
##    <fct> <fct>            <dbl>                  <dbl>          <dbl>
##  1 NP_A  Litoria rheocola  1.85                   8.34          17.6 
##  2 NP_A  Litoria nannotis  1.85                   8.34           1.10
##  3 NP_A  Rhinella marina   1.85                   8.34          25.7 
##  4 NP_B  Litoria rheocola  2.61                   2.38           0   
##  5 NP_B  Litoria nannotis  2.61                   2.38           0   
##  6 NP_B  Rhinella marina   2.61                   2.38          11.9 
##  7 NP_C  Litoria rheocola  1.36                  13.0           39.7 
##  8 NP_C  Litoria nannotis  1.36                  13.0           24.7 
##  9 NP_C  Rhinella marina   1.36                  13.0            2.17
## 10 NP_D  Litoria rheocola  1.33                  10.1           43.0 
## # ℹ 35 more rows

Figure X: insert caption here

...

Figure X: insert caption here

...

Figure X: insert caption here

Boundary

These patterns describe observed visible chytrid signs from 15 parks over summer 2023/2024, therefore do not confirm infection or population decline. Species differences are conditional to the stated average conditions.


Limitations

Accurate evidence

Using visible signs of infection as a response measure cannot accurately estimate true infection, fungal load or attributable mortality. Laboratory qPCR testing is required for accurate diagnostics to strengthen study inference, support more robust conclusions and increase the validity of management recommendations (Boyle et al., 2004; Wildlife Health Australia, 2025).

Bias

QPWS provided no background on animal ethics, swabbing protocols or capture, survey and diagnostic methods. Consequently, observed interspecific differences in chytrid signs may reflect capture or detection bias rather than actual disease prevalence, potentially misrepresenting more conspicuous species and underrepresenting cryptic species.

Cane toads are also an introduced species, so incomparable to the two native frogs as an infection host. Without long-term mortality or population data, it is impossible to distinguish severe infection impacts or asymptomatic reservoir carriers. Site selection methodology was also unknown, further risking bias or being unrepresentative.

Reduced variable pool

Spatial variation was similarly obscured by anonymised park predictors and unnamed creeks, which omitted critical site-level variables including elevation, habitat, canopy density, temperature and rainfall. This lack of spatial resolution limits ecological inference, hinders comparison with established microclimate studies, while introducing potential confounding variables and sampling inconsistencies.

Across the 15 unnamed national parks, the 225 repeated creek and species observations were not independent climate or visitation replicates, with VPD and visitation data comprising 15 park-level averages each, so site level contamination can’t be identified. Additionally, deriving VPD averages from entire national parks - each containing diverse ecosystems and microclimates - erases the fine-scale granularity required to identify frog refugia or aquatic connectivity (Sapsford et al. 2013), critical for targeted conservation interventions.

Temporal snapshot

Finally, summer typically represents the season with lowest Bd infections: research on Wet Tropics common mistfrogs highlight prevalence peaks during cooler winter months, so percentages here shouldn’t be read as annual averages (Sapsford et al. 2013). Restricted to one summer, the dataset cannot capture seasonal dynamics, population trends or post-chytrid recovery.

Mean park-wide annual visitation values similarly obscure immense spatial and temporal variation. Detail on peak visitation periods, specific area access and visitor restrictions would facilitate more targeted investigations into anthropogenic spread - to ultimately inform better practical biosecurity solutions. All results are also associations with observational data of visible chytrid signs - not confirmed diagnosis.


Management: precaution, prioritise, protect

Chytridiomycosis management has two levers: - reducing Bd in the environment or on hosts, and strengthening the capacity of populations to buffer its effects (Scheele et al., 2019). With Bd endemic, the aim is coexistence rather than eradication, as recovered upland rainforest populations demonstrate (Hollanders et al., 2022).

These results indicate where management should begin. Both native frogs showed fewer visible signs in parks with higher VPD and more signs in parks with higher visitation, so attention is best directed to lower-VPD, higher-visitation locations. Mistfrogs should be prioritised first, given their higher baseline probability of chytrid infection signs. Because the data here centres on associations of visible infection signs from one single summer, the actions below are recommendations, not proven interventions.

Immediate actions

Strengthen biosecurity at higher-visitation parks, starting with an audit of staff, contractor and visitor hygiene to identify gaps. This study cannot show that visitors spread Bd, but the consistent visitation association across both native frogs means that an audit is a proactive step forwards while better evidence is gathered.

The aim should be to limit spread to uninfected creeks, to avoid adding infection pressure, not to keep Bd out of parks where it is already established. Direct surveillance to lower-VPD parks is also paramount, starting with mistfrogs.

Strengthen the evidence

Each limitation above has a direct remedy: qPCR swabs can confirm infection; monthly sampling, especially during winter prevalence peaks, captures seasonal dynamics (Sapsford et al., 2013). Sampling several creeks per park may show infection variation at fine-scales, a first step to uncovering refugia (Sasso et al., 2024).

Incorporating site-level temperature and humidity data can enable testing if park-scale VPD reflects conditions frogs need to survive. Further investigation into visitation patterns (routes, creek and track use, geographic concentrations, seasonality and access points) can uncover where and when impacts occur. Such extensive research may take years: biosecurity strategies can tackle spread in the meantime.

Recommendations: what, who, why, when

Table X. Management recommendations: what, who, why, when.
Priority Action Evidence Who and when
Immediate Target surveillance at lower-VPD parks, mistfrogs first Signs fell as VPD rose for both native frogs (Q2, Fig. 2A); mistfrogs had the highest baseline (Q1) QPWS rangers and tea; monthly surveys ASAP, then review annually.
Immediate Audit and tighten biosecurity at higher-visitation parks Chytrid signs rose increased visitation for both frogs (Q3, Fig. 2B) QPWS operations; before next summer
Mid term Confirm infections with qPCR, sample in winter, survey multiple creeks per park Visible signs are not confirmed infection, also summer only sampling (Limitations) Monitoring team with research partners; next survey
Mid term Add loggers and visitor-route data VPD and visitation are park averages, from 15 total values (Limitations) Research partners with rangers; within a year
Long term Trial manmade thermal shelters, refuge protection and probiotics Not tested yet Research partners; multi-year

This analysis does not support a visitor threshold, canopy clearance or cane toad removal. It does support clear direction for initial efforts: surveillance where native frogs showed the most signs, biosecurity where visitation is highest, and better data before committing to large interventions.


\[ \text{Proportion with visible signs} = \frac{\text{Number with visible signs}}{\text{Number examined}} \]

Analysis used counts of amphibians with and without visible signs, alongside total number examined of amphibians observed per sample site.


References

A list of 10-15 references go here


Appendix

Model assessment

[insert R code here]

Acknowledgements