########################################################################################################################
########################################################################################################################
### Function to calculate and plot turbulent kinetic energy dissipation rate (epsilon) from 3D Nortek Vector ADV data
########################################################################################################################
########################################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## DETAILS
# solves for turbulent kinetic energy dissipation rate (epsilon) from ADV data in the inertial subrange 
# also provides estimates of various reach-scale turbulences metrics
# largely following Vingiani et al. 2021, Bluteau et al. 2011

# Please note: There is no golden standard method for estimating epsilon in rivers
# results are sensitive to many parameters, and must be quality checked  


# This is a wrapper function based on many other functions
# Requires ADV dataset loaded by function "loadADV", and further instrumental and environmental conditions
# Optional: - plot spectra (diagnostic=TRUE)


## References:
# Bluteau et al. (2011): Estimating turbulent kinetic energy dissipation using the inertial subrange method in environmental flows. Limnol. Oceanogr.: Methods 9, 2011, 302–321
# Vingiani et al. (2021): Evaluating stream CO2 outgassing via drifting and anchored flux chambers in a controlled flume experiment. Biogeosciences, 18, 1223–1240, https://doi.org/10.5194/bg-18-1223-2021


## INPUTS:
# data...flow velocity vector (u,v,w) with downstream, lateral and vertical component (m/s)
# freq...ADV sampling frequency (Hz)
# Water_Depth...Water depth (m)
# Water_Width...Pool width (m)
# SensorDepth...Depth of ADV sampling volume (m)
# SamplingVolume......Length scale of the sampling volume (mm)
# diagnostic...plot spectrum (yes/no)
# alpha...scaling coefficient to relate epsilon to energy spectrum
# n...order of zero-phase Butterworth filter
# Temperature...Water temperature (degrees celsius)
# inertial...estimate epsilon using inertial subrange method ()


## OUTPUTS:

## out
# epsilonMLE...turbulent kinetic energy dissipation (m2/s3), mean estimate, estimated using inertial subrange method
# epsilonMLElwr...turbulent kinetic energy dissipation (m2/s3), lower boundary of 95% confidence interval, estimated using inertial subrange method
# epsilonMLEupr...turbulent kinetic energy dissipation (m2/s3), upper boundary of 95% confidence interval, estimated using inertial subrange method
# realr2...coefficient of determination of the best spectral fit
# MAD...maximum absolute deviation of the best spectral fit
# lower.k...lower wavenumber boundary (rad/m) of window selected for fitting inertial subrange
# upper.k...upper wavenumber boundary (rad/m) of window selected for fitting inertial subrange
# f...frequency (Hz) associated with Kolmogorov scale
# decade...number of decades that the energy spectrum in the window selected for fitting inertial subrange covers
# epsilon_m...minimum resolvable turbulent kinetic energy dissipation (m2/s3), given the noise floor
# noisefloor...cutoff wavenumber where noise dominates (rad/m)
# sdVel...standard deviation of flow velocity (m/s)

## out2 
# TKE...Turbulent kinetic energy (m2/s2)
# epsUrms...turbulent kinetic energy dissipation (m2/s3) estimated from large-eddy scaling, using RMS velocity in u direction (Urms)
# Vadv...Advection velocity (m/s)
# Urms...RMS velocity in u direction (m/s), based on low-pass filtered data
# Urms_isr...RMS velocity in u direction (m/s), based on band-pass filtered data (inertial subrange)
# Vrms...RMS velocity in v direction (m/s)
# Vrms_isr...RMS velocity in v direction (m/s), based on band-pass filtered data (inertial subrange)
# Wrms...RMS velocity in w direction (m/s)
# Wrms_isr...RMS velocity in w direction (m/s), based on band-pass filtered data (inertial subrange)
# FrozenTurb...Urms/Vadv, for evaluation of Taylor's hypothesis of Frozen turbulence
# FrozenTurb_isr...Urms_isr/Vadv, for evaluation of Taylor's hypothesis of Frozen turbulence
# A_rad...horizontal flow velocity rotation angle
# theta_rad...vertical flow velocity rotation angle


## out3
# Stationarity2...means and standard deviations of flow velocities (u,v,w) for time series subsets for evaluation of stationarity

## out4 
# u,v,w... # rotated flow velocities in downstream, lateral and vertical direction (m/s)

## out5
# width.k... wavenumber associated with stream width (rad/m)
# depth.k... wavenumber associated with stream depth (rad/m)
# vol.k... wavenumber associated with ADV sampling volume length scale (rad/m)
# noisefloor... wavenumber where noise floor starts (rad/m)
# nk.k... Kolmogorov length scale (rad/m)

## out6 
# wavenum... wavenumber (rad/m)
# w.s[[1]]... wavenumber spectra (m2/s2) / (rad/m) for u direction
# w.s[[2]]... wavenumber spectra (m2/s2) / (rad/m) for v direction
# w.s[[3]]... wavenumber spectra (m2/s2) / (rad/m) for w direction

############################################################################################## 



###############################################
### load packages

library(oce)
library(forecast)
library(signal)
library(emdbook)
library(gdata)
library(stringr)
library(readxl)
library(segmented)
library(lmtest)
library(dplyr)
library(viridis)

##################################
### load helper functions

source("Code/0_Functions/FUNCTION_CreateNasmythSpectrum.R")
source("Code/0_Functions/FUNCTION_calculateTKE.R")
source("Code/0_Functions/FUNCTION_testStationarity.R")
source("Code/0_Functions/FUNCTION_loadADV.R")
source("Code/0_Functions/FUNCTION_findNoiseFloor.R")
source("Code/0_Functions/FUNCTION_EvaluateFrozenTurbulence.R")
source("Code/0_Functions/FUNCTION_fitDissipation.R")
source("Code/0_Functions/FUNCTION_projectADV.R")
source("Code/0_Functions/FUNCTION_transformCoordinatesADV.R")
source("Code/0_Functions/FUNCTION_Temp2kinematicViscosity.R")
source("Code/0_Functions/FUNCTION_calcDissipationLargeEddyScaling.R")


##################################
### load function

calcEpsilon <- function(data,freq=64, 
                        Water_Depth=Water_Depth, 
                        Water_Width=Water_Width, 
                        SensorDepth=SensorDepth,
                        SamplingVolume=SamplingVolume,
                        diagnostic = FALSE,
                        alpha=1.5*18/55*c(1,1.33,1.33),
                        n=4,
                        Temperature,
                        inertial=TRUE){
  

  ## Rotate velocities into mean flow direction
  resultproj <- projectADV(data=data)
  
  Vadv <- abs(resultproj$U)
  # horizontal rotation angle
  A_rad <- resultproj$A* 180/pi
  # vertical rotation angle
  # horizontal rotation angle
  theta_rad <- resultproj$theta* 180/pi
  
  ## select rotated flow components
  u <- resultproj$vel_project[,1]
  v <- resultproj$vel_project[,2]
  w <- resultproj$vel_project[,3]
  

  ## make time series
  uts <- ts(u, frequency=freq)
  vts <- ts(v, frequency=freq)
  wts <- ts(w, frequency=freq)
 
  ## make Welch spectra using default 8 segments with 50% overlap and tapered with a Hamming window
  ## (m2/s2 *1/s ); 
  ## fs does not need to be supplied here, because pwelch reads fs from ts object defined above
  wu <- pwelch(uts, plot=FALSE, detrend=TRUE,demean=TRUE)
  wv <- pwelch(vts, plot=FALSE, detrend=TRUE,demean=TRUE)
  ww <- pwelch(wts, plot=FALSE, detrend=TRUE,demean=TRUE)
  
  # Convert one-sided PSD to two-sided equivalent (for turbulence)
  Su <- wu$spec
  Su[2:(length(Su)-1)] <- 2 * Su[2:(length(Su)-1)]
  Sv <- wv$spec
  Sv[2:(length(Sv)-1)] <- 2 * Sv[2:(length(Sv)-1)]
  Sw <- ww$spec
  Sw[2:(length(Sw)-1)] <- 2 * Sw[2:(length(Sw)-1)]
  

  ## convert frequency spectra to wavenumber spectra (m2/s2 *1/s ) * m/s = (m2/s2) / (rad/m)
  w.s <- NULL
  w.s[[1]] <- Su*Vadv/ (2 * pi)
  w.s[[2]] <- Sv*Vadv/ (2 * pi)
  w.s[[3]] <- Sw*Vadv/ (2 * pi)


  ##########################################  
  ## calculate characteristic length scales

  wavenum <- 2*pi*wu$freq/Vadv # in radians/m ## conversion to wavenumber space
  vol.k = 2*pi*(1/SamplingVolume*1000) #/Vadv ## /1000 to convert mm to m
  width.k = 2*pi*(1/Water_Width) #/Vadv ## wave number corresponding to stream width
  depth.k = 2*pi*(1/Water_Depth) #/Vadv ## wave number corresponding to stream depth
  disBed.k = 2*pi*(1/(Water_Depth-SensorDepth))#/Vadv ## wave number corresponding to distance between sensor and gravel bed (Singh et al. 2010)


####################################################################################   
## find inertial subrange within which epsilon is calculated
## lower wavenumber limit is defined by stream depth, upper wavenumber limit is defined by ADV sampling volume
## fit spectrum for a series of candidate windows which where spectral density falls of by at least a decade  
## loop through candidate windows to find window with best model fit, i.e. lowest mean average deviation (MAD) (following Bluteau et al. 2011)

## make output vectors
epsilonMLE <- NULL
epsilonMLElwr <- NULL
epsilonMLEupr <- NULL
realr2 <- NULL
MAD <- NULL
lower.k <- NULL
upper.k <- NULL
decade <- NULL
noisefloor <- NULL

## loop through all 3 ADV beam components
for (h in 1:3){

 
res <- findNoiseFloor(k=wavenum, Ek=w.s[[h]],window = 151,slope_tol = 1,min_frac = 0.5,use_median = TRUE)
#res$noise_floor   # estimated noise floor level
noisefloor[h] <- res$k_cut         # cutoff wavenumber where noise dominates (rad/m)

if(h==1){
## Evaluate Taylors hypothesis of frozen turbulence
result_uU <- EvaluateFrozenTurbulence(data=cbind(u,v,w),SamplingVolume=SamplingVolume,n=4,Water_Depth=Water_Depth,noisefloor=noisefloor[h],Vadv=Vadv)
Urms <- abs(result_uU$u_rms)
Urms_isr <- abs(result_uU$u_rms_isr)
Vrms <- abs(result_uU$v_rms)
Vrms_isr <- abs(result_uU$v_rms_isr)
Wrms <- abs(result_uU$w_rms)
Wrms_isr <- abs(result_uU$w_rms_isr)
FrozenTurb <- result_uU$u_over_U
FrozenTurb_isr <- result_uU$uisr_over_U
}


########################################
## spectral fitting to estimate epsilon
########################################

if(inertial==TRUE){
result <- fitDissipation(
data=data.frame(y=w.s[[h]],x=wavenum),
global_xmin=depth.k, 
global_xmax=min(noisefloor[h],vol.k,na.rm=TRUE), 
min_y_ratio=10,
min_window_fraction = 0.10,  
max_window_fraction = 1,   
y_ratio_threshold=1.5,
reduction_factor = 0.9,
max_windows = 500,
wu=wu,
alpha=alpha[h]) 
}else{
  result <- list(best_window = NA, 
                 best_MAD = NA,
                 r2 = NA, 
                 n = NA, 
                 n_tot =   NA,
                 final_y_ratio_threshold = NA,
                 best_epsilonMLEmean=NA,
                 best_epsilonMLElwr=NA,
                 best_epsilonMLEupr=NA)
}


epsilonMLE[h] <- result$best_epsilonMLEmean
epsilonMLElwr[h] <- result$best_epsilonMLElwr
epsilonMLEupr[h] <- result$best_epsilonMLEupr
realr2[h] <- result$r2 
MAD[h] <- result$best_MAD
lower.k[h] <- result$best_window[1]
upper.k[h] <- result$best_window[2]
decade[h] <- result$final_y_ratio_threshold


} ## close h loop

########################################
## plot spectra for all ENU directions
########################################

  if (diagnostic){
    
    windows(width=8, height=8)
    layout(matrix(c(1:1), 1, 1, byrow = TRUE))
    par(mar=c(4.5,4.5,3,1),las=1,cex=1.3,mgp=c(3.1, 0.8, 0))

    plot(wavenum,w.s[[1]],log='xy',type="l",col=viridis(6)[2],xlab=expression(paste("wave number [rad ", m^-1,"]")),ylab=expression(paste("Power spectral density [( ",m^2, s^-2,")","/(rad ",m^-1,")]")),ylim=c(10^-10,10^-0),xaxt="n",yaxt="n")
    
    axis(side=2,c(seq(0.0000000001,0.000000001,0.0000000001),seq(0.000000001,0.00000001,0.000000001),seq(0.00000001,0.0000001,0.00000001),seq(0.0000001,0.000001,0.0000001),seq(0.000001,0.00001,0.000001),seq(0.00001,0.0001,0.00001),seq(0.0001,0.001,0.0001),seq(0.001,0.01,0.001),seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000)),labels=FALSE)
    axis(side=2,c(0.0000000001,0.000000001,0.00000001,0.0000001,0.000001,0.00001,0.0001,0.001,0.01,0.1,1,10,100,1000,10000),lwd=2)
    axis(side=1,c(seq(0.00001,0.0001,0.00001),seq(0.0001,0.001,0.0001),seq(0.001,0.01,0.001),seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000),seq(10000,100000,10000)),labels=FALSE)
    axis(side=1,c(0.01,0.1,1,10,100,1000,10000,100000),labels=c(0.01,0.1,1,10,100,1000,10000,100000),lwd=2)
    axis(side=3,c(0.01,0.1,1,10,100,1000,10000)/(Vadv)*2*pi,labels=c(0.01,0.1,1,10,100,1000,10000),lwd=2)
    axis(side=3,c(seq(0.00001,0.0001,0.00001),seq(0.0001,0.001,0.0001),seq(0.001,0.01,0.001),seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100),seq(1000,10000,1000))/(Vadv)*2*pi,labels=FALSE)
    mtext(side=3,line=2,"f [Hz]",cex=1.2)

    points(wavenum,w.s[[2]],col=viridis(6)[4],cex=.2,type="l")
    points(wavenum,w.s[[3]],col=viridis(6)[6],cex=.2,type="l")

    abline(v=width.k,lty=4)
    abline(v=depth.k,lty=2)
    abline(v=vol.k,lty=1,lwd=2)
    

    ## add lines based on which epsilon is estimated
    for (p in 1:3){
    ip <- wavenum>lower.k[p] & wavenum<upper.k[p]
    lines(wavenum[ip],alpha[p]*(epsilonMLE[p]^(2/3))*wavenum[ip]^(-5/3),col=viridis(6)[2*p],lwd=2)
    abline(v=noisefloor[p],col=viridis(6)[2*p],lwd=2,lty=2)

    abline(v=vol.k)
    }

    ## normalized plot coordinates
    x_rel <- grconvertX(0.3, from = "ndc", to = "user")
    y_rel1 <- grconvertY(0.85, from = "ndc", to = "user")
    y_rel2 <- grconvertY(0.8, from = "ndc", to = "user")
    y_rel3 <- grconvertY(0.75, from = "ndc", to = "user")
    y_rel4 <- grconvertY(0.65, from = "ndc", to = "user")
    y_rel5 <- grconvertY(0.6, from = "ndc", to = "user")
    y_rel6 <- grconvertY(0.55, from = "ndc", to = "user")
    
    ### add Nasmyth spectrum
    epsilon <- c(10^2,10^-0,10^-2,10^-4,10^-6,10^-8)
    wavenum_smooth <- exp(seq(
      log(min(wavenum[wavenum > 0])),
      log(max(wavenum)),
      length.out = 500
    ))
    for(e in (1:length(epsilon))){
      E_nas <- CreateNasmythSpectrum(wavenum_smooth, nu=Temp2kinematicViscosity(Temperature), epsilon[e], alpha=alpha[1])
      lines(
        wavenum_smooth, E_nas,
        col = "grey",
        lwd = 1,
        lty = 1
      )
    }
    
    
### kolmogorov length scale (threshold for noise)
k.vis <- Temp2kinematicViscosity(Temperature)
nk <- (k.vis^3/epsilonMLE)^(1/4) # rad (m)
nk.k <- 2*pi/(10*nk) # rad m-1

abline(v=nk.k,lty=3,col=viridis(6)[c(2,4,6)])

legend("topright",c("u","v","w"),col=viridis(6)[c(2,4,6)],lwd=1,bg="white")



#velocity spectrum noise floor (m² s⁻² / (rad m⁻¹))
epsilon_m <- NULL
for(h in 1:3){
  noiselevel <- median(w.s[[h]][which(wavenum > noisefloor[h])])
  a=upper.k[h]*nk[h]
  # minimum ε that can be resolved above the instrument noise floor
  epsilon_m[h] <- a^(20/3)/k.vis^5 * (noiselevel/(alpha[h]))^4
}

}

## frequency associated with kolmogorov scale; here I use it as input for filtering the spectrum
## rad m-1*m/s /rad=cycles s-1
  f= nk.k*Vadv/(2*pi)

  
   ###################### 
   ## Turbulence indices
   ###################### 
  
  ## filtering to remove high-frequency noise
  
  ## frequency expressed in terms of nyquist frequency and [0,1]
  ## remove noise
  uf <- filtfilt(butter(n, min(noisefloor[1],vol.k)*Vadv/(2*pi)/(0.5*freq), type="low"), u-mean(u))
  vf <- filtfilt(butter(n, min(noisefloor[2],vol.k)*Vadv/(2*pi)/(0.5*freq), type="low"), v-mean(v))
  wf <- filtfilt(butter(n, min(noisefloor[3],vol.k)*Vadv/(2*pi)/(0.5*freq), type="low"), w-mean(w))

  sdVel <-  apply(data.frame(uf,vf,wf),2,FUN=sd)
  names(sdVel) <- c("sdVel.u","sdVel.v","sdVel.w")
  
  ## Turbulent kinetic energy (m2/s2) 
  TKE <- calculateTKE(sdVel[1],sdVel[2],sdVel[3])
  
  ## Dissipation - Large Eddu scaling
  # In a system where production of turbulence (from shear) equals its dissipation (ε),
  # a balance occurs, and the dissipation rate can be scaled using shear stress and a length scale
  # use RMS–length-scale dissipation scaling, Vassicilos (2015)
  epsUrms <- calcDissipationLargeEddyScaling(Urms=Urms,C=1,Water_Depth=Water_Depth)
  
  
  ## Check stationarity of flow velocity over time
  Stationarity <- testStationarity(uf, vf, wf, n_sub = 4)
  Stationarity2 <- c(apply(Stationarity[,2:7],2,mean),
                     apply(Stationarity[,2:7],2,sd))
  names(Stationarity2)[1:6] <- paste0(names(Stationarity2)[1:6],"_mean")
  names(Stationarity2)[7:12] <- paste0(names(Stationarity2)[7:12],"_sd")
  
  
  ######################
  ## generate output
  ######################
  out <- rbind(epsilonMLE,epsilonMLElwr,epsilonMLEupr,realr2,MAD,lower.k,upper.k,f,decade,epsilon_m,noisefloor,sdVel)
  colnames(out) <- c("u","v","w")
  out2 <- rbind(TKE,epsUrms,Vadv,Urms,Urms_isr,Vrms,Vrms_isr,Wrms,Wrms_isr,FrozenTurb,FrozenTurb_isr,A_rad,theta_rad)
  out3 <- Stationarity2
  out4 <- cbind(u,v,w) # rotated velocities
  out5 <- data.frame(width.k,depth.k,vol.k,noisefloor,nk.k)
  out6 <- data.frame(wavenum,w.s[[1]],w.s[[2]],w.s[[3]]) # spectra
  return(list(out,out2,out3,out4,out5,out6))
}
######################################################################################################################

