Project: s41467-024-50841-9 | Function: SAD_models (r)

system: You are an expert R programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow R best practices and maintain consistent code style.
Return **only** the complete R function code.

user: Complete this R function:

**DESCRIPTION:** Implements species abundance distribution (SAD) modeling using four different models (lognormal, log-series, broken-stick, Zipf) to analyze DOM molecular formulae abundance patterns and determine which distribution best fits the data

**KEY TERMS:** {
  "SAD": "species abundance distribution",
  "poilog": "lognormal distribution model",
  "fitsad": "species abundance distribution fitting"
}

**CONTEXT CODE:** # @File: SAD_models.R
# @Author: Kai Ma
# Date: 03/12/2020


Rsquare <- function(obs, pred) {
  1 - (sum((log10(obs) - log10(pred))^2) / sum((log10(obs) - mean(log10(obs)))^2))
}

se <- function(x, na.rm = F) {
  x <- as.numeric(x)
  stats::sd(x, na.rm) / sqrt(length(x) - sum(is.na(x)))
}

rank_abun <- function(abun_vet) {
  rep(names(table(log10(abun_vet))), table(log10(abun_vet))) %>%
    rev() %>%
    as.numeric()
}

fitsad_zipf <- function(x, N, trunc, start.value, upper = 20, ...) {
  dots <- list(...)
  if (any(x <= 0)) stop("All x must be positive integers")
  if (!missing(trunc)) {
    if (min(x) <= trunc) stop("truncation point should be lower than the lowest data value")
  }
  if (missing(N)) {
    N <- sum(x)
  }
  if (missing(start.value)) {
    p <- x / sum(x)
    lzipf <- function(s, N) -s * log(1:N) - log(sum(1 / (1:N)^s))
    opt.f <- function(s) sum((log(p) - lzipf(s, length(p)))^2)
    opt <- optimize(opt.f, c(0.5, length(p)))
    sss <- opt$minimum
  } else {
    sss <- start.value
  }
  if (missing(trunc)) {
    LL <- function(N, s) -sum(dzipf(x, N = N, s = s, log = TRUE))
  } else {
    LL <- function(N, s) -sum(dtrunc("zipf", x = x, coef = list(N = N, s = s), trunc = trunc, log = TRUE))
  }
  result <- do.call("mle2", c(list(LL, start = list(s = sss), data = list(x = x), fixed = list(N = N), method = "Brent", lower = 0, upper = upper), dots))
  if (abs(as.numeric(result@coef) - upper) < 0.001) {
    warning("mle equal to upper bound provided. \n Try increase value for the 'upper' argument")
  }
  new("fitsad", result, sad = "zipf", distr = "discrete", trunc = ifelse(missing(trunc), NaN, trunc))
}

SAD_models <- function(data) {
  stop("Function implementation has been masked")
}


Complete the function implementation replacing "stop("Not implemented")".