#############################################################################
#############################################################################
## FIGURE 4 and lme models: Bubble size distribution metrics and drivers  
## alpha ... microbubble size distribution spectral slope (sub-Hinze)
## beta ... macrobubble size distribution spectral slope (supra-Hinze)
#############################################################################
#############################################################################

# Creates Figure 4 in
# Klaus, M., Durighetto, N., Khan, A. M., Chatton, E., Öquist, M., Peruzzo, P. and Botter, G. (in revision in "npj Hydrosphere").
# Bubble size spectra reveal distinct scaling patterns and downstream sorting in mountain streams

###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/08/10
###########################################################################################


## load libraries
library(nlme)
library(viridis)
library(MuMIn)
library(dplyr)
library(car)
library(fields)
library(lattice)
library(HLMdiag)

## prepare figure window
windows(width = 8, height = 4)
layout(matrix(1:2, 1, 2, byrow = TRUE))
par(mar=c(4.5,5.5,1.5,0.5),las=1,cex=1,mgp=c(3.4, 1, 0))

## print model evaluation plots?
ModelEval=FALSE


##############################################
##### lme model to predict microbubble spectral slope alpha
##############################################

# organize / rescale variables
xq=log10(DataSpot$Q)
xh=log10(DataSpot$h)
xd=log10(DataSpot$d)
xl=log10(DataSpot$l)
s=as.factor(DataSpot$Site)
c=as.factor(DataSpot$Catchment)
pH=DataSpot$pH
Temp=DataSpot$Temp
xc=log10(DataSpot$EC)

y=DataSpot$alpha


my_data=data.frame(y,xq,xh,xd,xl,s,c,xc,Temp,pH)[which(y>-99999),]

## select random effects
epsmod1 <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~1|c/s,data=my_data)
epsmod2 <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~xd|c/s,data=my_data)
#epsmod3 <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~xl|c/s,data=my_data)
anova(epsmod1,epsmod2)
VarCorr(epsmod2)
## -> random slope improve models, but slope and intercept correlate highly, indicating overfitting. keep simple random intercept model



## select fixed effects
full_model <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~1|c/s,data=my_data, method="ML")
dredge_alpha <- dredge(full_model)



## average best models within dAICc < 2
top_models_alpha <- get.models(dredge_alpha, subset = delta < 2)
AvgModel_alpha <- model.avg(top_models_alpha)

best_single_model_alpha <- top_models_alpha[[1]]



# Extract actual, fitted model objects from the dredge table
top_models_alpha <- get.models(dredge_alpha, subset = delta < 2)

# Extract Marginal and conditional R2 (R2m, R2c) values
r2m_values_alpha <- sapply(top_models_alpha, function(m) r.squaredGLMM(m)[1, "R2m"])
r2c_values_alpha <- sapply(top_models_alpha, function(m) r.squaredGLMM(m)[1, "R2c"])

# Extract the Akaike weights belonging to these top models 
top_weights_alpha <- subset(dredge_alpha, delta < 2)$weight

# Calculate weighted average R2m
weighted_r2m_alpha <- sum(r2m_values_alpha * top_weights_alpha) / sum(top_weights_alpha)
weighted_r2c_alpha <- sum(r2c_values_alpha * top_weights_alpha) / sum(top_weights_alpha)



########################################################
# model evaluation
if(ModelEval==TRUE){
  E2 <- resid(best_single_model_alpha , type = "normalized")
  
  xyplot(E2 ~ xd | s,
         data = my_data, ylab = "Residuals",
         xlab = "d",
         panel = function(x,y){
           panel.grid(h = -1, v = 2)
           panel.points(x, y, col = 1)
           panel.loess(x, y, span = 0.5, col = 1,lwd=2)})
  
  boxplot(E2 ~ xd, data = my_data,ylim = c(-3, 3))
  boxplot(E2 ~ xq, data = my_data,ylim = c(-3, 3))
  boxplot(E2 ~ xh, data = my_data,ylim = c(-3, 3))
  
  F2 <- fitted(best_single_model_alpha)
  plot(x = F2, y = E2, xlab = "Fitted values")
  plot(x = my_data$xd, y = E2, xlab = "Fitted values")
  plot(x = my_data$xh, y = E2, xlab = "Fitted values")
  plot(x = my_data$xq, y = E2, xlab = "Fitted values")
  
  ## Cook's Distance to identify influential points
  infl <- hlm_influence(best_single_model_alpha)
  infl_sorted <- infl[order(infl$cooksd, decreasing = TRUE), ]
  # View Cook's Distance
  dotplot_diag(infl$cooksd, name = "cooks.distance")
}
########################################################


########################
### alpha vs. h and Q
########################

colors <- plasma(max(round(my_data$xh*10)-min(round(my_data$xh*10))+1))[round(my_data$xh*10)-min(round(my_data$xh*10))+1]


# Create a sequence of Q values for prediction
xq_seq <- seq(min(my_data$xq), max(my_data$xq), length.out = 100)




# Temperatures for prediction
h_values <- c(5, 25, 70)

# Colours for prediction lines
line_cols <- plasma(30)[c(5, 15, 25)]

# Plot observed data
plot(
  y ~ xq,
  pch = 1,
  col = colors,
  xaxt = "n",
  xlab = "",
  data = my_data,
  ylab = expression(paste(alpha))
)

# Model-averaged predictions
for (i in seq_along(h_values)) {
  
  pred_data <- data.frame(
    xq   = xq_seq,
    xh = log10(h_values[i]),
    xc   = mean(my_data$xc, na.rm = TRUE),
    Temp   = mean(my_data$Temp, na.rm = TRUE),
    xd   = mean(my_data$xd, na.rm = TRUE),
    xl   = mean(my_data$xl, na.rm = TRUE),
    pH   = mean(my_data$pH, na.rm = TRUE)
  )
  
  pred <- predict(
    AvgModel_alpha,
    newdata = pred_data,
    level = 0
  )
  
  lines(
    xq_seq,
    pred,
    col = line_cols[i],
    lwd = 2
  )
}


axis(side=1,at=(log10(c(seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100)))),labels=NA)
axis(side=1,at=(log10(c(0.001,0.01,0.1,1,10,100,1000))),lwd=2,labels=c(0.001,0.01,0.1,1,10,100,1000))

text(log10(0.2),2.9,"A)",xpd=TRUE,font=2)

colorbar.plot(log10(70),1.3, 1:100,horizontal = FALSE, strip.width = 0.1, strip.length = 0.22,col=(plasma(38)))
text(log10(80),2.7,"h (cm)",cex=0.8,col=1)
text(log10(120),2,"72",cex=0.8,col=1)
text(log10(120),0.6,"5",cex=0.8,col=1)

mtext(expression(paste("Q (L ",s^-1,")")), side=1, line=3)  # Move X-axis label further away

abline(h=-3/2,lty=2)

text(log10(2.7),-4.7,"Buoyant rise",font=3)
text(log10(2.9),2.7,"Coalescence",font=3)




###################################
### lme model to predict macrobubble spectral slope beta
###################################


y=DataSpot$betaL

my_data=data.frame(y,xq,xh,xd,xl,s,c,xc,Temp,pH)[which(DataSpot$Whitecap=="yes" & y>-99999),]

## select random effects; xd effect does not converge
epsmod1 <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~1|c/s,data=my_data)
#epsmod2 <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~xd|c/s,data=my_data) ## model does not converge
#epsmod3 <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~xl|c/s,data=my_data)

## random slope model does not converge


## select fixed effects
full_model <- lme(y~xq+xd+xh+xl+xc+Temp+pH,random=~1|c/s,data=my_data, method="ML")
dredge_beta <- dredge(full_model)


## average best models within dAICc < 2
top_models_beta <- get.models(dredge_beta, subset = delta < 2)
AvgModel_beta <- model.avg(top_models_beta)

best_single_model_beta <- top_models_beta[[1]]


# Extract actual, fitted model objects from the dredge table
top_models_beta <- get.models(dredge_beta, subset = delta < 2)

# Extract Marginal and conditional R2 (R2m, R2c) values
r2m_values_beta <- sapply(top_models_beta, function(m) r.squaredGLMM(m)[1, "R2m"])
r2c_values_beta <- sapply(top_models_beta, function(m) r.squaredGLMM(m)[1, "R2c"])

# Extract the Akaike weights belonging to these top models 
top_weights_beta <- subset(dredge_beta, delta < 2)$weight

# Calculate weighted average R2m
weighted_r2m_beta <- sum(r2m_values_beta * top_weights_beta) / sum(top_weights_beta)
weighted_r2c_beta <- sum(r2c_values_beta * top_weights_beta) / sum(top_weights_beta)



########################################################
# model evaluation
if(ModelEval==TRUE){
  E2 <- resid(best_single_model_beta , type = "normalized")
  
  xyplot(E2 ~ xd | s,
         data = my_data, ylab = "Residuals",
         xlab = "d",
         panel = function(x,y){
           panel.grid(h = -1, v = 2)
           panel.points(x, y, col = 1)
           panel.loess(x, y, span = 0.5, col = 1,lwd=2)})
  
  boxplot(E2 ~ xd, data = my_data,ylim = c(-3, 3))
  boxplot(E2 ~ xq, data = my_data,ylim = c(-3, 3))
  boxplot(E2 ~ xh, data = my_data,ylim = c(-3, 3))
  
  F2 <- fitted(best_single_model_beta)
  plot(x = F2, y = E2, xlab = "Fitted values")
  plot(x = my_data$xd, y = E2, xlab = "Fitted values")
  plot(x = my_data$xh, y = E2, xlab = "Fitted values")
  plot(x = my_data$xq, y = E2, xlab = "Fitted values")
  
  ## Cook's Distance to identify influential points
  infl <- hlm_influence(best_single_model_beta)
  infl_sorted <- infl[order(infl$cooksd, decreasing = TRUE), ]
  # View Cook's Distance
  dotplot_diag(infl$cooksd, name = "cooks.distance")
}
########################################################


########################
### BETA vs. h and d
########################

colors <- plasma(max(round(my_data$xh*10)-min(round(my_data$xh*10))+1))[round(my_data$xh*10)-min(round(my_data$xh*10))+1]


# Mean water depth per site
my_data <- my_data %>%
  group_by(s) %>%
  mutate(site_mean_xl = mean(xl, na.rm = TRUE)) %>%
  ungroup()


plot(
  y ~ xd,
  pch = 1,
  col = colors,
  xaxt = "n",
  xlab = "",
  data = my_data,
  ylab = expression(paste(beta)),
  ylim = c(-7.5, -3)
)

# Unique sites
sites <- unique(my_data$s)

for (i in seq_along(sites)) {
  
  site_data <- subset(my_data, s == sites[i])
  
  # Range of xd for this site
  x_seq <- seq(
    min(site_data$xd, na.rm = TRUE),
    max(site_data$xd, na.rm = TRUE),
    length.out = 100
  )
  
  # Prediction data
  newdata <- data.frame(
    xd   = x_seq,
    c    = unique(site_data$c),
    s    = sites[i],
    xq   = unique(site_data$xq),
    xh   = unique(site_data$xh),
    xl   = unique(site_data$site_mean_xl),
    xc   = unique(site_data$xc),
    Temp = unique(site_data$Temp),
    pH   = unique(site_data$pH)
  )
  
  # Model-averaged, site-specific prediction
  pred <- predict(
    AvgModel_beta,
    newdata = newdata,
    level = 2
  )
  
  lines(
    x_seq,
    pred,
    col = colors[which(my_data$s == sites[i])[1]],
    lwd = 1
  )
}




axis(side=1,at=(log10(c(seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100)))),labels=NA)
axis(side=1,at=(log10(c(0.001,0.01,0.1,1,10,100,1000))),lwd=2,labels=c(0.001,0.01,0.1,1,10,100,1000))


text(log10(1.35),-3,"B)",xpd=TRUE,font=2)

mtext("d (cm)", side=1, line=3)  # Move X-axis label further away

abline(h=-10/3,lty=2)


text(log10(10),-7.3,"Buoyant rise",font=3)
text(log10(11),-2.0-1.05,"Coalescence",font=3)



