#############################################################################################################
#############################################################################################################
# Code to model evolution of bubble gas concentration and bubble radius during passage through plunge pool
#############################################################################################################
#############################################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
#############################################################################################################

## INPUTS:
# Data/Rawdata/Data_FieldObservations.tsv... hydraulic and physicochemical stream characteristics 
# Data/Intermediatedata/ADV/ADV_TKEdissipation_output.tsv... intermediate output from ADV processing
# Data/Cleandata/Data_Microbubblespectra.tsv... microbubble size spectral data
# Code/0_Functions/FUNCTION_BubbleGasExchange.R
  
## OUTPUTS:
# Data/Cleandata/Data_ModelledBubbleSizeEvolution.tsv
#   Site ... Site ID
#   d ... Distance to step (cm)
#   r0 ... initial bubble radius at entrainment (m)
#   Tdiss ... time until bubble dissolution (s)
#   TSurf ... time until bubble reaches water surface (s)
#   t ... travel time to reach sampling spot (s)
#   rt ... bubble radius at time t (m)
#   zt ... bubble depth at time t (m)
#   xt ... bubble position relative to step in downstream direction at time t (m)
#   C_int_XX ... gas concentration at bubble-water interface of gas XX (mol/m3), XX = c(N2, O2, Ar, CO2, CH4)
#   C_aq_XX ... aqueous concentration of gas XX (mol/m3), XX = c(N2, O2, Ar, CO2, CH4)
#   zmax ... maximum bubble penetration depth (m)
############################################################################################################

############################################################################################################
## load model code
############################################################################################################

source("Code/0_Functions/FUNCTION_BubbleGasExchange.R")

############################################################################################################
### load field observation data needed for model inputs
############################################################################################################

DataFieldObservations <- read.delim("Data/Rawdata/Data_FieldObservations.tsv")

## select only sites in Italy and France (because N2 data from Sweden is missing, but has large effect on bubble gas exchange)

DataFieldObservations <- DataFieldObservations[-which(is.na(as.numeric(DataFieldObservations$Site))),] ## will give warning, can be ignored
list2env(DataFieldObservations, envir = .GlobalEnv)

## Sampling ID
IDfield <- paste0(Site,"_",d)



################################################################################
## get water depth just below step

# Use 'ave' to perform the calculation per group
l0 <- ave(1:length(Site), Site, FUN = function(idx) {
  # 'idx' represents the row positions for the current group
  group_dist <- d[idx]
  group_wl   <- l[idx]
  # Return the WL at the minimum Distance for this group
  group_wl[which.min(group_dist)]
})


############################################################################################################
### load ADV data needed for model inputs
############################################################################################################

ADVdata <- read.delim("Data/Intermediatedata/ADV/ADV_TKEdissipation_output.tsv")

### match ADV data with field sheet
idADV <- match(IDfield,ADVdata$ID)  

## get turbulent velocity scale
Wrms = ADVdata$Wrms[idADV]

#################################################################################################################
## get time-integrated upstream mean velocity and travel time from step up to each sampling spot; using Vadv
## velocity that a transported bubble effectively experiences

# gap fill two spots
velocity=ADVdata$Vadv[idADV]
velocity[which(is.na(velocity))[1]] <- mean(velocity[which(is.na(velocity))[1]+1],velocity[which(is.na(velocity))[1]-1])
velocity[which(is.na(velocity))[1]] <- velocity[which(is.na(velocity))[1]+1]

source("Code/0_Functions/FUNCTION_averageFlowVelocity.R")

## time-integrated upstream mean flow velocity (m/s)
VAdv_mean <- averageFlowVelocity(Site=Site, velocity=velocity, d=d)$V_cum


############################################################################################################
### load Microbubble size spectra data needed for model inputs
############################################################################################################

### Microbubble size spectral data (from Acoustic bubble spectrometer (ABS) )
DataMicBub <- read.delim("Data/Cleandata/Data_Microbubblespectra.tsv")
DataMicBub <- DataMicBub[-which(is.na(as.numeric(DataMicBub$Site))),] ## warning can be ignored



#################
# User inputs
#################

# initial bubble radii to be evaluated
f <- as.numeric(substr(names(DataMicBub[,grep("^n",names(DataMicBub))]),3,6))
f <- f-median(DataMicBub$bin,na.rm=TRUE)/2
f <- na.omit(f[seq(1,length(f),2)])

## for modelling, use the frequency resolution as ABS data for microbubbles, and coarser resolution for macrobubbles 
radii <- c(f,600,1200,2400,4800,9600)


## should bubble be modeled to rise due to its buoyancy (TRUE) or assumed to have constant depth (FALSE)?
rise=TRUE


#########################################################
# run model in loop through all sampled spots
#########################################################


## make empty output to be filled
results <- NULL
outputxall <- NULL
outputzall <- NULL

for (i in 1:length(Temp)){

outputx <- NULL
outputz <- NULL

# minimum bubble radius to be modelled
r_min = 0.5*10^-6

for (r in 1:length(radii)){

results <- BubbleGasExchange(
  Site=Site[i],
  temp_C=Temp[i],
  R0_um=radii[r],
  Xatm_N2=0.78084,
  Xatm_O2=0.20946,
  Xatm_Ar=0.009340,
  Xatm_CH4=1.86*10^-6 ,
  Xatm_CO2=424*10^-6,
  sat_N2=N2sat[i]/100,
  sat_O2=O2sat[i]/100,
  sat_Ar=1, ## assume 100% saturation
  sat_CH4=1,## assume 100% saturation 
  sat_CO2=CO2sat[i]/100,  
  Cond=EC[i],
  P_atm=Press[i]*100000,
  Vu=-VAdv_mean[i],  
  Wrms=Wrms[i],  ## (this has no effect when choosing j=1)
  h=h[i]/100,
  dj=dj[i],   
  l0=l0[i]/100,    
  j=1,  ## j is 1-5 for different gas exchange models ("W93_Eq39","W93_Eq42","W93_Eq43","MM85_Eq5","MM85_Eq7")
  dt=0.05,
  r_min=r_min,
  t_max=500,
  x_max=d[i]/100,
  rise=rise)

# rescale depth
results$z <-  results$zmax + results$z

# bubble dissolution time (s)
  if(length(which(abs(results$r_m-r_min)<10^-10))>0) {
  Tdiss <- results$time[which(abs(results$r_m-r_min)<10^-10)]
  }else{ 
  Tdiss <- NA
  }

# in some cases, the model provides shaky output when bubble comes close to dissolution; then approximate dissolution time by extrapolating trend linearly
if(is.na(Tdiss) & length(which(abs(results$r_m/max(results$r_m))<0.3))>0) {
  y=results$r_m[(nrow(results)-10):(nrow(results))]
  x=results$time[(nrow(results)-10):(nrow(results))]
  x_predict=seq(max(results$time),2*max(results$time),0.05)
  y_predict <- predict(lmrob(y~x),newdata=data.frame(x=x_predict))
  Tdiss <- x_predict[min(which(y_predict<r_min))]
}

## bubble surfacing time (s)
  if(length(which(abs(results$z) < 10^-8))>0) {
    ## row ID when bubble reaches surface
    irz <- which(abs(results$z) < 10^-8)
    TSurf <- results$time[irz]
  outputz <- rbind(outputz,data.frame(Site[i],d[i],radii[r],Tdiss,TSurf,results[irz,]))
    }else{
  TSurf <- NA
  resultsNA <- matrix(NA,1,ncol(results))
  ## model output for (theoretical) conditions when bubbles has reached the surface 
  colnames(resultsNA)  <- colnames(results)
  outputz <- rbind(outputz,data.frame(Site[i],d[i],radii[r],Tdiss,TSurf,resultsNA))
  }
  

## row-number when bubble reaches spot i
irx <- min(which(results$x > d[i]/100))

## model output for conditions when bubbles has reached spot x
outputx <- rbind(outputx,data.frame(Site[i],d[i],radii[r],Tdiss,TSurf,results[irx,]))


} ## close radii loop
  
 
  
  ### Export data
  outputxall <- rbind(outputxall,outputx)

  DataModBub <- outputxall[,c(1:9,15:24,26)]
  colnames(DataModBub) <- c("Site","d","r0","Tdiss","TSurf","t","rt","zt","xt",
                            "C_int_N2","C_int_O2","C_int_Ar","C_int_CO2","C_int_CH4",
                            "C_aq_N2","C_aq_O2","C_aq_Ar","C_aq_CO2","C_aq_CH4","zmax")
  DataModBub$r0 <- DataModBub$r0*10^-6
  DataModBub$xt <- -DataModBub$xt
  
  write.table(DataModBub,"Data/Cleandata/Data_ModelledBubbleSizeEvolution.tsv"
              , quote=FALSE, sep='\t', row.names = FALSE)
  
} ## close sampling spot loop

