#######################################################################################################################
#######################################################################################################################
#######################################################################################################################
## Code to generate statistical output, figures and tables provided in the paper by Klaus et al.
#######################################################################################################################
#######################################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/08/20
###########################################################################################

# Reference:
# 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 

################################################################################################
################################################################################################
### LOAD CLEANED FINAL DATASETS
################################################################################################
################################################################################################

### Observations per sampling spot
DataSpot <- read.delim("Data/Cleandata/Data_Spotscale.tsv")

### Microbubble size spectral data (from Acoustic bubble spectrometer (ABS) )
DataMicBub <- read.delim("Data/Cleandata/Data_Microbubblespectra.tsv")

### Macrobubble size spectral data (from hydrophone recordings)
DataMacBub <- read.delim("Data/Cleandata/Data_Macrobubblespectra.tsv")

### Modelled bubble size evolution due to expansion and contraction
DataModBub <- read.delim("Data/Cleandata/Data_ModelledBubbleSizeEvolution.tsv")

### Bubble size distribution - literature data
DataLit <- read.delim("Data/Cleandata/Data_Microbubblespectra_Literature.tsv")



#############################################
### get numbers reported in the manuscript text
#############################################

### bubble spectral slope
mean(DataSpot$alpha,na.rm=TRUE)
range(DataSpot$alpha,na.rm=TRUE)
mean(DataSpot$betaL,na.rm=TRUE)
range(DataSpot$betaL,na.rm=TRUE)
mean(DataSpot$aH_app,na.rm=TRUE)
range(DataSpot$aH_app,na.rm=TRUE)
mean(DataSpot$Wec_app,na.rm=TRUE)
range(DataSpot$Wec_app,na.rm=TRUE)

# 95% confidence interval 
c(  mean(DataSpot$alpha - DataSpot$alpha_lwr95CI, na.rm = TRUE),
  range(DataSpot$alpha - DataSpot$alpha_lwr95CI, na.rm = TRUE))
c(  mean(DataSpot$betaL - DataSpot$betaL_lwr95CI, na.rm = TRUE),
  range(DataSpot$betaL - DataSpot$betaL_lwr95CI, na.rm = TRUE))

# due to log10 transformation, CIs for aH_app and Wc_app are theoretically asymmetric, but appear approximately symmetric here
c(  mean(DataSpot$aH_app - DataSpot$aH_app_lwr95CI, na.rm = TRUE),
  mean(DataSpot$aH_app_upr95CI - DataSpot$aH_app, na.rm = TRUE),
  range(DataSpot$aH_app - DataSpot$aH_app_lwr95CI, na.rm = TRUE),
  range(DataSpot$aH_app_upr95CI - DataSpot$aH_app, na.rm = TRUE))

c(  mean(DataSpot$Wec_app - DataSpot$Wec_app_lwr95CI, na.rm = TRUE),
  mean(DataSpot$Wec_app_upr95CI - DataSpot$Wec_app, na.rm = TRUE),
  range(DataSpot$Wec_app - DataSpot$Wec_app_lwr95CI, na.rm = TRUE),
  range(DataSpot$Wec_app_upr95CI - DataSpot$Wec_app, na.rm = TRUE))


### Kolmogorov length scale 
source("Code/0_Functions/FUNCTION_Temp2kinematicViscosity.R")
mean((Temp2kinematicViscosity(DataSpot$Temp)^3/DataSpot$epsUrms)^(1/4),na.rm=TRUE)*10^6
median((Temp2kinematicViscosity(DataSpot$Temp)^3/DataSpot$epsUrms)^(1/4),na.rm=TRUE)*10^6
min((Temp2kinematicViscosity(DataSpot$Temp)^3/DataSpot$epsUrms)^(1/4),na.rm=TRUE)*10^6

### quality checks of ADV data
## load Intermediate ADV data
IntermediatedataADV <- read.table("Data/Intermediatedata/ADV/ADV_TKEdissipation_output.tsv", sep='\t',header=TRUE)

## proportion of observation with spectral energy drops in inertial subrange > 1 decade
length(which(IntermediatedataADV$decade.u==10))/length(which(IntermediatedataADV$decade.u>0))
## mean/median energy drop of spectral energy in inertial subrange
median(IntermediatedataADV$decade.u[which(IntermediatedataADV$decade.u<10)],na.rm=TRUE)
mean(IntermediatedataADV$decade.u[which(IntermediatedataADV$decade.u<10)],na.rm=TRUE)

## proportion of observation with invalid Taylor's hypothesis of frozen turbulence
length(which(DataSpot$Frozen_isr<0.2))/length(which(DataSpot$Frozen_isr>0))

## proportion of observations that passed certain quality criteria
length(which(DataSpot$SNRU>30))/length(which(DataSpot$SNRU>0))
length(which(DataSpot$corrU>70))/length(which(DataSpot$corrU>0))
length(which(DataSpot$R2U_isr>0))/length(which(DataSpot$R2U_isr>-99999))
length(which(DataSpot$epsU_isr/DataSpot$epsUmin_isr>3))/length(which(DataSpot$R2U_isr>-99999))

length(which(DataSpot$SNRU>30 & DataSpot$corrU>70 & DataSpot$epsU_isr/DataSpot$epsUmin_isr>3 & DataSpot$R2U_isr>0))/length(which(DataSpot$R2U_isr>-99999))


################################################################################################
################################################################################################
### GENERATE STATISTICAL ANALYSES, FIGURES AND TABLES
################################################################################################
################################################################################################

################################################################################################
### Print main figures
################################################################################################

source("Code/3_MakeFigures/FIGURE_2_DriversOfBubbleConcentration.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/Fig2_DriversOfBubbleConcentration.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_3_BubbleSizeSpectra_BubbleAbundance.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/Fig3_BubbleSizeSpectra_BubbleAbundance.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_4_DriversOfBubbleSizeSpectralSlopes.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/Fig4_DriversOfBubbleSizeSpectralSlopes.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_5_DriversOfHinzeCriticalWeber.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/Fig5_DriversOfHinzeCriticalWeber.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


################################################################################################
### Print supplementary figures
################################################################################################

source("Code/3_MakeFigures/FIGURE_S3_QualityChecksADV.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/FigS3_QualityChecksADV.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S4_DissipationRatios.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/FigS4_DissipationRatios.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S5_FlowVelocities.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/FigS5_FlowVelocities.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S6_DriversOfDissipation.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/FigS6_DriversOfDissipation.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S7_BubbleSizeSpectra_VoidFraction.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/FigS7_BubbleSizeSpectra_VoidFraction.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S8_ScatterPlots_StreamCharacteristics.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file="Output/Figures/FigS8_ScatterPlots_StreamCharacteristics.jpg", width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S9_AdditionalDriversOfBubbleSizeSpectralSlopes.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/FigS9_AdditionalDriversOfBubbleSizeSpectralSlopes.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S10_AdditionalDriversOfHinze.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/FigS10_AdditionalDriversOfHinze.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S12_BubbleSizeEvolutionModelOutput.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/FigS12_BubbleSizeEvolutionModelOutput.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


source("Code/3_MakeFigures/FIGURE_S13_ContractionEffectOnBubbleSizeSpectralSlope.R")
local({
  dev.set (2)
  dev.print (device=jpeg, file=paste0("Output/Figures/FigS13_ContractionEffectOnBubbleSizeSpectralSlope.jpg"), width=par("din")[1]*200, res=200);
})
dev.off()


################################################################################################
### Print Tables
################################################################################################


source("Code/4_MakeTables/TABLE_S1_SiteCharacteristics.R")
write.table(TableS1,"Output/Tables/TableS1_StudySiteCharacteristics.tsv", quote=FALSE, sep='\t', row.names = FALSE) ## Note that this only contains the numeric information included in Table S1

source("Code/4_MakeTables/TABLE_S2_LinearModelOutput.R")
write.table(TableS2,"Output/Tables/TableS2_LinearModelOutput.tsv", quote=FALSE, sep='\t', row.names = FALSE)

source("Code/4_MakeTables/TABLE_S3_ModelRanking.R")
write.table(TableS3,"Output/Tables/TableS3_ModelRanking.tsv", quote=FALSE, sep='\t', row.names = FALSE)

source("Code/4_MakeTables/TABLE_S4_CorrelationMatrix.R")
write.table(TableS4,"Output/Tables/TableS4_CorrelationMatrix.tsv", quote=FALSE, sep='\t', row.names = FALSE)

source("Code/4_MakeTables/TABLE_S5_LinearModelOutput.R")
write.table(TableS5,"Output/Tables/TableS5_LinearModelOutput.tsv", quote=FALSE, sep='\t', row.names = FALSE)

source("Code/4_MakeTables/TABLE_S6_LinearModelOutput.R")
write.table(TableS6,"Output/Tables/TableS6_LinearModelOutput.tsv", quote=FALSE, sep='\t', row.names = FALSE)


################################################################################################
### Print list with all libraries used in this R project
################################################################################################

lock <- jsonlite::read_json("renv.lock")

pkgs <- lock$Packages

package_table <- data.frame(
  Package = names(pkgs),
  Version = sapply(pkgs, function(x) x$Version),
  stringsAsFactors = FALSE
)

package_table <- package_table[order(package_table$Package), ]

print(package_table)


write.table(package_table,
          "package_versions.tsv",
          quote=FALSE, sep='\t', row.names = FALSE)

