
#############################################################################
#############################################################################
## FIG 3  Bubble size distributions ######################################
#############################################################################
#############################################################################

# Creates Figure 3 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/04/30
###########################################################################################

library(emdbook)
library(viridis)
library(fields)


## plot literature data
lit=FALSE


windows(width = 8, height = 5)
layout(matrix(1:2, 1, 2, byrow = TRUE))
par(mar=c(4.5,5.5,4.5,0.5),las=1,mgp=c(3.6, 1, 0))


options(scipen = 0)

#############################################################################
#############################################################################
## FIG 3A  ABS-based Microbubble size distribution ###########################
#############################################################################
#############################################################################



# Global range on log scale for colors representing distance to step
log_min <- log10(min(DataSpot$d))
log_max <- log10(max(DataSpot$d))

# Define color palette
ncol <- 200
colors <- inferno(ncol)
map_colors <- function(x, log_min, log_max, palette) {
  lx <- log10(x)
  scaled <- (lx - log_min) / (log_max - log_min)  # 0–1 scaling in log space
  scaled <- pmax(pmin(scaled, 1), 0)
  palette[ceiling(scaled * (length(palette) - 1)) + 1]
}
coll <- map_colors(DataSpot$d, log_min, log_max, colors)



# bubble radius
f <- as.numeric(substr(names(DataMicBub[,grep("^n",names(DataMicBub))]),3,6))
f <- f-mean(DataMicBub$bin,na.rm=TRUE)/2

plot(as.numeric(DataMicBub[10,grep("^n",names(DataMicBub))])~f,log="xy",col=0,xlim=c(11,350),ylim=c(10^0,10^8),xaxt="n",
     ylab=expression(paste("N(a)  (",m^-3,mu,m^-1,")")),
     #ylab="",
     yaxt="n",xlab="")

mtext(expression(paste("a (",mu,"m)")), side=1, line=3)  # Move X-axis label further away




for(i in 1:nrow(DataMicBub)){
  points(as.numeric(DataMicBub[i,grep("^n",names(DataMicBub))])~f,pch=1,col=adjustcolor(coll[i],alpha.f=0.09),cex=0.6)
}




# Add a scatter smooth curve
x=log(rep(f,nrow(DataMicBub[which(DataSpot$d<=0.25*100),])))
y=log(as.vector(t(DataMicBub[which(DataSpot$d<=0.25*100),grep("^n",names(DataMicBub))])))
x <- x[which(y>-9999)]
y <- y[which(y>-9999)]
smoothed <- lowess(x,y, f = 2/3)  # Compute smoothed values
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(10, log_min, log_max, colors), lwd = 2)

x=log(rep(f,nrow(DataMicBub[which(DataSpot$d>0.25*100 & DataSpot$d<=0.75*100),])))
y=log(as.vector(t(DataMicBub[which(DataSpot$d>0.25*100 & DataSpot$d<=0.75*100),grep("^n",names(DataMicBub))])))
x <- x[which(y>-9999)]
y <- y[which(y>-9999)]
smoothed <- lowess(x,y, f = 2/3)  # Compute smoothed values
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(30, log_min, log_max, colors), lwd = 2)

x=log(rep(f,nrow(DataMicBub[which(DataSpot$d>0.75*100 & DataSpot$d<=1.25*100),])))
y=log(as.vector(t(DataMicBub[which(DataSpot$d>0.75*100 & DataSpot$d<=1.25*100),grep("^n",names(DataMicBub))])))
x <- x[which(y>-9999)]
y <- y[which(y>-9999)]
smoothed <- lowess(x,y, f = 2/3)  # Compute smoothed values
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(80, log_min, log_max, colors), lwd = 2)

x=log(rep(f,nrow(DataMicBub[which(DataSpot$d>1.25*100 & DataSpot$d<=2.5*100),])))
y=log(as.vector(t(DataMicBub[which(DataSpot$d>1.25*100 & DataSpot$d<=2.5*100),grep("^n",names(DataMicBub))])))
x <- x[which(y>-9999)]
y <- y[which(y>-9999)]
smoothed <- lowess(x,y, f = 2/3)  # Compute smoothed values
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(160, log_min, log_max, colors), lwd = 2)

x=log(rep(f,nrow(DataMicBub[which(DataSpot$d>2.5*100),])))
y=log(as.vector(t(DataMicBub[which(DataSpot$d>2.5*100),grep("^n",names(DataMicBub))])))
x <- x[which(y>-9999)]
y <- y[which(y>-9999)]
smoothed <- lowess(x,y, f = 2/3)  # Compute smoothed values
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(300, log_min, log_max, colors), lwd = 2)



#### add literature data

## study identifier
Study <- paste0(DataLit[,1],DataLit[,2],"_Fig",DataLit[,3])

for (j in 1:length(unique(Study))){
  jj <-  which(Study==unique(Study)[j])
  # Ling & Pao 1988, WS=10-15m/s, d=5m, lake, low
  if(j==1){
    points(DataLit$BubbleRadius[jj],DataLit$BubbleConc[jj],type="l",col="lightblue3",lty=2)
  }
  # Ling & Pao 1988, Swimming pool
  if(j==2){
    points(DataLit$BubbleRadius[jj],DataLit$BubbleConc[jj],type="l",col="lightgrey",lty=2)
  }
  # Trevorrow 1996, d=0.45m, WS=2m/s, lake, high
  if(j==3){
    points(DataLit$BubbleRadius[jj],DataLit$BubbleConc[jj],type="l",col="blue",lty=2)
  }
  # Randolph 2014, Day76, d=6m, WS=12.8m/s,  off shore, low
  if(j==4){
    points(DataLit$BubbleRadius[jj],DataLit$BubbleConc[jj],type="l",col="grey60",lty=2)
    # Phelps et al. 1997, surf zone, high
  }
  # Phelps et al. 1997, d=1.5m, WS=12-14m/s, surf zone, intermediate
  if(j==5){
    points(DataLit$BubbleRadius[jj],DataLit$BubbleConc[jj],type="l",col="black",lty=2)
  }
}


axis(side=1,at=(c(seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000),seq(10000,100000,10000))),labels=NA)
axis(side=1,at=(c(1,10,100,1000)),lwd=2, labels=format(c(1,10,100,1000), scientific=TRUE))

axis(side=2,at=(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)))*1,ylab="",labels=NA)
axis(side=2,at=(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)


text(3.2,10^8,"A)",xpd=TRUE,font=2)

par(xpd=TRUE)
legend("top", inset = c(0, -0.28),c(
  expression(paste("This study,         d ≤ 25")),
  expression(paste("This study, 25 ≤ d < 75")),
  expression(paste("This study, 75 ≤ d < 125")),
  expression(paste("This study, 125 ≤ d < 250")),
  expression(paste("This study,   250  ≤ d")),
  "Ocean surf (P97)","Lake (T96)","Lake (LP88)","Ocean open (R14)","Pool (LP88)"
),col=c(inferno(8)[c(3,4,5,6,7)],"black","blue","lightblue3","grey60","lightgrey"),lwd=c(rep(3,5),1,1,1,1,1),cex=0.7,bty="n",lty=c(1,1,1,1,1,2,2,2,2,2),ncol=2)


ticks=c(0.1, 0.5, 1, 2, 5, 7)
colorbar.plot(14,2*10^1, strip=1:100,horizontal = FALSE, strip.width = 3, strip.length = 5,col=rev(colors))
text(15,10*10^1,expression("d (cm)"),cex=0.8,col=1)
text(20,3*10^1,"5",cex=0.8,col=1)
text(22,0.15*10^1,"580",cex=0.8,col=1)

## add reference line
xf=lseq(15,65,100)
ff=9.2
lines(xf, 10^ff*(xf)^(-3/2)/c(0,diff(xf)),col="grey30",lwd=2)
text(37,0.5*10^8,"-3/2",font=2,col="grey30")








####################################################################################
####################################################################################
###  FIG 3B Hydrophone-based macrobubble spectrum
####################################################################################
####################################################################################

par(xpd=FALSE)



x=DataMacBub$a*10^6
y=DataMacBub$N/c(0,-diff(DataMacBub$a))*10^-6      


## max y per site in DataMacBub
ymaxSite <- tapply(y,DataMacBub$Site,max,na.rm=TRUE)
tapply(y,DataMacBub$Site,mean,na.rm=TRUE)
DataMacBubymaxSite <- ymaxSite[match(DataMacBub$Site,names(ymaxSite))]

y=y/DataMacBubymaxSite ## normalize to maximum at a given site; accounting for that the method is relative, not absolute
z=DataMacBub$valid




## subsample to reduce size and speed up processing

idd <- unique(floor(lseq(1,8192,100)))
idd <- idd[-c(1,2)]

xs <- rep(1:8192, length(x)/8192)

idddvalid <-which(match(xs,idd)>0 & z==TRUE)
iddd <-which(match(xs,idd)>0 & x>0 & y>0)
idddinvalid <-which(match(xs,idd)>0 & z==FALSE)



## color code
coll <- map_colors(DataMacBub$d, log_min, log_max, colors)


plot(x[idddvalid],y[idddvalid],log="xy",col=0,xlab="",ylab=expression(paste("N(a)/max(N(a)) (unitless)")),
     ylim=c(10^-9,1),xlim=c(0.2,30)*10^3,yaxt="n",xaxt="n",pch=1)

mtext(expression(paste("a (",mu,"m)")), side=1, line=3)  # Move X-axis label further away

points(x[idddinvalid],y[idddinvalid],col=adjustcolor(coll[idddinvalid],alpha.f=0.02),pch=1)
points(x[idddvalid],y[idddvalid],col=adjustcolor(coll[idddvalid],alpha.f=0.1),pch=1)




### add Hinze scale

  idp <- DataSpot$Whitecap=="yes" & DataSpot$d<=25
  abline(v=median(DataSpot$aH_app[idp]*10^6,na.rm=TRUE),lty=3,col=inferno(8)[3])
  idp <- DataSpot$Whitecap=="yes" & DataSpot$d>25 & DataSpot$d<=75
  abline(v=median(DataSpot$aH_app[idp]*10^6,na.rm=TRUE),lty=3,col=inferno(8)[4])
  idp <- DataSpot$Whitecap=="yes" & DataSpot$d>75 & DataSpot$d<=125
  abline(v=median(DataSpot$aH_app[idp]*10^6,na.rm=TRUE),lty=3,col=inferno(8)[5])
  idp <- DataSpot$Whitecap=="yes" & DataSpot$d>125 & DataSpot$d<=200
  abline(v=median(DataSpot$aH_app[idp]*10^6,na.rm=TRUE),lty=3,col=inferno(8)[6])
  text(1.35*10^4,60*10^-3,expression(paste("Apparent ",a[H])),srt=-90)




## get median of smallest valid bubble radius across all datasets
xTrue <- x[which(z==TRUE)]
breaks <- c(0, which(diff(xTrue) > 0), length(xTrue))
vecsx <- mapply(function(i, j) xTrue[(i+1):j], breaks[-length(breaks)], breaks[-1], SIMPLIFY = FALSE)
minradiusperDataset <- sapply(vecsx, min)

DataMacBubDistTrue <- DataMacBub$d[which(z==TRUE)]
vecsDataMacBubDist <- mapply(function(i, j) DataMacBubDistTrue[(i+1):j], breaks[-length(breaks)], breaks[-1], SIMPLIFY = FALSE)
DataMacBubDistperdataset <- sapply(vecsDataMacBubDist, min)


classes <- cut(DataMacBubDistperdataset, breaks = c(0,10, 30, 50,100,500), 
               labels = c("10", "30", "50","100","500"))
medians <- tapply(minradiusperDataset, classes, median)


### add lowess regression lines to plot

idddall <-which(match(xs,idd)>0 & (z==TRUE | z==FALSE))

idis <- which(DataMacBub$d[idddall]<=25)
smoothed <- lowess(log(x[idddall][idis]),log(y[idddall][idis]),f = 0.5/3)  # Compute smoothed values
# only plot line for valid median radius of respective distance class
idlinevalid10 <- which(exp(smoothed$x) > medians[1])
lines(exp(smoothed$x)[idlinevalid10], exp(smoothed$y)[idlinevalid10], col = map_colors(10, log_min, log_max, colors), lwd = 2,lty=2)
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(10, log_min, log_max, colors), lwd = 2,lty=3)

idis <- which(DataMacBub$d[idddall]>25 & DataMacBub$d[idddall]<=75)
smoothed <- lowess(log(x[idddall][idis]),log(y[idddall][idis]),f = 0.5/3)  # Compute smoothed values
idlinevalid30 <- which(exp(smoothed$x) > medians[2])
lines(exp(smoothed$x)[idlinevalid30], exp(smoothed$y)[idlinevalid30], col = map_colors(30, log_min, log_max, colors), lwd = 2,lty=2)
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(30, log_min, log_max, colors), lwd = 2,lty=3)

idis <- which(DataMacBub$d[idddall]>75 & DataMacBub$d[idddall]<=125)
smoothed <- lowess(log(x[idddall][idis]),log(y[idddall][idis]),f = 0.5/3)  # Compute smoothed values
idlinevalid50 <- which(exp(smoothed$x) > medians[3])
lines(exp(smoothed$x)[idlinevalid50], exp(smoothed$y)[idlinevalid50], col = map_colors(80, log_min, log_max, colors), lwd = 2,lty=2)
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(80, log_min, log_max, colors), lwd = 2,lty=3)

idis <- which(DataMacBub$d[idddall]>125 & DataMacBub$d[idddall]<=250)
smoothed <- lowess(log(x[idddall][idis]),log(y[idddall][idis]),f = 0.5/3)  # Compute smoothed values
idlinevalid50 <- which(exp(smoothed$x) > medians[3])
lines(exp(smoothed$x)[idlinevalid50], exp(smoothed$y)[idlinevalid50], col = map_colors(160, log_min, log_max, colors), lwd = 2,lty=2)
lines(exp(smoothed$x), exp(smoothed$y), col = map_colors(160, log_min, log_max, colors), lwd = 2,lty=3)


xf=lseq(3*10^-1,5,10)*10^3
ff=6
lines(xf, 10^ff*(xf)^(-3/2)/c(0,diff(xf)),col="grey30",lwd=2)
text(1.8*10^3,2*10^-1,"-3/2",font=2,col="grey30")

xf=lseq(8,30,10)*10^3
ff=12.5
lines(xf, 3*10^ff*(xf)^(-10/3)/c(0,diff(xf)),col="grey60",lwd=2)
text(2.4*10^4,9*10^-5,"-10/3",font=2,col="grey60")


axis(side=1,at=(c(seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000),seq(10000,100000,10000),seq(100000,1000000,100000))),labels=NA)
axis(side=1,at=(c(1,10,100,1000,10000,100000,1000000)),lwd=2)

axis(side=2,at=(c(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)))*1,ylab="",labels=NA)
axis(side=2,at=(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)


text((30),(10^0),"B)",xpd=TRUE,font=2)



ticks=c(0.1, 0.5, 1, 2, 5, 7)
colorbar.plot(250,7.25*10^-9, strip=1:100,horizontal = FALSE, strip.width = 45, strip.length = 0.000000001500,col=rev(colors[1:160]))
text(285,4*10^-8,expression("d (cm)"),cex=0.8,col=1)
text(390,9*10^-9,"5",cex=0.8,col=1)
text(420,1.3*10^-9,"200",cex=0.8,col=1)






