##################################################################################################
##################################################################################################
# Rotation of 3D flow velocities into mean flow direction  (mean(v)=0)
##################################################################################################
##################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## INPUTS:
# data...dataframe with flow velocities (u,v,w) (downstream, lateral, vertical)

## OUTPUTS:
# vel_project...rotated flow velocity vector
# theta...vertical rotation angle
# A...horizontal rotation angle
# U...Mean advective flow velocity (m/s)

## Reference
# Thomas Foken (2008): Micrometeorology. Springer-Verlag, Berlin, Heidelberg
# https://link.springer.com/book/10.1007%2F978-3-540-74666-9
# See Chapter 4 eqs 4.5, 4.6, 4.7 and 4.8 for this method.
###########################################################################################


projectADV <- function(data) {
  
  u <- data[,1] ## parallel with flow
  v <- data[,2] ## perpendicular with flow
  w <- data[,3] ## vertical
  
  A = atan2(mean(v,na.rm=TRUE),mean(u,na.rm=TRUE))
  
  urot = u*cos(A)+v*sin(A)
  vrot = -u*sin(A)+v*cos(A)
  
  umean = mean(urot,na.rm=TRUE)
  wmean = mean(w,na.rm=TRUE) 
  theta= atan2(wmean,umean) 
  
  wcor = w * cos(theta) - urot * sin(theta) 
  ucor = w * sin(theta) + urot * cos(theta) 
  
  # Mean advective flow
  U <- mean(ucor, na.rm=TRUE)
  
  return(list(
    U = U,
    A=A,
    theta=theta,
    vel_project = cbind(ucor, vrot, wcor)
  ))
}
###########################################################
