########################################################################################################################
########################################################################################################################
## FIGURE 5 and lme models: Apparent Hinze scale (aH) and apparent critical Weber number (Wc)
## aH is derived from breakpoint in macrobubble size spectrum
## Wc is calculated from apparent aH and turbulent kinetic energy dissipation rate derived from large-Eddy scaling
########################################################################################################################
########################################################################################################################

# Creates Figure 5 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/20
###########################################################################################

## 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,0.5,0.55),las=1,cex=1,mgp=c(3.6, 1, 0))

## print model evaluation plots?
ModelEval=FALSE


##############################################
##### lme model tp predict apparent Hinze scale (aH_app)
##############################################

# 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=log10(DataSpot$aH_app)

my_data=data.frame(y,xq,xh,xd,xl,s,c,xc,Temp,pH)[which(DataSpot$Whitecap=="yes" & y>-99999 & DataSpot$betaL < DataSpot$betaS),]

## select random effects (does not converge with xd as random slope)
epsmod1 <- lme(y~xq+xd+xh+xl+xc+Temp,random=~1|c/s,data=my_data)
#epsmod2 <- lme(y~xq+xd+xh+xl+xc+Temp,random=~xd|c/s,data=my_data)
#epsmod3 <- lme(y~xq+xd+xh+xl+xc+Temp,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_aHemp <- dredge(full_model)


## average best models within dAICc < 2
top_models_aHemp <- get.models(dredge_aHemp, subset = delta < 2)
AvgModel_aHemp <- model.avg(top_models_aHemp)

best_single_model_aHemp <- top_models_aHemp[[1]]

# Extract actual, fitted model objects from the dredge table
top_models_aHemp <- get.models(dredge_aHemp, subset = delta < 2)

# Extract Marginal and conditional R2 (R2m, R2c) values
r2m_values_aHemp <- sapply(top_models_aHemp, function(m) r.squaredGLMM(m)[1, "R2m"])
r2c_values_aHemp <- sapply(top_models_aHemp, function(m) r.squaredGLMM(m)[1, "R2c"])

# Extract the Akaike weights belonging to these top models 
top_weights_aHemp <- subset(dredge_aHemp, delta < 2)$weight

# Calculate weighted average R2m
weighted_r2m_aHemp <- sum(r2m_values_aHemp * top_weights_aHemp) / sum(top_weights_aHemp)
weighted_r2c_aHemp <- sum(r2c_values_aHemp * top_weights_aHemp) / sum(top_weights_aHemp)



########################################################
# model evaluation
if(ModelEval==TRUE){
  E2 <- resid(best_single_model_aHemp , 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_aHemp)
  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_aHemp)
  infl_sorted <- infl[order(infl$cooksd, decreasing = TRUE), ]
  # View Cook's Distance
  dotplot_diag(infl$cooksd, name = "cooks.distance")
}
########################################################



########################
### Hinze vs. h and d
########################


colors <- viridis(max(round(my_data$xq*10)-min(round(my_data$xq*10))+1))[round(my_data$xq*10)-min(round(my_data$xq*10))+1]

plot(y~xd, pch=1,col=colors, yaxt="n", xaxt="n",xlab="",data=my_data,
     ylab=expression(paste("Apparent ",a[H]," (m)")))


# Unique sites
sites <- unique(my_data$s)

for (i in seq_along(sites)) {
  
  site_data <- subset(my_data, s == sites[i])
  
  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   = mean(site_data$xl),
    xc   = unique(site_data$xc),
    Temp = unique(site_data$Temp),
    pH   = unique(site_data$pH)
  )
  
  # Model-averaged prediction
  pred <- predict(
    AvgModel_aHemp,
    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))



axis(side=2,at=(log10(c(seq(0.001,0.01,0.001),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=2,at=(log10(c(0.0001,0.001,0.003,0.01,0.1,1,10,100,1000))),lwd=2,labels=c(0.0001,0.001,0.003,0.01,0.1,1,10,100,1000))



colorbar.plot(log10(6),log10(0.0131), 1:100,horizontal = FALSE, strip.width = 0.1, strip.length = 0.25,col=(viridis(38)))
text(log10(7.7),log10(0.0185),expression(paste("Q (L ",s^-1,")")),cex=0.8,col=1)
text(log10(9.3),log10(0.0158),"144",cex=0.8,col=1)
text(log10(8.5),log10(0.011),"1",cex=0.8,col=1)

mtext("d (cm)", side=1, line=3)  # Move X-axis label further away


text(log10(1.35),log10(0.0186),"A)",xpd=TRUE,font=2)


##############################################
##### lme model tp predict apparent critical Weber number 
##############################################

y=log10(DataSpot$Wec_app)



## selection
my_data=data.frame(y,xq,xh,xd,xl,s,c,xc,Temp,pH)[which(DataSpot$Whitecap=="yes" & y>-99999 & DataSpot$betaL < DataSpot$betaS),]

## select random effects (model 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)
#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_Wec <- dredge(full_model)


## average best models within dAICc < 2
top_models_Wec <- get.models(dredge_Wec, subset = delta < 2)
AvgModel_Wec <- model.avg(top_models_Wec)

best_single_model_Wec <- top_models_Wec[[1]]


# Extract actual, fitted model objects from the dredge table
top_models_Wec <- get.models(dredge_Wec, subset = delta < 2)

# Extract Marginal and conditional R2 (R2m, R2c) values
r2m_values_Wec <- sapply(top_models_Wec, function(m) r.squaredGLMM(m)[1, "R2m"])
r2c_values_Wec <- sapply(top_models_Wec, function(m) r.squaredGLMM(m)[1, "R2c"])

# Extract the Akaike weights belonging to these top models 
top_weights_Wec <- subset(dredge_Wec, delta < 2)$weight

# Calculate weighted average R2m
weighted_r2m_Wec <- sum(r2m_values_Wec * top_weights_Wec) / sum(top_weights_Wec)
weighted_r2c_Wec <- sum(r2c_values_Wec * top_weights_Wec) / sum(top_weights_Wec)




########################################################
# model evaluation
if(ModelEval==TRUE){
  E2 <- resid(best_single_model_Wec , 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_Wec)
  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_Wec)
  infl_sorted <- infl[order(infl$cooksd, decreasing = TRUE), ]
  # View Cook's Distance
  dotplot_diag(infl$cooksd, name = "cooks.distance")
}
########################################################




colors <- viridis(max(round(my_data$xq*10)-min(round(my_data$xq*10))+1))[round(my_data$xq*10)-min(round(my_data$xq*10))+1]


plot(my_data$y~my_data$xd, pch=1,col=colors, xaxt="n",yaxt="n",xlab="",
     ylab=expression(paste("Apparent ",We[c])))


for (i in seq_along(sites)) {
  
  site_data <- subset(my_data, s == sites[i])
  
  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   = mean(site_data$xl),
    xc   = unique(site_data$xc),
    Temp = unique(site_data$Temp),
    pH   = unique(site_data$pH)
  )
  
  # Model-averaged prediction
  pred <- predict(
    AvgModel_Wec,
    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))

axis(side=2,at=(log10(c(seq(0.001,0.01,0.001),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=2,at=(log10(c(0.0001,0.001,0.01,0.1,1,10,100,1000))),lwd=2,labels=c(0.0001,0.001,0.01,0.1,1,10,100,1000))

text(log10(1.35),log10(20),"B)",xpd=TRUE,font=2)

mtext("d (cm)", side=1, line=3)  # Move X-axis label further away








