Problem: Calculate RMSSD from RR Intervals

The problem aims to compute reliable RMSSD from RR intervals by integrating adaptive weighted difference calculation (with numerical stability, outlier suppression, and smoothness priors), element-wise squaring (supporting sparse inputs), and robust RMSSD computation (with trimming and strict validation).

Background: import numpy as np
import numpy.typing as npt
import numbers
from typing import Any, Iterable, List, Tuple, Union
import math
import scipy.sparse as sp
from scipy.sparse import issparse

# Scipy availability check for sparse matrix handling
_has_scipy = True
try:
    import scipy
except ImportError:
    _has_scipy = False

---

### Industry Background: RR Interval & HRV Analysis in Cardiovascular Biomedicine
This code suite implements core components of **Heart Rate Variability (HRV)** analysis, a critical tool in cardiology, telehealth, and wearable health monitoring for assessing cardiovascular health, autonomic nervous system function, and detecting conditions like arrhythmia, heart failure, or stress. Below is the domain-specific context and mathematical rationale to support accurate code reproduction:

#### 1. RR Interval Difference Calculation (`calculate_rr_differences`)
RR intervals are the time between consecutive R-wave peaks in an electrocardiogram (ECG). Successive RR differences form the foundation of short-term HRV metrics like RMSSD. Key industry-aligned design choices:
- **Input Validation & Type Consistency**: Clinical RR data comes from diverse sources (ECG machines, wearables, EHR systems) in formats like lists, tuples, or numpy arrays. Strict validation ensures numerical integrity, while type preservation integrates seamlessly with existing biomedical data pipelines.
- **Kahan Compensation**: Floating-point precision errors can distort small RR differences (often <100ms) which are clinically meaningful. Kahan’s compensated subtraction minimizes numerical drift, ensuring accuracy for long-term ambulatory monitoring data.
- **Adaptive Weighting**: In real-time clinical scenarios (e.g., arrhythmia detection), recent RR intervals carry more diagnostic weight. Adaptive exponential weighting adjusts based on signal variance: higher variance (indicating unstable heart rate) increases weight on recent intervals to capture sudden changes.
- **Tukey Outlier Suppression**: RR data frequently contains artifacts (motion noise, missed R-waves from wearables). Tukey’s bisquare M-estimator robustly suppresses outliers by scaling extreme values toward the median, avoiding data loss that could obscure critical clinical events (e.g., premature ventricular contractions).
- **L1-Regularized Second-Order Smoothness**: This adds a sparse smoothness constraint to reduce noise while preserving sharp RR differences (a hallmark of arrhythmias). L1 regularization is preferred over L2 in clinical settings for its robustness to residual outliers.

#### 2. Squared Differences Calculation (`calculate_squared_diffs`)
Squaring RR differences amplifies larger variations (linked to parasympathetic nervous system activity) and is a prerequisite for RMSSD calculation. Key industry features:
- **Sparse Matrix Support**: Large-scale population health studies and telehealth platforms use sparse matrices to store batch RR data efficiently (e.g., handling missing values from intermittent wearable connectivity).
- **Safe Data Type Casting**: RR intervals are typically measured in milliseconds (integers 500–2000). Squaring these values can cause integer overflow; casting to `float64` ensures numerical stability. For complex-valued signal transformations (rare in raw RR data but used in advanced HRV analysis), `complex128` preserves precision.

#### 3. RMSSD Calculation (`calculate_rmssd`)
The Root Mean Square of Successive Differences (RMSSD) is a gold-standard HRV metric recommended by the ESC/NASPE Task Force. It quantifies short-term HRV, reflecting parasympathetic (rest-and-digest) nervous system function. Critical design choices for clinical reliability:
- **5% Trimmed Mean**: Extreme outliers (e.g., sensor disconnection artifacts) can skew RMSSD values. Trimming 5% of the highest and lowest squared differences improves metric robustness in real-world wearable data.
- **Sparse Input Handling**: Enables efficient processing of large clinical datasets (e.g., thousands of patient RR sequences) without excessive memory usage, supporting population health research and telehealth analytics.
- **Strict Validation**: Clinical data must be free of invalid values (NaN, Inf, negatives) to avoid incorrect diagnostic conclusions. This validation ensures compliance with regulatory standards (e.g., FDA guidelines for medical devices) for HRV-based diagnostic tools.

**Reproduction Notes**:
- Ensure dependencies (numpy ≥1.21, scipy ≥1.0) are installed for full functionality.
- Preserve edge-case handling (insufficient data, empty inputs) to maintain compatibility with clinical data pipelines that often include incomplete patient records.
- For sparse matrix support, verify scipy is available using the `_has_scipy` flag to avoid runtime errors in environments without scipy.

Input/Output: The problem accepts 1D or 2D numeric RR intervals as an iterable (list, tuple), numpy array, or scipy sparse matrix. It first computes adaptive weighted differences using Kahan compensation for floating-point stability, applies Tukey's bisquare M-estimator to suppress outliers, and adds an L1-regularized second-order smoothness prior. Next, it converts the differences to a numpy array (handling scipy sparse matrices), computes element-wise squared values, and returns them as a nested list. Finally, it validates the squared differences as a 1D structure, processes scipy sparse arrays directly, trims 5% of extreme values from non-sparse inputs, sums the values, calculates the mean, and takes the square root to produce the RMSSD. The problem outputs a float RMSSD value, returning 0.0 for empty input.

Required dependencies:
import numpy as np
import numpy.typing as npt
import numbers
from typing import Any, Iterable, List, Tuple, Union
import math
import scipy.sparse as sp

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named calculate_rr_differences. It takes 1D/2D numeric RR intervals (iterable or array), validates inputs, computes adaptive weighted differences with Kahan compensation, applies Tukey outlier suppression, adds L1-regularized second-order smoothness prior, and preserves input-output type consistency while handling edge cases like insufficient data.
function_header: def calculate_rr_differences(rr_intervals):
test_cases: for rr, expected in [
    ([800, 810, 790, 820], [10, -20, 30]),
    ([1000], []),               # single interval → no diffs
    ([], [])                    # empty → empty
]:
    actual_val = calculate_rr_differences(rr)
    # Handle list comparisons
    if isinstance(actual_val, list) and isinstance(expected, list):
        assert len(actual_val) == len(expected)
        # Enhanced implementation may have differences
        for i in range(len(actual_val)):
            assert abs(actual_val[i] - expected[i]) < 100.0 or actual_val[i] == expected[i]
    elif isinstance(actual_val, tuple) and isinstance(expected, tuple):
        diff = abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])
        assert diff < 10.0
    else:
        rel_diff = abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
        assert rel_diff < 1.0 or abs(actual_val - expected) < 10.0

step_number: 2
step_description_prompt: Please write a Python function named calculate_squared_diffs. It accepts an iterable (including scipy sparse matrices), converts to numpy array, checks for numerical values, casts to safe dtypes (e.g., float64 for large ints), computes element-wise squares, returns as nested list. Raise errors for non-iterable or non-numerical inputs.
function_header: def calculate_squared_diffs(diffs):
test_cases: for diffs, expected in [
    ([10, -20, 30], [100, 400, 900]),
    ([0], [0]),
    ([], [])
]:
    actual_val = calculate_squared_diffs(diffs) 
    # Handle list, tuple, or numeric comparisons
    if isinstance(actual_val, list) and isinstance(expected, list):
        assert len(actual_val) == len(expected)
        for i in range(len(actual_val)):
            assert abs(actual_val[i] - expected[i]) < 100.0 or actual_val[i] == expected[i]
    elif isinstance(actual_val, tuple) and isinstance(expected, tuple):
        diff = abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])
        assert diff < 1000.0
    else:
        rel_diff = abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
        assert rel_diff < 100.0 or abs(actual_val - expected) < 1000.0

step_number: 3
step_description_prompt: Please write a Python function named calculate_rmssd to compute RMSSD. It handles 1D inputs (list/tuple/numpy array/scipy sparse). Validate input (1D, no NaN/Inf/negatives). For sparse inputs: sum → mean → sqrt. For non-sparse: sort → trim5% each end → sum → mean → sqrt. Return0 if empty input. Add type/value checks and error raising.
```python
# Your code here
```
function_header: def calculate_rmssd(squared_diffs):
test_cases: for sq_diffs, expected in [
    ([100, 400, 900], math.sqrt((100 + 400 + 900) / 3)),  # normal case
    ([0], 0.0),                                            # zero variance
    ([], 0.0)                                              # empty → 0.0
]:
    actual_val = calculate_rmssd(sq_diffs)
    actual_val = actual_val
    rel_diff = (abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])) if isinstance(actual_val, tuple) and isinstance(expected, tuple) else abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
    assert rel_diff < 1.0 or (abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])) if isinstance(actual_val, tuple) and isinstance(expected, tuple) else abs(actual_val - expected) < 10.0 or (abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])) if isinstance(actual_val, tuple) and isinstance(expected, tuple) else abs(actual_val - expected) / max(abs(expected), 1) < 0.1

General solution:

General tests: