
##############################################################################################
##############################################################################################
### Function to fit 5/3 slope to empirical flow velocity spectrum to calculate turbulent 
#### kinetic energy dissipation rate finding optimal sampling window 
##############################################################################################
##############################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

### Details
## MLE function to fit 5/3 slope is from Bluteau et al. (2011)
## randomly samples max_windows number of windows that contain a proportion of window_fraction of the original data
## within defined lower and upper wavenumber boundaries xmin and xmax
## search algorithm starts with looking for a search wind that covers at least a decade range of 
## spectral energy; if this is not present, it reduces the criterion stepwise by reduction_factor

## INPUTS: 
# data...data.frame(y,x), where x is wavenumber (rad/m) and y is wavenumber spectrum (m2/s2)/(rad/m), i.e. list where y[[1]] is for u direction, y[[2]] is for v direction and y[[3]] is for w direction
# global_xmin...minimum wavenumber considered for inertial subrange fitting
# global_xmax...maximum wavenumber considered for inertial subrange fitting
# min_y_ratio...minimum energy drop (max/min spectrum level) that the inertial subrange should cover 
# y_ratio_threshold...if min_y_ratio is not possible, it is step wise reduced until reaching this minimum threshold
# min_window_fraction...Min % of full wavenumber range per window
# max_window_fraction...Max % of full wavenumber range per window
# reduction_factor...factor by which the minimum energy drop (max/min spectrum level) that the inertial subrange should cover is reduced per step
# max_windows...number of sliding windows used for inertial subrange spectral fitting
# wu...Energy spectrum (m2/s2 per rad/m)
# alpha...scaling coefficient to relate epsilon to energy spectrum

## OUTPUTS:
# best_window...wavenumber range (rad/m) of the window that yielded the best spectral fit
# best_MAD...maximum absolute deviation of the best spectral fit
# r2... coefficient of determination of the best spectral fit
# n... number of observations  of the window that yielded the best spectral fit
# n_tot... total number of observations
# final_y_ratio_threshold... energy drop (max/min spectrum level) in the window that yielded the best spectral fit 
# best_epsilonMLEmean...turbulent kinetic energy dissipation (m2/s3), mean estimate
# best_epsilonMLElwr...turbulent kinetic energy dissipation (m2/s3), lower boundary of 95% confidence interval
# best_epsilonMLEupr...turbulent kinetic energy dissipation (m2/s3), upper boundary of 95% confidence interval

## Reference:
# Bluteau et al. (2011): Estimating turbulent kinetic energy dissipation using the inertial 
# subrange method in environmental flows. Limnol. Oceanogr.: Methods 9, 2011, 302–321
###########################################################################################

fitDissipation <- function(data, 
                           global_xmin, 
                           global_xmax,  
                           min_y_ratio=10,
                           y_ratio_threshold=1.5, 
                           min_window_fraction = 0.10,  
                           max_window_fraction = 1,  
                           reduction_factor = 0.9,
                           max_windows = 500,
                           wu=wu,
                           alpha=alpha) {  
  
  # make empty vectors
  best_MAD <- Inf
  best_window <- c(NA, NA)
  best_n <- NA
  best_epsilonMLEmean <- NA
  best_epsilonMLElwr <- NA
  best_epsilonMLEupr <- NA
  original_y_ratio <- min_y_ratio
  
  # Filter full dataset within global xmin-xmax
  data <- data[data$x >= global_xmin & data$x <= global_xmax, ]
  
  n_tot <- nrow(data)
  n <- nrow(data)
  
  if (n < 5) {
    stop("Not enough x values in range to form a valid window.")
  }
  
  # Compute min and max window sizes
  full_x_range <- global_xmax - global_xmin
  min_window_size <- max(5, floor(n * min_window_fraction))  
  max_window_size <- floor(n * max_window_fraction)
  
  
  while (is.na(best_window[1]) && min_y_ratio > y_ratio_threshold) {  # Continue reducing min_y_ratio if no valid window is found
    for (sample_iter in 1:max_windows) {
      
      
      # Dynamically select window size
      window_size <- sample(seq(min_window_size, max_window_size), 1)  
      set.seed(sample_iter)
      # Randomly select xmin within global range
      dynamic_xmin <- sample(seq(global_xmin, global_xmax - full_x_range * min_window_fraction, length.out = 100), 1)
      dynamic_xmax <- dynamic_xmin + (full_x_range * sample(seq(min_window_fraction, max_window_fraction, length.out = 10), 1))
      
      # Ensure xmax does not exceed global_xmax
      dynamic_xmax <- min(dynamic_xmax, global_xmax)
      
      # Select data within this new dynamic range
      sampled_data <- data[data$x >= dynamic_xmin & data$x <= dynamic_xmax, ]
      
      
      x_range <- range(sampled_data$x)
      x=sampled_data$x
      y=sampled_data$y
      
      if (nrow(sampled_data) < 5) next  # Skip if not enough points for regression
      
      ### Fit epsilon using MLE (Bluteau et al. 2011, eq. 15)
      n=length(y)
      d=wu$df
      logL <- NULL
      
      ## generate range of potential epsilon values
      ep <- lseq(0.0000001,100,1000)
      
      ## loop through this range
      for(e in 1:length(ep)){
        predK <- alpha*(ep[e]^(2/3))*(x)^(-5/3)
        a=d*y/predK
        
        # prob. dens. function of the xd2 distributed sample
        fa <- (a^((d-2)/2)*exp(-a/2))/(2^(d/2)*gamma(d/2))
        logL[e] = n*log(d)-sum(log(predK))+sum(log(fa))
      }
      
      
      # estimate variance of epsilon, i.e. the curvature of logL at its maximum (Bluteau et al. 2011, eq. 16)
      imax <- which.max(logL)
      eps_hat <- ep[imax]
      
      # Fit a quadratic to logL vs log(ep) near the max for curvature
      mwidth <- 3  # use 3 to 7 points
      i_start <- max(1, imax - floor(mwidth/2))
      i_end   <- min(length(ep), imax + floor(mwidth/2))
      logep <- log(ep[i_start:i_end])
      ylogL <- logL[i_start:i_end]
      qfit <- lm(ylogL ~ stats::poly(logep, 2, raw = TRUE))
      # quadratic coefficient c = coef(qfit)[3] (since poly 2)
      ccoef <- coef(qfit)[3]
      # curvature in log-space approximate; convert back to variance of eps_hat
      # approximate variance on eps in log-space
      var_log_eps <- -1/(2 * ccoef)
      # approximate variance in eps (not log) via delta method:
      vare <- (exp(log(eps_hat))^2) * var_log_eps
      # approximate standard error: sqrt(vare)
      
      
      # estimate mean and asymptotic 95% confidence interval of epsilon
      epsilonMLEmean <- ep[which.max(logL)]
      epsilonMLElwr <- ep[which.max(logL)] - 1.96*sqrt(vare)
      epsilonMLEupr <- ep[which.max(logL)] + 1.96*sqrt(vare)
      
      
      ## predict spectral data
      predK <- alpha*(epsilonMLEmean^(2/3))*x^(-5/3)
      
      
      ## calculate R2 of model fit 
      SStot <- sum((y-mean(y))^2)
      SSres <- sum((y-predK)^2)
      #SSreg <- sum((predK-mean(y))^2)
      r2 <- 1-(SSres/SStot)
      
      ## calulate maximum absolute deviation (MAD) 
      MAD <- 1/length(y)* sum( abs(y/predK-mean(y/predK)) )  
      ## reject MAD?
      if(is.na(MAD)==FALSE){
        if(MAD > 2*(2/d)^(1/2)){
          MAD <- 99999
        }
      }
      # ratio of y values within the x range
      y_ratio <- max(predK)/min(predK)
      
      # Check if the y range meets the condition
      if (y_ratio >= min_y_ratio && MAD < best_MAD) {
        r2 <- r2
        best_MAD <- MAD
        best_n <- n
        best_window <- x_range
        best_epsilonMLEmean <- epsilonMLEmean 
        best_epsilonMLElwr <- epsilonMLElwr 
        best_epsilonMLEupr <- epsilonMLEupr 
        
      }
      
    } # close for loop
    
    # If no valid window found or if R2 is negative, reduce the min_y_ratio
    if (is.na(best_window[1]) | r2<0) {
      min_y_ratio <- min_y_ratio * reduction_factor
    }
  } ## close while loop
  
  return(list(best_window = best_window, 
              best_MAD = best_MAD,
              r2 = r2, 
              n = best_n, 
              n_tot =   n_tot,
              final_y_ratio_threshold = min_y_ratio,
              best_epsilonMLEmean=best_epsilonMLEmean,
              best_epsilonMLElwr=best_epsilonMLElwr,
              best_epsilonMLEupr=best_epsilonMLEupr))
}

##############################################################################################
