##############################################################################################################################
##############################################################################################################################
## Code for ADV Data processing
## calculates turbulent kinetic energy dissipation and several other hydraulic parameters from Nortek Vector ADV data
##############################################################################################################################
##############################################################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/08/12
## adjusted for dataset from step-pool systems in France, Italy and Sweden; described in manuscript
## Klaus, M., Durighetto, N., Khan, A. M., Chatton, E., Öquist, M., Peruzzo, P. and Botter, G. (in revision in "npj Hydrosphere").
## Bubble size spectra reveal distinct scaling patterns and downstream sorting in mountain streams 

###########################################################################################
###
### Please note: There is no golden standard method for estimating epsilon in rivers
### results are sensitive to many parameters, and must always be quality checked!
###
### Please note: For use with different ADV, the code needs to be adjusted
###
###############################################################################################################
### METHOD
### Code largely follows method described in detail in
###  
### Vingiani, F., Durighetto, N, Klaus, M., Schelker, J., Labasque, T. and Botter, W. (2021): Evaluatingstream CO2 
### outgassing via Drifting and Anchored chambers:results of a flume experiment, Biogeosciences, 18, 1223–1240, https://doi.org/10.5194/bg-18-1223-2021
###  
### Bluteau, C., Jones, N., and Ivey, G. (2011): Estimating turbulent kinetic energy dissipation using the inertial 
### subrange method in environmental flows, Limnology and Oceanography: Methods, 9, https://doi.org/10.4319/lom.2011.9.302, 
###
###############################################################################################################
### INPUTS: 
# ADV files (.dat, .hdr, .sen), Nortek Vector ADV

## Field observation data table with, among others,
# Site... Site name
# d... distance to step (cm)
# Temp... water temperature (°C)
# l... Water depth (m)
# Width... Stream width (m)
# EC... electrical conductivity (uS/cm)
# Press... air pressure (bar)
# SensorDepth... sensor depth (m)
# ADVDir ... Orientation of ADV probe in stream ("Up"
#        "Up" =  facing upstream, parallel with main flow direction (probe direction = 0°)
#        "UpRight" =  facing upstream, parallel with main flow direction (probe direction = 45°)
#        "Right" =  facing upstream, parallel with main flow direction (probe direction = 90°)
#        "Down" =  facing upstream, parallel with main flow direction (probe direction = 180°)
#        "Left" =  facing upstream, parallel with main flow direction (probe direction = 270°)
#        "UpLeft" =  facing upstream, parallel with main flow direction (probe direction = 315°)

### OUTPUTS: 

# (1) plot with flow velocity spectra and lines showing inertial subrange fits

# (2) output.tsv-file which contains the following columns:
# Variable name:		Explanation:
# ID...    Sampling ID
# filename...			Filename
# Site...   Study site name
# d...  distance to step (m)
# DataTime...			Date and time
# VelocityRange...	Vectrino setting of Velocity range (m/s)
# TransmitLength...		Vectrino setting of Transmit length (mm)
# SamplingVolume...		Vectrino setting of Sampling volume length scale (mm)
# Headwavelength...   characteristic acoustic wavelength (mm) defining the minimum resolvable particle size                                                 
# Temperature...		Instrument temperature (°C) (Note: this is not water temperature, because ADV casing may have been kept outside water, temperature effects on sound propagation was corrected for a posteriori)
# VelocityScaling...		Vectrino setting of Velocity scaling
# CoordinateSystem...	Coordinate system of data aquisition
# l...		Stream depth (m)
# Width...		Stream width (m)
# TKE...				Turbulent kinetic energy (m2/s2)
# u_mean...				mean flow velocity in u direction (m/s)
# v_mean...				mean flow velocity in v direction (m/s)
# w_mean...				mean flow velocity in w direction (m/s)
# urot_mean...			 mean flow velocity in u direction (m/s), after rotation in mean flow direction
# vrot_mean...				 mean flow velocity in v direction (m/s), after rotation in mean flow direction
# wrot_mean...				 mean flow velocity in w direction (m/s), after rotation in mean flow direction
# 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)
# Vadv...Advection velocity (m/s)
# epsUrms...turbulent kinetic energy dissipation (m2/s3) estimated from large-eddy scaling, using RMS velocity in u direction (Urms)
# signal.rat.X		signal to noise ratio for X direction, despiked data
# signal.rat.Y		signal to noise ratio for Y direction
# signal.rat.Z		signal to noise ratio for Z direction
# correlation.X		correlation for X direction
# correlation.Y		correlation for Y direction
# correlation.Z		correlation for Z direction
# 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 (°)
# mean_u_mean... mean across time segments of mean flow velocities i u direction per segment (m/s)
# mean_v_mean... mean across time segments of mean flow velocities i v direction per segment (m/s)
# mean_w_mean... mean across time segments of mean flow velocities i w direction per segment (m/s)
# sd_u_mean... mean across time segments of standard deviation of flow velocities i u direction per segment (m/s)
# sd_v_mean... mean across time segments of standard deviation of flow velocities i v direction per segment (m/s)
# sd_w_mean... mean across time segments of standard deviation of flow velocities i w direction per segment (m/s)
# mean_u_sd... standard deviation across time segments of mean flow velocities i u direction per segment (m/s)
# mean_v_sd... standard deviation across time segments of mean flow velocities i v direction per segment (m/s)
# mean_w_sd... standard deviation across time segments of mean flow velocities i w direction per segment (m/s)
# sd_u_sd... standard deviation across time segments of standard deviation of flow velocities i u direction per segment (m/s)
# sd_v_sd... standard deviation across time segments of standard deviation of flow velocities i v direction per segment (m/s)
# sd_w_sd... standard deviation across time segments of standard deviation of flow velocities i w direction per segment (m/s)
# epsilonMLE:u...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (u direction), mean
# epsilonMLE:v...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (v direction), mean
# epsilonMLE:w...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (w direction), mean
# epsilonMLElwr:u...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (u direction), lower boundary of 95% confidence interval
# epsilonMLElwr:v...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (v direction),  lower boundary of 95% confidence interval
# epsilonMLElwr:w...	Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (w direction),  lower boundary of 95% confidence interval
# epsilonMLEupr:u...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (u direction), upper boundary of 95% confidence interval
# epsilonMLEupr:v...		Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (v direction),  upper boundary of 95% confidence interval
# epsilonMLEupr:w...	Maximum Likelihood estimate of TKE dissipation rate (m2/s3) (w direction),  upper boundary of 95% confidence interval
# realr2:u...			Coefficient of determination of maximum likelihood predicted vs. observed spectrum (u direction)
# realr2:v...			Coefficient of determination of maximum likelihood predicted vs. observed spectrum (v direction)
# realr2:w...			Coefficient of determination of maximum likelihood predicted vs. observed spectrum (w direction)
# MAD:u...			Maximum absolute deviation of maximum likelihood predicted vs. observed spectrum (u direction)
# MAD:v...			Maximum absolute deviation of maximum likelihood predicted vs. observed spectrum (v direction)
# MAD:w...			Maximum absolute deviation of maximum likelihood predicted vs. observed spectrum (w direction)
# lower.k:u...			selected lower wave number threshold (rad/m) for inertial subrange (u direction)
# lower.k:v...			selected lower wave number threshold (rad/m) for inertial subrange (v direction)
# lower.k:w...		selected lower wave number threshold (rad/m) for inertial subrange (w direction)
# upper.k:u...			selected upper wave number threshold (rad/m) for inertial subrange (u direction)
# upper.k:v...			selected upper wave number threshold (rad/m) for inertial subrange (v direction)
# upper.k:w...		selected upper wave number threshold (rad/m) for inertial subrange (w direction)
# f:u...				frequency associated with kolmogorov scale (above which spectrum shows noise) (u direction) (Hz)
# f:v...				frequency associated with kolmogorov scale (above which spectrum shows noise) (v direction) (Hz)
# f:w...			frequency associated with kolmogorov scale (above which spectrum shows noise) (w direction) (Hz)
# decade:u...				spectral width (extent of energy drop) of inertial subrange expressed as decades/10 (u direction)
# decade:v...				spectral width (extent of energy drop) of inertial subrange expressed as decades/10 (v direction)
# decade:w...			spectral width (extent of energy drop) of inertial subrange expressed as decades/10 (w direction)
# epsilon_m:u... minimum resolvable TKE dissipation rate (m2/s3) (u direction)
# epsilon_m:v... minimum resolvable TKE dissipation rate (m2/s3) (v direction)
# epsilon_m:w... minimum resolvable TKE dissipation rate (m2/s3) (w direction)
# noisefloor:u... wavenumber above which noise floor starts (rad/m) (u direction)
# noisefloor:v... wavenumber above which noise floor starts (rad/m) (v direction)
# noisefloor:w... wavenumber above which noise floor starts (rad/m) (w direction)
# sdVel:u... standard deviation of flow velocity, filtered for high-frequency noise (u direction) (m/s)
# sdVel:v... standard deviation of flow velocity, filtered for high-frequency noise (v direction) (m/s)
# sdVel:w... standard deviation of flow velocity, filtered for high-frequency noise (w direction) (m/s)
# spikeALL... proportion of time series that had simultaneous spikes in all three flow directions (according to despiking algorithm)
# spikeANY... proportion of time series that had spikes in any flow direction (according to despiking algorithm)
# spikeONE... proportion of time series that had spikes in one flow direction (according to despiking algorithm)
# spikeTWO... proportion of time series that had spikes in two flow directions (according to despiking algorithm)
# spikeONETWO... proportion of time series that had simultaneous spikes in one or two flow directions (according to despiking algorithm)

###############################################################################################################

######################################
## load support functions
######################################
source("Code/0_Functions/FUNCTION_calcEpsilon.R")
source("Code/0_Functions/FUNCTION_Conductivity2Salinity.R")
source("Code/0_Functions/FUNCTION_calcSoundSpeed.R")
source("Code/0_Functions/FUNCTION_TempSal2FreshwaterDensity.R")

####################################
### load Field observation data
####################################
DataFieldObservations <- read.delim("Data/Rawdata/Data_FieldObservations.tsv")

IDfield <- paste0(DataFieldObservations$Site,"_",DataFieldObservations$d)


######################################
## Load ADV data
######################################

## get filenames; select only those files despiked earlier using the matlab code, but keep names of raw data in filenamesraw
files <- list.files("Data/Rawdata/ADV",pattern="*.dat", full.names=TRUE)
filenames <- substr(files,18,99) 
filenamesraw <- filenames[-grep("despike",filenames)]
filenames <- filenames[grep("despike",filenames)]
filenameshdr <- substr(list.files("Data/Rawdata/ADV",pattern="*.hdr", full.names=TRUE),18,99) 
filenamessen <- substr(list.files("Data/Rawdata/ADV",pattern="*.sen", full.names=TRUE),18,99) 

## ADV file ID
IDADV <- substr(filenamesraw,5,nchar(filenamesraw)-4)

## make same order as in field observations
idw <- match(IDADV,IDfield)
IDADV[which(is.na(idw))]


## load stream characteristics needed for TKE dissipation calculation
Site <- DataFieldObservations$Site[idw]
d <- DataFieldObservations$d[idw]/100
Temp <- DataFieldObservations$Temp[idw]
l <- DataFieldObservations$l[idw]/100
Width <- DataFieldObservations$Width[idw]/100
EC <- DataFieldObservations$EC[idw]
Press <- DataFieldObservations$Press[idw] 

S <- Conductivity2Salinity(Cond=EC,Temp=Temp,Press=Press) 

## assign probe deployment (roll) angle, using field notes on how the probe was positioned in the stream relative to main flow direction
ProbeDir <- DataFieldObservations$ADVdir[idw]
ProbeDir[which(ProbeDir=="Up")] <- 0
ProbeDir[which(ProbeDir=="UpRight")] <- 45
ProbeDir[which(ProbeDir=="Right")] <- 90
ProbeDir[which(ProbeDir=="Down")] <- 180
ProbeDir[which(ProbeDir=="Left")] <- 270
ProbeDir <- as.numeric(ProbeDir)

SensorDepth <- 0.05 # m


######################################
## loop through all files
######################################

## should flow velocity spectral data be saved (used for Supplementary Figure S2 in Klaus et al.)
savespectraldata <- rep(FALSE,length(filenames))
## select four sites
savespectraldata[which(
  filenames=="ADV_6_50.dat_despike.dat" | 
  filenames=="ADV_14_80.dat_despike.dat" |
  filenames=="ADV_B_150.dat_despike.dat" |
  filenames=="ADV_C14_20.dat_despike.dat")] <- TRUE

## should flow velocity spectra be plotted and plots be saved?
diagnostic = TRUE


## make empty output file
output <- NULL

for (i in 1:length(filenames)){

## define position of ADV
position_data <- NULL
position_data$heading <- 180
position_data$pitch <- 90 
position_data$roll <- ProbeDir[i]


################################################################################
## extract metadata on ADV collection from the .hdr file
################################################################################

ihdr <- match(substr(filenamesraw[i],1,str_locate(filenamesraw,".dat")[i,1]),substr(filenameshdr,1,str_locate(filenameshdr,".hdr")[,1]))
isen <- match(substr(filenamesraw[i],1,str_locate(filenamesraw,".dat")[i,1]),substr(filenamessen,1,str_locate(filenamessen,".sen")[,1]))
DateTime <- sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=7)[7]) ## DateTime
freq <- gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=12)[12]))
freq  <- as.numeric(gsub("/", "",freq))
VelocityRange <- gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=13)[13]))
VelocityRange  <- as.numeric(gsub("/", "",VelocityRange))
TransmitLength <- gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=18)[18]))
SamplingVolume <- gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=16)[16]))
SamplingVolume <- as.numeric(gsub("/", "",SamplingVolume))


## .sen files have slightly different structures for observations from sites in France/Italy and Abisko/Krycklan
# France / Italy (Site names for this region were numeric)
if(is.na(as.numeric(Site[i]))==TRUE){
Temperature <- str_split(readLines(paste0("Data/Rawdata/ADV/",filenamessen[isen]),n=1)," ")[[1]][18]
Temperature <- as.numeric(gsub("/", "",Temperature))
c_uncorr <- str_split(readLines(paste0("Data/Rawdata/ADV/",filenamessen[isen]),n=1)," ")[[1]][11]
c_uncorr <- as.numeric(gsub("/", "",c_uncorr))
VelocityScaling <- gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=26)[26]))
VelocityScaling <- as.numeric(gsub("/", "",VelocityScaling))
coord <- readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=32)[32]
CoordinateSystem <- substr(coord,nchar(coord)-2,nchar(coord))
}

# Abisko/Krycklan (Site names for this region were non-numeric)
if(is.na(as.numeric(Site[i]))==FALSE){
vec <- str_split(readLines(paste0("Data/Rawdata/ADV/",filenamessen[isen]),n=1)," ")[[1]]
vec <- vec[vec != ""]
Temperature <- vec[14]
Temperature <- as.numeric(gsub("/", "",Temperature))
c_uncorr <- vec[10]
c_uncorr <- as.numeric(gsub("/", "",c_uncorr))
VelocityScaling <- gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=26)[26]))
VelocityScaling <- as.numeric(gsub("/", "",VelocityScaling))
coord <- readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=32)[32]
CoordinateSystem <- substr(coord,nchar(coord)-2,nchar(coord))
}

### extract ADV transformation matrix
Transformationmatrix1 <- as.numeric(unlist(strsplit((gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=101)[101])))," ")))
Transformationmatrix2 <- as.numeric(unlist(strsplit((gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=102)[102])))," ")))
Transformationmatrix3 <- as.numeric(unlist(strsplit((gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=103)[103])))," ")))
trans_data <- c(Transformationmatrix1,Transformationmatrix2,Transformationmatrix3) # trans matrix for example package data
trans_matrix <- matrix(data = trans_data, ncol = 3, byrow = TRUE)
# Scale the transformation matrix correctly to floating point numbers
trans_matrix <- trans_matrix/4096 

################################################################################
## load ADV velocity data file
################################################################################

dataOrig <- loadADV(filenames[i],"Data/Rawdata/ADV")

## truncate one file where time series after 155s was erroneous
if(filenames[i]=="ADV_8_170.dat_despike.dat"){
  dataOrig <- dataOrig[1:(155*freq),]
}

## save original file for archive
dataOrig <- dataOrig[,3:ncol(dataOrig)]

########################################
## transform coordinates (XYZ -> ENU) 
# X negative = downwards
# Y negative = towards left
# Z negative = flow upstream
# E is cross-stream  (negative = towards right)
# N is upstream (negative = flow downstream)
# U is vertical  (negative = downwards)
data_transf <- transformCoordinatesADV(trans_matrix, dataOrig, position_data)

#### resort vector to convert ENU to uvw
## data_transf[,2] = u is upstream (negative = flow downstream)
## data_transf[,1] = v is cross-stream  (negative = towards right)
## data_transf[,3] = w is vertical  (negative = downwards)
data_transf <- data_transf[,c(2,1,3)]


###################################################################
## compute speed of sound (m/s) 
c_Field = calcSoundSpeed(Temp=Temp[i],Depth=SensorDepth,S=S[i])
  
## correct flow velocity for sound speed ratio
data = data_transf * (c_Field/c_uncorr)

headfrequency <- as.numeric(unlist(strsplit((gsub("[[:alpha:]]", "", sub("\\D+","",readLines(paste0("Data/Rawdata/ADV/",filenameshdr[ihdr]),n=98)[98])))," ")))

## characteristic acoustic wavelength (m/s / KHz = mm) defining the minimum resolvable particle size; should be large relative to particles
headwavelength <- c_Field/headfrequency


#######################################################################################
## extract some useful velocity statistics and quality measures from ADV data

## Signal-to-noise-ratio (SNR) + correlation 
SNR <- colMeans(dataOrig[,7:9],na.rm=TRUE)
CORR <- colMeans(dataOrig[,10:12],na.rm=TRUE)

## frequency of spikes in time series caused by bubbles (Birjani et al. 2011)
# spikes in all three flow directions
spikeALL <- length(which(is.na(dataOrig[,7]) & is.na(dataOrig[,8]) & is.na(dataOrig[,9]))) / length(dataOrig[,7])
# spikes in any of the three flow directions
spikeANY <- length(which(is.na(dataOrig[,7]) | is.na(dataOrig[,8]) | is.na(dataOrig[,9]))) / length(dataOrig[,7])
# spikes in two of the three flow directions
spikeTWO <- length(which(
  (is.na(dataOrig[,7]) & is.na(dataOrig[,8]) & dataOrig[,9]>=0) |
    (is.na(dataOrig[,7]) & is.na(dataOrig[,9]) & dataOrig[,8]>=0) |
    (is.na(dataOrig[,8]) & is.na(dataOrig[,9]) & dataOrig[,7]>=0) 
)) / length(dataOrig[,7])
# spikes in one of the three flow directions
spikeONE <- length(which(
  (is.na(dataOrig[,7]) & dataOrig[,8]>=0 & dataOrig[,9]>=0) |
    (is.na(dataOrig[,8]) & dataOrig[,9]>=0 & dataOrig[,7]>=0) |
    (is.na(dataOrig[,9]) & dataOrig[,8]>=0 & dataOrig[,7]>=0) 
)) / length(dataOrig[,7])
# spikes in one or two of the three flow directions
spikeONETWO <- length(which(
  (is.na(dataOrig[,7]) & dataOrig[,8]>=0 & dataOrig[,9]>=0) |
    (is.na(dataOrig[,8]) & dataOrig[,9]>=0 & dataOrig[,7]>=0) |
    (is.na(dataOrig[,9]) & dataOrig[,8]>=0 & dataOrig[,7]>=0) |
    (is.na(dataOrig[,7]) & is.na(dataOrig[,8]) & dataOrig[,9]>=0) |
    (is.na(dataOrig[,7]) & is.na(dataOrig[,9]) & dataOrig[,8]>=0) |
    (is.na(dataOrig[,8]) & is.na(dataOrig[,9]) & dataOrig[,7]>=0) 
)) / length(dataOrig[,7])



################################################
### calculate epsilon
################################################


## calculate for unfiltered spectrum, for estimation of epsilon
Epsilon <- calcEpsilon(data=data,freq=freq, Water_Depth=l[i], Water_Width=Width[i], 
SensorDepth=SensorDepth, SamplingVolume=SamplingVolume, diagnostic = diagnostic, n=4, Temperature=Temp[i],inertial=TRUE)

local({
dev.set (2)
dev.print (device=tiff, file=paste0("Data/Intermediatedata/ADV/",filenames[i],"_Spectra.tiff"), width=par("din")*100, res=100);
})
dev.off ()


if(savespectraldata[i]==TRUE){
## save data of selected figures for data repository (Klaus et al. Supplement)
PSD <- data.frame(Epsilon[[6]],Epsilon[[6]][,1]*Epsilon[[2]]["Vadv",1]/(2*pi))
colnames(PSD) <- c("wavenumber_radm","PSD_u_m2s2radm","PSD_v_m2s2radm","PSD_w_m2s2radm","frequency_Hz")
Ablines <- data.frame(Epsilon[[5]][1,1],Epsilon[[5]][1,2],Epsilon[[5]][1,3],
                      Epsilon[[5]][1,4],Epsilon[[5]][2,4],Epsilon[[5]][3,4],
                      Epsilon[[5]][1,5],Epsilon[[5]][2,5],Epsilon[[5]][3,5])
colnames(Ablines) <- c("wave_number_StreamWidth_radm","wave_number_WaterDepth_radm","wave_number_SamplingVolume_radm",
                       "wave_number_Noise_u_radm","wave_number_Noise_v_radm","wave_number_Noise_w_radm",
                       "wave_number_KolmogorovLength_u_radm","wave_number_KolmogorovLength_v_radm","wave_number_KolmogorovLength_w_radm")

## save data
write.table(PSD,paste0("Data/Cleandata/Data_FigS2_FlowVelocitySpectra_",IDADV[i],".tsv"), 
                     quote=FALSE, sep='\t', row.names = FALSE)
write.table(Ablines,paste0("Data/Cleandata/Data_FigS2_FlowVelocitySpectraMetaData_",IDADV[i],".tsv"), 
                         quote=FALSE, sep='\t', row.names = FALSE)
}


############################
#### compile and save output
############################

output0 <- c(
IDADV[i],
filenames[i],
Site[i],
d[i],
DateTime,
VelocityRange,
TransmitLength,
SamplingVolume,
headwavelength,
Temperature,
VelocityScaling,
CoordinateSystem,
l[i],
Width[i],
Epsilon[[2]]["TKE",1],
u_mean=mean(data[,1]),
v_mean=mean(data[,2]),
w_mean=mean(data[,3]),
urot_mean=mean(Epsilon[[4]][,1]),
vrot_mean=mean(Epsilon[[4]][,2]),
wrot_mean=mean(Epsilon[[4]][,3]),
Epsilon[[2]]["Urms",1],
Epsilon[[2]]["Urms_isr",1],
Epsilon[[2]]["Vrms",1],
Epsilon[[2]]["Vrms_isr",1],
Epsilon[[2]]["Wrms",1],
Epsilon[[2]]["Wrms_isr",1],
Epsilon[[2]]["Vadv",1],
Epsilon[[2]]["epsUrms",1],
SNR,
CORR,
Epsilon[[2]]["FrozenTurb",1],
Epsilon[[2]]["FrozenTurb_isr",1],
Epsilon[[2]]["A_rad",1],
Epsilon[[2]]["theta_rad",1],
Epsilon[[3]],
unmatrix(Epsilon[[1]],byrow=TRUE),
spikeALL,
spikeANY,
spikeONE,
spikeTWO,
spikeONETWO)

names(output0)[c(1:29)] <- c("ID","filename","Site","d","DataTime","VelocityRange","TransmitLength","SamplingVolume","Headwavelength",
"Temperature","VelocityScaling","CoordinateSystem","l","Width","TKE","u_mean","v_mean","w_mean","urot_mean","vrot_mean","wrot_mean","Urms","Urms_isr","Vrms","Vrms_isr","Wrms","Wrms_isr","Vadv","epsUrms")
 
names(output0)[c(36:39)] <- c("FrozenTurb","FrozenTurb_isr","A_rad","theta_rad")


names(output0)[(length(names(output0))-4):length(names(output0))] <- c("spikeALL","spikeANY","spikeONE","spikeTWO","spikeONETWO")

output <- rbind(output,output0)

# save updated model output dataframe
write.table(output, file="Data/Intermediatedata/ADV/ADV_TKEdissipation_output.tsv", quote=FALSE, sep='\t', row.names = FALSE)

} ## close i loop (through different files)







