
#############################################################################################
#############################################################################################
### Figure S13: Plot 
### - modelled bubble size distribution after passing a fictive pool
### - modelled vs. measured bubble size spectral slope for microbubbles 
#############################################################################################
#############################################################################################

# Creates Figure S13 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 helper functions

library(viridis)
library(nlme)
library(MuMIn)

source("Code/0_Functions/FUNCTION_FitMicrobubbleSpectrum.R")




## make figure

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))

## select only sites in France and Italy (for which N2 data needed as model inputs was available)
selout <- which(match(DataModBub$Site,DataSpot$Site[1:95])>0)

## generate theoretical bubble number spectrum with -3/2 slope
Na_mod <- 10^8*(DataModBub$r0*10^6)^(-3/2)
## modelled bubble radius
a_mod <- DataModBub$rt



plot(log10(DataModBub$r0[selout]*10^6),log10(Na_mod[selout]),type="b",ylim=log10(c(4*10^4,0.3*10^7)),xlim=log10(c(2,100)*10^-6),xaxt="n",yaxt="n",pch=2,col=0,
     ylab=expression(paste("N(a)  (",m^-3,mu,m^-1,")")),
     xlab=expression(paste("a (",mu,"m)")) )
#points(log10(a_mod[selout]),log10(Na_mod[selout]),pch=1,col=rgb(0,0,0,0.2))
#points(log10(DataModBub$r0[selout]*10^-6),log10(Na_mod[selout]),type="l",pch=2,col=4,lwd=3)

axis(side=1,at=log10(c(seq(1,10,1),seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000),seq(10000,100000,10000))*10^-6),labels=NA)
axis(side=1,at=log10(c(0.1,1,10,100,1000,10000,1000000)*10^-6),lwd=2, labels=format(c(0.1,1,10,100,1000,10000,1000000), scientific=TRUE))

axis(side=2,at=log10(c(seq(1,10,1),seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000),seq(10000,100000,10000),seq(100000,1000000,100000),seq(1000000,10000000,1000000),seq(10000000,100000000,10000000))),ylab="",labels=NA)
axis(side=2,at=log10(c(10^10,10^9,10^8,10^7,10^6,10^5,10^4,10^3,10^2,10^1,10^0,10^-1,10^-2,10^-3,10^-4,10^-5,10^-6,10^-7,10^-8,10^-9,10^-10)),lwd=2,labels=format(c(10^10,10^9,10^8,10^7,10^6,10^5,10^4,10^3,10^2,10^1,10^0,10^-1,10^-2,10^-3,10^-4,10^-5,10^-6,10^-7,10^-8,10^-9,10^-10), scientific=TRUE))



## calculate spectral slope alpha50


DataModBub_Site_Dist <- paste0(DataModBub$Site,"_",DataModBub$d)

alphaABS_mod <- matrix(NA,length(unique(DataModBub_Site_Dist )),4)
alphaABS50s_mod <- matrix(NA,length(unique(DataModBub_Site_Dist )),4)
alphaABS50l_mod <- matrix(NA,length(unique(DataModBub_Site_Dist )),4)
R2ABS_mod <- matrix(NA,length(unique(DataModBub_Site_Dist )),1)
R2ABS50s_mod <- matrix(NA,length(unique(DataModBub_Site_Dist )),1)
R2ABS50l_mod <- matrix(NA,length(unique(DataModBub_Site_Dist )),1)



## match travel time to DataModBub file
idmDataModBub <- match(paste0(DataModBub$Site,"_",DataModBub$d),paste0(DataSpot$Site,"_",DataSpot$d))

colors <- inferno(max(round(log10(DataSpot$tt[idmDataModBub][selout])*100)-min(round(log10(DataSpot$tt[idmDataModBub][selout])*100))+1))[round(log10(DataSpot$tt[idmDataModBub][selout])*100)-min(round(log10(DataSpot$tt[idmDataModBub][selout])*100))+1]


## loop through all sites
for (i in 1:length(unique(DataModBub_Site_Dist[selout] ))){
  
  idr <- which(DataModBub_Site_Dist[selout]==unique(DataModBub_Site_Dist[selout])[i])
  
  new_col <- adjustcolor(colors[idr], alpha.f = 0.2)
  
  # linear regression
  yy <- log10(Na_mod[selout][idr])
  xx <- log10(a_mod[selout][idr])
  yy50s = log10(Na_mod[selout][idr])[a_mod[selout][idr]<50*10^-6]
  xx50s = log10(a_mod[selout][idr])[a_mod[selout][idr]<50*10^-6]
  yy50l = log10(Na_mod[selout][idr])[a_mod[selout][idr]>=50*10^-6]
  xx50l = log10(a_mod[selout][idr])[a_mod[selout][idr]>=50*10^-6]

  points(yy~xx,col=  new_col,pch=1)
  
  ## fit linear models, use robust lm for datasubsets because of small number of observations
  fit <- tryCatch(lm(yy ~ xx), error = function(e) NA)
  fit50s <- tryCatch(lm(yy50s ~ xx50s), error = function(e) NA)
  fit50l <- tryCatch(lm(yy50l ~ xx50l), error = function(e) NA)
  
  if(length(which(yy50s>-99999 & xx50s>-99999))>1){
    x_range <- seq(min(xx50s, na.rm = TRUE), max(xx50s, na.rm = TRUE), length.out = 100)
    y_pred <- predict(fit50s, newdata = data.frame(xx50s = x_range))
    lines(x_range, y_pred, col = new_col)
  }
  if(length(which(yy50l>-99999 & xx50l>-99999))>1){
  }
  
  alphaABS_mod[i,] <- tryCatch(tryCatch(summary(fit)$coefficients[2,], error = function(e) c(fit$coefficients[2],rep(NA,3))), error = function(e) NA)
  alphaABS50s_mod[i,] <- tryCatch(tryCatch(summary(fit50s)$coefficients[2,], error = function(e) c(fit50s$coefficients[2],rep(NA,3))), error = function(e) NA)
  alphaABS50l_mod[i,] <- tryCatch(tryCatch(summary(fit50l)$coefficients[2,], error = function(e) c(fit50l$coefficients[2],rep(NA,3))), error = function(e) NA)
  R2ABS_mod[i] <- if(length(na.omit(xx))==0){NA}else{ tryCatch(summary(fit)$r.squared, error = function(e) NA) }
  R2ABS50s_mod[i] <- if(length(na.omit(xx50s))==0){NA}else{ tryCatch(summary(fit50s)$r.squared, error = function(e) NA) }
  R2ABS50l_mod[i] <- if(length(na.omit(xx50l))==0){NA}else{ tryCatch(summary(fit50l)$r.squared, error = function(e) NA) }
  

}

text(log10(0.4*10^-6),log10(3*10^6),"A)",xpd=TRUE,font=2)

text(-3.3,4.5,"Expansion",font=3,srt=-47)
text(-3.3,3.5,"Contraction",font=3,srt=-47)


abline(a = -1, b = -1.5, lty=2)

clip(-4.5, -4.1, 0, 10)
abline(a = -0.5, b = -1.5, lwd = 2)
text(-4.2,6.05,"-3/2",font=2,col="grey30")



#########################################################
### inset: proportion of bubbles dissolved 
#########################################################
inset=TRUE ## only one site shows dissolution of the smallest bubble size class, so no need for a graph on this

if(inset==TRUE){
#DataModBub[selout,1:7][438:449,]
  #DataModBub[selout,1:7][230:250,]
  #DataModBub[selout,1:7][which(DataModBub$time[selout]>20),]
  
  DataModBub[which(DataModBub$Tdiss[selout]>0 & is.na(DataModBub$t[selout])),]
  
  
ndiss <- hist(DataModBub$r0[selout][which(DataModBub$Tdiss[selout]>0 & is.na(DataModBub$t[selout]))]*10^6,breaks=c(6,12,18,24,29,35,41,47,400000),plot=FALSE)


# Add inset (position defined in normalized coordinates: 0–1)


op <- par(no.readonly = TRUE)


par(fig = c(0.14, 0.43, 0.2, 0.6), new = TRUE, mar = c(2,3.5,1,1),mgp=c(2.4, 1, 0),cex=0.8)
barx <- barplot(
  ndiss$counts / 95,
  ylab = expression(paste(N[diss](a), ":", N[tot](a))),
  names.arg = c(12,18,24,29,35,41,47,">47"),xaxt="n")
box()
text(barx,-0.02,c(12,18,24,29,35,41,47,">47"),xpd=TRUE,cex=0.8)

par(op)
}


################################################################################################################
#### compare modelled and measured alpha, only for FRIT for which we have N2 data and model is reliable (1:95)
################################################################################################################


par(mfg = c(1, 2))




xt <- log10(DataSpot$tt[1:95])
y=alphaABS50s_mod[1:95,1]
x=DataSpot$alpha50[1:95]
xd=log10(DataSpot$d[1:95])
s=DataSpot$Site[1:95]

colors <- inferno(max(round(log10(DataSpot$tt[1:95])*100)-min(round(log10(DataSpot$tt[1:95])*100))+1))[round(log10(DataSpot$tt[1:95])*100)-min(round(log10(DataSpot$tt[1:95])*100))+1]

## linear mixed effects model to compare modelled and measured microbubble size spectral slope
my_data=data.frame(y,x,xd,xt,s,colors)[which(y>-9999 & x>-9999),]
modalphaABS50s_mod <- lme(y~x,random=~1|s,data=my_data)

## model output
summary(modalphaABS50s_mod)
r.squaredGLMM(modalphaABS50s_mod)



plot(y~x,col=colors[1:95],pch=1,xlab=expression(paste("measured ",alpha['<50'])),
     ylab=expression(paste("modelled ",alpha['<50'])),ylim=c(-1.6,-0.5))

for (i in seq_along(my_data$s)) {
  site_data <- subset(my_data, my_data$s == my_data$s[i])  # Data for this site
  x_seq <- seq(min(site_data$x), max(site_data$x), length.out = 100)  # X range
  pred <- predict(modalphaABS50s_mod, newdata = data.frame(x = x_seq, s = my_data$s[i]), level = 1)  # Predictions
  
  lines(x_seq, pred, col = my_data$colors[i], lwd = 1)  # Add line
}



text(-7.5,-0.5,"B)",xpd=TRUE,font=2)


abline(v=-1.5,lty=2)
abline(h=-1.5,lty=2)

text(-1,-1.42,"Contraction",font=3)
text(-1,-1.57,"Expansion",font=3)


text(log10(2.4),log10(8.9*10^5),"d (cm)",xpd=TRUE,cex=0.8)

# range of travel times (for plotting colorbar legend)


colorbar.plot(-5.3,-0.24-0.5, 1:100,horizontal = FALSE, strip.width = 0.1, strip.length = 0.25,col=((inferno(38))))
text(-5.1,-0.03-0.5,expression(paste(Theta," (s)")),cex=0.8,col=1)
text(-4.6,-0.11-0.5,round(max(DataSpot$tt[1:95]),2),cex=0.8,col=1)
text(-4.6,-0.35-0.5,round(min(DataSpot$tt[1:95]),2),cex=0.8,col=1)






