############################################################################################################
############################################################################################################
## function to convert underwater sound spectra to bubble size spectra
############################################################################################################
############################################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################
##
## Please note the assumptions behind this conversion: 
## (1) the sound spectrum is only due to bubbles oscillating 
## at their natural frequencies in a free field
## (2)single bubble's contribution
## to the spectrum is only in a narrow frequency band about f
## (3) bubble pressure pulses are damped following a sinosoidal law
## (4) bubble pressure pulses of neighboring bubbles do not affect each other  

## uncertainty in key input parameters (R, L, ep) are propagated through bootstrap approach
## 
#########################################################################################
#
# INPUTS 
# SigWaveDir = directory to signal wave file (with bubble sound)
# channel = hydrophone channel (here, select "L" for left and "R" for right
# Temp = Water temperature ( C)
# S = total dissolved salt (parts per thousand)
# P0 = pressure of surrounding liquid (Pa)
# d = distance between hydrophone and the free water surface (m)
# Lmin = minimum estimate of twice the distance between the bubble center and the free water surface (m)
# Lmax = maximum estimate of twice the distance between the bubble center and the free water surface (m)
# Rmin = minimum estimate distance between hydrophone receiver and bubble (m) 
# Rmax = maximum estimate distance between hydrophone receiver and bubble (m) 
# ovlp = overlap between two successive fft analysis windows (in %) (seewave package)
# wl = length of the window for the fft analysis (seewave package)
# Diff = subtract reference wave with background noise from signal wave? (TRUE/FALSE)
# Filter = filter spectrum by running median to remove spikes? (TRUE/FALSE)
# nfilt = filter window size
# pref = reference pressure level (Pa)
# sta = starting time at which .wav file should be cropped for analysis
# sto = stop time at which .wav file should be cropped for analysis
#
# CONSTANTS
# ga = ratio of the specific heats of the bubble gas (adiabatic compression), for air it is 1.4
# epmin = minimum estimate of amplitude of the bubble surface oscillations divided by the equilibrium bubble radius
# epmax = maximum estimate of amplitude of the bubble surface oscillations divided by the equilibrium bubble radius
#
# CALCULATED VARIABLES
# ph = Water density (Kg/m3)
# c = speed of sound (m/s) 
# P = mean square of measured sound spectrum level (dB re 1  Pa)
# fg = frequencies associated to P (1/s)
# f = selected frequency (1/s)
# de = bubble damping coefficient (dimensionless)
# k = acoustic wave number (m)
# ag = bubble radius associated to f
# p2 = mean square signal level for a single bubble resonating at frequency f (Pa^2)
#
# OUTPUTS
# list with 5 elements:
# [[1]] power spectral density of sound pressure levels and bubble size distributions of signal wave (with bubbles)
#   FileID... file name
#   f Frequency (Hz)... Frequency (Hz)
#   a Radius (m)... bubble radius (m)
#   Valid bubbles... are bubble density estimates valid (fulfill method assumptions)?
#   N rel #bubbles 2.5%CI... number of bubbles, 2.5% confidence interval bound estimate (note that this estimate should be treated as relative, as reference volume is not defined)
#   N rel #bubbles 50%CI... number of bubbles, median estimate (note that this estimate should be treated as relative, as reference volume is not defined)
#   N rel #bubbles 97.5%CI... number of bubbles, 97.5% confidence interval bound estimate (note that this estimate should be treated as relative, as reference volume is not defined)
#   P PSD (Pa2/Hz)... Sound power spectral density, raw spectrum (Pa2/Hz)
#   P PSD (Pa2/Hz) smoothed... Sound power spectral density, smoothed spectrum (Pa2/Hz)

# [[2]] summary of input and output data
#  SigWaveDir ... wave file directory
#   Temp ... Water temperature ( C)
#   S ... total dissolved salt (parts per thousand)
#   P0 ... pressure of surrounding liquid (Pa)
#   d ... distance between hydrophone and the free water surface (m)
#   min(L) ... minimum estimate of twice the distance between the bubble center and the free water surface (m)
#   max(L) ... maximum estimate of twice the distance between the bubble center and the free water surface (m)
#   min(R) ... minimum estimate distance between hydrophone receiver and bubble (m) 
#   max(R) ... maximum estimate distance between hydrophone receiver and bubble (m) 
#   min(ep) ... minimum estimate of amplitude of the bubble surface oscillations divided by the equilibrium bubble radius
#   max(ep) ... maximum estimate of amplitude of the bubble surface oscillations divided by the equilibrium bubble radius
#  amean025 ... mean bubble size, 2.5% confidence interval bound estimate,  weighted by number of bubbles
#  amean500 ... mean bubble size, median estimate,  weighted by number of bubbles
#  amean975 ... mean bubble size, 97.5% confidence interval bound estimate,  weighted by number of bubbles
#  asd025 ... standard deviation of bubble size, 2.5% confidence interval bound estimate,  weighted by number of bubbles
#  asd500 ... standard deviation of bubble size, median estimate,  weighted by number of bubbles
#  asd975 ... standard deviation of bubble size, 97.5% confidence interval bound estimate,  weighted by number of bubbles
#   Filter ... filter spectrum by running median to remove spikes? (TRUE/FALSE)
#   nfilt ... filter window size

# [[3]] sound pressure levels of signal wave as means for 10 octaves and for frequency bands associated with flow sound/turbulence and surfacing bubbles (see code (1))
# table with mean+-sd sound pressure levels ("SPLm" and "SPLsd") for octaves from 16 Hz to 32 KHz, 
# and for frequency intervals associated to flow sound / turbulence and surfacing bubbles (prmst and prmsb)


## Reference
## Loewen, M. R., and W. K. Melville. 1991. A model of the sound generated by breaking waves. 
## J. Acoust. Soc. Am. 90: 2075 2080. doi:https://doi.org/10.1121/1.401634

# number average bubble size and measure of spread, following 
# Pandit, A. B., J. Varley, R. B. Thorpe, and J. F. Davidson. 1992. 
# Measurement of Bubble Size Distribution: An acoustic technique. 
# Chem. Eng. Sci. 47: 1079 1089. doi:https://doi.org/10.1016/0009-2509(92)80233-3

##################################################################### 

Sound2Bubblesize <- function(
SigWaveDir,
channel,
Temp,
S,
P0,
epmin,
epmax,
d,
Lmin,
Lmax,
Rmin,
Rmax,
ga,
ovlp,
wl,
id,
Filter,
nfilt,
pref,
sta,
sto){



## load libraries and helper functions
library(seewave)
library(emdbook)
library(tuneR)
library(Hmisc)
  
source("Code/0_Functions/FUNCTION_calcSoundSpeed.R")
source("Code/0_Functions/FUNCTION_TempSal2FreshwaterDensity.R")
source("Code/0_Functions/FUNCTION_smoothSpectrum.R")
source("Code/0_Functions/FUNCTION_getOctaveSPL.R")

# functions to get percentiles
perc025 <- function(x){quantile(x,0.025,na.rm=TRUE)}
perc975 <- function(x){quantile(x,0.975,na.rm=TRUE)}
perc500 <- function(x){quantile(x,0.5,na.rm=TRUE)}
  
  
# compute freshwater density (Kg/m3)    
ph=TempSal2FreshwaterDensity(Temp)

## compute speed of sound (m/s)
c = calcSoundSpeed(Temp=Temp,S=S,Depth=d)

## load signal sound wave
SigWave <- lapply(SigWaveDir, readWave)
SigWave_R <- mono(SigWave[[1]], which = "right")
SigWave_L <- mono(SigWave[[1]], which = "left")

# set start and stop time, exclude first and last second
start=sta
Sigstop=sto

# calculate sound pressure spectrum (power spectral density (Pa^2/Hz))
if(channel=="L"){
SigWave <- meanspec(SigWave_L,wl = wl, ovlp = ovlp,FUN=mean,PSD=TRUE,PMF=FALSE,norm=FALSE,from=start,to=Sigstop,plot=FALSE)
}
if(channel=="R"){
SigWave <- meanspec(SigWave_R,wl = wl, ovlp = ovlp,FUN=mean,PSD=TRUE,PMF=FALSE,norm=FALSE,from=start,to=Sigstop,plot=FALSE)
}
if(Filter==TRUE){
# 1/N octave smoothing the frequency spectrum
SigWaveSmoothed <- smoothSpectrum(SigWave, N = nfilt)
}else{
SigWaveSmoothed <- SigWave
}




# convert frequency from kHz to Hz
f=SigWaveSmoothed[,1]*1000
# convert f to radian frequency (rad/s)
w=2*pi*f

# bubble damping coefficient (energy loss due to thermal conduction, work against viscous forces + energy lost as acoustic wave)
de = (4.4*10^-4*f^0.5)/(1+f/(2.5^10^5))  # Crowther (1988), cited in Loewen and Melville (1991)

# acoustic wave number (1/m)
k = 2*pi*f/c

## bubble radius associated to f
a = 1/(w)*(3*ga*P0/ph)^(1/2)

#################################
## compute bubble size spectrum

# get measured sound power spectrum density (square of spectrum) (Pa2/Hz)
P <- SigWaveSmoothed[,2]


## use monte carlo method to propagate uncertainty in parameters ep, L and R
set.seed(1)
epi = runif(1000,epmin,epmax)
set.seed(1)
Li = runif(1000,Lmin,Lmax)
set.seed(1)
Ri = runif(1000,Rmin,Rmax)

R <- matrix(NA,nrow=wl/2,ncol=1000)
L <- matrix(NA,nrow=wl/2,ncol=1000)
ep <- matrix(NA,nrow=wl/2,ncol=1000)
for(h in 1:1000){
R[,h] <- Ri[h]
L[,h] <- Li[h]
ep[,h] <- epi[h]
}

## mean square signal level of single bubble resonating at frequency f (Pa2)
p2 =  (3*ga*P0/ph)^3*(ph*ep*d*L/(R^2*c))^2* ( (2/(de*w*(de^2+4))+(de^2+2)/((k*R)^2*(de*w*(de^2+4))))-2/(k*R*w*(de^2+4) ) ) 

#  number of bubbles oscillating at frequency f
N = (P/p2)

N025 <- apply(N,1,perc025)
N500 <- apply(N,1,perc500)
N975 <- apply(N,1,perc975)

# compute N only if the following assumptions are fulfilled:
# - k*L<1, this removes extremely small bubbles 
# - k*a should be <<1
# note that algorithm also predicts extremely (unrealistically) large bubbles (even if at very low concentrations)
# maximum bubble radius found in other studies was 7.4 mm (Loewen and Melville 1991)

id = which(k*Lmax<1 & k*a<0.05) 


# number average bubble size and measure of spread 

amean025 = sum(N025[id]*a[id],na.rm=TRUE)/sum(N025[id],na.rm=TRUE)
amean500 = sum(N500[id]*a[id],na.rm=TRUE)/sum(N500[id],na.rm=TRUE)
amean975 = sum(N975[id]*a[id],na.rm=TRUE)/sum(N975[id],na.rm=TRUE)

# standard deviation of bubble size
asd025 = sqrt(wtd.var(a[id], N025[id]))
asd500 = sqrt(wtd.var(a[id], N500[id]))
asd975 = sqrt(wtd.var(a[id], N975[id]))



#########################################################################################################
## extract sound pressure for each octave and at frequencies related to flow/turbulence and surfacing bubbles
#########################################################################################################

dbSig <- getOctaveSPL(SigWave,SigWaveDir,pref=pref)

# add variable that is TRUE if conditions for bubble size estimation are fulfilled
BubbleTest <- k*Lmax<1 & k*a<0.05

####################################
### make output files
####################################

SigSpectrum <- data.frame(SigWaveDir,f,a,BubbleTest,N025,N500,N975,SigWave[,2],SigWaveSmoothed[,2])

colnames(SigSpectrum) <- c("FileID","f Frequency (Hz)","a Radius (m)","Valid bubbles",
"N rel #bubbles 2.5%CI","N rel #bubbles 50%CI","N rel #bubbles 97.5%CI","P PSD (Pa2/Hz)","P PSD (Pa2/Hz) smoothed")


metadata <- data.frame(SigWaveDir,Temp,S,P0,d,min(R),max(R),min(L),max(L),min(ep),max(ep),
amean025,amean500,amean975,asd025,asd500,asd975,Filter,nfilt)

return(list(SigSpectrum,metadata,dbSig))
}





