
#############################################################################################################
#############################################################################################################
## Code to generate sound pressure spectra and bubble size spectra from hydrophone recordings
#############################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## INPUTS: 
# Field observation data table with, among others,
#   Site... Site name
#   Temp... water temperature (°C)
#   EC... electrical conductivity (uS/cm)
#   Press... air pressure (bar)

#   d... hydrophone depth (m)

# .wav files with underwater sound recording

## Intermediate OUTPUS: 
# Data/Intermediatedata/HYDROPHONE/HYDROPHONE_",IDfilenames[i],"_Channel_",channel,"_oscillo.jpeg... figures, one per wav-file, with oscillograms
# Data/Intermediatedata/HYDROPHONE/HYDROPHONE_",IDfilenames[i],"_Channel_",channel,"_SPL.jpeg"... figures, one per wav-file, with sound pressure level spectrum 

# Data/Intermediatedata/HYDROPHONE/HYDROPHONE_metadata.tsv... metadata of bubble size distribution (for details, see Code/0_Functions/FUNCTION_Sound2Bubblesize.R and Data_Readme.pdf)
# Data/Intermediatedata/HYDROPHONE/HYDROPHONE_OctaveSPL.tsv... sound pressure level spectrum data (for details, see Code/0_Functions/FUNCTION_Sound2Bubblesize.R and Data_Readme.pdf) 
# Data/Intermediatedata/HYDROPHONE/HYDROPHONE_spectrum.tsv... bubble size distribution data (for details, see Code/0_Functions/FUNCTION_Sound2Bubblesize.R and Data_Readme.pdf)

## Clean OUTPUS:
# Data/Cleandata/Data_Macrobubblespectra.tsv... macrobubble size spectra file
#     IDfield.... Site/Spot ID
#     d ... Distance to step (cm)
#     f ... frequency (Hz)
#     a ... bubble radius (m)
#     valid ... Valid are estimates valid / fulfill model assumptions (TRUE/FALSE)
#     N ... relative number of bubbles for a given bubble radius

###########################################################################################

## load helper functions
library(tuneR)
library(plyr)
library(data.table)

source("Code/0_Functions/FUNCTION_Sound2Bubblesize.R")
source("Code/0_Functions/FUNCTION_Conductivity2Salinity.R")
source("Code/0_Functions/FUNCTION_selectMostStationaryWindow.R")

## should sound pressure level and bubble size spectra be plotted?
plotting=TRUE


####################################
### load Field observation data
####################################
DataFieldObservations <- read.delim("Data/Rawdata/Data_FieldObservations.tsv")

IDfield <- paste0(DataFieldObservations$Site,"_",DataFieldObservations$d)


#########################################
### load wav-filenames
#########################################

filenames <- list.files("Data/Rawdata/HYDROPHONE",pattern="*.wav", full.names=TRUE) 
IDfilenames <- substr(filenames,regexpr("_",filenames)+1,nchar(filenames)-4)

### match wav files with field excel sheet
idw <- match(IDfilenames,IDfield)

### get input data for bubble size model
EC <- DataFieldObservations$EC[idw]    # electrical conductivity (μS cm-1)
Temp <- DataFieldObservations$Temp[idw]    # water temperature (°C)
Press <- DataFieldObservations$Press[idw]  # air pressure (bar)
S = Conductivity2Salinity(Cond=EC,Temp=Temp,Press=Press) # Salinity (per mille)
d = 0.035 #hydrophone depth (centered) (m)


spectrum <- NULL
metadata <- NULL
OctaveSPL <- NULL


### loop through all .wav files and channels

for(w in 1:2){
  if(w==1){channel="L"}
  if(w==2){channel="R"}
  
  for (i in 1:length(filenames)){
    SigWaveDir <- filenames[i]
    
    ## select window with least artificial peaks caused by transient nonstationary events
    MostStationaryWindow <- selectMostStationaryWindow(
      filenames[i],
      window_sec = 8,
      hop_sec = 0.5,
      frame_ms = 50,
      channel = channel
    )
    
    
    ######## calculate bubbles size distribution
    
    Bubblesize <- Sound2Bubblesize(
      SigWaveDir=SigWaveDir,channel=channel,Temp=Temp[i],S=S[i],P0=Press[i]*10^5,
      epmin=0.005,epmax=0.025,d=d,Lmin = 2*d,Lmax=2*d,Rmin=0.01,Rmax=0.1,
      ga=1.4,ovlp=50,wl = 8192*2, Filter=TRUE,nfilt=3,pref=10^-6,sta=MostStationaryWindow$start_sec ,sto=MostStationaryWindow$end_sec )
    
    
    ########################################################################################################################
    ### plot oscissolgrams and sound pressure level spectra
    ### (bubble size spectra will be plotted later in "Code/2_MergeData/MERGEDATA_ABS_ADV_HYDRO_GasExchangeMODEL.R")
    ########################################################################################################################
  
    if(plotting==TRUE){
      
      ## plot oscillogram 
      
      ldf <- lapply(filenames[i], readWave)
      ldf_mono <- mono(ldf[[1]], which = if(channel=="L"){"left"}else{"right"} )

      jpeg(file=paste0("Data/Intermediatedata/HYDROPHONE/HYDROPHONE_",IDfilenames[i],"_Channel_",channel,"_oscillo.jpeg"))
      oscillo(ldf_mono,fastdisp=TRUE)
      abline(v=c(MostStationaryWindow$start_sec,MostStationaryWindow$end_sec),col=2,lwd=4)
      dev.off()
      
  
      ### plot sound pressure spectrum
    
      id=Bubblesize[[1]]$`Valid bubbles`
      SPL=Bubblesize[[1]]$`P PSD (Pa2/Hz)`
      SPLsmooth=Bubblesize[[1]]$`P PSD (Pa2/Hz) smoothed`
      f=Bubblesize[[1]]$`f Frequency (Hz)`

      jpeg(file=paste0("Data/Intermediatedata/HYDROPHONE/HYDROPHONE_",IDfilenames[i],"_Channel_",channel,"_SPL.jpeg"))
      
      plot(f[2:length(f)],SPL[2:length(f)],log="xy",type="l",ylim=c(1,max(SPL,na.rm=T)),col="orange",xlab="f (kHz)",ylab=expression(paste("PSD (",mu,"Pa2/Hz)")))
      abline(v=c(0.016,0.031,0.063,0.125),lty=2)
      lines(f[2:length(f)], SPLsmooth[2:length(f)], col="blue", lwd=2)
      legend("bottomleft", c("raw", "valid", "1/3-oct smoothed"),
             col=c("orange","red","blue"), lwd=c(1,2), bty="n")
      lines(f[id], SPLsmooth[id],lwd=2,col=2,lty=2)
      
      dev.off()
      
    }
    
    
    ## compile and save results
    
    spectrum0 <- cbind(channel,Bubblesize[[1]])
    metadata0 <- cbind(channel,Bubblesize[[2]])
    OctaveSPL0 <- cbind(channel,Bubblesize[[3]])
    
    spectrum <- rbind.fill(spectrum,spectrum0)
    metadata <- rbind.fill(metadata,metadata0)
    OctaveSPL <- rbind(OctaveSPL,OctaveSPL0)
    
    write.table(metadata,"Data/Intermediatedata/HYDROPHONE/HYDROPHONE_metadata.tsv", quote=FALSE, sep='\t', row.names = FALSE)
    write.table(OctaveSPL,"Data/Intermediatedata/HYDROPHONE/HYDROPHONE_OctaveSPL.tsv", quote=FALSE, sep='\t', row.names = FALSE)
    
  } # file
} # channel

## save spectrum outside loo to avoid slow computation times
write.table(spectrum,"Data/Intermediatedata/HYDROPHONE/HYDROPHONE_spectrum.tsv", quote=FALSE, sep='\t', row.names = FALSE)


###############################################################################
## restructure data to prepare export to final clean data

## get Site and distance to step for spectrum.tsv file
first_pos <- regexpr("_", spectrum$FileID)
all_pos <- gregexpr("_", spectrum$FileID)
second_pos <- sapply(all_pos, function(p) {
  if (length(p) >= 2 && p[1] != -1) p[2] else NA
})
spectrum$Site <- substr(spectrum$FileID,first_pos+1,second_pos-1)
spectrum$d <- substr(spectrum$FileID,second_pos+1,nchar(spectrum$FileID)-4)


## remove right (R) channel for some sites where R channel was not working properly
spectrum[which(spectrum$channel=="R" & (spectrum$Sit=="C6" | spectrum$Site=="C7") ),c(4:11)] <- NA

# check
table(spectrum$FileID[which(is.na(spectrum$'N rel #bubbles 50%CI'))])

## average R and L channel
setDT(spectrum)
cols_to_avg <- setdiff(names(spectrum), c("channel", "FileID", "f.Frequency..Hz.","Site","d"))
spectrum <- spectrum[
  ,
  c(
    list(
      Site = first(Site),
      d = first(d)
    ),
    lapply(.SD, mean, na.rm = TRUE)
  ),
  by = .(FileID, `f Frequency (Hz)`),
  .SDcols = cols_to_avg
]
spectrum$`Valid bubbles`[which(spectrum$`Valid bubbles`==1)] <- "TRUE"
spectrum$`Valid bubbles`[which(spectrum$`Valid bubbles`==0)] <- "FALSE"



###############################################################################
### EXPORT Macrobubble size spectral data (from hydrophone recordings)

DataMacBub <- spectrum[,c(3,4,2,6,7,9)]
colnames(DataMacBub) <- c("Site","d","f","a","valid","N")

write.table(DataMacBub,"Data/Cleandata/Data_Macrobubblespectra.tsv"
            , quote=FALSE, sep='\t', row.names = FALSE)

###############################################################################

