##########################################################################################################################################
##########################################################################################################################################
# ## function to model temporal evolution of radius and gas concentration of a bubble in a step pool system 
##########################################################################################################################################
##########################################################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## ASSUMPTIONS:
# bubbles are spherical
# bubble-water gas exchange and rise velocity behave similarly to contaminated (“dirty”) bubbles, but surface tension is not reduced by surfactants 
# dissolved gas is well-mixed in the pool and inside bubbles
# there is no chemical enhancement of bubble-water gas exchange velocity
# Bubble is injected to a depth zmax and then moves passively with bulk water flow and rises due to its buoancy
# there is no bubble-bubble or bubble-fluid interactions, e.g. cross-flow due to drag, slip, wake effects, bubble deformation)

## INPUTS:
# Site ... Site ID
# temp_C ... Water temperature (°C)
# R0_um ...  Initial radius (μm)
# Xatm_N2 ... atmospheric N2 molar mixing ratio (unitless)
# Xatm_O2 ... atmospheric O2 molar mixing ratio (unitless)
# Xatm_Ar ... atmospheric Ar molar mixing ratio (unitless)
# Xatm_CH4 ... atmospheric CH4 molar mixing ratio (unitless)
# Xatm_CO2 ... atmospheric CO2 molar mixing ratio (unitless)
# sat_N2 ... aquous N2 Saturation level (unitless)
# sat_O2 ... aquous O2 Saturation level (unitless)
# sat_Ar ... aquous Ar Saturation level (unitless)
# sat_CH4 ... aquous CH4 Saturation level (unitless)
# sat_CO2 ... aquous CO2 Saturation level (unitless)
# Cond ... electrical conductivity (uS/cm)
# P_atm ... air pressure (Pa)
# Vu ... advective (downstream) flow velocity (m/s)
# Wrms ...  turbulent vertical flow velocity (m/s)
# h ... step height (m)
# dj ... jet diameter (m)
# l0 ... water depth below step (m)
# j ... ID of bubble-water gas exchange model (select 1-5)
# R_gas ... Universal Gas Constant (J/mol*K) = Kg m2 s-2 K-1 mol-1
# g ... gravitational acceleration (m/s2)
# k_bub_models ... bubble-water gas exchange models
# dt ... time step of simulation (s); to be set to <0.1s for bubble radii < ~30 micron
# R_min ... minimum bubble radius at which simulation stops (m)
# t_max ... maximum duration of simulation (s)
# x_max ... distance to step (m) = maximum x to consider in model
# rise ... should bubble be modeled to rise due to its buoyancy? (TRUE/FALSE)

## OUTPUTS:
# time ... time (s)
# r_um ... bubble radius (μm)
# z ... depth (m)
# x ... position relative to step in downstream direction (m)
# N_bub_XX ... gas amount in bubble of gas XX (mol)
# C_int_XX ... gas concentration at bubble-water interface of gas XX (mol/m3 )
# C_aq_XX ... aqueous concentration of gas XX (mol/m3) 
# zmax ... maximum bubble penetration depth (m)

###########################################################################################

BubbleGasExchange <- function(
    Site,
    temp_C,
    R0_um,
    Xatm_N2,
    Xatm_O2,
    Xatm_Ar,
    Xatm_CH4,
    Xatm_CO2,
    sat_N2,
    sat_O2,
    sat_Ar,
    sat_CH4,
    sat_CO2,
    Cond,
    P_atm,
    Vu,
    Wrms,
    h,
    dj,
    l0,
    j,
    dt,
    r_min,
    t_max,
    x_max,
    rise){
  
  ##################################
  ### LOAD helper functions
  ##################################
  source("Code/0_Functions/FUNCTION_CalcGasSolubilities.R")
  source("Code/0_Functions/FUNCTION_Conductivity2Salinity.R")
  source("Code/0_Functions/FUNCTION_TempSal2FreshwaterDensity.R")
  source("Code/0_Functions/FUNCTION_Temp2SurfTension.R")
  source("Code/0_Functions/FUNCTION_Temp2kinematicViscosity.R")
  source("Code/0_Functions/FUNCTION_calcKBubble.R")
  source("Code/0_Functions/FUNCTION_calcBubbleRiseVelocity.R")
  
  library(deSolve)
  library(robustbase)
  
  k_bub_models = c("W93_Eq39","W93_Eq42","W93_Eq43","MM85_Eq5","MM85_Eq7")
  
  ##############
  # CONSTANTS 
  ##############
  R_gas <- 8.314        
  g <- 9.81   
  
  ##########################################
  # PHYSICAL CONDITIONS
  ##########################################
  # temperature in Kelvin
  T_K   <- temp_C + 273.15
  # Salinity (per mille)
  S <- Conductivity2Salinity(Cond=Cond,Temp=temp_C,Press=P_atm*10^-5)
  # Water density (kg/m3)
  p <- TempSal2FreshwaterDensity(Temp=temp_C,S=S)
  # Surface tension (N/m)
  sigma <- Temp2SurfTension(temp_C)
  # kinemtic viscosity (m2/s)
  v <- Temp2kinematicViscosity(temperature=temp_C)
  
  ##########################################
  # SOLUBILITY
  ##########################################
  # Henry's constants ( mol/(L*atm) * 1000 L/m3 * 9.87*10^-6 atm/Pa = mol/(m3*Pa) )
  kh_N2 <- CalcGasSolubilities(Temp=temp_C,Gas="N2",S=S)$KH*1000*(9.87*10^-6) 
  kh_O2 <- CalcGasSolubilities(Temp=temp_C,Gas="O2",S=S)$KH*1000*(9.87*10^-6)
  kh_Ar <- CalcGasSolubilities(Temp=temp_C,Gas="Ar",S=S)$KH*1000*(9.87*10^-6)
  kh_CO2 <- CalcGasSolubilities(Temp=temp_C,Gas="CO2",S=S)$KH*1000*(9.87*10^-6)
  kh_CH4 <- CalcGasSolubilities(Temp=temp_C,Gas="CH4",S=S)$KH*1000*(9.87*10^-6)

  # Schmidt number (unitless)
  Sc_N2 <- CalcGasSolubilities(Temp=temp_C,Gas="N2",S=S)$Sc 
  Sc_O2 <- CalcGasSolubilities(Temp=temp_C,Gas="O2",S=S)$Sc
  Sc_Ar <- CalcGasSolubilities(Temp=temp_C,Gas="Ar",S=S)$Sc
  Sc_CO2 <- CalcGasSolubilities(Temp=temp_C,Gas="CO2",S=S)$Sc
  Sc_CH4 <- CalcGasSolubilities(Temp=temp_C,Gas="CH4",S=S)$Sc
  
  # Diffusivity (m2/s) 
  D_N2 <- v/Sc_N2
  D_O2 <- v/Sc_O2
  D_Ar <- v/Sc_Ar
  D_CO2 <- v/Sc_CO2
  D_CH4 <- v/Sc_CH4
  
  
  #####################################################
  # APPROXIMATION OF BUBBLE PENETRATION DEPTH
  #####################################################
  
  ## jet velocity (m/s)
  # from energy conservation (gravitational potential energy = kinetic energy at impact)
  # we yield m*g*H=1/2m*v2 
  # and hence
  vj=sqrt(2*g*h)
  
  ## bubble penetration depth (m), Bin 1993, Eq. 57
  z=1.20*vj^0.77*dj^0.625*h^-0.094
  
  # set bubble penetration depth to water depth below step, if bigger
  if(z>l0){
    z=l0
  }
  
  zmax=z
  
  ##########################################
  # INITIAL CONDITIONS
  ##########################################
  r0 <- R0_um * 1e-6
  z0 <- 0
  x0 <- 0
  
  # Initial internal bubble pressure (Atmospheric + Laplace) (Pa) when bubble entrains at surface
  Pb0 <- P_atm + 2*sigma/r0
  
  # Initial gas amount in bubble (mol)
  # ideal gas law (pV=nRT), (1 * Pa * m3 / (J/(mol*K) *K)=(Pa * m3 / ( (Pa*m3)/(mol*K) *K) = mol)
  N0_N2 <- Xatm_N2 * Pb0 * 4/3*pi*r0^3 / (R_gas*T_K)
  N0_O2 <- Xatm_O2 * Pb0 * 4/3*pi*r0^3 / (R_gas*T_K)
  N0_Ar <- Xatm_Ar * Pb0 * 4/3*pi*r0^3 / (R_gas*T_K)
  N0_CO2 <- Xatm_CO2 * Pb0 * 4/3*pi*r0^3 / (R_gas*T_K)
  N0_CH4 <- Xatm_CH4 * Pb0 * 4/3*pi*r0^3 / (R_gas*T_K)
  
  state <- c(
    r_m = r0,
    z = z0,
    x = x0,
    N_N2 = N0_N2,
    N_O2 = N0_O2,
    N_Ar = N0_Ar,
    N_CO2 = N0_CO2,
    N_CH4 = N0_CH4
  )
  
  ##########################################
  # ODE SYSTEM
  ##########################################
  
  rootfun <- function(t, state, parms) {
    r_m <- state["r_m"]
    z   <- state["z"]
    
    return(c(
      r_m - r_min,     # triggers when r_m = r_min
      z + zmax         # triggers when z = -zmax
    ))
  }
  
  bubble_ode <- function(t, state, parms){
    
    # define state variables
    r_m <- state["r_m"]
    z   <- state["z"]
    x   <- state["x"]
    
    N_N2 <- state["N_N2"]
    N_O2 <- state["N_O2"]
    N_Ar <- state["N_Ar"]
    N_CO2 <- state["N_CO2"]
    N_CH4 <- state["N_CH4"]
    

    # Hydrostatic pressure (Pa)
    P_hyd <- (zmax+z)*g*p
    
    # Internal bubble pressure (Atmospheric + Laplace) (Pa)
    Pb <- P_atm + P_hyd + 2*sigma/r_m
    
    ## total substance (mol)
    N_total <- N_N2+N_O2+N_Ar+N_CO2+N_CH4
    
    # mole fraction in bubble (mol/mol)
    X_N2 <- N_N2/N_total
    X_O2 <- N_O2/N_total
    X_Ar <- N_Ar/N_total
    X_CO2 <- N_CO2/N_total
    X_CH4 <- N_CH4/N_total
    
    # gas concentration at bubble-water-interface ( mol/(m3*Pa) * Pa * mol/mol = mol/m3 )
    C_int_N2 <- kh_N2 * Pb * X_N2
    C_int_O2 <- kh_O2 * Pb * X_O2
    C_int_Ar <- kh_Ar * Pb * X_Ar
    C_int_CO2 <- kh_CO2 * Pb * X_CO2
    C_int_CH4 <- kh_CH4 * Pb * X_CH4
    
    # aqueous concentration of gas (Pa * 1 * 1 * mol/(m^3*Pa) =  mol/m3) 
    C_aq_N2 <- (P_atm+P_hyd)*sat_N2*Xatm_N2*kh_N2
    C_aq_O2 <- (P_atm+P_hyd)*sat_O2*Xatm_O2*kh_O2
    C_aq_Ar <- (P_atm+P_hyd)*sat_Ar*Xatm_Ar*kh_Ar
    C_aq_CO2 <- (P_atm+P_hyd)*sat_CO2*Xatm_CO2*kh_CO2
    C_aq_CH4 <- (P_atm+P_hyd)*sat_CH4*Xatm_CH4*kh_CH4
    
    ########################################################
    ## bubble movement
    
    ## bubble rise velocity (m/s), 
    Vb = calcBubbleRiseVelocity(r_m,g,p,v)
    
    ## change rate in bubble depth (m/s)
    if(rise==TRUE){
    dz_dt = -Vb
    }else{
    dz_dt = 0  
    }
    
    ## change rate in bubble longitude (m/s)
    dx_dt = -Vu
    
    
    ############################################################
    ## bubble-water gas exchange
    
    # bubble-water gas exchange velocity (m/s)
    ## note: "For most  bubbles, neither explicit nor numerical solutions  are possible, and simplifications of the bubble
    ## hydrodynamics and boundary layer are necessary. (Leifer et al. 2002)
    
    k_bub_N2 <- calcKBubble(D=D_N2,Vb=Wrms,v=v,r=r_m,g=g,k_bub_model=k_bub_models[j])
    k_bub_O2 <- calcKBubble(D=D_O2,Vb=Wrms,v=v,r=r_m,g=g,k_bub_model=k_bub_models[j])
    k_bub_Ar <- calcKBubble(D=D_Ar,Vb=Wrms,v=v,r=r_m,g=g,k_bub_model=k_bub_models[j])
    k_bub_CO2 <- calcKBubble(D=D_CO2,Vb=Wrms,v=v,r=r_m,g=g,k_bub_model=k_bub_models[j])
    k_bub_CH4 <- calcKBubble(D=D_CH4,Vb=Wrms,v=v,r=r_m,g=g,k_bub_model=k_bub_models[j])
    
    # bubble mass flux   ( m/s * m2 * mol/m3 = mol/s); Leifer et al. (2002)
    dN_dt_N2 <- k_bub_N2*4*pi*r_m^2*(C_aq_N2-C_int_N2)
    dN_dt_O2 <- k_bub_O2*4*pi*r_m^2*(C_aq_O2-C_int_O2) 
    dN_dt_Ar <- k_bub_Ar*4*pi*r_m^2*(C_aq_Ar-C_int_Ar) 
    dN_dt_CO2 <- k_bub_CO2*4*pi*r_m^2*(C_aq_CO2-C_int_CO2) 
    dN_dt_CH4 <- k_bub_CH4*4*pi*r_m^2*(C_aq_CH4-C_int_CH4) 
    
    # total mass flux in/out of the bubble for all gases (mol/s)
    dN_dt_total <- dN_dt_N2+dN_dt_O2+dN_dt_Ar+dN_dt_CO2+dN_dt_CH4
    
    ############################################################
    ## bubble radius change
    
    # a) simplified form; Leifer et al. (2002), Eq. 8  # N = Kg m/s2
    # q, defined from the ideal gas law; ( J/(mol*k) * K / m3  = Pa m3/mol  = Pa/mol )
    q <- R_gas*T_K/(4/3*pi*r_m^3)
    
    # Pa = Kg/(m s2)
    # unit check: m * ( Pa/mol * mol/s - Kg/m3*m/s2*m/s ) * (Pa + Kg/m3*m/s2*m) + N/m / m )^-1
    # unit check: m * ( Kg/(m s3) - Kg/(m s3) ) * (Kg/(m s2)  +  Kg/(m s2)  +  Kg/(m s2) )^-1 = m/s
    
    dr_dt <- r_m * (q * dN_dt_total - p*g*dz_dt) * ( 3 * (P_atm + p*g*(zmax+z)) + 4*sigma/r_m )^-1
    
    # b) full form gives the same result; Leifer et al. (2002), Eq. 7 
    #dr_dt <- (R_gas * T_K * dN_dt - 4/3*pi*r_m^3 * p*g*dz_dt) * (4*pi*r_m^2 * (P_atm+ p*g*z + 2*sigma/r_m) - 4/3*pi*r_m^3 * 2*sigma/r_m^2)^-1
    
    
    ###########################
    ## define output variables
    
    list(c(
      dr_dt,
      dz_dt,
      dx_dt,
      dN_dt_N2,
      dN_dt_O2,
      dN_dt_Ar,
      dN_dt_CO2,
      dN_dt_CH4
    ),
    
    c(
      C_int_N2 = C_int_N2,
      C_int_O2 = C_int_O2,
      C_int_Ar = C_int_Ar,
      C_int_CO2 = C_int_CO2,
      C_int_CH4 = C_int_CH4,
      
      C_aq_N2 = C_aq_N2,
      C_aq_O2 = C_aq_O2,
      C_aq_Ar = C_aq_Ar,
      C_aq_CO2 = C_aq_CO2,
      C_aq_CH4 = C_aq_CH4
    )
    )
  }
  
  ##########################################
  # SOLVE
  ##########################################
  times <- seq(0, t_max, by = dt)
  
  out <- ode(
    y = state,
    times = times,
    func = bubble_ode,
    parms = NULL,
    method = "lsoda",
    rtol = 1e-8,
    atol = 1e-12,
    rootfun = rootfun
  )
  
  ## add additional output variables
  out <- as.data.frame(out)
  out$r_um <- out$r_m * 1e6
  out$zmax <- zmax 
  
  return(out)
  
}





