#############################################################################
#############################################################################
## FIGURE S9 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 S9 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)

## should model evaluation be plotted?
ModelEval=FALSE

## prepare figure window
windows(width = 4, height = 4)
layout(matrix(1:1, 1, 1, byrow = TRUE))
par(mar=c(4.5,5.5,1.5,0.5),las=1,cex=1,mgp=c(3.4, 1, 0))


###################################
##### lme model 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")
}
########################################################


###############################
### plot beta vs. Q and l
##############################


colors <- rev(cividis(max(round(my_data$xl*10)-min(round(my_data$xl*10))+1))[round(my_data$xl*10)-min(round(my_data$xl*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
l_values <- c(10, 30, 90)

# Colours for prediction lines
line_cols <- cividis(30)[c(25, 15, 5)]

# Plot observed data
plot(
  y ~ xq,
  pch = 1,
  col = colors,
  xaxt = "n",
  xlab = "",
  data = my_data,
  ylab = expression(paste(beta)),
  ylim=c(-7.5,-3)
)

# Model-averaged predictions
for (i in seq_along(h_values)) {
  
  pred_data <- data.frame(
    xq   = xq_seq,
    xl = log10(l_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),
    xh   = mean(my_data$xh, na.rm = TRUE),
    pH   = mean(my_data$pH, na.rm = TRUE)
  )
  
  pred <- predict(
    AvgModel_beta,
    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))



mtext(expression(paste("Q (L ",s^-1,")")), side=1, line=3)  # Move X-axis label further away

abline(h=-10/3,lty=2)

colorbar.plot(log10(1.6),-4.25, 1:100,horizontal = FALSE, strip.width = 0.1, strip.length = 0.20,col=(cividis(38)))
text(log10(1.8),-3.55,expression(paste("l (cm)")),cex=0.8,col=1)
text(log10(2.6),-3.85,"11",cex=0.8,col=1)
text(log10(2.6),-4.6,"92",cex=0.8,col=1)

text(log10(65),-7.4,"Buoyant rise",font=3)
text(log10(60),-2.0-1.05,"Coalescence",font=3)





