############################################################################################
############################################################################################
### Function to calculate and plot bubble size distribution spectral properties 
### (spectral slopes and breakpoints)
############################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/08/05
###########################################################################################

## INPUTS:
# Na... Bubble number density
# a... bubble radius
# k... window size of moving average (unitless)
# plotting... should spectrum be plotted? (TRUE/FALSE)

## OUTPUTS:
# betaHYDS... spectral slope of sub-Hinze bubbles
# R2HYDS... coefficient of determination of spectral fit for supra-Hinze bubbles
# betaHYDL... spectral slope of supra-Hinze bubbles
# R2HYDL... coefficient of determination of spectral fit for supra-Hinze bubbles
# changepointMean2... radius at which bubble spectrum steepens
# AICresult... Akaikes Information Criterion (AIC) value of linear model, bilinear model and trilinear model, respectively
# selected_model... selected model name (linear or segmented with 1 or 2 breakpoints (bilinear, trilinear)
# lag1_acf... lag-1 residual autocorrelation
# maxsiglag... number of lags where autocorrelation remains significant
###########################################################################################

FitMacrobubbleSpectrum <- function(Na,a,k,plotting=TRUE){

## load helper functions
library(segmented)
  
  
## fit linear / piecewise linear regression to spectral data
  ## Moving median smoothing
  if(!is.null(k)){
    Na <- runmed(Na, k = k, endrule = "keep")
  }

  
fit_lm = lm(Na ~ a)  # intercept-only model
fit_segmented1 = tryCatch(segmented(fit_lm, seg.Z = ~a, npsi = 1),error = function(e) NA)
fit_segmented2 = tryCatch(segmented(fit_lm, seg.Z = ~a, npsi = 2,control=seg.control(quant=TRUE)),error = function(e) NA)



# if trilinear model is better than linear and bilinear model, use trilinear model 
if(AIC(fit_lm,fit_segmented1)$AIC[1] > AIC(fit_lm,fit_segmented1)$AIC[2] &
   AIC(fit_segmented1,fit_segmented2)$AIC[1] > AIC(fit_segmented1,fit_segmented2)$AIC[2]){

  changepointMean2 <- 10^fit_segmented2$psi[2,2]
  changepointMean1 <- 10^fit_segmented2$psi[1,2]
  ## 95% Confidence intervals
  changepointMean2_lwr95CI <- 10^(fit_segmented2$psi[2,2] - 1.96*fit_segmented2$psi[2,3])
  changepointMean2_upr95CI <- 10^(fit_segmented2$psi[2,2] + 1.96*fit_segmented2$psi[2,3])
  changepointMean1_lwr95CI <- 10^(fit_segmented2$psi[1,2] - 1.96*fit_segmented2$psi[1,3])
  changepointMean1_upr95CI <- 10^(fit_segmented2$psi[1,2] + 1.96*fit_segmented2$psi[1,3])
  
  # Identified Intervals
  left_indices <- which(a < log10(changepointMean2) & a > log10(changepointMean1))  # Points left of breakpoint
  right_indices <- which(a > log10(changepointMean2)) # Points right of breakpoint
  
  selected_model <- fit_segmented2
  selected_model_name <- "segmented2"
  
  # if bilinear model is better than linear model, use bilinear model 
}else{
  
  if(AIC(fit_lm,fit_segmented1)$AIC[1] > AIC(fit_lm,fit_segmented1)$AIC[2]){
    changepointMean1 <- NA
    changepointMean2 <- 10^fit_segmented1$psi[1,2]
    ## 95% Confidence intervals
    changepointMean2_lwr95CI <- 10^(fit_segmented1$psi[1,2] - 1.96*fit_segmented1$psi[1,3])
    changepointMean2_upr95CI <- 10^(fit_segmented1$psi[1,2] + 1.96*fit_segmented1$psi[1,3])

    # Identified Intervals
    left_indices <- which(a < log10(changepointMean2))  # Points left of breakpoint
    right_indices <- which(a > log10(changepointMean2)) # Points right of breakpoint
    
    selected_model <- fit_segmented1
    selected_model_name <- "segmented1"
    
  }else{
    changepointMean1 <- NA
    changepointMean2 <- NA
    ## 95% Confidence intervals
    changepointMean2_lwr95CI <- NA
    changepointMean2_upr95CI <- NA

    
    selected_model <- fit_lm
    selected_model_name <- "linear"
    
  }
}

# linear regression for both regions
al <- a[left_indices]
Nal <- Na[left_indices]
ar <- a[right_indices]
Nar <- Na[right_indices]

left_fit <- lm(Nal ~ al)
right_fit <- lm(Nar ~ ar)



if(plotting==TRUE){
  
  ## plot data
  
  windows(width = 4, height = 4)
  layout(matrix(1:1, 1, 1, byrow = TRUE))
  par(mar=c(4.5,5.5,1.5,0.5),las=1,mgp=c(3.6, 1, 0))
  
  plot(Na~a,xlim=log10(c(10^-4,0.1)),ylim=log10(c(10^-5,1)),xaxt="n",yaxt="n",
       ylab=expression(paste("#Bubbles/max #Bubbles (unitless)")),xlab="Bubble radius [m]")
  
  alseq=seq(min(al),max(al),0.0001)
  lines(alseq,predict(left_fit,newdata = data.frame(al=alseq)),col=7,lwd=2)
  
  arseq=seq(min(ar),max(ar),0.0001)
  lines(arseq,predict(right_fit,newdata = data.frame(ar=arseq)),col=6,lwd=2)

  abline(v=log10(changepointMean1),lty=2)
  abline(v=log10(changepointMean2),lty=2)
  abline(h=(seq(-10,12,1)),col=8,lty=2)
  
  axis(side=2,at=(log10(c(10^-10,10^-9,10^-8,10^-7,10^-6,10^-5,10^-4,10^-3,10^-2,0.1,1))),labels=c(10^-10,10^-9,10^-8,10^-7,10^-6,10^-5,10^-4,10^-3,10^-2,0.1,1),lwd=2)
  axis(side=2,at=(log10(c(seq(0.00000001,0.0000001,0.00000001),seq(0.0000001,0.000001,0.0000001),seq(0.000001,0.00001,0.000001),seq(0.00001,0.0001,0.00001),seq(0.0001,0.001,0.0001),seq(0.001,0.01,0.001),seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100)))),labels=NA)
  axis(side=2,at=(log10(c(10^-10,10^-9,10^-8,10^-7,10^-6,10^-5,10^-4,10^-3,10^-2,0.1,1))),lwd=2,labels=NA)
  
  axis(side=1,at=(log10(c(seq(0.00001,0.0001,0.00001),seq(0.0001,0.001,0.0001),seq(0.001,0.01,0.001),seq(0.01,0.1,0.01),seq(0.1,1,0.1),seq(1,10,1),seq(10,100,10),seq(100,1000,100)))),labels=NA,lwd=2)
  axis(side=1,at=(log10(c(0.00001,0.0001,0.001,0.01,0.1,1,10,100,1000))),lwd=2,labels=c(0.00001,0.0001,0.001,0.01,0.1,1,10,100,1000))
  
}

## extract model slopes and fit statistics 
betaHYDS <- summary(left_fit)$coefficients[2,]
betaHYDL <- summary(right_fit)$coefficients[2,]
R2HYDS <- summary(left_fit)$r.squared
R2HYDL <- summary(right_fit)$r.squared
AICresult <- t(as.matrix(c(AIC(fit_lm),AIC(fit_segmented1),AIC(fit_segmented2))))


# residual autocorrelation
acf_test <- acf(residuals(selected_model), plot = FALSE)

# Lag-1 residual autocorrelation
acf1 <- acf_test$acf[2]
  
n <- length(residuals(selected_model))
limit <- 1.96/sqrt(n)

significant_lags <- which(abs(acf_test$acf[-1]) > limit)

# number of lags where autocorrelation remains significant
maxsiglag <- max(significant_lags)



return(list(
  betaHYDS=betaHYDS,
  R2HYDS=R2HYDS,
  betaHYDL=betaHYDL,
  R2HYDL=R2HYDL,
  changepointMean2=changepointMean2,
  changepointMean2_lwr95CI=changepointMean2_lwr95CI,
  changepointMean2_upr95CI=changepointMean2_upr95CI,
  AICresult=AICresult,
  selected_model = selected_model_name,
  lag1_acf = acf1,
  maxsiglag = maxsiglag
))
}
