Project: s41467-024-45976-8 | Function: calc_sens_slopes (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:** Calculates the elasticity (sensitivity slope) of chlorophyll time series by computing the relationship between threshold changes and the number of days exceeding those thresholds. Implements the core elasticity metric defined in the paper using log-linear regression.

**KEY TERMS:** {
  "scaling": "relative threshold difference ε",
  "ns": "relative difference in daily change N",
  "mod$coefficients[2]": "elasticity β₁",
  "diff": "daily chlorophyll-a change",
  "no.trials": "number of threshold combinations (1000)"
}

**CONTEXT CODE:** 
#######The following code is designed to calculate the elasticity of an entire dataset of time series######

load("sample.Rdata") ####A dataset of 5000 chl-a concentration time series
load("sample_loc.Rdata") ####Location (Lat-lon) of the time series in the dataset

slopes <- vector()
median_chl <- vector()

library(tidyverse)

calc_sens_slopes <- function(ts, no.trials) {
  stop("Function implementation has been masked")
  # Remove missing values
  ts <- ts[!is.na(ts)]

  if (length(ts) < 2) {
    stop("Time series must have at least two values")
  }

  # Calculate daily chlorophyll-a changes
  diff <- diff(ts)

  # Generate threshold combinations
  thresholds <- quantile(ts, seq(0, 1, length.out = (no.trials + 1)))
  thresholds <- thresholds[-1]  # Remove the minimum threshold to avoid division by zero
  thresholds <- thresholds[-length(thresholds)]  # Remove the maximum threshold

  ns <- matrix(0, nrow = no.trials, ncol = length(ts) - 1)
  for (i in 1:no.trials) {
    ns[i, ] <- (diff[ts > thresholds[i]] > 0)
  }

  # Normalize ns and diff by the median of the original series
  ns <- ns / median(ts, na.rm = TRUE)
  diff <- diff / median(ts, na.rm = TRUE)

  # Perform log-linear regression for each threshold combination
  slopes <- sapply(1:no.trials, function(i) {
    mod <- lm(log(ns[i, ] + 1) ~ log(diff + 1))
    abs(mod$coefficients[2])
  })

  # Return the mean of the elasticity coefficients
  mean(slopes[!is.na(slopes)])
}

# Example usage
slopes <- vector()
median_chl <- vector()

# Assuming sample is already loaded
for(k in 1:length(sample)){
  df <- as.data.frame(sample[[k]])
  chl <- df$chl_values

  slopes[k] <- calc_sens_slopes(ts = chl, no.trials = 1000)
  median_chl[k] <- median(chl, na.rm = TRUE)

  print(k)
}

# The results are stored in the vector 'slopes', and 'median_chl' contains the median of each time series
```

### EXPLANATION:
1. **Missing Values**: The function first removes missing values to ensure valid calculations.
2. **Daily Changes**: The daily chlorophyll-a changes are calculated using the `diff` function.
3. **Threshold Combinations**: Quantiles of the chlorophyll-a values are used to create threshold combinations. These are then adjusted to avoid using the maximum and minimum values.
4. **Normalization**: The relative differences (`ns`) and daily changes (`diff`) are normalized by the median of the original chlorophyll-a series to ensure consistency.
5. **Regression**: A log-linear regression is performed for each threshold combination, and the absolute value of the elasticity coefficient is calculated.
6. **Mean Slope**: The mean of the elasticity coefficients is returned as the final result.



for(k in 1:length(sample)){  #####loop to automate the calculation for all the time series
  
  df <- as.data.frame(sample[[k]])
  chl <- df$chl_values
  
  slopes[k] <- calc_sens_slopes(ts = chl,no.trials = 1000) ###number of trials determines how many threshold combinations are tested for each time series
  median_chl[k] <- median(chl, na.rm = T)
  
  print(k)
  
}

#####the results are stored in the vector 'slopes', the elasticity metric is the absolute value of 'slopes'
####the median of each time series is stored in 'median_chl'



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