hrvkit

Heart Rate Variability (HRV) toolkit in MoonBit for recovery monitoring and training status analysis.

hrv
heart-rate-variability
health
sports-science
moon add zhzh12345678/hrvkit@0.3.0
Download zip
Version
0.3.0
License
Apache-2.0
Last updated
6 hours ago
Downloads
1
README

#moonbit-hrvkit

CI

moonbit-hrvkit is a pure MoonBit toolkit for analyzing RR-interval recordings and turning them into reproducible HRV, signal-quality, recovery, and longitudinal training features. It is designed for wearable-data pipelines, local command-line analysis, and small embedded services that need the same implementation across MoonBit targets.

The library is deterministic, does not require native FFI, and provides explicit quality metadata alongside numerical results. It is an engineering and research component; physiological outputs should be interpreted with an appropriate domain protocol and are not a substitute for clinical diagnosis.

#Project positioning

The package covers the complete path from a raw RR stream to an auditable analysis report:

  1. ingest and normalize wearable samples with duplicate, ordering, gap, and quality diagnostics;
  2. validate and clean intervals with removal or interpolation policies;
  3. calculate time-domain, geometric, frequency-domain, and nonlinear features;
  4. build longitudinal recovery, training-load, forecast, and what-if scenario views;
  5. apply transparent quality gates and explainable decision actions;
  6. export stable CSV/JSON-friendly reports, provenance events, and runtime measurements.

#Core capabilities

  • RR validation with physiological bounds, non-finite detection, duplicate checks, gap candidates, and quality grades.
  • Auditable cleaning with local-median and linear interpolation, artifact events, replacement confidence, and correction magnitude.
  • Standard HRV metrics including mean RR/HR, SDNN, RMSSD, pNN20/pNN50, SDSD, CVNN, MAD, Poincaré descriptors, histogram geometry, and stress/vagal indices.
  • Periodogram and Welch spectral analysis with VLF/LF/HF bands, ratios, entropy, centroid, edge frequency, respiratory peak estimation, and autocorrelation.
  • Nonlinear descriptors including sample entropy, approximate entropy, DFA, recurrence rate, turning-point ratio, and histogram entropy.
  • Morning baselines, readiness scores, sleep-recovery summaries, ambulatory activity segmentation, training-load summaries, and longitudinal session status.
  • Wearable ingestion cursors, CSV protocol adapters, bounded telemetry storage, cohort percentiles, recovery forecasts, training scenarios, and quality-aware decision support.
  • Streaming statistics, batch/cohort summaries, calibration, protocol compliance, paired recording comparison, feature tables, provenance audit trails, runtime budgets, and deterministic simulation fixtures.
  • A small CLI for cleaning, metrics, trends, full reports, quality diagnostics, and repeatable benchmarks.

#Quick start

Install a current stable MoonBit toolchain, then verify the workspace:

moon version --all moon update moon fmt --check moon check --deny-warn --target all moon test --deny-warn --target native

Use the library from MoonBit code through the package namespace zhzh12345678/hrvkit:

let config = @hrvkit.HrvConfig::default()
let (cleaned, quality) = @hrvkit.clean_rr_intervals(
[800.0, 802.0, 798.0, 2200.0, 801.0],
@hrvkit.InterpolateLocalMedian,
config,
)
let metrics = @hrvkit.calculate_metrics(cleaned, config, quality)
println(metrics.rmssd.to_string())

#CLI

Run the executable with:

moon run --target native cmd/main -- [options]

OptionValuesPurpose
--actionclean, metrics, trends, report, quality, benchmarkSelect the operation
--formatcsv, jsonInput and output encoding for the selected operation
--cleaningremove, median, linearArtifact correction policy
--sample-ratepositive numberTachogram sample rate for reports and benchmarks
--repetitionspositive integerNumber of benchmark repetitions
--datainline CSV or JSONInput recording or morning-history data

Examples:

# Calculate metrics from a JSON array and emit JSON. moon run --target native cmd/main -- --action metrics --format json --data "[800,802,798,805,801]" # Clean a CSV recording and emit CSV. moon run --target native cmd/main -- --action clean --format csv --cleaning median --data "800,802,2200,798,801" # Generate a complete analysis report. moon run --target native cmd/main -- --action report --format json --sample-rate 4 --data "[800,802,798,805,801]" # Run the deterministic benchmark workload. moon run --target native --release cmd/main -- --action benchmark --format csv --repetitions 10 --sample-rate 4

#Architecture

The repository keeps the public library in the root package and the executable in cmd/main.

hrvkit.mbt / indicators.mbt domain types and core HRV metrics validation.mbt / cleaning*.mbt validation, artifact policy, and repair audit statistics.mbt / time_domain*.mbt robust descriptive and time-domain features frequency*.mbt / respiration.mbt spectral and respiratory features nonlinear.mbt / advanced_indicators.mbt geometric and nonlinear features pipeline.mbt / reporting*.mbt end-to-end reports and stable exports readiness*.mbt / sleep*.mbt recovery, sleep, and training summaries session*.mbt / streaming.mbt longitudinal and online analysis wearable_pipeline.mbt normalized wearable ingestion and windows protocol_adapters.mbt source-specific CSV dialect adaptation training_load_plus.mbt load dose, ratios, monotony, and alerts longitudinal_plus.mbt robust recovery baselines and trajectories quality_pipeline.mbt staged quality gates and batch orchestration decision_support.mbt explainable findings and action plans forecast_plus.mbt / scenario*.mbt forecasts and what-if training plans telemetry_store.mbt / cohort*.mbt bounded storage and quality-aware cohorts reporting_plus.mbt / audit*.mbt structured reports and provenance events runtime_diagnostics.mbt runtime aggregates and regression budgets configuration_registry.mbt validated application profiles batch.mbt / matrix.mbt cohort aggregation and feature computation protocol*.mbt / calibration*.mbt reproducible recording and sensor handling synthetic*.mbt / benchmarks.mbt deterministic fixtures and benchmark API cmd/main/main.mbt command-line interface

All public data structures derive JSON traits where useful and carry quality or validity fields instead of silently discarding unusable input.

#Benchmark

The built-in benchmark uses a deterministic 256-sample resting RR fixture, runs the complete analysis pipeline, and repeats the workload ten times. A representative native release run produced:

samples=256, repetitions=10, feature_count=35 mean_rr=799.8931407352728, rmssd=2.368779541044154 total_power=14633.821047418522, quality_ratio=1

The checked-in benchmark record contains the deterministic output, coverage summary, source-scale measurement, toolchain version, and six warm-cache CLI timings. The timing includes process startup and the cached native build, so it is an integration baseline rather than a hardware-independent claim. The current local measurement contains 20,006 physical production MoonBit lines (17,059 non-comment, non-blank code lines) and 265 passing tests.

moon run --target native --release cmd/main -- --action benchmark --format csv --repetitions 10 --sample-rate 4

#Tests

The test suite covers empty inputs, singleton and constant series, malformed CSV/JSON, non-finite values, physiological boundaries, invalid sample rates, artifact bursts, short spectral windows, degenerate matrices, wearable duplicates and gaps, protocol failures, quality-gate rejection, forecast short history, telemetry retention, scenario bounds, audit provenance, configuration failures, calibration round trips, report serialization, cohort aggregation, and CLI-facing output shapes.

Run the portable local targets directly:

moon test --deny-warn --target wasm-gc moon test --deny-warn --target native

The local acceptance run contains 265 tests; wasm, wasm-gc, JavaScript, and native targets pass. A native coverage run records 5,233/7,297 covered lines (71.71%). CI also runs the JavaScript target after installing Node.js explicitly.

#CI

.github/workflows/check.yml checks formatting, strict warnings, all MoonBit targets, generated interface information, native execution, coverage, and the 20,000-line production source-size guard on Ubuntu, macOS, and Windows. The workflow installs the current stable MoonBit toolchain and Node.js instead of relying on repository-local runtimes.

#License

Licensed under the Apache License 2.0.

#
HrvParseError

pub suberror HrvParseError {
InvalidNumber(input~ : String)
InvalidRow(msg~ : String)
EmptyInput
} derive(ToJson,
Debug
,
FromJson
)

Parser error representation.

#
ActivityBlock

pub(all) struct ActivityBlock {
start_index : Int
end_index : Int
state : ActivityState
duration_seconds : Double
sample_count : Int
mean_hr : Double
mean_rr : Double
rmssd : Double
quality_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A contiguous activity block.

#
ActivityState

pub(all) enum ActivityState {
Rest
LightActivity
ModerateActivity
VigorousActivity
UnknownActivity
} derive(Eq, ToJson,
Debug
,
FromJson
)

Coarse activity state inferred from heart rate and movement.

#
ActivityThresholds

pub(all) struct ActivityThresholds {
resting_hr_upper : Double
light_hr_upper : Double
moderate_hr_upper : Double
resting_movement_upper : Double
unknown_quality_floor : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Default heart-rate and movement thresholds.

#
ActivityThresholds::default

Conservative thresholds for mixed wearable data.

#
AmbulatorySample

pub(all) struct AmbulatorySample {
timestamp_seconds : Double
rr_ms : Double
heart_rate_bpm : Double
movement : Double
temperature_c : Double
quality_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

One synchronized wearable observation.

#
AmbulatorySummary

pub(all) struct AmbulatorySummary {
sample_count : Int
duration_seconds : Double
rest_seconds : Double
light_seconds : Double
moderate_seconds : Double
vigorous_seconds : Double
mean_hr : Double
mean_rr : Double
valid_ratio : Double
block_count : Int
dominant_state : ActivityState
hr_load : Double
temperature_mean : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Day-level ambulatory summary.

#
AnalysisOptions

pub(all) struct AnalysisOptions {
cleaning_method : CleaningMethod
sample_rate_hz : Double
remove_trend : Bool
window_function : WindowFunction
segment_size : Int
segment_hop : Int
nonlinear_enabled : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Options for the end-to-end HRV analysis pipeline.

#
AnalysisOptions::default

Conservative defaults suitable for short wearable recordings.

#
AnalysisReport

pub(all) struct AnalysisReport {
raw_count : Int
cleaned_intervals : Array[Double]
raw_validation : IntervalValidation
quality : QualityReport
metrics : HrvMetrics
distribution : DistributionStats
poincare : PoincareMetrics
geometric : GeometricMetrics
heart_rate : HeartRateSummary
frequency : FrequencyMetrics
nonlinear : NonlinearMetrics
segments : Array[SegmentSummary]
feature_vector : Array[Double]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Full report for a single RR recording.

#
ApplicationConfig

pub(all) struct ApplicationConfig {
environment : ConfigurationEnvironment
hrv : HrvConfig
analysis : AnalysisOptions
ingest : WearableIngestConfig
gate : QualityGatePolicy
load : LoadModelConfig
forecast : ForecastConfig
subject_retention_days : Int
deterministic : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ApplicationConfig::default

#
ArtifactCluster

pub(all) struct ArtifactCluster {
start : Int
end : Int
count : Int
ratio : Double
severity : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

A contiguous cluster of artifacts.

#
ArtifactEvent

pub(all) struct ArtifactEvent {
index : Int
value : Double
kind : IntervalDisposition
replacement : Double
confidence : Double
left_neighbor : Double
right_neighbor : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

One detected artifact with enough context for audit logs.

#
ArtifactProfile

pub(all) struct ArtifactProfile {
sample_count : Int
flagged_count : Int
range_violations : Int
local_outliers : Int
sudden_jumps : Int
repeated_values : Int
missing_values : Int
artifact_ratio : Double
median_step : Double
mad_step : Double
flags : Array[QualityFlag]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Quality profile of an RR stream.

#
ArtifactReason

pub(all) enum ArtifactReason {
None
PhysiologicalRange
LocalOutlier
SuddenJump
RepeatedValue
MissingValue
} derive(Eq, ToJson,
Debug
,
FromJson
)

Reason assigned to a suspicious sample.

#
AuditEvent

pub(all) struct AuditEvent {
ordinal : Int
run_id : String
timestamp : String
kind : AuditEventKind
outcome : AuditOutcome
component : String
message : String
input_count : Int
output_count : Int
quality_score : Double
checksum : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
AuditEventKind

pub(all) enum AuditEventKind {
AuditInputReceived
AuditInputRejected
AuditNormalization
AuditQualityGate
AuditAnalysis
AuditDecision
AuditExport
AuditWarning
AuditCompletion
} derive(Eq, ToJson,
Debug
,
FromJson
)

Reproducibility and provenance records for application runs. Audit events contain no credentials and are suitable for a local export or a structured log sink supplied by the host application.

#
AuditFilter

pub(all) struct AuditFilter {
run_id : String?
component : String?
kind : AuditEventKind?
outcome : AuditOutcome?
minimum_quality : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
AuditOutcome

pub(all) enum AuditOutcome {
AuditSuccess
AuditAcceptedWithWarning
AuditRejected
AuditError
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
AuditSummary

pub(all) struct AuditSummary {
event_count : Int
success_count : Int
warning_count : Int
rejection_count : Int
error_count : Int
component_count : Int
mean_quality : Double
last_outcome : AuditOutcome
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
AuditTrail

pub(all) struct AuditTrail {
run_id : String
started_at : String
finished_at : String
events : Array[AuditEvent]
outcome : AuditOutcome
input_checksum : String
output_checksum : String
feature_count : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
AuditTrail::append

fn AuditTrail::append(self : AuditTrail, kind : AuditEventKind, outcome : AuditOutcome, component : String, message : String, input_count : Int, output_count : Int, quality_score : Double, checksum : String, timestamp : String) -> Unit

#
AuditTrail::event_count

fn AuditTrail::event_count(self : AuditTrail) -> Int

#
AuditTrail::finish

fn AuditTrail::finish(self : AuditTrail, finished_at : String, output_checksum : String, feature_count : Int) -> Unit

#
AuditTrail::has_errors

fn AuditTrail::has_errors(self : AuditTrail) -> Bool

#
AuditTrail::has_warnings

fn AuditTrail::has_warnings(self : AuditTrail) -> Bool

#
AuditTrail::is_reproducible

fn AuditTrail::is_reproducible(self : AuditTrail) -> Bool

#
AuditTrail::new

fn AuditTrail::new(run_id : String, started_at : String, input_checksum : String) -> AuditTrail

#
BandPower

pub(all) struct BandPower {
name : String
lower_hz : Double
upper_hz : Double
power : Double
normalized_power : Double
contribution_percent : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Power and normalized power for one band.

#
BatchRecord

pub(all) struct BatchRecord {
subject_id : String
session_id : String
date : String
rmssd : Double
sdnn : Double
mean_hr : Double
quality_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A record in a multi-athlete or multi-session batch.

#
BenchmarkConfig

pub(all) struct BenchmarkConfig {
recording_length : Int
repetitions : Int
baseline_rr : Double
sample_rate_hz : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Deterministic benchmark configuration shared by local and CI runs.

#
BenchmarkConfig::default

The default workload is large enough to exercise every major layer.

#
BenchmarkSummary

pub(all) struct BenchmarkSummary {
samples : Int
repetitions : Int
feature_count : Int
mean_rr : Double
rmssd : Double
total_power : Double
quality_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Aggregate benchmark output that can be copied into a report.

#
CalibrationReport

pub(all) struct CalibrationReport {
input_count : Int
output_count : Int
changed_count : Int
rejected_count : Int
mean_shift_ms : Double
max_shift_ms : Double
jitter_rms_ms : Double
passed : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A calibration audit record.

#
ChangePoint

pub(all) struct ChangePoint {
index : Int
before_mean : Double
after_mean : Double
magnitude : Double
confidence : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A detected change point between two local windows.

#
CleaningMethod

pub(all) enum CleaningMethod {
Remove
InterpolateLocalMedian
InterpolateLinear
} derive(Eq, ToJson,
Debug
,
FromJson
)

Cleaning methods for RR intervals.

#
CleaningResult

pub(all) struct CleaningResult {
intervals : Array[Double]
quality : QualityReport
validation : IntervalValidation
events : Array[ArtifactEvent]
changed_count : Int
max_correction : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Result of an auditable cleaning pass.

#
CohortComparison

pub(all) struct CohortComparison {
reference : String
quality_ok : Bool
ranks : Array[CohortRank]
flags : Array[String]
similarity_score : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
CohortComparisonSummary

pub(all) struct CohortComparisonSummary {
observations : Int
quality_eligible : Int
quality_ratio : Double
ranges : Array[CohortMetricRange]
comparisons : Array[CohortComparison]
feature_vector : Array[Double]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
CohortMetricRange

pub(all) struct CohortMetricRange {
metric : String
sample_count : Int
minimum : Double
lower_quartile : Double
median : Double
upper_quartile : Double
maximum : Double
mean : Double
standard_deviation : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
CohortObservation

pub(all) struct CohortObservation {
reference : String
rmssd_ms : Double
mean_rr_ms : Double
resting_hr_bpm : Double
readiness_score : Double
training_load : Double
signal_quality : Double
age_band : String
activity_band : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Privacy-friendly cohort comparison primitives. The module accepts already de-identified observations and returns ranges, ranks, and quality-aware flags without retaining personal identifiers.

#
CohortRank

pub(all) struct CohortRank {
reference : String
metric : String
value : Double
percentile : Double
z_score : Double
quality_adjusted : Bool
label : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
CohortSummary

pub(all) struct CohortSummary {
record_count : Int
subject_count : Int
rmssd_mean : Double
rmssd_median : Double
rmssd_sd : Double
rmssd_q1 : Double
rmssd_q3 : Double
mean_hr : Double
mean_quality : Double
low_quality_count : Int
strongest_subject : String
weakest_subject : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Cohort-level distribution and quality summary.

#
ConfigIssue

pub(all) struct ConfigIssue {
key : String
severity : String
message : String
observed : Double
expected : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ConfigValidation

pub(all) struct ConfigValidation {
valid : Bool
issues : Array[ConfigIssue]
normalized : ApplicationConfig
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ConfigurationEnvironment

pub(all) enum ConfigurationEnvironment {
ConfigurationDevelopment
ConfigurationProduction
ConfigurationBenchmark
ConfigurationResearch
} derive(Eq, ToJson,
Debug
,
FromJson
)

Validated application configuration profiles. Keeping policy validation in the library prevents silently accepting impossible windows or unsafe thresholds from CLI and service callers.

#
DailyLoadLedger

pub(all) struct DailyLoadLedger {
date : String
entries : Array[TrainingLoadEntry]
doses : Array[LoadDose]
total_load : Double
effective_load : Double
duration_minutes : Double
session_count : Int
average_intensity : Double
quality_ratio : Double
recovery_cost : Double
high_intensity_minutes : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DateParts

pub(all) struct DateParts {
year : Int
month : Int
day : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Calendar date used to validate morning measurement records.

#
DecisionAction

pub(all) struct DecisionAction {
priority : Int
title : String
instruction : String
duration_minutes : Double
intensity_ceiling : Double
requires_recheck : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DecisionContext

pub(all) struct DecisionContext {
quality_report : QualityReport?
recovery_report : LongitudinalRecoveryReport?
load_plan : TrainingLoadPlan?
sleep_hours : Double
sleep_efficiency : Double
symptom_score : Double
user_goal : String
requested_intensity : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DecisionDomain

pub(all) enum DecisionDomain {
DecisionSignal
DecisionRecovery
DecisionTraining
DecisionSleep
DecisionConsistency
DecisionSystem
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DecisionFinding

pub(all) struct DecisionFinding {
code : String
domain : DecisionDomain
severity : DecisionSeverity
title : String
evidence : String
observed : Double
reference : Double
confidence : Double
action : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DecisionPlan

pub(all) struct DecisionPlan {
score : Double
confidence : Double
level : DecisionSeverity
findings : Array[DecisionFinding]
actions : Array[DecisionAction]
headline : String
disclaimer : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DecisionSeverity

pub(all) enum DecisionSeverity {
DecisionInfo
DecisionAdvisory
DecisionWarning
DecisionUrgent
} derive(Eq, ToJson,
Debug
,
FromJson
)

Explainable decision support built on HRV quality, recovery, and load data. It intentionally emits findings and actions instead of opaque medical claims.

#
DecisionThresholds

pub(all) struct DecisionThresholds {
quality_floor : Double
readiness_floor : Double
readiness_ceiling : Double
load_ratio_watch : Double
load_ratio_warning : Double
sleep_floor_hours : Double
confidence_floor : Double
symptom_warning : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
DecisionThresholds::default

#
DistributionStats

pub(all) struct DistributionStats {
count : Int
sum : Double
mean : Double
median : Double
variance : Double
standard_deviation : Double
minimum : Double
maximum : Double
q1 : Double
q3 : Double
interquartile_range : Double
median_absolute_deviation : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Descriptive statistics used by HRV reports and signal diagnostics.

#
ExportDocument

pub(all) struct ExportDocument {
schema : String
generated_by : String
rows : Array[ExportRow]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Export document with version and provenance.

#
ExportRow

pub(all) struct ExportRow {
key : String
value : String
unit : String
status : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

One serializable result row.

#
FeatureScaler

pub(all) struct FeatureScaler {
names : Array[String]
centers : Array[Double]
scales : Array[Double]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Feature scaling parameters learned from a reference set.

#
FeatureTable

pub(all) struct FeatureTable {
schema_version : String
features : Array[NamedFeature]
valid_count : Int
missing_count : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

A deterministic feature table.

#
FeatureTable::from_features

fn FeatureTable::from_features(features : Array[NamedFeature], schema_version : String) -> FeatureTable

Make a table and count finite versus missing values.

#
ForecastBacktest

pub(all) struct ForecastBacktest {
folds : Int
observations : Int
mean_absolute_error : Double
mean_absolute_percentage_error : Double
directional_accuracy : Double
worst_error : Double
stable : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ForecastBundle

pub(all) struct ForecastBundle {
recovery : OperationalForecastResult
load : OperationalForecastResult
backtest : ForecastBacktest
recommendation : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ForecastConfig

pub(all) struct ForecastConfig {
horizon : Int
window : Int
ewma_alpha : Double
minimum_history : Int
uncertainty_scale : Double
lower_bound : Double
upper_bound : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ForecastConfig::default

#
ForecastMethod

pub(all) enum ForecastMethod {
ForecastLastValue
ForecastMovingAverage
ForecastEwma
ForecastLinearTrend
ForecastEnsemble
} derive(Eq, ToJson,
Debug
,
FromJson
)

Deterministic recovery and workload forecasting primitives. Forecasts are deliberately bounded and accompanied by holdout error so consumers can show uncertainty rather than treating a point estimate as fact.

#
ForecastPoint

pub(all) struct ForecastPoint {
step : Int
value : Double
lower : Double
upper : Double
confidence : Double
algorithm : ForecastMethod
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ForecastResult

pub(all) struct ForecastResult {
predictions : Array[Double]
slope : Double
intercept : Double
residual_sd : Double
lower_95 : Array[Double]
upper_95 : Array[Double]
} derive(Eq, ToJson,
Debug
,
FromJson
)

A one-step or multi-step forecast with uncertainty metadata.

#
FrequencyBandPower

pub(all) struct FrequencyBandPower {
name : String
lower_hz : Double
upper_hz : Double
power : Double
normalized_power : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Power accumulated in a named frequency band.

#
FrequencyMetrics

pub(all) struct FrequencyMetrics {
sample_rate_hz : Double
total_power : Double
vlf : FrequencyBandPower
lf : FrequencyBandPower
hf : FrequencyBandPower
lf_hf_ratio : Double
spectral_centroid_hz : Double
spectral_entropy : Double
peak_frequency_hz : Double
spectrum : Array[SpectrumBin]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Frequency-domain HRV descriptors.

#
GeometricMetrics

pub(all) struct GeometricMetrics {
triangular_index : Double
tinn : Double
mode_rr : Double
mode_count : Int
bin_width : Double
bins : Array[Int]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Geometric HRV descriptors derived from an RR histogram.

#
HeartRateSummary

pub(all) struct HeartRateSummary {
mean_bpm : Double
minimum_bpm : Double
maximum_bpm : Double
median_bpm : Double
resting_bpm : Double
zone1_seconds : Double
zone2_seconds : Double
zone3_seconds : Double
zone4_seconds : Double
zone5_seconds : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A compact set of heart-rate zones for training dashboards.

#
HrvConfig

pub(all) struct HrvConfig {
min_rr : Double
max_rr : Double
relative_threshold : Double
pnn_threshold : Double
rolling_window : Int
normal_range_sd_factor : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Configuration for HRV analysis.

#
HrvConfig::default

fn HrvConfig::default() -> HrvConfig

Default configuration values.

#
HrvMetrics

pub(all) struct HrvMetrics {
mean_rr : Double
mean_hr : Double
sdnn : Double
rmssd : Double
pnn50 : Double
pnn_custom : Double
quality : QualityReport
} derive(Eq, ToJson,
Debug
,
FromJson
)

Computed time-domain HRV metrics.

#
HrvPipelineRun

pub(all) struct HrvPipelineRun {
run_id : String
report : AnalysisReport?
gate : QualityGateResult
stages : Array[PipelineStageTrace]
input_count : Int
accepted : Bool
feature_vector : Array[Double]
export_csv : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
IngestCursor

pub(all) struct IngestCursor {
last_timestamp_seconds : Double
accepted_count : Int
rejected_count : Int
gap_count : Int
quality_sum : Double
finished : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A compact state for an incremental ingest loop.

#
IngestCursor::feature_vector

fn IngestCursor::feature_vector(self : IngestCursor) -> Array[Double]

Return a compact cursor feature vector.

#
IngestCursor::finish

fn IngestCursor::finish(self : IngestCursor) -> Unit

Mark a cursor complete and freeze further updates.

#
IngestCursor::mean_quality

fn IngestCursor::mean_quality(self : IngestCursor) -> Double

Return the mean quality observed by a cursor.

#
IngestCursor::new

Create an empty cursor for a streaming adapter.

#
IngestCursor::push

Add one sample to a cursor without retaining the raw stream.

#
IngestNotice

pub(all) struct IngestNotice {
index : Int
code : String
message : String
severity : String
disposition : WearableSampleDisposition
} derive(Eq, ToJson,
Debug
,
FromJson
)

An ingestion notice is machine-readable and suitable for audit logs.

#
IntervalDisposition

pub(all) enum IntervalDisposition {
Normal
TooShort
TooLong
NonFinite
} derive(Eq, ToJson,
Debug
,
FromJson
)

Physiological interpretation of one RR interval.

#
IntervalObservation

pub(all) struct IntervalObservation {
index : Int
value : Double
disposition : IntervalDisposition
distance_from_median : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Detailed observation retained by the validation report.

#
IntervalValidation

pub(all) struct IntervalValidation {
total : Int
valid : Int
invalid : Int
too_short : Int
too_long : Int
non_finite : Int
duplicates : Int
monotonic_breaks : Int
minimum : Double
maximum : Double
median : Double
observations : Array[IntervalObservation]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Input validation summary for a raw RR series.

#
LoadAlert

pub(all) struct LoadAlert {
date : String
level : LoadRiskLevel
code : String
title : String
explanation : String
observed : Double
threshold : Double
action : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
LoadDose

pub(all) struct LoadDose {
duration_component : Double
cardiovascular_component : Double
perceived_effort_component : Double
distance_component : Double
elevation_component : Double
quality_weight : Double
raw_load : Double
effective_load : Double
intensity_score : Double
band : LoadIntensityBand
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
LoadIntensityBand

pub(all) enum LoadIntensityBand {
LoadRecovery
LoadAerobic
LoadTempo
LoadThreshold
LoadHighIntensity
LoadMaximal
} derive(Eq, ToJson,
Debug
,
FromJson
)

A production-oriented training load ledger for longitudinal HRV workflows. The module keeps raw session context, transparent dose components, and conservative status labels together so downstream applications can explain why a recommendation was produced.

#
LoadModelConfig

pub(all) struct LoadModelConfig {
max_hr_bpm : Double
resting_hr_floor_bpm : Double
acute_window_days : Int
chronic_window_days : Int
easy_rpe : Double
hard_rpe : Double
quality_floor : Double
monotony_floor : Double
caution_ratio : Double
critical_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
LoadModelConfig::default

#
LoadRiskLevel

pub(all) enum LoadRiskLevel {
LoadStable
LoadWatch
LoadCaution
LoadCritical
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
LongitudinalRecoveryReport

pub(all) struct LongitudinalRecoveryReport {
records : Array[RecoveryDayRecord]
assessments : Array[RecoveryDayAssessment]
baseline : RecoveryBaseline
trajectory : RecoveryTrajectory
current_score : Double
current_status : RecoveryDayStatus
missing_days : Int
quality_ratio : Double
stable_streak : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
MatrixShape

pub(all) struct MatrixShape {
rows : Int
columns : Int
rectangular : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Matrix shape.

#
MetricRow

pub(all) struct MetricRow {
key : String
value : String
unit : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

A stable key/value row for human-readable metric exports.

#
MorningAlert

pub(all) struct MorningAlert {
date : String
severity : String
code : String
message : String
value : Double
baseline : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

An explainable alert emitted for a morning series.

#
MorningBaselineState

pub(all) struct MorningBaselineState {
count : Int
center : Double
deviation : Double
lower : Double
upper : Double
trend_slope : Double
latest_status : String
missing_days : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Baseline state used by repeated morning measurements.

#
MorningMeasurement

pub(all) struct MorningMeasurement {
date : String
rmssd : Double
sdnn : Double
rr_mean : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A single day's morning HRV measurement.

#
MorningTrend

pub(all) struct MorningTrend {
date : String
today_rmssd : Double
rmssd_rolling_avg : Double
rmssd_rolling_sd : Double
rmssd_normal_range_lower : Double
rmssd_normal_range_upper : Double
rmssd_status : String
recovery_score : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Computed morning baseline and trend analysis for a specific day.

#
NamedFeature

pub(all) struct NamedFeature {
name : String
value : Double
source : String
valid : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

One named numeric feature with provenance.

#
NonlinearMetrics

pub(all) struct NonlinearMetrics {
sample_entropy : Double
approximate_entropy : Double
dfa_alpha : Double
turning_point_ratio : Double
recurrence_rate : Double
histogram_entropy : Double
lag1_autocorrelation : Double
complexity_index : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Non-linear HRV descriptors for rhythm complexity and recurrence.

#
NormalizedWearableSample

pub(all) struct NormalizedWearableSample {
sample : WearableSample
quality_weight : Double
disposition : WearableSampleDisposition
repaired : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A normalized sample with a source-independent quality weight.

#
OnlineStats

pub(all) struct OnlineStats {
count : Int
mean : Double
m2 : Double
minimum : Double
maximum : Double
last : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Online moments and extrema for long-running RR ingestion.

#
OnlineStats::merge

fn OnlineStats::merge(self : OnlineStats, other : OnlineStats) -> Unit

Merge another accumulator using Chan's parallel moments formula.

#
OnlineStats::new

Create an empty streaming accumulator.

#
OnlineStats::push

fn OnlineStats::push(self : OnlineStats, value : Double) -> Unit

Add one observation using Welford's stable update.

#
OnlineStats::push_all

fn OnlineStats::push_all(self : OnlineStats, values : Array[Double]) -> Unit

Add all observations in order.

#
OnlineStats::snapshot

fn OnlineStats::snapshot(self : OnlineStats) -> DistributionStats

Return an immutable snapshot of the current accumulator.

#
OnlineStats::standard_deviation

fn OnlineStats::standard_deviation(self : OnlineStats) -> Double

Return sample standard deviation from an online accumulator.

#
OnlineStats::variance

fn OnlineStats::variance(self : OnlineStats) -> Double

Return sample variance from an online accumulator.

#
OperationalForecastResult

pub(all) struct OperationalForecastResult {
algorithm : ForecastMethod
history_count : Int
points : Array[ForecastPoint]
baseline : Double
slope : Double
mean_absolute_error : Double
root_mean_squared_error : Double
coverage : Double
usable : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
OperationalReport

pub(all) struct OperationalReport {
report_id : String
generated_at : String
subject_id : String
headline : String
overall_score : Double
confidence : Double
sections : Array[OperationalReportSection]
feature_vector : Array[Double]
warnings : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
OperationalReportMetric

pub(all) struct OperationalReportMetric {
key : String
label : String
value : Double
unit : String
status : String
confidence : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
OperationalReportSection

pub(all) struct OperationalReportSection {
kind : ReportSectionKind
title : String
summary : String
metrics : Array[OperationalReportMetric]
rows : Array[Array[String]]
warnings : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
PipelineBatchSummary

pub(all) struct PipelineBatchSummary {
runs : Array[HrvPipelineRun]
total_runs : Int
accepted_runs : Int
rejected_runs : Int
acceptance_ratio : Double
average_quality : Double
average_feature_count : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
PipelineStageKind

pub(all) enum PipelineStageKind {
PipelineInput
PipelineValidation
PipelineCleaning
PipelineTimeDomain
PipelineFrequency
PipelineNonlinear
PipelineQualityGate
PipelineExport
} derive(Eq, ToJson,
Debug
,
FromJson
)

Auditable orchestration for turning raw RR data into a usable decision. Every stage has a status, duration supplied by the caller, and explicit reasons so a dashboard can distinguish a failed gate from missing data.

#
PipelineStageStatus

pub(all) enum PipelineStageStatus {
PipelinePending
PipelinePassed
PipelineSkipped
PipelineFailed
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
PipelineStageTrace

pub(all) struct PipelineStageTrace {
ordinal : Int
kind : PipelineStageKind
status : PipelineStageStatus
input_count : Int
output_count : Int
quality : Double
duration_ms : Double
message : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
PoincareMetrics

pub(all) struct PoincareMetrics {
sd1 : Double
sd2 : Double
sd1_sd2_ratio : Double
ellipse_area : Double
center_rr : Double
points : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Poincare-plot descriptors of short-term and long-term variability.

#
ProtocolAdapterConfig

pub(all) struct ProtocolAdapterConfig {
dialect : WearableProtocolDialect
delimiter : String
has_header : Bool
default_quality : Double
source_id : String
start_timestamp_seconds : Double
infer_heart_rate : Bool
infer_quality : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ProtocolAdapterConfig::default

#
ProtocolAdapterNotice

pub(all) struct ProtocolAdapterNotice {
row_index : Int
code : String
severity : String
message : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ProtocolAdapterResult

pub(all) struct ProtocolAdapterResult {
dialect : WearableProtocolDialect
mapping : ProtocolColumnMapping
samples : Array[WearableSample]
notices : Array[ProtocolAdapterNotice]
accepted_count : Int
rejected_count : Int
header : Array[String]
source_id : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ProtocolColumnMapping

pub(all) struct ProtocolColumnMapping {
timestamp_index : Int
rr_index : Int
heart_rate_index : Int
quality_index : Int
movement_index : Int
temperature_index : Int
timestamp_unit : ProtocolUnit
rr_unit : ProtocolUnit
quality_unit : ProtocolUnit
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ProtocolPlan

pub(all) struct ProtocolPlan {
name : String
version : String
steps : Array[ProtocolStep]
target_beats : Int
target_duration_seconds : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A complete operator protocol.

#
ProtocolRunReport

pub(all) struct ProtocolRunReport {
plan_name : String
completed_steps : Int
required_steps : Int
completion_ratio : Double
duration_error_seconds : Double
passed : Bool
results : Array[ProtocolStepResult]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Protocol completion report.

#
ProtocolStep

pub(all) struct ProtocolStep {
ordinal : Int
name : String
duration_seconds : Double
instruction : String
required : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A protocol step shown to an operator.

#
ProtocolStepResult

pub(all) struct ProtocolStepResult {
ordinal : Int
observed_seconds : Double
completed : Bool
deviation_seconds : Double
note : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Completion state for a protocol step.

#
ProtocolUnit

pub(all) enum ProtocolUnit {
ProtocolMilliseconds
ProtocolSeconds
ProtocolBeatsPerMinute
ProtocolKilometers
ProtocolMeters
ProtocolG
ProtocolCelsius
ProtocolPercent
ProtocolUnknown
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ProtocolValidation

pub(all) struct ProtocolValidation {
passed : Bool
reasons : Array[String]
sample_count : Int
duration_seconds : Double
artifact_ratio : Double
date_gaps : Int
quality_grade : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Protocol validation result with actionable reasons.

#
QualityDecision

pub(all) struct QualityDecision {
accepted : Bool
confidence : Double
reasons : Array[String]
recommended_method : CleaningMethod
validation : IntervalValidation
diagnostic : SignalDiagnostic
} derive(Eq, ToJson,
Debug
,
FromJson
)

An explainable policy decision.

#
QualityFlag

pub(all) struct QualityFlag {
index : Int
value : Double
reason : ArtifactReason
severity : Double
replacement : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

One sample-level quality flag with a normalized severity.

#
QualityGatePolicy

pub(all) struct QualityGatePolicy {
minimum_samples : Int
minimum_clean_ratio : Double
minimum_signal_quality : Double
maximum_artifact_ratio : Double
maximum_gap_ratio : Double
require_frequency : Bool
require_nonlinear : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
QualityGatePolicy::default

#
QualityGateResult

pub(all) struct QualityGateResult {
passed : Bool
score : Double
clean_ratio : Double
artifact_ratio : Double
gap_ratio : Double
reasons : Array[String]
warnings : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
QualityPolicy

pub(all) struct QualityPolicy {
minimum_beats : Int
minimum_valid_ratio : Double
maximum_gap_candidates : Int
maximum_drift_ms_per_beat : Double
reject_non_finite : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Policy thresholds for deciding whether a recording can be scored.

#
QualityPolicy::daily_recovery

fn QualityPolicy::daily_recovery() -> QualityPolicy

A balanced policy for daily recovery measurements.

#
QualityReport

pub(all) struct QualityReport {
total_beats : Int
valid_beats : Int
ectopic_beats : Int
clean_ratio : Double
is_low_quality : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Signal quality and cleaning statistics report.

#
RangePosition

pub(all) struct RangePosition {
value : Double
percentile : Double
z_score : Double
band : String
in_range : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Position of a value within a reference range.

#
RateEpisode

pub(all) struct RateEpisode {
start : Int
end : Int
peak_bpm : Double
minimum_bpm : Double
average_bpm : Double
duration_seconds : Double
kind : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

A sustained heart-rate episode.

#
ReadinessLevel

pub(all) enum ReadinessLevel {
VeryLow
Low
Moderate
High
VeryHigh
} derive(Eq, ToJson,
Debug
,
FromJson
)

Readiness interpretation for daily recovery dashboards.

#
ReadinessScore

pub(all) struct ReadinessScore {
score : Double
level : ReadinessLevel
baseline_z : Double
trend_component : Double
quality_component : Double
explanation : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

A bounded readiness score with explainable components.

#
RecordingComparison

pub(all) struct RecordingComparison {
left_mean : Double
right_mean : Double
mean_delta : Double
left_rmssd : Double
right_rmssd : Double
rmssd_delta : Double
standardized_delta : Double
agreement_bias : Double
agreement_limits_lower : Double
agreement_limits_upper : Double
distance : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Paired comparison between two HRV recordings.

#
RecordingProtocol

pub(all) struct RecordingProtocol {
minimum_beats : Int
target_duration_seconds : Double
minimum_duration_seconds : Double
maximum_artifact_ratio : Double
required_sample_rate_hz : Double
require_ordered_dates : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Recording protocol used to validate an analysis request.

#
RecordingProtocol::morning

Short field protocol suitable for a morning readiness check.

#
RecordingProtocol::resting

Standard resting protocol: five minutes, at least 300 intervals.

#
RecoveryBaseline

pub(all) struct RecoveryBaseline {
sample_count : Int
mean_rr : Double
median_rr : Double
mad_rr : Double
median_rmssd : Double
mad_rmssd : Double
median_resting_hr : Double
mad_resting_hr : Double
median_sleep_hours : Double
quality_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RecoveryDayAssessment

pub(all) struct RecoveryDayAssessment {
record : RecoveryDayRecord
baseline : RecoveryBaseline
rr_z : Double
rmssd_z : Double
heart_rate_z : Double
sleep_z : Double
readiness_score : Double
status : RecoveryDayStatus
confidence : Double
reasons : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RecoveryDayRecord

pub(all) struct RecoveryDayRecord {
date : String
mean_rr_ms : Double
rmssd_ms : Double
sdnn_ms : Double
resting_hr_bpm : Double
sleep_hours : Double
sleep_efficiency : Double
respiratory_rate : Double
training_load : Double
signal_quality : Double
source : String
missing : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RecoveryDayStatus

pub(all) enum RecoveryDayStatus {
RecoveryReady
RecoveryModerate
RecoveryStrained
RecoveryUnavailable
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RecoveryTrajectory

pub(all) enum RecoveryTrajectory {
RecoveryImproving
RecoveryStable
RecoveryWorsening
RecoveryInsufficient
} derive(Eq, ToJson,
Debug
,
FromJson
)

Longitudinal recovery records and robust baselines for real-world use. Missing or low-quality mornings remain visible in the audit trail instead of being silently converted into zero-valued physiology.

#
RecoveryTrendPoint

pub(all) struct RecoveryTrendPoint {
date : String
score : Double
rmssd : Double
resting_hr : Double
load : Double
status : RecoveryDayStatus
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RecoveryWeekSummary

pub(all) struct RecoveryWeekSummary {
week_index : Int
start_date : String
end_date : String
record_count : Int
usable_count : Int
average_readiness : Double
minimum_readiness : Double
average_rmssd : Double
average_sleep_hours : Double
total_training_load : Double
quality_ratio : Double
missing_count : Int
trajectory : RecoveryTrajectory
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ReferenceRange

pub(all) struct ReferenceRange {
name : String
lower : Double
upper : Double
center : Double
sample_count : Int
source : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

A reference range with a label and sample provenance.

#
RegressionSummary

pub(all) struct RegressionSummary {
slope : Double
intercept : Double
correlation : Double
r_squared : Double
residual_standard_error : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A least-squares trend fitted to an ordered sequence.

#
ReportSectionKind

pub(all) enum ReportSectionKind {
ReportOverview
ReportQuality
ReportRecovery
ReportTraining
ReportForecast
ReportDecision
ReportActions
} derive(Eq, ToJson,
Debug
,
FromJson
)

Structured operational reports for CLI output, dashboards, and archives. Values remain machine-readable while headline text stays concise enough for a coach or operator to act on.

#
ReportTable

pub(all) struct ReportTable {
title : String
columns : Array[String]
rows : Array[Array[String]]
} derive(Eq, ToJson,
Debug
,
FromJson
)

A tabular report that can be exported to CSV or rendered by a dashboard.

#
RespirationConfig

pub(all) struct RespirationConfig {
sample_rate_hz : Double
minimum_rate_bpm : Double
maximum_rate_bpm : Double
minimum_cycles : Int
band_width_hz : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Respiratory analysis configuration.

#
RespirationConfig::default

Default adult resting respiration search range.

#
RespirationSummary

pub(all) struct RespirationSummary {
rate_bpm : Double
peak_frequency_hz : Double
modulation_depth_ms : Double
coherence : Double
phase_consistency : Double
confidence : Double
cycles : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Respiratory modulation summary.

#
RobustBaseline

pub(all) struct RobustBaseline {
center : Double
spread : Double
lower : Double
upper : Double
retained : Int
rejected : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Robust baseline statistics for a sequence of morning RMSSD values.

#
RollingLoadProfile

pub(all) struct RollingLoadProfile {
dates : Array[String]
daily_loads : Array[Double]
acute_load : Double
chronic_load : Double
acute_chronic_ratio : Double
exponentially_weighted_load : Double
monotony : Double
strain : Double
load_trend : Double
rest_day_count : Int
high_load_day_count : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RuntimeAggregate

pub(all) struct RuntimeAggregate {
case_name : String
target : String
sample_count : Int
mean_ms : Double
median_ms : Double
minimum_ms : Double
maximum_ms : Double
standard_deviation_ms : Double
throughput_per_second : Double
stable : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RuntimeBudget

pub(all) struct RuntimeBudget {
case_name : String
target : String
maximum_mean_ms : Double
maximum_p95_ms : Double
minimum_throughput : Double
minimum_stability : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RuntimeCheck

pub(all) struct RuntimeCheck {
aggregate : RuntimeAggregate
budget : RuntimeBudget
passed : Bool
reasons : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RuntimeReport

pub(all) struct RuntimeReport {
samples : Array[RuntimeSample]
aggregates : Array[RuntimeAggregate]
checks : Array[RuntimeCheck]
passed : Bool
feature_vector : Array[Double]
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
RuntimeSample

pub(all) struct RuntimeSample {
case_name : String
target : String
repetitions : Int
elapsed_ms : Double
input_size : Int
output_size : Int
accepted : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Runtime diagnostics for reproducible local and CI performance checks. Callers provide measured wall-clock values; this module summarizes them without embedding machine-specific claims in the library.

#
ScalarWindow

pub(all) struct ScalarWindow {
start_index : Int
end_index : Int
mean : Double
median : Double
standard_deviation : Double
minimum : Double
maximum : Double
valid : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

One scalar window observation.

#
ScenarioComparison

pub(all) struct ScenarioComparison {
baseline : ScenarioResult
alternatives : Array[ScenarioResult]
recommended_index : Int
recommendation : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ScenarioConfig

pub(all) struct ScenarioConfig {
easy_intensity : Double
recovery_intensity : Double
volume_reduction : Double
progression_limit : Double
minimum_score_for_hard : Double
forecast_weight : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ScenarioConfig::default

#
ScenarioResult

pub(all) struct ScenarioResult {
kind : TrainingScenarioKind
sessions : Array[ScenarioSession]
projected_load : Double
projected_ratio : Double
intensity_ceiling : Double
recovery_cost : Double
risk_score : Double
suitable : Bool
rationale : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
ScenarioSession

pub(all) struct ScenarioSession {
date : String
duration_minutes : Double
intensity : Double
expected_load : Double
purpose : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
SegmentRange

pub(all) struct SegmentRange {
start : Int
end : Int
ordinal : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

A half-open index range in an RR stream.

#
SegmentSummary

pub(all) struct SegmentSummary {
range : SegmentRange
count : Int
mean_rr : Double
sdnn : Double
rmssd : Double
pnn50 : Double
median_rr : Double
quality_ratio : Double
sd1 : Double
sd2 : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Metrics attached to one analysis segment.

#
SensorCalibration

pub(all) struct SensorCalibration {
scale : Double
offset_ms : Double
minimum_rr : Double
maximum_rr : Double
timestamp_jitter_ms : Double
name : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Sensor calibration parameters for vendor-neutral RR streams.

#
SensorCalibration::identity

Return a neutral calibration profile.

#
SensorCalibration::millisecond_sensor

fn SensorCalibration::millisecond_sensor() -> SensorCalibration

Return a calibration profile for a common millisecond sensor feed.

#
SessionAnalytics

pub(all) struct SessionAnalytics {
count : Int
usable_count : Int
mean_rmssd : Double
median_rmssd : Double
rmssd_trend : Double
rmssd_volatility : Double
mean_hr : Double
mean_quality : Double
total_load : Double
load_trend : Double
best_session_id : String
worst_session_id : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Aggregated session analytics.

#
SessionObservation

pub(all) struct SessionObservation {
session_id : String
date : String
duration_minutes : Double
rmssd : Double
sdnn : Double
mean_hr : Double
quality_score : Double
training_load : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

One analyzed session with quality metadata.

#
SessionStatus

pub(all) struct SessionStatus {
session_id : String
baseline_rmssd : Double
rmssd_z : Double
load : Double
quality_score : Double
recovery_label : String
should_review : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Per-session status relative to a rolling baseline.

#
SignalDiagnostic

pub(all) struct SignalDiagnostic {
sample_count : Int
duration_seconds : Double
valid_ratio : Double
artifact_ratio : Double
mean_rr : Double
median_rr : Double
mean_hr : Double
hr_range : Double
rmssd : Double
sdnn : Double
drift_slope : Double
gap_candidates : Int
grade : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

A numeric diagnostic for a recording and its clean-up result.

#
SignalQualityComponents

pub(all) struct SignalQualityComponents {
range_score : Double
continuity_score : Double
stationarity_score : Double
coverage_score : Double
plausibility_score : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Quality components on a common zero-to-one scale.

#
SignalQualitySummary

pub(all) struct SignalQualitySummary {
components : SignalQualityComponents
score : Double
grade : String
usable : Bool
reasons : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

Weighted quality score and decision.

#
SignalQualityWeights

pub(all) struct SignalQualityWeights {
range : Double
continuity : Double
stationarity : Double
coverage : Double
plausibility : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Quality-score weights.

#
SignalQualityWeights::default

Balanced default weights for daily RR data.

#
SimulationConfig

pub(all) struct SimulationConfig {
length : Int
baseline_rr : Double
variability_ms : Double
sample_rate_hz : Double
scenario : SimulationScenario
artifact_period : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Simulation parameters.

#
SimulationConfig::default

Default deterministic simulation configuration.

#
SimulationScenario

pub(all) enum SimulationScenario {
Stable
RespiratoryModulated
GradualDrift
ExerciseTransition
ArtifactBurst
} derive(Eq, ToJson,
Debug
,
FromJson
)

Scenario type for synthetic RR data.

#
SleepEpoch

pub(all) struct SleepEpoch {
start_minute : Double
duration_minutes : Double
stage : SleepStage
mean_rr : Double
rmssd : Double
quality_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

One scored sleep epoch.

#
SleepRecoverySummary

pub(all) struct SleepRecoverySummary {
total_minutes : Double
asleep_minutes : Double
awake_minutes : Double
deep_minutes : Double
rem_minutes : Double
light_minutes : Double
sleep_efficiency : Double
stage_transition_count : Int
overnight_mean_rr : Double
overnight_rmssd : Double
overnight_quality : Double
recovery_delta : Double
fragmentation_index : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Overnight recovery summary.

#
SleepStage

pub(all) enum SleepStage {
Awake
Light
Deep
Rem
Unknown
} derive(Eq, ToJson,
Debug
,
FromJson
)

Coarse sleep stage labels suitable for wearable summaries.

#
SpectralBand

pub(all) struct SpectralBand {
name : String
lower_hz : Double
upper_hz : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Named power-band definition.

#
SpectralProfile

pub(all) struct SpectralProfile {
bands : Array[BandPower]
total_power : Double
dominant_band : String
centroid_hz : Double
entropy : Double
edge_95_hz : Double
slope : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Spectral profile over a set of bands.

#
SpectrumBin

pub(all) struct SpectrumBin {
frequency_hz : Double
power : Double
amplitude : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

One-sided periodogram bin.

#
StreamingSession

pub(all) struct StreamingSession {
stats : OnlineStats
intervals : Array[Double]
config : HrvConfig
started : Bool
finished : Bool
} derive(
Debug
)

Streaming recording state for incremental RR ingestion.

#
StreamingSession::finish

fn StreamingSession::finish(self : StreamingSession) -> Unit

Mark a session finished; later pushes are ignored.

#
StreamingSession::is_usable

fn StreamingSession::is_usable(self : StreamingSession) -> Bool

Return whether the session is ready for recovery scoring.

#
StreamingSession::last

fn StreamingSession::last(self : StreamingSession) -> Double

Return the latest interval, or zero before the first sample.

#
StreamingSession::length

fn StreamingSession::length(self : StreamingSession) -> Int

Return the current sample count.

#
StreamingSession::mean

fn StreamingSession::mean(self : StreamingSession) -> Double

Return the current online mean without materializing a report.

#
StreamingSession::new

Create an empty streaming session.

#
StreamingSession::push

fn StreamingSession::push(self : StreamingSession, interval : Double) -> Unit

Ingest one RR interval and update the online moments.

#
StreamingSession::push_all

fn StreamingSession::push_all(self : StreamingSession, values : Array[Double]) -> Unit

Ingest a sequence of RR intervals.

#
StreamingSession::reset

fn StreamingSession::reset(self : StreamingSession) -> Unit

Reset a session while retaining its configuration.

#
StreamingSession::snapshot

Return a snapshot without changing the session.

#
StreamingSnapshot

pub(all) struct StreamingSnapshot {
metrics : HrvMetrics
validation : IntervalValidation
diagnostic : SignalDiagnostic
sample_count : Int
duration_seconds : Double
finished : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A finished streaming session snapshot.

#
SubjectSummary

pub(all) struct SubjectSummary {
subject_id : String
record_count : Int
rmssd_mean : Double
rmssd_sd : Double
quality_mean : Double
percentile : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Subject-specific aggregate used in cohort comparison.

#
Tachogram

pub(all) struct Tachogram {
sample_rate_hz : Double
timestamps_s : Array[Double]
values_ms : Array[Double]
} derive(Eq, ToJson,
Debug
,
FromJson
)

A uniformly sampled tachogram used by spectral analysis.

#
TelemetryQuery

pub(all) struct TelemetryQuery {
subject_id : String?
source_id : String?
start_seconds : Double?
end_seconds : Double?
minimum_quality : Double
limit : Int
descending : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TelemetryRecord

pub(all) struct TelemetryRecord {
record_id : String
subject_id : String
source_id : String
timestamp_seconds : Double
rr_ms : Double
heart_rate_bpm : Double
movement_g : Double
temperature_c : Double
signal_quality : Double
tags : Array[String]
} derive(Eq, ToJson,
Debug
,
FromJson
)

A dependency-free in-memory telemetry store for CLI tools, tests, and embedded applications. It provides deduplication, bounded retention, deterministic queries, and stable export without pretending to be a DB.

#
TelemetryRetentionResult

pub(all) struct TelemetryRetentionResult {
before_count : Int
after_count : Int
removed_count : Int
cutoff_seconds : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TelemetryStore

pub(all) struct TelemetryStore {
records : Array[TelemetryRecord]
notices : Array[TelemetryStoreNotice]
policy : TelemetryStorePolicy
} derive(
Debug
)

#
TelemetryStore::apply_retention

fn TelemetryStore::apply_retention(self : TelemetryStore, newest_timestamp : Double) -> TelemetryRetentionResult

#
TelemetryStore::count

fn TelemetryStore::count(self : TelemetryStore) -> Int

#
TelemetryStore::enforce_limits

fn TelemetryStore::enforce_limits(self : TelemetryStore) -> Int

#
TelemetryStore::export_csv

fn TelemetryStore::export_csv(self : TelemetryStore) -> String

#
TelemetryStore::insert

fn TelemetryStore::insert(self : TelemetryStore, record : TelemetryRecord) -> Bool

#
TelemetryStore::insert_many

fn TelemetryStore::insert_many(self : TelemetryStore, records : Array[TelemetryRecord]) -> Int

#
TelemetryStore::new

#
TelemetryStore::notice_count

fn TelemetryStore::notice_count(self : TelemetryStore) -> Int

#
TelemetryStore::notices

#
TelemetryStore::query

#
TelemetryStore::records

#
TelemetryStore::retain_after

fn TelemetryStore::retain_after(self : TelemetryStore, cutoff_seconds : Double) -> TelemetryRetentionResult

#
TelemetryStoreNotice

pub(all) struct TelemetryStoreNotice {
code : String
record_id : String
accepted : Bool
message : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TelemetryStorePolicy

pub(all) struct TelemetryStorePolicy {
maximum_records : Int
minimum_quality : Double
reject_duplicate_ids : Bool
reject_non_monotonic_subjects : Bool
retention_seconds : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TelemetryStorePolicy::default

#
TelemetrySummary

pub(all) struct TelemetrySummary {
record_count : Int
subject_count : Int
source_count : Int
first_timestamp : Double
last_timestamp : Double
duration_seconds : Double
mean_rr_ms : Double
mean_heart_rate_bpm : Double
mean_quality : Double
low_quality_count : Int
duplicate_notice_count : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TelemetryWindow

pub(all) struct TelemetryWindow {
ordinal : Int
start_seconds : Double
end_seconds : Double
samples : Array[WearableSample]
rr_intervals : Array[Double]
mean_quality : Double
gap_count : Int
complete : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A fixed-width time window over accepted telemetry.

#
TimeDomainExtended

pub(all) struct TimeDomainExtended {
mean_rr : Double
mean_hr : Double
sdnn : Double
rmssd : Double
sdsd : Double
cvnn : Double
pnn20 : Double
pnn50 : Double
median_rr : Double
iqr_rr : Double
min_rr : Double
max_rr : Double
range_rr : Double
mad_rr : Double
triangular_index : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Extended time-domain feature set.

#
TrainingDaySummary

pub(all) struct TrainingDaySummary {
date : String
session_count : Int
duration_minutes : Double
total_load : Double
average_intensity : Double
rmssd_change : Double
recovery_cost : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Daily training and recovery aggregates.

#
TrainingLoadEntry

pub(all) struct TrainingLoadEntry {
date : String
session_id : String
duration_minutes : Double
average_hr_bpm : Double
maximum_hr_bpm : Double
resting_hr_bpm : Double
rpe : Double
distance_km : Double
elevation_m : Double
signal_quality : Double
band : LoadIntensityBand
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TrainingLoadPlan

pub(all) struct TrainingLoadPlan {
days : Array[DailyLoadLedger]
profile : RollingLoadProfile
alerts : Array[LoadAlert]
total_load : Double
total_effective_load : Double
average_session_load : Double
peak_day : String
recommended_easy_days : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

#
TrainingLoadSummary

pub(all) struct TrainingLoadSummary {
total_minutes : Double
total_load : Double
average_intensity : Double
monotony : Double
strain : Double
acute_load : Double
chronic_load : Double
acute_chronic_ratio : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Daily training load summary using session duration and intensity.

#
TrainingPlanMetrics

pub(all) struct TrainingPlanMetrics {
days : Array[TrainingDaySummary]
total_load : Double
average_daily_load : Double
load_trend : Double
monotony : Double
strain : Double
recovery_cost : Double
high_load_days : Int
rest_days : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

Longitudinal training-load indicators.

#
TrainingScenarioKind

pub(all) enum TrainingScenarioKind {
ScenarioBaseline
ScenarioRecoveryDay
ScenarioEasyAerobic
ScenarioReducedVolume
ScenarioProgression
ScenarioReturnToHard
} derive(Eq, ToJson,
Debug
,
FromJson
)

What-if planning for recovery-aware training decisions. Scenarios are deterministic transformations of a baseline plan and never mutate the caller's sessions, which makes them safe for UI previews.

#
TrendDecomposition

pub(all) struct TrendDecomposition {
original : Array[Double]
baseline : Array[Double]
residual : Array[Double]
slope : Double
intercept : Double
turning_points : Int
explained_variance : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

Trend decomposition components.

#
WearableIngestConfig

pub(all) struct WearableIngestConfig {
minimum_quality : Double
maximum_gap_seconds : Double
maximum_duration_seconds : Double
allow_out_of_order : Bool
reject_duplicates : Bool
derive_missing_heart_rate : Bool
derive_missing_rr : Bool
source_name : String
} derive(Eq, ToJson,
Debug
,
FromJson
)

Ingestion settings shared by batch and streaming adapters.

#
WearableIngestConfig::default

Conservative defaults for wearable telemetry.

#
WearableIngestReport

pub(all) struct WearableIngestReport {
samples : Array[WearableSample]
notices : Array[IngestNotice]
accepted_count : Int
rejected_count : Int
duplicate_count : Int
out_of_order_count : Int
low_quality_count : Int
invalid_count : Int
gap_count : Int
duration_seconds : Double
quality_ratio : Double
complete : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

A stable summary returned by every ingestion operation.

#
WearableProtocolDialect

pub(all) enum WearableProtocolDialect {
ProtocolGeneric
ProtocolPolar
ProtocolGarmin
ProtocolAppleHealth
ProtocolFitExport
} derive(Eq, ToJson,
Debug
,
FromJson
)

CSV protocol adapters for common wearable exports. The adapter layer separates source-specific column names and units from the source-independent WearableSample and ingestion pipeline.

#
WearableSample

pub(all) struct WearableSample {
timestamp_seconds : Double
rr_ms : Double
heart_rate_bpm : Double
movement_g : Double
temperature_c : Double
signal_quality : Double
source_id : String
sequence_number : Int
} derive(Eq, ToJson,
Debug
,
FromJson
)

A source-neutral sample emitted by a wearable or an offline recorder.

The type deliberately keeps the original timestamp and sensor metadata so downstream reports can explain how a metric was produced. A sample may carry both an RR interval and a heart-rate value; the ingestion layer reconciles them without silently discarding the source values.

#
WearableSampleDisposition

pub(all) enum WearableSampleDisposition {
Accepted
Invalid
Duplicate
OutOfOrder
LowQuality
} derive(Eq, ToJson,
Debug
,
FromJson
)

Disposition of a sample after validation.

#
WindowFunction

pub(all) enum WindowFunction {
Rectangular
Hann
Hamming
Blackman
} derive(Eq, ToJson,
Debug
,
FromJson
)

Window functions for periodogram input.

#
WindowSchedule

pub(all) struct WindowSchedule {
size : Int
hop : Int
include_partial : Bool
} derive(Eq, ToJson,
Debug
,
FromJson
)

Window schedule.

#
WindowSchedule::default

Default overlapping schedule for display metrics.

#
WindowedAnalysis

pub(all) struct WindowedAnalysis {
start : Int
end : Int
mean_rr : Double
mean_hr : Double
sdnn : Double
rmssd : Double
quality_ratio : Double
readiness_proxy : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A rolling analysis window with quality and headline metrics.

#
WorkoutSession

pub(all) struct WorkoutSession {
date : String
duration_minutes : Double
intensity : Double
rmssd_before : Double
rmssd_after : Double
} derive(Eq, ToJson,
Debug
,
FromJson
)

A training session aligned with a morning recovery measurement.

#
absolute_successive_differences

fn absolute_successive_differences(intervals : Array[Double]) -> Array[Double]

Return absolute successive changes, useful for artifact dashboards.

#
activity_state_weight

fn activity_state_weight(state : ActivityState) -> Double

Return a numeric load weight for an activity state.

#
acute_chronic_workout_ratio

fn acute_chronic_workout_ratio(sessions : Array[WorkoutSession], date_index : Int) -> Double

Calculate a seven-day load ratio from a session list.

#
add_feature

fn add_feature(table : FeatureTable, feature : NamedFeature) -> FeatureTable

Add a derived feature to a table.

#
advanced_feature_vector

fn advanced_feature_vector(intervals : Array[Double]) -> Array[Double]

Return a robust HRV feature vector for downstream scoring.

#
aggregate_runtime_samples

fn aggregate_runtime_samples(samples : Array[RuntimeSample], case_name : String, target : String) -> RuntimeAggregate

#
agreement_rate

fn agreement_rate(left : Array[Double], right : Array[Double], tolerance : Double) -> Double

Calculate the proportion of paired values within a tolerance.

#
ambulatory_activity_load

fn ambulatory_activity_load(blocks : Array[ActivityBlock]) -> Double

Calculate a weighted activity load from blocks.

#
ambulatory_feature_vector

fn ambulatory_feature_vector(summary : AmbulatorySummary) -> Array[Double]

Return a state-duration feature vector.

#
ambulatory_summary_is_usable

fn ambulatory_summary_is_usable(summary : AmbulatorySummary) -> Bool

Return whether an ambulatory summary has enough usable signal.

#
analysis_export_document

fn analysis_export_document(report : AnalysisReport) -> ExportDocument

Create a document for a report.

#
analysis_export_rows

fn analysis_export_rows(report : AnalysisReport) -> Array[ExportRow]

Convert an analysis report to a stable row set.

#
analysis_preview

fn analysis_preview(report : AnalysisReport, limit : Int) -> Array[Double]

Return the first n cleaned intervals for preview cards.

#
analysis_quality_summary

fn analysis_quality_summary(report : AnalysisReport) -> String

Return a short human-readable quality summary.

#
analysis_report_markdown

fn analysis_report_markdown(report : AnalysisReport) -> String

Export a report as a Markdown table.

#
analysis_report_markdown_with_quality

fn analysis_report_markdown_with_quality(report : AnalysisReport) -> String

Create a Markdown report with the quality summary and feature vector size.

#
analyze_rr

fn analyze_rr(intervals : Array[Double], config : HrvConfig, options : AnalysisOptions) -> AnalysisReport

Analyze an RR sequence through cleaning, quality, time, frequency, and non-linear layers.

#
analyze_rr_default

fn analyze_rr_default(intervals : Array[Double]) -> AnalysisReport

Analyze using the package defaults.

#
analyze_streams

fn analyze_streams(streams : Array[Array[Double]], config : HrvConfig) -> Array[StreamingSnapshot]

Analyze a batch as a set of independent streaming sessions.

#
analyze_windows

fn analyze_windows(intervals : Array[Double], window_size : Int, hop_size : Int, config : HrvConfig) -> Array[WindowedAnalysis]

Analyze overlapping windows without computing expensive spectral features.

#
application_config_for

fn application_config_for(environment : ConfigurationEnvironment) -> ApplicationConfig

#
apply_window

fn apply_window(values : Array[Double], function : WindowFunction) -> Array[Double]

Apply a window without changing the input array.

#
artifact_feature_vector

fn artifact_feature_vector(profile : ArtifactProfile) -> Array[Double]

Create a stable artifact feature vector for model input.

#
artifact_quality_score

fn artifact_quality_score(profile : ArtifactProfile) -> Double

Calculate a quality score that penalizes severe and repeated artifacts.

#
artifact_runs

fn artifact_runs(profile : ArtifactProfile) -> Array[SegmentRange]

Group contiguous flags into artifact runs.

#
assess_recovery_day

fn assess_recovery_day(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> RecoveryDayAssessment

#
audit_calibration

fn audit_calibration(raw : Array[Double], calibration : SensorCalibration) -> CalibrationReport

Calculate the audit report for one calibration pass.

#
audit_event_for_component

fn audit_event_for_component(trail : AuditTrail, component : String) -> Array[AuditEvent]

#
audit_event_row

fn audit_event_row(event : AuditEvent) -> Array[String]

#
audit_events_csv

fn audit_events_csv(events : Array[AuditEvent]) -> String

#
audit_filter_all

fn audit_filter_all() -> AuditFilter

#
audit_filter_component

fn audit_filter_component(component : String) -> AuditFilter

#
audit_has_decision_event

fn audit_has_decision_event(trail : AuditTrail) -> Bool

#
audit_has_input_event

fn audit_has_input_event(trail : AuditTrail) -> Bool

#
audit_is_complete

fn audit_is_complete(trail : AuditTrail) -> Bool

#
audit_kind_name

fn audit_kind_name(kind : AuditEventKind) -> String

#
audit_latest_event

fn audit_latest_event(trail : AuditTrail) -> AuditEvent?

#
audit_merge

fn audit_merge(left : AuditTrail, right : AuditTrail) -> AuditTrail

#
audit_outcome_name

fn audit_outcome_name(outcome : AuditOutcome) -> String

#
audit_quality_floor_events

fn audit_quality_floor_events(trail : AuditTrail, floor : Double) -> Array[AuditEvent]

#
audit_query

fn audit_query(trails : Array[AuditTrail], filter : AuditFilter) -> Array[AuditEvent]

#
audit_summary

fn audit_summary(events : Array[AuditEvent]) -> AuditSummary

#
audit_summary_csv

fn audit_summary_csv(summary : AuditSummary) -> String

#
audit_trail_csv

fn audit_trail_csv(trail : AuditTrail) -> String

#
audit_trail_feature_vector

fn audit_trail_feature_vector(trail : AuditTrail) -> Array[Double]

#
audit_trail_status_message

fn audit_trail_status_message(trail : AuditTrail) -> String

#
audit_trails_summary

fn audit_trails_summary(trails : Array[AuditTrail]) -> AuditSummary

#
autocorrelation

fn autocorrelation(values : Array[Double], lag : Int) -> Double

Autocorrelation at a lag, normalized by zero-lag energy.

#
average_stream_rmssd

fn average_stream_rmssd(snapshots : Array[StreamingSnapshot]) -> Double

Return the average RMSSD across non-empty snapshots.

#
average_window_readiness

fn average_window_readiness(windows : Array[WindowedAnalysis]) -> Double

Return the average recovery proxy across windows.

#
baevsky_stress_index

fn baevsky_stress_index(intervals : Array[Double]) -> Double

Calculate a stress index based on histogram mode and spread.

#
band_power_ratio

fn band_power_ratio(bands : Array[BandPower], numerator : String, denominator : String) -> Double

Calculate a band power ratio with a safe zero denominator.

#
baseline_state

fn baseline_state(history : Array[MorningMeasurement], today_index : Int, config : HrvConfig) -> MorningBaselineState

Build a baseline state from the historical values before today.

#
batch_quality_decision

fn batch_quality_decision(decisions : Array[QualityDecision]) -> QualityDecision?

Combine policy decisions from a batch conservatively.

#
benchmark_csv

fn benchmark_csv(summary : BenchmarkSummary) -> String

Export benchmark values as a single CSV row.

#
benchmark_input

fn benchmark_input(config : BenchmarkConfig) -> Array[Double]

Generate the deterministic workload for a benchmark run.

#
benchmark_is_valid

fn benchmark_is_valid(summary : BenchmarkSummary) -> Bool

Return whether a benchmark summary has usable output.

#
best_scalar_window

fn best_scalar_window(windows : Array[ScalarWindow]) -> ScalarWindow?

Return the best window by a scalar field.

#
best_telemetry_window

fn best_telemetry_window(windows : Array[TelemetryWindow]) -> TelemetryWindow?

Return the window with the strongest quality-weighted sample count.

#
best_window

fn best_window(windows : Array[WindowedAnalysis]) -> WindowedAnalysis?

Return the window with the highest readiness proxy.

#
block_for_index

fn block_for_index(blocks : Array[ActivityBlock], index : Int) -> ActivityBlock?

Find the contiguous block containing an index.

#
bpm_to_rr

fn bpm_to_rr(rate_bpm : Double) -> Double

Convert beats per minute into milliseconds per beat.

#
bucket_window_means

fn bucket_window_means(windows : Array[ScalarWindow], bucket_count : Int) -> Array[Double]

Downsample window means into a fixed number of buckets.

#
build_cohort_summary

fn build_cohort_summary(observations : Array[CohortObservation], quality_floor : Double) -> CohortComparisonSummary

#
build_decision_plan

fn build_decision_plan(context : DecisionContext, thresholds : DecisionThresholds) -> DecisionPlan

#
build_forecast_bundle

fn build_forecast_bundle(recovery_scores : Array[Double], load_values : Array[Double], config : ForecastConfig) -> ForecastBundle

#
build_longitudinal_recovery_report

fn build_longitudinal_recovery_report(records : Array[RecoveryDayRecord], baseline_window : Int) -> LongitudinalRecoveryReport

#
build_operational_report

fn build_operational_report(report_id : String, generated_at : String, subject_id : String, analysis : AnalysisReport?, gate : QualityGateResult, recovery : LongitudinalRecoveryReport?, training : TrainingLoadPlan?, forecast : ForecastBundle?, decision : DecisionPlan?) -> OperationalReport

#
build_recovery_baseline

fn build_recovery_baseline(records : Array[RecoveryDayRecord]) -> RecoveryBaseline

#
build_report_table

fn build_report_table(report : AnalysisReport) -> ReportTable

Build a table from a headline analysis report.

#
build_rolling_load_profile

fn build_rolling_load_profile(days : Array[DailyLoadLedger], config : LoadModelConfig) -> RollingLoadProfile

#
build_runtime_report

fn build_runtime_report(samples : Array[RuntimeSample], budgets : Array[RuntimeBudget]) -> RuntimeReport

#
build_training_load_plan

fn build_training_load_plan(entries : Array[TrainingLoadEntry], config : LoadModelConfig) -> TrainingLoadPlan

#
calculate_approximate_entropy

fn calculate_approximate_entropy(values : Array[Double], dimension : Int, tolerance : Double) -> Double

Calculate approximate entropy with self-matches included.

#
calculate_band_powers

fn calculate_band_powers(spectrum : Array[SpectrumBin], bands : Array[SpectralBand]) -> Array[BandPower]

Calculate all named band powers and relative contributions.

#
calculate_cvnn

fn calculate_cvnn(intervals : Array[Double]) -> Double

Calculate coefficient of variation of NN intervals in percent.

#
calculate_dfa_alpha

fn calculate_dfa_alpha(values : Array[Double], minimum_scale : Int, maximum_scale : Int) -> Double

Calculate a compact detrended fluctuation analysis exponent.

#
calculate_fragmentation_index

fn calculate_fragmentation_index(epochs : Array[SleepEpoch]) -> Double

Calculate an epoch fragmentation index per hour of recording.

#
calculate_frequency_metrics

fn calculate_frequency_metrics(intervals : Array[Double], sample_rate_hz : Double) -> FrequencyMetrics

Compute conventional VLF, LF, and HF HRV bands.

#
calculate_geometric_metrics

fn calculate_geometric_metrics(intervals : Array[Double], bin_width : Double) -> GeometricMetrics

Calculate histogram-based triangular index and an approximate TINN width.

#
calculate_load_dose

fn calculate_load_dose(entry : TrainingLoadEntry, config : LoadModelConfig) -> LoadDose

#
calculate_load_monotony

fn calculate_load_monotony(days : Array[DailyLoadLedger]) -> Double

#
calculate_load_ratio

fn calculate_load_ratio(days : Array[DailyLoadLedger], acute_window : Int, chronic_window : Int) -> Double

#
calculate_load_strain

fn calculate_load_strain(days : Array[DailyLoadLedger]) -> Double

#
calculate_metrics

fn calculate_metrics(intervals : Array[Double], config : HrvConfig, quality : QualityReport) -> HrvMetrics

Calculate all time-domain HRV metrics for cleaned intervals.

#
calculate_monotony

fn calculate_monotony(daily_loads : Array[Double]) -> Double

Calculate monotony as mean daily load divided by its standard deviation.
fn calculate_morning_trends(history : Array[MorningMeasurement], window_size : Int, config : HrvConfig) -> Array[MorningTrend]

Calculate morning trends and baseline parameters for a history of measurements.

#
calculate_nonlinear_metrics

fn calculate_nonlinear_metrics(values : Array[Double]) -> NonlinearMetrics

Calculate all non-linear metrics with robust default parameters.

#
calculate_periodogram

fn calculate_periodogram(values : Array[Double], sample_rate_hz : Double) -> Array[SpectrumBin]

Calculate a real-valued DFT periodogram for a sampled sequence.

#
calculate_pnn

fn calculate_pnn(intervals : Array[Double], threshold_ms : Double) -> Double

Calculate the percentage of successive RR intervals differing by more than threshold_ms.

#
calculate_pnn_fraction

fn calculate_pnn_fraction(intervals : Array[Double], threshold_ms : Double) -> Double

Calculate a robust pNN metric using an arbitrary threshold.

#
calculate_poincare

fn calculate_poincare(intervals : Array[Double]) -> PoincareMetrics

Calculate SD1 and SD2 from successive RR pairs.

#
calculate_readiness

fn calculate_readiness(today_rmssd : Double, baseline : RobustBaseline, trend_slope : Double, quality_ratio : Double) -> ReadinessScore

Calculate readiness from today's RMSSD, a baseline, and signal quality.

#
calculate_readiness_series

fn calculate_readiness_series(history : Array[MorningMeasurement], config : HrvConfig) -> Array[ReadinessScore]

Turn a morning history into readiness scores with robust baselines.

#
calculate_recovery_score

fn calculate_recovery_score(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> Double

#
calculate_rmssd

fn calculate_rmssd(intervals : Array[Double]) -> Double

Calculate the Root Mean Square of Successive Differences (RMSSD).

#
calculate_robust_baseline

fn calculate_robust_baseline(values : Array[Double], fence : Double, range_factor : Double) -> RobustBaseline

Compute a median/MAD baseline with a configurable outlier fence.

#
calculate_sample_entropy

fn calculate_sample_entropy(values : Array[Double], dimension : Int, tolerance : Double) -> Double

Calculate sample entropy with Chebyshev template distance.

#
calculate_sdnn

fn calculate_sdnn(intervals : Array[Double]) -> Double

Calculate the Standard Deviation of NN intervals (SDNN).

#
calculate_sdsd

fn calculate_sdsd(intervals : Array[Double]) -> Double

Calculate the standard deviation of successive differences.

#
calculate_sleep_efficiency

fn calculate_sleep_efficiency(epochs : Array[SleepEpoch]) -> Double

Calculate sleep efficiency from epoch durations.

#
calculate_spectral_profile

fn calculate_spectral_profile(intervals : Array[Double], sample_rate_hz : Double, bands : Array[SpectralBand]) -> SpectralProfile

Calculate the spectral profile for a tachogram.

#
calculate_strain

fn calculate_strain(daily_loads : Array[Double]) -> Double

Calculate training strain as total load multiplied by monotony.

#
calculate_tinn

fn calculate_tinn(intervals : Array[Double]) -> Double

Approximate the triangular interpolation of the NN interval histogram.

#
calculate_triangular_index

fn calculate_triangular_index(intervals : Array[Double]) -> Double

Convenience wrapper using a 7.8125 ms histogram bin.

#
calibrate_intervals

fn calibrate_intervals(raw : Array[Double], calibration : SensorCalibration) -> Array[Double]

Calibrate and retain only values in the profile's range.

#
calibrate_value

fn calibrate_value(raw : Double, calibration : SensorCalibration) -> Double

Convert one raw sensor reading into milliseconds.

#
cardiac_vagal_index

fn cardiac_vagal_index(intervals : Array[Double]) -> Double

Calculate a normalized cardiac vagal index from RMSSD and mean RR.

#
changed_windows

fn changed_windows(windows : Array[ScalarWindow], threshold : Double) -> Array[ScalarWindow]

Return windows whose values changed by at least a threshold.

#
check_runtime_budget

fn check_runtime_budget(aggregate : RuntimeAggregate, budget : RuntimeBudget) -> RuntimeCheck

#
clamp_to_reference_range

fn clamp_to_reference_range(value : Double, range : ReferenceRange) -> Double

Clamp a value into a reference range.

#
classify_activity

fn classify_activity(sample : AmbulatorySample, thresholds : ActivityThresholds) -> ActivityState

Classify a synchronized sample.

#
classify_interval

fn classify_interval(value : Double, config : HrvConfig) -> IntervalDisposition

Classify a value against the physiological range in a configuration.

#
classify_load_risk

fn classify_load_risk(profile : RollingLoadProfile, config : LoadModelConfig) -> LoadRiskLevel

#
classify_session_history

fn classify_session_history(observations : Array[SessionObservation], window_size : Int, load_threshold : Double) -> Array[SessionStatus]

Create statuses for all observations using a trailing baseline.

#
classify_session_status

fn classify_session_status(observation : SessionObservation, baseline_rmssd : Double, baseline_scale : Double, load_threshold : Double) -> SessionStatus

Calculate a baseline-relative session status.

#
classify_sleep_epoch

fn classify_sleep_epoch(mean_rr : Double, rmssd : Double, movement_score : Double, quality_ratio : Double) -> SleepStage

Infer a coarse stage from RR-derived recovery markers.

#
clean_rr_intervals

fn clean_rr_intervals(intervals : Array[Double], cleaning_method : CleaningMethod, config : HrvConfig) -> (Array[Double], QualityReport)

Clean RR intervals and generate a quality report.

#
cleaning_feature_vector

fn cleaning_feature_vector(result : CleaningResult) -> Array[Double]

Return a compact cleaning feature vector.

#
coefficient_of_variation

fn coefficient_of_variation(values : Array[Double]) -> Double

Return the coefficient of variation as a percentage.

#
cohort_compare

fn cohort_compare(observation : CohortObservation, observations : Array[CohortObservation], quality_floor : Double) -> CohortComparison

#
cohort_comparisons_csv

fn cohort_comparisons_csv(comparisons : Array[CohortComparison]) -> String

#
cohort_feature_vector

fn cohort_feature_vector(summary : CohortSummary) -> Array[Double]

Return a deterministic cohort feature vector for dashboards.

#
cohort_findings

fn cohort_findings(comparison : CohortComparison) -> Array[String]

#
cohort_metric_range

fn cohort_metric_range(observations : Array[CohortObservation], metric : String) -> CohortMetricRange

#
cohort_observation_is_eligible

fn cohort_observation_is_eligible(observation : CohortObservation, quality_floor : Double) -> Bool

#
cohort_percentile_for

fn cohort_percentile_for(summary : CohortComparisonSummary, reference : String, metric : String) -> Double

#
cohort_quality_adjusted_score

fn cohort_quality_adjusted_score(observation : CohortObservation, summary : CohortComparisonSummary) -> Double

#
cohort_range_row

fn cohort_range_row(range : CohortMetricRange) -> Array[String]

#
cohort_ranges

fn cohort_ranges(observations : Array[CohortObservation], quality_floor : Double) -> Array[CohortMetricRange]

#
cohort_rank

fn cohort_rank(observation : CohortObservation, observations : Array[CohortObservation], metric : String, higher_is_better : Bool, quality_floor : Double) -> CohortRank

#
cohort_recovery_flag

fn cohort_recovery_flag(observation : CohortObservation, summary : CohortComparisonSummary) -> Bool

#
cohort_similarity_for

fn cohort_similarity_for(summary : CohortComparisonSummary, reference : String) -> Double

#
cohort_summary_csv

fn cohort_summary_csv(summary : CohortComparisonSummary) -> String

#
cohort_summary_feature_vector

fn cohort_summary_feature_vector(summary : CohortComparisonSummary) -> Array[Double]

#
cohort_summary_is_usable

fn cohort_summary_is_usable(summary : CohortComparisonSummary) -> Bool

#
cohort_training_load_flag

fn cohort_training_load_flag(observation : CohortObservation, summary : CohortComparisonSummary) -> Bool

#
compare_analysis_reports

fn compare_analysis_reports(left : AnalysisReport, right : AnalysisReport) -> Double

Compare two reports using normalized feature distance.

#
compare_recordings

fn compare_recordings(left : Array[Double], right : Array[Double]) -> RecordingComparison

Calculate a paired comparison and Bland-Altman-style agreement limits.

#
compare_subject_to_cohort

fn compare_subject_to_cohort(subject : SubjectSummary, cohort : Array[SubjectSummary]) -> SubjectSummary

Compare one subject's mean RMSSD with a cohort distribution.

#
compare_training_scenarios

fn compare_training_scenarios(plan : TrainingLoadPlan, recovery_score : Double, config : ScenarioConfig) -> ScenarioComparison

#
comparison_feature_vector

fn comparison_feature_vector(comparison : RecordingComparison) -> Array[Double]

Return a compact comparison feature vector.

#
concatenate_feature_tables

fn concatenate_feature_tables(tables : Array[FeatureTable]) -> FeatureTable

Concatenate feature vectors and preserve their source names.

#
config_allows_streaming

fn config_allows_streaming(config : ApplicationConfig) -> Bool

#
config_analysis_window_is_safe

fn config_analysis_window_is_safe(config : ApplicationConfig) -> Bool

#
config_environment_is_safe

fn config_environment_is_safe(config : ApplicationConfig) -> Bool

#
config_environment_line

fn config_environment_line(config : ApplicationConfig) -> String

#
config_feature_vector

fn config_feature_vector(config : ApplicationConfig) -> Array[Double]

#
config_for_ci

fn config_for_ci() -> ApplicationConfig

#
config_for_cli

fn config_for_cli() -> ApplicationConfig

#
config_for_tests

fn config_for_tests() -> ApplicationConfig

#
config_forecast_horizon

fn config_forecast_horizon(config : ApplicationConfig) -> Int

#
config_forecast_policy_line

fn config_forecast_policy_line(config : ApplicationConfig) -> String

#
config_has_valid_bounds

fn config_has_valid_bounds(config : ApplicationConfig) -> Bool

#
config_has_valid_windows

fn config_has_valid_windows(config : ApplicationConfig) -> Bool

#
config_ingest_policy_line

fn config_ingest_policy_line(config : ApplicationConfig) -> String

#
config_is_benchmark_ready

fn config_is_benchmark_ready(config : ApplicationConfig) -> Bool

#
config_is_deterministic

fn config_is_deterministic(config : ApplicationConfig) -> Bool

#
config_is_production_ready

fn config_is_production_ready(config : ApplicationConfig) -> Bool

#
config_is_strictly_valid

fn config_is_strictly_valid(config : ApplicationConfig) -> Bool

#
config_is_valid

fn config_is_valid(config : ApplicationConfig) -> Bool

#
config_issue_count

fn config_issue_count(config : ApplicationConfig) -> Int

#
config_load_policy_line

fn config_load_policy_line(config : ApplicationConfig) -> String

#
config_maximum_gap

fn config_maximum_gap(config : ApplicationConfig) -> Double

#
config_policy_lines

fn config_policy_lines(config : ApplicationConfig) -> Array[String]

#
config_quality_floor

fn config_quality_floor(config : ApplicationConfig) -> Double

#
config_quality_floor_is_safe

fn config_quality_floor_is_safe(config : ApplicationConfig) -> Bool

#
config_quality_policy_line

fn config_quality_policy_line(config : ApplicationConfig) -> String

#
config_readiness_line

fn config_readiness_line(config : ApplicationConfig) -> String

#
config_requires_frequency

fn config_requires_frequency(config : ApplicationConfig) -> Bool

#
config_requires_nonlinear

fn config_requires_nonlinear(config : ApplicationConfig) -> Bool

#
config_retention_days

fn config_retention_days(config : ApplicationConfig) -> Int

#
config_retention_seconds

fn config_retention_seconds(config : ApplicationConfig) -> Double

#
config_status

fn config_status(config : ApplicationConfig) -> String

#
config_summary

fn config_summary(config : ApplicationConfig) -> String

#
config_validation_csv

fn config_validation_csv(validation : ConfigValidation) -> String

#
config_validation_error_keys

fn config_validation_error_keys(validation : ConfigValidation) -> Array[String]

#
config_validation_has_errors

fn config_validation_has_errors(validation : ConfigValidation) -> Bool

#
config_validation_message

fn config_validation_message(validation : ConfigValidation) -> String

#
config_validation_warning_count

fn config_validation_warning_count(validation : ConfigValidation) -> Int

#
config_window_days

fn config_window_days(config : ApplicationConfig) -> Array[Int]

#
configuration_environment_name

fn configuration_environment_name(environment : ConfigurationEnvironment) -> String

#
configuration_is_strict

fn configuration_is_strict(environment : ConfigurationEnvironment) -> Bool

#
continuity_quality_score

fn continuity_quality_score(intervals : Array[Double], threshold_ms : Double) -> Double

Score continuity using large successive changes.

#
correlation_value

fn correlation_value(left : Array[Double], right : Array[Double]) -> Double

Pearson correlation for paired values.

#
count_activity_state

fn count_activity_state(samples : Array[AmbulatorySample], state : ActivityState, thresholds : ActivityThresholds) -> Int

Count samples belonging to a state.

#
count_gap_candidates

fn count_gap_candidates(intervals : Array[Double], config : HrvConfig, multiplier : Double) -> Int

Count gaps between two plausible beats using a configurable multiplier.

#
count_in_reference_range

fn count_in_reference_range(values : Array[Double], range : ReferenceRange) -> Int

Count observations inside a reference range.

#
count_large_successive_changes

fn count_large_successive_changes(intervals : Array[Double], threshold_ms : Double) -> Int

Count intervals whose local change exceeds a threshold.

#
count_quality_records

fn count_quality_records(records : Array[BatchRecord], threshold : Double) -> Int

Return the number of records that meet a quality threshold.

#
count_turning_points

fn count_turning_points(values : Array[Double]) -> Int

Count direction changes in a residual sequence.

#
covariance_matrix

fn covariance_matrix(matrix : Array[Array[Double]]) -> Array[Array[Double]]

Calculate a column covariance matrix.

#
covariance_value

fn covariance_value(left : Array[Double], right : Array[Double]) -> Double

Return covariance using the sample denominator.

#
coverage_quality_score

fn coverage_quality_score(sample_count : Int, minimum : Int, target : Int) -> Double

Score sample coverage relative to a minimum and target length.

#
cumulative_power_frequency

fn cumulative_power_frequency(spectrum : Array[SpectrumBin], fraction : Double) -> Double

Return the frequency at which a cumulative power fraction is reached.

#
date_distance

fn date_distance(left : DateParts, right : DateParts) -> Int

Return the signed day distance from left to right.

#
date_to_ordinal

fn date_to_ordinal(date : DateParts) -> Int

Convert a valid date to a monotonically increasing day number.

#
dates_are_ordered

fn dates_are_ordered(values : Array[String]) -> Bool

Return whether dates are strictly increasing.

#
days_in_month

fn days_in_month(year : Int, month : Int) -> Int

Return the number of days in a month.

#
decision_action

fn decision_action(priority : Int, title : String, instruction : String, duration_minutes : Double, intensity_ceiling : Double, requires_recheck : Bool) -> DecisionAction

#
decision_actions

fn decision_actions(context : DecisionContext, findings : Array[DecisionFinding], score : Double) -> Array[DecisionAction]

#
decision_actions_csv

fn decision_actions_csv(plan : DecisionPlan) -> String

#
decision_collect_findings

fn decision_collect_findings(context : DecisionContext, thresholds : DecisionThresholds) -> Array[DecisionFinding]

#
decision_confidence

fn decision_confidence(findings : Array[DecisionFinding]) -> Double

#
decision_domain_counts

fn decision_domain_counts(findings : Array[DecisionFinding]) -> Array[Int]

#
decision_domain_name

fn decision_domain_name(value : DecisionDomain) -> String

#
decision_finding

fn decision_finding(code : String, domain : DecisionDomain, severity : DecisionSeverity, title : String, evidence : String, observed : Double, reference : Double, confidence : Double, action : String) -> DecisionFinding

#
decision_findings_for_severity

fn decision_findings_for_severity(plan : DecisionPlan, severity : DecisionSeverity) -> Array[DecisionFinding]

#
decision_load_findings

fn decision_load_findings(plan : TrainingLoadPlan, thresholds : DecisionThresholds) -> Array[DecisionFinding]

#
decision_max_severity

fn decision_max_severity(findings : Array[DecisionFinding]) -> DecisionSeverity

#
decision_plan_csv

fn decision_plan_csv(plan : DecisionPlan) -> String

#
decision_plan_feature_vector

fn decision_plan_feature_vector(plan : DecisionPlan) -> Array[Double]

#
decision_plan_has_domain

fn decision_plan_has_domain(plan : DecisionPlan, domain : DecisionDomain) -> Bool

#
decision_plan_intensity_ceiling

fn decision_plan_intensity_ceiling(plan : DecisionPlan) -> Double

#
decision_plan_is_actionable

fn decision_plan_is_actionable(plan : DecisionPlan) -> Bool

#
decision_plan_message

fn decision_plan_message(plan : DecisionPlan) -> String

#
decision_plan_recheck_required

fn decision_plan_recheck_required(plan : DecisionPlan) -> Bool

#
decision_plan_risk_score

fn decision_plan_risk_score(plan : DecisionPlan) -> Double

#
decision_plan_summary

fn decision_plan_summary(plan : DecisionPlan) -> String

#
decision_quality_finding

fn decision_quality_finding(report : QualityReport, thresholds : DecisionThresholds) -> DecisionFinding?

#
decision_recovery_findings

fn decision_recovery_findings(report : LongitudinalRecoveryReport, thresholds : DecisionThresholds) -> Array[DecisionFinding]

#
decision_score

fn decision_score(context : DecisionContext, findings : Array[DecisionFinding]) -> Double

#
decision_severity_name

fn decision_severity_name(value : DecisionSeverity) -> String

#
decision_sleep_findings

fn decision_sleep_findings(context : DecisionContext, thresholds : DecisionThresholds) -> Array[DecisionFinding]

#
decision_symptom_finding

fn decision_symptom_finding(context : DecisionContext, thresholds : DecisionThresholds) -> DecisionFinding?

#
decompose_trend

fn decompose_trend(values : Array[Double], window_size : Int) -> TrendDecomposition

Decompose a series into robust baseline and residual.

#
default_analysis_feature_table

fn default_analysis_feature_table(report : AnalysisReport) -> FeatureTable

Create a table from the complete default analysis vector.

#
detect_artifact_clusters

fn detect_artifact_clusters(intervals : Array[Double], config : HrvConfig, minimum_count : Int) -> Array[ArtifactCluster]

Detect clusters of invalid values in an RR stream.

#
detect_change_points

fn detect_change_points(values : Array[Double], window_size : Int, minimum_magnitude : Double) -> Array[ChangePoint]

Detect local mean shifts using adjacent windows.

#
detect_morning_alerts

fn detect_morning_alerts(history : Array[MorningMeasurement], config : HrvConfig) -> Array[MorningAlert]

Detect low/high RMSSD and date-quality alerts.

#
detect_rate_episodes

fn detect_rate_episodes(intervals : Array[Double], lower_bpm : Double, upper_bpm : Double, minimum_beats : Int) -> Array[RateEpisode]

Detect sustained tachycardia or bradycardia episodes.

#
detrend_linear

fn detrend_linear(values : Array[Double]) -> Array[Double]

Remove the least-squares linear trend from a sequence.

#
diagnose_signal

fn diagnose_signal(intervals : Array[Double], config : HrvConfig) -> SignalDiagnostic

Build a dashboard diagnostic without running the full spectral pipeline.

#
diagnostic_csv

fn diagnostic_csv(diagnostic : SignalDiagnostic) -> String

Export a diagnostic as CSV.

#
diagnostic_recommendation

fn diagnostic_recommendation(diagnostic : SignalDiagnostic) -> String

Return a one-line recommendation for a signal-quality card.

#
dominant_activity_state

fn dominant_activity_state(blocks : Array[ActivityBlock]) -> ActivityState

Choose the state with the largest duration.

#
dominant_autocorrelation_lag

fn dominant_autocorrelation_lag(values : Array[Double], minimum_lag : Int, maximum_lag : Int) -> Int

Estimate the dominant period in samples from autocorrelation peaks.

#
dominant_band_name

fn dominant_band_name(bands : Array[BandPower]) -> String

Find the band with the largest absolute power.

#
dominant_spectrum_bin

fn dominant_spectrum_bin(spectrum : Array[SpectrumBin]) -> SpectrumBin

Return the largest non-DC spectrum bin.

#
downsample_mean

fn downsample_mean(values : Array[Double], block_size : Int) -> Array[Double]

Downsample a sequence by averaging fixed-size blocks.

#
endpoint_change

fn endpoint_change(values : Array[Double]) -> Double

Return the signed change between the endpoints of a series.

#
entropy_tolerance

fn entropy_tolerance(values : Array[Double], multiplier : Double) -> Double

Estimate sample entropy tolerance from a standard deviation multiplier.

#
estimate_offset

fn estimate_offset(reference : Array[Double], observed : Array[Double]) -> Double

Apply an offset correction estimated from a reference sequence.

#
estimate_respiration

fn estimate_respiration(intervals : Array[Double], config : RespirationConfig) -> RespirationSummary

Estimate respiration from the dominant respiratory spectral peak.

#
estimate_respiratory_cycles

fn estimate_respiratory_cycles(intervals : Array[Double], frequency_hz : Double, sample_rate_hz : Double) -> Int

Estimate the number of respiratory cycles in a candidate frequency.

#
estimate_scale

fn estimate_scale(reference : Array[Double], observed : Array[Double]) -> Double

Estimate a multiplicative scale from paired reference/observed values.

#
estimate_trace_rate

fn estimate_trace_rate(trace : Array[Double], sample_rate_hz : Double) -> Double

Return a respiratory rate from a direct breathing trace.

#
evaluate_protocol_run

fn evaluate_protocol_run(plan : ProtocolPlan, results : Array[ProtocolStepResult], tolerance_seconds : Double) -> ProtocolRunReport

Validate step results against a plan.

#
evaluate_quality_policy

fn evaluate_quality_policy(intervals : Array[Double], config : HrvConfig, policy : QualityPolicy) -> QualityDecision

Evaluate a signal against a policy and return rejection reasons.

#
evaluate_quality_with_runs

fn evaluate_quality_with_runs(intervals : Array[Double], config : HrvConfig, minimum_run : Int) -> SignalQualitySummary

Return a quality summary with a custom run-coverage reason.

#
evaluate_signal_quality

fn evaluate_signal_quality(intervals : Array[Double], config : HrvConfig, weights : SignalQualityWeights, minimum_beats : Int, target_beats : Int) -> SignalQualitySummary

Evaluate an RR stream with explainable components.

#
ewma_morning_baseline

fn ewma_morning_baseline(history : Array[MorningMeasurement], alpha : Double) -> Array[Double]

Return a seven-day exponentially weighted RMSSD baseline.

#
exponential_moving_average

fn exponential_moving_average(values : Array[Double], alpha : Double) -> Array[Double]

Calculate an exponentially weighted moving average.

#
exponential_smooth

fn exponential_smooth(values : Array[Double], alpha : Double) -> Array[Double]

Smooth a series while preserving its length.

#
exponentially_weighted_deviation

fn exponentially_weighted_deviation(values : Array[Double], alpha : Double) -> Array[Double]

Calculate a rolling exponentially weighted baseline and deviations.

#
exponentially_weighted_load

fn exponentially_weighted_load(days : Array[DailyLoadLedger], decay : Double) -> Double

#
export_daily_load_csv

fn export_daily_load_csv(plan : TrainingLoadPlan) -> String

#
export_document_csv

fn export_document_csv(document : ExportDocument) -> String

Export a document as a CSV table.

#
export_escape

fn export_escape(value : String) -> String

Escape a value for a simple key-value export.

#
export_load_alerts_csv

fn export_load_alerts_csv(plan : TrainingLoadPlan) -> String

#
export_log_line

fn export_log_line(report : AnalysisReport) -> String

Return a compact one-line summary for logs.

#
export_review_count

fn export_review_count(rows : Array[ExportRow]) -> Int

Return the number of rows marked for review.

#
export_row

fn export_row(key : String, value : Double, unit : String, status : String) -> ExportRow

Create one row.

#
export_row_is_numeric

fn export_row_is_numeric(row : ExportRow) -> Bool

Return whether an export row contains a finite numeric value.

#
export_rows_ndjson

fn export_rows_ndjson(rows : Array[ExportRow]) -> String

Export rows as a compact JSON-like line protocol without external state.

#
export_training_load_plan_csv

fn export_training_load_plan_csv(plan : TrainingLoadPlan) -> String

#
export_with_provenance

fn export_with_provenance(content : String, source : String) -> String

Add a provenance footer to a text export.

#
feature_completeness

fn feature_completeness(table : FeatureTable) -> Double

Return a feature completeness ratio.

#
feature_names

fn feature_names(table : FeatureTable) -> Array[String]

Return the feature names in table order.

#
feature_schema_matches

fn feature_schema_matches(left : FeatureTable, right : FeatureTable) -> Bool

Return whether two tables have exactly the same feature schema.

#
feature_table_distance

fn feature_table_distance(left : FeatureTable, right : FeatureTable) -> Double

Calculate an L2 distance between aligned feature tables.

#
feature_table_row

fn feature_table_row(table : FeatureTable) -> Array[String]

Return a CSV-compatible row with the table values.

#
feature_value

fn feature_value(table : FeatureTable, name : String) -> Double?

Look up a named feature.

#
feature_value_or

fn feature_value_or(table : FeatureTable, name : String, fallback : Double) -> Double

Look up a named feature and return a fallback when absent.

#
feature_values

fn feature_values(table : FeatureTable, missing_value : Double) -> Array[Double]

Return values in table order, replacing missing values with a default.

#
field_protocol_plan

fn field_protocol_plan() -> ProtocolPlan

Make a short field protocol plan.

#
fit_feature_scaler

fn fit_feature_scaler(table : FeatureTable) -> FeatureScaler

Learn robust center and scale parameters for a table.

#
fit_linear_trend

fn fit_linear_trend(values : Array[Double]) -> RegressionSummary

Fit y = slope * x + intercept to an ordered sequence of y values.

#
fit_scaler_from_tables

fn fit_scaler_from_tables(tables : Array[FeatureTable]) -> FeatureScaler

Learn a scaler from aligned feature tables.

#
fit_two_feature_regression

fn fit_two_feature_regression(features : Array[Array[Double]], target : Array[Double]) -> Array[Double]

Calculate a two-feature least-squares regression with intercept.

#
forecast_adjusted_intensity

fn forecast_adjusted_intensity(forecast : OperationalForecastResult, requested : Double) -> Double

#
forecast_average_interval

fn forecast_average_interval(result : OperationalForecastResult) -> Double

#
forecast_backtest

fn forecast_backtest(history : Array[Double], algorithm : ForecastMethod, config : ForecastConfig, holdout : Int) -> ForecastBacktest

#
forecast_backtest_csv

fn forecast_backtest_csv(backtest : ForecastBacktest) -> String

#
forecast_bundle_csv

fn forecast_bundle_csv(bundle : ForecastBundle) -> String

#
forecast_bundle_feature_vector

fn forecast_bundle_feature_vector(bundle : ForecastBundle) -> Array[Double]

#
forecast_coverage

fn forecast_coverage(actual : Array[Double], forecast : ForecastResult) -> Double

Return the proportion of points inside a confidence interval.

#
forecast_ewma

fn forecast_ewma(values : Array[Double], alpha : Double) -> Double

#
forecast_interval_width

fn forecast_interval_width(point : ForecastPoint) -> Double

#
forecast_is_declining

fn forecast_is_declining(result : OperationalForecastResult) -> Bool

#
forecast_last_point

fn forecast_last_point(result : OperationalForecastResult) -> ForecastPoint?

#
forecast_linear

fn forecast_linear(values : Array[Double], horizon : Int) -> ForecastResult

Fit a linear forecast and return approximate 95% prediction bounds.

#
forecast_linear_next

fn forecast_linear_next(values : Array[Double]) -> Double

#
forecast_mae

fn forecast_mae(actual : Array[Double], predicted : Array[Double]) -> Double

Calculate mean absolute forecast error.

#
forecast_method_name

fn forecast_method_name(algorithm : ForecastMethod) -> String

#
forecast_method_value

fn forecast_method_value(values : Array[Double], algorithm : ForecastMethod, config : ForecastConfig) -> Double

#
forecast_morning_rmssd

fn forecast_morning_rmssd(history : Array[MorningMeasurement], horizon : Int) -> ForecastResult

Forecast future RMSSD from a morning history.

#
forecast_moving_average

fn forecast_moving_average(values : Array[Double], window : Int) -> Double

#
forecast_point

fn forecast_point(step : Int, value : Double, scale : Double, confidence : Double, algorithm : ForecastMethod, config : ForecastConfig) -> ForecastPoint

#
forecast_point_at

fn forecast_point_at(result : OperationalForecastResult, step : Int) -> ForecastPoint?

#
forecast_points_csv

fn forecast_points_csv(result : OperationalForecastResult) -> String

#
forecast_result_feature_vector

fn forecast_result_feature_vector(result : OperationalForecastResult) -> Array[Double]

#
forecast_result_is_usable

fn forecast_result_is_usable(result : OperationalForecastResult) -> Bool

#
forecast_values

fn forecast_values(history : Array[Double], algorithm : ForecastMethod, config : ForecastConfig) -> OperationalForecastResult

#
frame_values

fn frame_values(values : Array[Double], frame_size : Int, hop_size : Int) -> Array[Array[Double]]

Split a sequence into overlapping frames for streaming or spectral work.

#
frequency_feature_vector

fn frequency_feature_vector(intervals : Array[Double], sample_rate_hz : Double) -> Array[Double]

Return a concise frequency feature vector for model inputs.

#
generate_drift_fixture

fn generate_drift_fixture(length : Int, baseline : Double, drift_per_beat : Double) -> Array[Double]

Generate a controlled drift fixture.

#
generate_resting_fixture

fn generate_resting_fixture(length : Int, baseline : Double) -> Array[Double]

Generate a deterministic resting RR fixture for tests and benchmarks.

#
group_training_load_days

fn group_training_load_days(entries : Array[TrainingLoadEntry], config : LoadModelConfig) -> Array[DailyLoadLedger]

#
has_band_power

fn has_band_power(spectrum : Array[SpectrumBin], band : SpectralBand, minimum : Double) -> Bool

Return whether a spectrum has measurable power in a band.

#
heart_rate_in_zone

fn heart_rate_in_zone(rate : Double, lower_bpm : Double, upper_bpm : Double) -> Bool

Return whether a heart rate is within a closed zone.

#
heart_rate_recovery_after_activity

fn heart_rate_recovery_after_activity(blocks : Array[ActivityBlock], recovery_minutes : Double) -> Double

Estimate heart-rate recovery after a vigorous block.

#
histogram_entropy

fn histogram_entropy(values : Array[Double], bin_count : Int) -> Double

Calculate entropy of an amplitude histogram.

#
histogram_mode

fn histogram_mode(bins : Array[Int], minimum : Double, bin_width : Double) -> (Double, Int)

Return the most populated histogram bin, preferring the lower bin on ties.

#
ingest_sorted_wearable_samples

fn ingest_sorted_wearable_samples(input : Array[WearableSample], config : WearableIngestConfig) -> WearableIngestReport

Ingest after ordering a device batch by timestamp.

#
ingest_wearable_samples

fn ingest_wearable_samples(input : Array[WearableSample], config : WearableIngestConfig) -> WearableIngestReport

Ingest a batch, reject malformed events, and retain an audit trail.

#
inject_artifacts

fn inject_artifacts(values : Array[Double]) -> Array[Double]

Add deterministic ectopic and boundary artifacts to a fixture.

#
inject_missing_run

fn inject_missing_run(values : Array[Double], start : Int, length : Int) -> Array[Double]

Inject a deterministic missing-value run.

#
inspect_cleaning

fn inspect_cleaning(intervals : Array[Double], cleaning_method : CleaningMethod, config : HrvConfig) -> CleaningResult

Detect artifacts and record the replacement used by a cleaning method.

#
integrate_band_power

fn integrate_band_power(spectrum : Array[SpectrumBin], lower_hz : Double, upper_hz : Double) -> Double

Sum periodogram power in a half-open frequency interval.

#
interpolate_artifact

fn interpolate_artifact(intervals : Array[Double], index : Int, config : HrvConfig) -> Double

Interpolate an artifact from the nearest valid neighbors.

#
interpolate_at

fn interpolate_at(timestamps : Array[Double], values : Array[Double], timestamp : Double) -> Double

Linearly interpolate a value at a timestamp, clamping at the endpoints.

#
interpolate_spectrum

fn interpolate_spectrum(spectrum : Array[SpectrumBin], step_hz : Double, maximum_hz : Double) -> Array[SpectrumBin]

Interpolate a spectrum onto an evenly-spaced frequency grid.

#
intervals_to_heart_rate

fn intervals_to_heart_rate(intervals : Array[Double]) -> Array[Double]

Convert RR intervals in milliseconds to instantaneous heart rate.

#
is_extreme_anomaly

fn is_extreme_anomaly(score : Double, threshold : Double) -> Bool

Return whether a value is an extreme local anomaly.

#
is_leap_year

fn is_leap_year(year : Int) -> Bool

Return whether a Gregorian year is a leap year.

#
is_publishable

fn is_publishable(decision : QualityDecision) -> Bool

Return whether a report is safe to publish to a dashboard.

#
is_recovery_signal_usable

fn is_recovery_signal_usable(diagnostic : SignalDiagnostic) -> Bool

Return whether a signal is acceptable for recovery scoring.

#
is_valid_date

fn is_valid_date(year : Int, month : Int, day : Int) -> Bool

Validate a Gregorian date.

#
last_finite

fn last_finite(values : Array[Double]) -> Double

Return the latest finite value in a stream, or zero when none exists.

#
latest_morning_status

fn latest_morning_status(history : Array[MorningMeasurement], config : HrvConfig) -> MorningBaselineState

Produce a robust status for the most recent measurement.

#
load_adjusted_recovery

fn load_adjusted_recovery(status : SessionStatus) -> Double

Calculate a load-adjusted recovery score.

#
load_alert_for_profile

fn load_alert_for_profile(profile : RollingLoadProfile, config : LoadModelConfig) -> LoadAlert?

#
load_band_from_score

fn load_band_from_score(score : Double) -> LoadIntensityBand

#
load_band_name

fn load_band_name(band : LoadIntensityBand) -> String

#
load_days_in_range

fn load_days_in_range(days : Array[DailyLoadLedger], start_date : String, end_date : String) -> Array[DailyLoadLedger]

#
load_dose_is_high

fn load_dose_is_high(dose : LoadDose) -> Bool

#
load_dose_recovery_cost

fn load_dose_recovery_cost(dose : LoadDose, entry : TrainingLoadEntry) -> Double

#
load_dose_to_row

fn load_dose_to_row(entry : TrainingLoadEntry, dose : LoadDose) -> Array[String]

#
load_dose_total

fn load_dose_total(dose : LoadDose) -> Double

#
load_entry_from_workout

fn load_entry_from_workout(session : WorkoutSession, session_id : String) -> TrainingLoadEntry

#
load_entry_intensity_score

fn load_entry_intensity_score(entry : TrainingLoadEntry, config : LoadModelConfig) -> Double

#
load_entry_quality_weight

fn load_entry_quality_weight(entry : TrainingLoadEntry) -> Double

#
load_high_day_count

fn load_high_day_count(days : Array[DailyLoadLedger]) -> Int

#
load_plan_alert_count

fn load_plan_alert_count(plan : TrainingLoadPlan) -> Int

#
load_plan_compare

fn load_plan_compare(current : TrainingLoadPlan, previous : TrainingLoadPlan) -> Array[Double]

#
load_plan_duration

fn load_plan_duration(plan : TrainingLoadPlan) -> Double

#
load_plan_feature_vector

fn load_plan_feature_vector(plan : TrainingLoadPlan) -> Array[Double]

#
load_plan_from_workouts

fn load_plan_from_workouts(sessions : Array[WorkoutSession]) -> TrainingLoadPlan

#
load_plan_hard_minutes

fn load_plan_hard_minutes(plan : TrainingLoadPlan) -> Double

#
load_plan_has_high_intensity

fn load_plan_has_high_intensity(plan : TrainingLoadPlan) -> Bool

#
load_plan_is_more_stressful

fn load_plan_is_more_stressful(current : TrainingLoadPlan, previous : TrainingLoadPlan) -> Bool

#
load_plan_is_recovering

fn load_plan_is_recovering(plan : TrainingLoadPlan) -> Bool

#
load_plan_is_usable

fn load_plan_is_usable(plan : TrainingLoadPlan) -> Bool

#
load_plan_next_day_budget

fn load_plan_next_day_budget(plan : TrainingLoadPlan, readiness_score : Double) -> Double

#
load_plan_peak_value

fn load_plan_peak_value(plan : TrainingLoadPlan) -> Double

#
load_plan_quality

fn load_plan_quality(plan : TrainingLoadPlan) -> Double

#
load_plan_recovery_cost

fn load_plan_recovery_cost(plan : TrainingLoadPlan) -> Double

#
load_plan_recovery_message

fn load_plan_recovery_message(plan : TrainingLoadPlan) -> String

#
load_plan_summary_line

fn load_plan_summary_line(plan : TrainingLoadPlan) -> String

#
load_plan_with_quality_floor

fn load_plan_with_quality_floor(entries : Array[TrainingLoadEntry], minimum_quality : Double) -> TrainingLoadPlan

#
load_profile_csv

fn load_profile_csv(profile : RollingLoadProfile) -> String

#
load_profile_row

fn load_profile_row(profile : RollingLoadProfile) -> Array[String]

fn load_recommended_intensity(plan : TrainingLoadPlan, readiness_score : Double) -> Double

#
load_recovery_correlation

fn load_recovery_correlation(observations : Array[SessionObservation]) -> Double

Calculate a workload-to-recovery correlation.

#
load_rest_day_count

fn load_rest_day_count(days : Array[DailyLoadLedger]) -> Int

#
load_risk_name

fn load_risk_name(level : LoadRiskLevel) -> String

#
load_risk_requires_rest

fn load_risk_requires_rest(level : LoadRiskLevel) -> Bool

#
load_risk_score

fn load_risk_score(level : LoadRiskLevel) -> Double

#
load_schedule_is_monotonic

fn load_schedule_is_monotonic(days : Array[DailyLoadLedger]) -> Bool

#
load_trend

fn load_trend(days : Array[DailyLoadLedger]) -> Double

#
local_median_smooth

fn local_median_smooth(intervals : Array[Double], radius : Int) -> Array[Double]

Apply a robust local median smoother without deleting samples.

#
long_run_coverage

fn long_run_coverage(profile : ArtifactProfile, minimum_run : Int) -> Double

Return the fraction of clean contiguous runs longer than a threshold.

#
longest_clean_run

fn longest_clean_run(profile : ArtifactProfile) -> Int

Return the longest contiguous clean run.

#
longest_valid_run

fn longest_valid_run(intervals : Array[Double], config : HrvConfig) -> Int

Return the longest consecutive run of valid intervals.

#
longest_valid_segment

fn longest_valid_segment(intervals : Array[Double], config : HrvConfig) -> Array[Double]

Return the largest contiguous run after removing invalid intervals.

#
mad_filter

fn mad_filter(intervals : Array[Double], multiplier : Double) -> Array[Double]

Remove values outside a median absolute deviation fence.

#
make_audit_event

fn make_audit_event(ordinal : Int, run_id : String, timestamp : String, kind : AuditEventKind, outcome : AuditOutcome, component : String, message : String, input_count : Int, output_count : Int, quality_score : Double, checksum : String) -> AuditEvent

#
make_cohort_observation

fn make_cohort_observation(reference : String, rmssd_ms : Double, mean_rr_ms : Double, resting_hr_bpm : Double, readiness_score : Double, training_load : Double, signal_quality : Double, age_band : String, activity_band : String) -> CohortObservation

#
make_decision_context

fn make_decision_context(quality_report : QualityReport?, recovery_report : LongitudinalRecoveryReport?, load_plan : TrainingLoadPlan?, sleep_hours : Double, sleep_efficiency : Double, symptom_score : Double, user_goal : String, requested_intensity : Double) -> DecisionContext

#
make_frequency_band

fn make_frequency_band(name : String, lower_hz : Double, upper_hz : Double, spectrum : Array[SpectrumBin], total_power : Double) -> FrequencyBandPower

Create a named frequency band from a spectrum.

#
make_named_features

fn make_named_features(names : Array[String], values : Array[Double], source : String) -> Array[NamedFeature]

Build named features from a vector and a name list.

#
make_quality_gate

fn make_quality_gate(report : AnalysisReport, policy : QualityGatePolicy) -> QualityGateResult

#
make_recovery_day_record

fn make_recovery_day_record(date : String, mean_rr_ms : Double, rmssd_ms : Double, sdnn_ms : Double, resting_hr_bpm : Double, sleep_hours : Double, sleep_efficiency : Double, respiratory_rate : Double, training_load : Double, signal_quality : Double, source : String) -> RecoveryDayRecord

#
make_reference_range

fn make_reference_range(values : Array[Double], name : String, source : String) -> ReferenceRange

Build a robust reference range from observed values.

#
make_runtime_sample

fn make_runtime_sample(case_name : String, target : String, repetitions : Int, elapsed_ms : Double, input_size : Int, output_size : Int, accepted : Bool) -> RuntimeSample

#
make_segment_ranges

fn make_segment_ranges(length : Int, segment_size : Int, hop_size : Int) -> Array[SegmentRange]

Build overlapping segment ranges. The final partial segment is omitted.

#
make_telemetry_record

fn make_telemetry_record(record_id : String, subject_id : String, source_id : String, timestamp_seconds : Double, rr_ms : Double, heart_rate_bpm : Double, movement_g : Double, temperature_c : Double, signal_quality : Double, tags : Array[String]) -> TelemetryRecord

#
make_training_load_entry

fn make_training_load_entry(date : String, session_id : String, duration_minutes : Double, average_hr_bpm : Double, maximum_hr_bpm : Double, resting_hr_bpm : Double, rpe : Double, distance_km : Double, elevation_m : Double, signal_quality : Double) -> TrainingLoadEntry

#
make_wearable_sample

fn make_wearable_sample(timestamp_seconds : Double, rr_ms : Double, heart_rate_bpm : Double, signal_quality : Double, source_id : String, sequence_number : Int) -> WearableSample

Make a sample without requiring a particular device SDK.

#
matrix_add

fn matrix_add(left : Array[Array[Double]], right : Array[Array[Double]]) -> Array[Array[Double]]

Add two aligned matrices.

#
matrix_center

fn matrix_center(matrix : Array[Array[Double]]) -> Array[Array[Double]]

Center each matrix column.

#
matrix_column_means

fn matrix_column_means(matrix : Array[Array[Double]]) -> Array[Double]

Calculate column means.

#
matrix_column_scales

fn matrix_column_scales(matrix : Array[Array[Double]]) -> Array[Double]

Calculate sample standard deviations by column.

#
matrix_copy

fn matrix_copy(matrix : Array[Array[Double]]) -> Array[Array[Double]]

Return a deep copy of a matrix.

#
matrix_diagonal

fn matrix_diagonal(matrix : Array[Array[Double]]) -> Array[Double]

Return a diagonal from a square matrix.

#
matrix_flatten

fn matrix_flatten(matrix : Array[Array[Double]]) -> Array[Double]

Flatten a rectangular matrix row by row.

#
matrix_identity

fn matrix_identity(size : Int) -> Array[Array[Double]]

Make an identity matrix.

#
matrix_is_usable

fn matrix_is_usable(matrix : Array[Array[Double]]) -> Bool

Return whether a matrix is finite and rectangular.

#
matrix_multiply

fn matrix_multiply(left : Array[Array[Double]], right : Array[Array[Double]]) -> Array[Array[Double]]

Multiply two rectangular matrices.

#
matrix_scale

fn matrix_scale(matrix : Array[Array[Double]], scalar : Double) -> Array[Array[Double]]

Multiply a matrix by a scalar.

#
matrix_shape

fn matrix_shape(matrix : Array[Array[Double]]) -> MatrixShape

Return the shape of a nested array.

#
matrix_standardize

fn matrix_standardize(matrix : Array[Array[Double]]) -> Array[Array[Double]]

Standardize each matrix column, using one as a zero-variance scale.

#
matrix_subtract

fn matrix_subtract(left : Array[Array[Double]], right : Array[Array[Double]]) -> Array[Array[Double]]

Subtract two aligned matrices.

#
matrix_transpose

fn matrix_transpose(matrix : Array[Array[Double]]) -> Array[Array[Double]]

Transpose a rectangular matrix.

#
matrix_unflatten

fn matrix_unflatten(values : Array[Double], rows : Int, columns : Int) -> Array[Array[Double]]

Rebuild a matrix from a row-major vector.

#
matrix_vector_multiply

fn matrix_vector_multiply(matrix : Array[Array[Double]], vector : Array[Double]) -> Array[Double]

Multiply a matrix by a vector.

#
matrix_zeros

fn matrix_zeros(rows : Int, columns : Int) -> Array[Array[Double]]

Make a zero matrix.

#
mean_absolute_deviation

fn mean_absolute_deviation(values : Array[Double]) -> Double

Backward-compatible mean absolute deviation around the arithmetic mean.

#
mean_value

fn mean_value(values : Array[Double]) -> Double

Return the arithmetic mean, or zero for an empty sequence.

#
median_absolute_deviation

fn median_absolute_deviation(values : Array[Double]) -> Double

Return the median absolute deviation around the sample median.

#
median_successive_difference

fn median_successive_difference(intervals : Array[Double]) -> Double

Calculate the median absolute successive difference.

#
median_value

fn median_value(values : Array[Double]) -> Double

Return the median using the midpoint of the two central values for even sized samples.

#
merge_feature_tables

fn merge_feature_tables(left : FeatureTable, right : FeatureTable) -> FeatureTable

Merge two feature tables while preferring values from the right table.

#
merge_reference_ranges

fn merge_reference_ranges(ranges : Array[ReferenceRange]) -> ReferenceRange?

Return the widest of several reference ranges.

#
metrics_rows

fn metrics_rows(metrics : HrvMetrics) -> Array[MetricRow]

Convert core time-domain metrics into a stable table.

#
missing_calendar_days

fn missing_calendar_days(values : Array[String]) -> Int

Count missing calendar days in an ordered date series.

#
missing_protocol_results

fn missing_protocol_results(plan : ProtocolPlan, results : Array[ProtocolStepResult]) -> Array[ProtocolStepResult]

Generate missing step results with actionable notes.

#
missing_recovery_day

fn missing_recovery_day(date : String) -> RecoveryDayRecord

#
morning_protocol_plan

fn morning_protocol_plan() -> ProtocolPlan

Make a resting morning protocol plan.

#
moving_average

fn moving_average(values : Array[Double], window_size : Int) -> Array[Double]

Calculate an unweighted or zero-filled moving average.

#
moving_standard_deviation

fn moving_standard_deviation(values : Array[Double], window_size : Int) -> Array[Double]

Calculate a moving sample standard deviation.

#
nonlinear_feature_vector

fn nonlinear_feature_vector(values : Array[Double]) -> Array[Double]

Return the main non-linear features in stable column order.

#
normalize_spectral_band

fn normalize_spectral_band(band : SpectralBand) -> SpectralBand

Clamp and normalize a user-provided spectral band.

#
normalize_unit_interval

fn normalize_unit_interval(values : Array[Double]) -> Array[Double]

Normalize values into [0, 1]. Constant sequences map to 0.5.

#
normalize_wearable_sample

fn normalize_wearable_sample(sample : WearableSample, config : WearableIngestConfig) -> NormalizedWearableSample

Normalize one sample and report whether a channel was derived.

#
normalized_sequence_distance

fn normalized_sequence_distance(left : Array[Double], right : Array[Double]) -> Double

Compare two aligned sequences with a symmetric normalized distance.

#
operational_report_feature_vector

fn operational_report_feature_vector(report : OperationalReport) -> Array[Double]

#
operational_report_headline

fn operational_report_headline(report : OperationalReport) -> String

#
operational_report_is_usable

fn operational_report_is_usable(report : OperationalReport) -> Bool

#
operational_report_markdown

fn operational_report_markdown(report : OperationalReport) -> String

#
operational_report_rows_csv

fn operational_report_rows_csv(report : OperationalReport) -> String

#
operational_report_section

fn operational_report_section(report : OperationalReport, kind : ReportSectionKind) -> OperationalReportSection?

#
operational_report_to_csv

fn operational_report_to_csv(report : OperationalReport) -> String

#
operational_report_warning_count

fn operational_report_warning_count(report : OperationalReport) -> Int

#
overnight_recovery_delta

fn overnight_recovery_delta(overnight_rmssd : Double, baseline_rmssd : Double) -> Double

Compare overnight RMSSD to a personal baseline.

#
paired_effect_size

fn paired_effect_size(left : Array[Double], right : Array[Double]) -> Double

Calculate a paired effect size using the standard deviation of differences.

#
parse_csv

fn parse_csv(content : String) -> Array[Array[String]]

CSV Parser using a state-machine. Handles optional double quotes and escapes.

#
parse_date

fn parse_date(value : String) -> DateParts?

Parse a strict YYYY-MM-DD date.

#
parse_morning_csv

fn parse_morning_csv(content : String) -> Array[MorningMeasurement] raise HrvParseError

Parse a CSV string containing historical morning measurements.

#
parse_rr_csv

fn parse_rr_csv(content : String) -> Array[Double] raise HrvParseError

Parse a CSV string containing RR interval numbers.

#
parse_simulation_scenario

fn parse_simulation_scenario(name : String) -> SimulationScenario

Parse a scenario name with stable fallback behavior.

#
peak_training_days

fn peak_training_days(metrics : TrainingPlanMetrics, limit : Int) -> Array[TrainingDaySummary]

Return the dates with the largest training loads.

#
percentile_rank

fn percentile_rank(values : Array[Double], value : Double) -> Double

Calculate percentile rank using a cohort of scalar values.

#
personal_rmssd_range

fn personal_rmssd_range(history : Array[MorningMeasurement]) -> ReferenceRange

Calculate a robust personal reference range from a history.

#
pipeline_batch_csv

fn pipeline_batch_csv(summary : PipelineBatchSummary) -> String

#
pipeline_batch_is_stable

fn pipeline_batch_is_stable(summary : PipelineBatchSummary) -> Bool

#
pipeline_batch_summary

fn pipeline_batch_summary(runs : Array[HrvPipelineRun]) -> PipelineBatchSummary

#
pipeline_gate_feature_vector

fn pipeline_gate_feature_vector(gate : QualityGateResult) -> Array[Double]

#
pipeline_gate_summary

fn pipeline_gate_summary(gate : QualityGateResult) -> String

#
pipeline_policy_is_conservative

fn pipeline_policy_is_conservative(policy : QualityGatePolicy) -> Bool

#
pipeline_policy_with_minimum_samples

fn pipeline_policy_with_minimum_samples(policy : QualityGatePolicy, samples : Int) -> QualityGatePolicy

#
pipeline_run_duration

fn pipeline_run_duration(run : HrvPipelineRun) -> Double

#
pipeline_run_failure_reasons

fn pipeline_run_failure_reasons(run : HrvPipelineRun) -> Array[String]

#
pipeline_run_feature_count

fn pipeline_run_feature_count(run : HrvPipelineRun) -> Int

#
pipeline_run_is_usable

fn pipeline_run_is_usable(run : HrvPipelineRun) -> Bool

#
pipeline_run_quality

fn pipeline_run_quality(run : HrvPipelineRun) -> Double

#
pipeline_run_stage

fn pipeline_run_stage(run : HrvPipelineRun, kind : PipelineStageKind) -> PipelineStageTrace?

#
pipeline_run_warning_count

fn pipeline_run_warning_count(run : HrvPipelineRun) -> Int

#
pipeline_stage_counts

fn pipeline_stage_counts(run : HrvPipelineRun) -> Array[Int]

#
pipeline_stage_csv

fn pipeline_stage_csv(run : HrvPipelineRun) -> String

#
pipeline_stage_name

fn pipeline_stage_name(kind : PipelineStageKind) -> String

#
pipeline_status_name

fn pipeline_status_name(status : PipelineStageStatus) -> String

#
plausibility_quality_score

fn plausibility_quality_score(intervals : Array[Double], config : HrvConfig) -> Double

Score plausibility of the median and spread.

#
population_variance

fn population_variance(values : Array[Double]) -> Double

Population variance, useful for complete windows rather than samples.

#
position_in_reference_range

fn position_in_reference_range(value : Double, range : ReferenceRange, standard_deviation_value : Double, population_values : Array[Double]) -> RangePosition

Calculate a range position using a supplied standard deviation.

#
post_episode_recovery_slope

fn post_episode_recovery_slope(intervals : Array[Double], episode : RateEpisode, observation_beats : Int) -> Double

Return a per-beat recovery slope after a detected episode.

#
prepare_spectral_values

fn prepare_spectral_values(values : Array[Double], remove_trend : Bool, function : WindowFunction) -> Array[Double]

Center and optionally detrend a tachogram before a periodogram.

#
prepare_tachogram

fn prepare_tachogram(intervals : Array[Double], sample_rate_hz : Double, remove_trend : Bool, function : WindowFunction) -> Tachogram

Resample, center, detrend, and window an RR series in one call.

#
profile_artifacts

fn profile_artifacts(intervals : Array[Double], config : HrvConfig) -> ArtifactProfile

Profile artifacts with robust step-based and physiological checks.

#
prolonged_awakenings

fn prolonged_awakenings(epochs : Array[SleepEpoch], threshold_minutes : Double) -> Array[SleepEpoch]

Return awake intervals longer than a configurable threshold.

#
protocol_config_for_name

fn protocol_config_for_name(name : String, source_id : String) -> ProtocolAdapterConfig

#
protocol_dialect_from_name

fn protocol_dialect_from_name(name : String) -> WearableProtocolDialect

#
protocol_duration_error

fn protocol_duration_error(duration_seconds : Double, protocol : RecordingProtocol) -> Double

Return a protocol-specific expected recording duration.

#
protocol_has_errors

fn protocol_has_errors(result : ProtocolAdapterResult) -> Bool

#
protocol_mapping_csv

fn protocol_mapping_csv(mapping : ProtocolColumnMapping) -> String

#
protocol_mapping_for_headers

fn protocol_mapping_for_headers(dialect : WearableProtocolDialect, headers : Array[String]) -> ProtocolColumnMapping

#
protocol_mapping_is_usable

fn protocol_mapping_is_usable(mapping : ProtocolColumnMapping) -> Bool

#
protocol_next_action

fn protocol_next_action(plan : ProtocolPlan, results : Array[ProtocolStepResult]) -> String

Return a human-readable next action.

#
protocol_normalize_quality

fn protocol_normalize_quality(value : Double, unit : ProtocolUnit, fallback : Double) -> Double

#
protocol_notice_count_for

fn protocol_notice_count_for(result : ProtocolAdapterResult, code : String) -> Int

#
protocol_notices_csv

fn protocol_notices_csv(result : ProtocolAdapterResult) -> String

#
protocol_parse_csv

fn protocol_parse_csv(content : String, config : ProtocolAdapterConfig) -> ProtocolAdapterResult

#
protocol_plan_duration

fn protocol_plan_duration(plan : ProtocolPlan) -> Double

Return the total planned duration.

#
protocol_plan_is_valid

fn protocol_plan_is_valid(plan : ProtocolPlan) -> Bool

Return whether a plan is internally consistent.

#
protocol_recommendation

fn protocol_recommendation(validation : ProtocolValidation) -> String

Return a useful protocol recommendation.

#
protocol_rejection_ratio

fn protocol_rejection_ratio(result : ProtocolAdapterResult) -> Double

#
protocol_result_csv

fn protocol_result_csv(result : ProtocolAdapterResult) -> String

#
protocol_result_feature_vector

fn protocol_result_feature_vector(result : ProtocolAdapterResult) -> Array[Double]

#
protocol_result_is_usable

fn protocol_result_is_usable(result : ProtocolAdapterResult) -> Bool

#
protocol_result_summary

fn protocol_result_summary(result : ProtocolAdapterResult) -> String

#
protocol_roundtrip_quality

fn protocol_roundtrip_quality(content : String, config : ProtocolAdapterConfig) -> Double

#
protocol_run_feature_vector

fn protocol_run_feature_vector(report : ProtocolRunReport) -> Array[Double]

Return a protocol feature vector.

#
protocol_samples_to_csv

fn protocol_samples_to_csv(samples : Array[WearableSample]) -> String

#
protocol_step

fn protocol_step(plan : ProtocolPlan, ordinal : Int) -> ProtocolStep?

Find a step by ordinal.

#
protocol_unit_name

fn protocol_unit_name(value : ProtocolUnit) -> String

#
quality_change_is_material

fn quality_change_is_material(left : SignalQualitySummary, right : SignalQualitySummary, threshold : Double) -> Bool

Return whether quality changes are material.

#
quality_from_cleaning

fn quality_from_cleaning(result : CleaningResult, config : HrvConfig) -> SignalQualitySummary

Create a score from a cleaning result.

#
quality_grade

fn quality_grade(validation : IntervalValidation) -> String

Return a quality grade suitable for dashboards.

#
quality_score_delta

fn quality_score_delta(left : SignalQualitySummary, right : SignalQualitySummary) -> Double

Compare two quality summaries.

#
quality_weight

fn quality_weight(decision : QualityDecision) -> Double

Convert a policy decision into a multiplicative score weight.

#
quantile_value

fn quantile_value(values : Array[Double], probability : Double) -> Double

Compute a linearly interpolated quantile in the closed interval [0, 1].

#
quantize_interval

fn quantize_interval(value : Double, resolution_ms : Double) -> Double

Quantize a value to a device resolution while preserving a stable unit.

#
quantize_intervals

fn quantize_intervals(values : Array[Double], resolution_ms : Double) -> Array[Double]

Quantize an entire recording.

#
quantize_simulation

fn quantize_simulation(values : Array[Double], resolution_ms : Double) -> Array[Double]

Apply deterministic quantization noise.

#
range_center_distance

fn range_center_distance(value : Double, range : ReferenceRange) -> Double

Return a normalized distance from the center of a range.

#
range_quality_score

fn range_quality_score(validation : IntervalValidation) -> Double

Score physiological-range compliance.

#
rank_sessions_by_recovery

fn rank_sessions_by_recovery(observations : Array[SessionObservation], window_size : Int, load_threshold : Double) -> Array[SessionStatus]

Return a sorted copy from highest recovery score to lowest.

#
readiness_level

fn readiness_level(score : Double) -> ReadinessLevel

Convert a score into an ordinal readiness level.

#
recommend_cleaning_method

fn recommend_cleaning_method(validation : IntervalValidation) -> CleaningMethod

Choose a correction method from the observed artifact ratio.

#
recommend_recovery_day

fn recommend_recovery_day(metrics : TrainingPlanMetrics) -> Bool

Recommend a recovery day when load and recent recovery cost are high.

#
reconcile_cardiac_channels

fn reconcile_cardiac_channels(sample : WearableSample, config : WearableIngestConfig) -> (WearableSample, Bool)

Reconcile an RR interval and heart rate without changing source metadata.

#
recovery_best_day

fn recovery_best_day(assessments : Array[RecoveryDayAssessment]) -> RecoveryDayAssessment?

#
recovery_compare_days

fn recovery_compare_days(current : RecoveryDayRecord, previous : RecoveryDayRecord) -> Array[Double]

#
recovery_confidence

fn recovery_confidence(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> Double

#
recovery_data_completeness

fn recovery_data_completeness(records : Array[RecoveryDayRecord]) -> Array[Double]

#
recovery_day_is_better

fn recovery_day_is_better(current : RecoveryDayAssessment, previous : RecoveryDayAssessment) -> Bool

#
recovery_heart_rate_z

fn recovery_heart_rate_z(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> Double

#
recovery_missing_days

fn recovery_missing_days(records : Array[RecoveryDayRecord]) -> Int

#
recovery_quality_ratio

fn recovery_quality_ratio(records : Array[RecoveryDayRecord]) -> Double

#
recovery_recent_records

fn recovery_recent_records(records : Array[RecoveryDayRecord], count : Int) -> Array[RecoveryDayRecord]

#
recovery_record_is_usable

fn recovery_record_is_usable(record : RecoveryDayRecord) -> Bool

#
recovery_record_quality

fn recovery_record_quality(record : RecoveryDayRecord) -> Double

#
recovery_record_to_row

fn recovery_record_to_row(record : RecoveryDayRecord) -> Array[String]

#
recovery_records_csv

fn recovery_records_csv(records : Array[RecoveryDayRecord]) -> String

#
recovery_report_csv

fn recovery_report_csv(report : LongitudinalRecoveryReport) -> String

#
recovery_report_feature_vector

fn recovery_report_feature_vector(report : LongitudinalRecoveryReport) -> Array[Double]

#
recovery_report_headline

fn recovery_report_headline(report : LongitudinalRecoveryReport) -> String

#
recovery_report_is_usable

fn recovery_report_is_usable(report : LongitudinalRecoveryReport) -> Bool

#
recovery_report_load_adjustment

fn recovery_report_load_adjustment(report : LongitudinalRecoveryReport) -> Double

#
recovery_report_message

fn recovery_report_message(report : LongitudinalRecoveryReport) -> String

#
recovery_report_risk_score

fn recovery_report_risk_score(report : LongitudinalRecoveryReport) -> Double

#
recovery_rmssd_z

fn recovery_rmssd_z(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> Double

#
recovery_rr_z

fn recovery_rr_z(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> Double

#
recovery_score_average

fn recovery_score_average(assessments : Array[RecoveryDayAssessment]) -> Double

#
recovery_score_quantile

fn recovery_score_quantile(assessments : Array[RecoveryDayAssessment], proportion : Double) -> Double

#
recovery_score_sd

fn recovery_score_sd(assessments : Array[RecoveryDayAssessment]) -> Double

#
recovery_sleep_z

fn recovery_sleep_z(record : RecoveryDayRecord, baseline : RecoveryBaseline) -> Double

#
recovery_stable_streak

fn recovery_stable_streak(assessments : Array[RecoveryDayAssessment]) -> Int

#
recovery_status_from_score

fn recovery_status_from_score(score : Double, record : RecoveryDayRecord) -> RecoveryDayStatus

#
recovery_status_is_actionable

fn recovery_status_is_actionable(status : RecoveryDayStatus) -> Bool

#
recovery_status_name

fn recovery_status_name(value : RecoveryDayStatus) -> String

#
recovery_trajectory_from_assessments

fn recovery_trajectory_from_assessments(assessments : Array[RecoveryDayAssessment]) -> RecoveryTrajectory

#
recovery_trajectory_from_scores

fn recovery_trajectory_from_scores(scores : Array[Double]) -> RecoveryTrajectory

#
recovery_trajectory_is_positive

fn recovery_trajectory_is_positive(trajectory : RecoveryTrajectory) -> Bool

#
recovery_trajectory_name

fn recovery_trajectory_name(value : RecoveryTrajectory) -> String

#
recovery_trend_points

fn recovery_trend_points(report : LongitudinalRecoveryReport) -> Array[RecoveryTrendPoint]

#
recovery_week_csv

fn recovery_week_csv(weeks : Array[RecoveryWeekSummary]) -> String

#
recovery_worst_day

fn recovery_worst_day(assessments : Array[RecoveryDayAssessment]) -> RecoveryDayAssessment?

#
recurrence_rate

fn recurrence_rate(values : Array[Double], radius : Double, minimum_lag : Int) -> Double

Calculate recurrence rate using a fixed radius around the median.

#
reference_range_coverage

fn reference_range_coverage(values : Array[Double], range : ReferenceRange) -> Double

Calculate the coverage ratio of a range.

#
reference_range_feature_vector

fn reference_range_feature_vector(position : RangePosition) -> Array[Double]

Create a range feature vector.

#
reference_range_interpretation

fn reference_range_interpretation(position : RangePosition) -> String

Return a plain-language range interpretation.

#
repair_invalid_intervals

fn repair_invalid_intervals(intervals : Array[Double], config : HrvConfig) -> Array[Double]

Replace isolated invalid observations while preserving valid runs.

#
repair_profiled_artifacts

fn repair_profiled_artifacts(intervals : Array[Double], profile : ArtifactProfile) -> Array[Double]

Repair only the flagged samples and preserve the original length.

#
repeat_fixture

fn repeat_fixture(values : Array[Double], repetitions : Int) -> Array[Double]

Repeat a fixture without sharing its backing array.

#
replacements_are_plausible

fn replacements_are_plausible(profile : ArtifactProfile, config : HrvConfig) -> Bool

Check that all replacements are within the configured physiological range.

#
report_action_section

fn report_action_section(actions : Array[DecisionAction]) -> OperationalReportSection

#
report_decision_section

fn report_decision_section(plan : DecisionPlan) -> OperationalReportSection

#
report_forecast_section

fn report_forecast_section(bundle : ForecastBundle) -> OperationalReportSection

#
report_headline_csv

fn report_headline_csv(report : AnalysisReport) -> String

Export a full report's headline metrics as CSV.

#
report_metric

fn report_metric(key : String, label : String, value : Double, unit : String, status : String, confidence : Double) -> OperationalReportMetric

#
report_overview_section

fn report_overview_section(report : AnalysisReport, gate : QualityGateResult) -> OperationalReportSection

#
report_recovery_section

fn report_recovery_section(report : LongitudinalRecoveryReport) -> OperationalReportSection

#
report_section

fn report_section(kind : ReportSectionKind, title : String, summary : String, metrics : Array[OperationalReportMetric], rows : Array[Array[String]], warnings : Array[String]) -> OperationalReportSection

#
report_section_name

fn report_section_name(kind : ReportSectionKind) -> String

#
report_summary

fn report_summary(report : AnalysisReport) -> String

Format the report for a compact terminal summary.

#
report_table_append

fn report_table_append(table : ReportTable, row : Array[String]) -> ReportTable

Add a row while preserving the table schema.

#
report_table_filter

fn report_table_filter(table : ReportTable, predicate : (Array[String]) -> Bool) -> ReportTable

Return a table with rows selected by a predicate.

#
report_table_find

fn report_table_find(table : ReportTable, key : String) -> Array[String]

Return the first matching row by its metric key.

#
report_table_grid

fn report_table_grid(table : ReportTable) -> Array[Array[String]]

Convert a report table to a stable JSON-like key/value grid.

#
report_table_size

fn report_table_size(table : ReportTable) -> Int

Return the number of data rows.

#
report_table_summary

fn report_table_summary(table : ReportTable) -> String

Return a report table summary line for logs.

#
report_table_to_csv

fn report_table_to_csv(table : ReportTable) -> String

Serialize a table with one header row.

#
report_training_section

fn report_training_section(plan : TrainingLoadPlan) -> OperationalReportSection

#
resample_rr

fn resample_rr(intervals : Array[Double], sample_rate_hz : Double) -> Tachogram

Resample the instantaneous RR series onto an evenly spaced time grid.

#
residual_anomaly_indices

fn residual_anomaly_indices(residual : Array[Double], threshold : Double) -> Array[Int]

Detect points that exceed a residual threshold.

#
respiration_feature_vector

fn respiration_feature_vector(summary : RespirationSummary) -> Array[Double]

Return a compact respiration feature vector.

#
respiration_is_usable

fn respiration_is_usable(summary : RespirationSummary) -> Bool

Return whether respiration can be used as a report annotation.

#
respiratory_band_ratio

fn respiratory_band_ratio(intervals : Array[Double], sample_rate_hz : Double) -> Double

Calculate a respiration-aware LF/HF modulation ratio.

#
respiratory_coherence

fn respiratory_coherence(intervals : Array[Double], frequency_hz : Double, sample_rate_hz : Double) -> Double

Calculate a normalized correlation between RR modulation and a sinusoid.

#
respiratory_modulation

fn respiratory_modulation(intervals : Array[Double], radius : Int) -> Array[Double]

Calculate a smoothed RR modulation signal.

#
respiratory_modulation_depth

fn respiratory_modulation_depth(intervals : Array[Double]) -> Double

Estimate the modulation depth using robust quartiles.

#
respiratory_peak_frequency

fn respiratory_peak_frequency(intervals : Array[Double], sample_rate_hz : Double) -> Double

Estimate a respiratory peak from the respiratory band.

#
respiratory_phase_consistency

fn respiratory_phase_consistency(intervals : Array[Double], frequency_hz : Double, sample_rate_hz : Double) -> Double

Calculate phase consistency as the mean absolute sinusoidal alignment.

#
respiratory_phase_series

fn respiratory_phase_series(intervals : Array[Double], frequency_hz : Double, sample_rate_hz : Double) -> Array[Double]

Estimate an RR-respiration phase series from a candidate frequency.

#
respiratory_rate_bpm

fn respiratory_rate_bpm(frequency_hz : Double) -> Double

Convert a respiratory frequency to breaths per minute.

#
retained_ratio

fn retained_ratio(profile : ArtifactProfile) -> Double

Return the proportion of the stream retained after removing flags.

#
rmssd_windows

fn rmssd_windows(intervals : Array[Double], schedule : WindowSchedule) -> Array[ScalarWindow]

Aggregate RMSSD from complete RR windows.

#
rolling_anomaly_scores

fn rolling_anomaly_scores(values : Array[Double], window_size : Int) -> Array[Double]

Calculate a rolling standardized deviation from a local baseline.

#
rolling_load_average

fn rolling_load_average(days : Array[DailyLoadLedger], end_index : Int, window : Int) -> Double

#
rolling_median

fn rolling_median(intervals : Array[Double], window_size : Int) -> Array[Double]

Calculate a robust moving median for display or denoising.

#
rolling_residuals

fn rolling_residuals(intervals : Array[Double], window_size : Int) -> Array[Double]

Return a centered moving baseline and residual series.

#
rolling_rmssd

fn rolling_rmssd(intervals : Array[Double], window_size : Int) -> Array[Double]

Calculate a causal rolling RMSSD series.

#
rolling_rmssd_with_stride

fn rolling_rmssd_with_stride(intervals : Array[Double], window_size : Int, stride : Int) -> Array[Double]

Calculate a short-window RMSSD for every complete window.

#
rolling_rr_variability

fn rolling_rr_variability(intervals : Array[Double], window_size : Int) -> Array[Double]

Calculate a causal rolling coefficient of variation.

#
rolling_trend_slopes

fn rolling_trend_slopes(values : Array[Double], window_size : Int) -> Array[Double]

Calculate a trailing slope for every complete window.

#
rr_histogram

fn rr_histogram(intervals : Array[Double], bin_width : Double, minimum : Double, bin_count : Int) -> Array[Int]

Build an integer histogram of RR intervals.

#
rr_timestamps

fn rr_timestamps(intervals : Array[Double]) -> Array[Double]

Convert RR durations into cumulative beat timestamps.

#
rr_to_bpm

fn rr_to_bpm(interval_ms : Double) -> Double

Convert a calibrated value into beats per minute.

#
run_benchmark

fn run_benchmark(config : BenchmarkConfig) -> BenchmarkSummary

Run repeated analyses and average stable numeric fields.

#
run_benchmark_once

fn run_benchmark_once(config : BenchmarkConfig) -> BenchmarkSummary

Run the full analysis workload once.

#
run_hrv_quality_pipeline

fn run_hrv_quality_pipeline(run_id : String, intervals : Array[Double], config : HrvConfig, options : AnalysisOptions, policy : QualityGatePolicy) -> HrvPipelineRun

#
runtime_acceptance_ratio

fn runtime_acceptance_ratio(samples : Array[RuntimeSample]) -> Double

#
runtime_aggregate_feature_vector

fn runtime_aggregate_feature_vector(aggregate : RuntimeAggregate) -> Array[Double]

#
runtime_budget

fn runtime_budget(case_name : String, target : String, maximum_mean_ms : Double, maximum_p95_ms : Double, minimum_throughput : Double, minimum_stability : Double) -> RuntimeBudget

#
runtime_check_csv

fn runtime_check_csv(report : RuntimeReport) -> String

#
runtime_has_regression

fn runtime_has_regression(current : RuntimeAggregate, previous : RuntimeAggregate, threshold : Double) -> Bool

#
runtime_input_throughput

fn runtime_input_throughput(sample : RuntimeSample) -> Double

#
runtime_output_throughput

fn runtime_output_throughput(sample : RuntimeSample) -> Double

#
runtime_regression_ratio

fn runtime_regression_ratio(current : RuntimeAggregate, previous : RuntimeAggregate) -> Double

#
runtime_report_csv

fn runtime_report_csv(report : RuntimeReport) -> String

#
runtime_report_feature_vector

fn runtime_report_feature_vector(report : RuntimeReport) -> Array[Double]

#
runtime_report_is_usable

fn runtime_report_is_usable(report : RuntimeReport) -> Bool

#
runtime_report_summary

fn runtime_report_summary(report : RuntimeReport) -> String

#
runtime_samples_for

fn runtime_samples_for(samples : Array[RuntimeSample], case_name : String, target : String) -> Array[RuntimeSample]

#
runtime_throughput_ratio

fn runtime_throughput_ratio(current : RuntimeAggregate, previous : RuntimeAggregate) -> Double

#
sample_delta_seconds

fn sample_delta_seconds(left : AmbulatorySample, right : AmbulatorySample) -> Double

Return the duration between adjacent samples with a safe fallback.

#
scalar_windows

fn scalar_windows(values : Array[Double], schedule : WindowSchedule) -> Array[ScalarWindow]

Return valid windows according to a schedule.

#
scale_feature_table

fn scale_feature_table(table : FeatureTable, scaler : FeatureScaler) -> FeatureTable

Apply a center-scale transform.

#
scenario_comparison_csv

fn scenario_comparison_csv(comparison : ScenarioComparison) -> String

#
scenario_comparison_feature_vector

fn scenario_comparison_feature_vector(comparison : ScenarioComparison) -> Array[Double]

#
scenario_from_plan

fn scenario_from_plan(plan : TrainingLoadPlan, recovery_score : Double, kind : TrainingScenarioKind) -> ScenarioResult

#
scenario_from_workout

fn scenario_from_workout(session : WorkoutSession) -> ScenarioSession

#
scenario_is_lower_load

fn scenario_is_lower_load(candidate : ScenarioResult, baseline : ScenarioResult) -> Bool

#
scenario_name

fn scenario_name(kind : TrainingScenarioKind) -> String

#
scenario_plan_message

fn scenario_plan_message(comparison : ScenarioComparison) -> String

fn scenario_recommended(comparison : ScenarioComparison) -> ScenarioResult

#
scenario_requires_recovery

fn scenario_requires_recovery(result : ScenarioResult) -> Bool

#
scenario_session

fn scenario_session(date : String, duration_minutes : Double, intensity : Double, purpose : String) -> ScenarioSession

#
score_latest_morning

fn score_latest_morning(history : Array[MorningMeasurement], config : HrvConfig) -> ReadinessScore

Score the current history using a robust baseline and trend.

#
segment_activity

fn segment_activity(samples : Array[AmbulatorySample], thresholds : ActivityThresholds, minimum_block_samples : Int) -> Array[ActivityBlock]

Segment samples into activity blocks, merging short runs.

#
segment_report_table

fn segment_report_table(summaries : Array[SegmentSummary]) -> ReportTable

Build a table containing one row per segment.

#
select_features

fn select_features(table : FeatureTable, names : Array[String]) -> FeatureTable

Select a named subset while preserving the requested order.

#
select_load_peaks

fn select_load_peaks(days : Array[DailyLoadLedger], limit : Int) -> Array[DailyLoadLedger]

#
serialize_metrics_csv

fn serialize_metrics_csv(metrics : HrvMetrics) -> String

Serialize HrvMetrics to CSV string.
fn serialize_trends_csv(trends : Array[MorningTrend]) -> String

Serialize morning baseline trends to CSV string.

#
session_analytics_feature_vector

fn session_analytics_feature_vector(summary : SessionAnalytics) -> Array[Double]

Create a fixed-order longitudinal feature vector.

#
session_analytics_is_usable

fn session_analytics_is_usable(summary : SessionAnalytics) -> Bool

Return whether longitudinal analytics contain enough signal.

#
session_baseline

fn session_baseline(observations : Array[SessionObservation], end_exclusive : Int, window_size : Int) -> (Double, Double)

Calculate a robust baseline over the preceding sessions.

#
session_is_usable

fn session_is_usable(observation : SessionObservation, minimum_quality : Double) -> Bool

Return whether an observation is usable for longitudinal scoring.

#
session_observations_csv

fn session_observations_csv(observations : Array[SessionObservation]) -> String

Export a batch of observations as CSV.

#
session_outlier_indices

fn session_outlier_indices(observations : Array[SessionObservation], z_threshold : Double, window_size : Int) -> Array[Int]

Return indices of sessions that differ materially from a baseline.

#
session_review_ratio

fn session_review_ratio(statuses : Array[SessionStatus]) -> Double

Return the proportion of sessions that need review.

#
session_training_load

fn session_training_load(duration_minutes : Double, intensity : Double) -> Double

Calculate a session load as duration multiplied by normalized intensity.

#
signal_quality_explanation

fn signal_quality_explanation(summary : SignalQualitySummary) -> String

Return a human-readable explanation of a quality summary.

#
signal_quality_feature_vector

fn signal_quality_feature_vector(summary : SignalQualitySummary) -> Array[Double]

Return a fixed-order quality feature vector.

#
signal_quality_grade

fn signal_quality_grade(score : Double) -> String

Convert a score to a stable quality grade.

#
simulate_ambulatory_samples

fn simulate_ambulatory_samples(config : SimulationConfig) -> Array[AmbulatorySample]

Generate synchronized ambulatory samples from an RR scenario.

#
simulate_respiratory_trace

fn simulate_respiratory_trace(length : Int, sample_rate_hz : Double, rate_bpm : Double) -> Array[Double]

Generate a direct sinusoidal respiratory trace.

#
simulate_rr

fn simulate_rr(config : SimulationConfig) -> Array[Double]

Generate one scenario without random state.

#
simulate_scenario_matrix

fn simulate_scenario_matrix(length : Int, baseline_rr : Double) -> Array[Array[Double]]

Run all scenarios with one shared length for smoke tests.

#
simulate_training_scenario

fn simulate_training_scenario(sessions : Array[ScenarioSession], kind : TrainingScenarioKind, recovery_score : Double, current_ratio : Double, config : ScenarioConfig) -> ScenarioResult

#
simulation_scenario_names

fn simulation_scenario_names() -> Array[String]

Return deterministic scenario names for test discovery.

#
simulation_summary

fn simulation_summary(values : Array[Double], config : HrvConfig) -> Array[Double]

Return a compact set of scenario validation metrics.

#
sleep_feature_vector

fn sleep_feature_vector(summary : SleepRecoverySummary) -> Array[Double]

Create a compact sleep feature vector.

#
sleep_offset

fn sleep_offset(epochs : Array[SleepEpoch]) -> SleepEpoch?

Return the last epoch that contributes to sleep duration.

#
sleep_onset

fn sleep_onset(epochs : Array[SleepEpoch]) -> SleepEpoch?

Return the first sleep onset epoch, if one exists.

#
sleep_quality_ratio

fn sleep_quality_ratio(epochs : Array[SleepEpoch]) -> Double

Calculate the proportion of epochs with usable signal quality.

#
sleep_regularity

fn sleep_regularity(start_minutes : Array[Double]) -> Double

Calculate a sleep regularity score from start-time deltas.

#
sleep_stage_code

fn sleep_stage_code(stage : SleepStage) -> Int

Return a stable numeric code for a sleep stage.

#
sleep_stage_is_asleep

fn sleep_stage_is_asleep(stage : SleepStage) -> Bool

Return whether an epoch contributes to sleep duration.

#
sleep_stage_minutes

fn sleep_stage_minutes(epochs : Array[SleepEpoch], stage : SleepStage) -> Double

Calculate total minutes spent in a stage.

#
sleep_stage_transitions

fn sleep_stage_transitions(epochs : Array[SleepEpoch]) -> Int

Count transitions between consecutive scored epochs.

#
sleep_summary_is_usable

fn sleep_summary_is_usable(summary : SleepRecoverySummary) -> Bool

Return whether an overnight summary is safe to display.

#
slice_segment

fn slice_segment(values : Array[Double], range : SegmentRange) -> Array[Double]

Copy one segment from an RR series.

#
smooth_spectrum

fn smooth_spectrum(spectrum : Array[SpectrumBin], radius : Int) -> Array[SpectrumBin]

Smooth spectral power with a moving average.

#
solve_two_by_two

fn solve_two_by_two(matrix : Array[Array[Double]], target : Array[Double]) -> Array[Double]

Solve a two-variable linear system by Cramer's rule.

#
sort_recovery_records

fn sort_recovery_records(values : Array[RecoveryDayRecord]) -> Array[RecoveryDayRecord]

#
sort_wearable_samples

fn sort_wearable_samples(samples : Array[WearableSample]) -> Array[WearableSample]

Sort a batch by timestamp while preserving deterministic tie order.

#
spectral_band_power

fn spectral_band_power(spectrum : Array[SpectrumBin], band : SpectralBand) -> Double

Calculate power in a band from an already-computed periodogram.

#
spectral_centroid

fn spectral_centroid(spectrum : Array[SpectrumBin]) -> Double

Calculate the power-weighted average frequency.

#
spectral_edge_frequency

fn spectral_edge_frequency(spectrum : Array[SpectrumBin], proportion : Double) -> Double

Return the first frequency whose cumulative power reaches a proportion.

#
spectral_entropy

fn spectral_entropy(spectrum : Array[SpectrumBin]) -> Double

Calculate normalized spectral entropy from non-negative powers.

#
spectral_log_slope

fn spectral_log_slope(spectrum : Array[SpectrumBin]) -> Double

Calculate a simple log-log spectral slope.

#
spectral_profile_feature_vector

fn spectral_profile_feature_vector(profile : SpectralProfile) -> Array[Double]

Return a stable spectral feature vector.

#
spectral_profile_is_usable

fn spectral_profile_is_usable(profile : SpectralProfile) -> Bool

Return whether the spectral profile contains valid finite values.

#
split_at_gaps

fn split_at_gaps(intervals : Array[Double], gap_threshold_ms : Double) -> Array[Array[Double]]

Split an RR stream at intervals that exceed a physiological gap.

#
split_wearable_gaps

fn split_wearable_gaps(samples : Array[WearableSample], maximum_gap_seconds : Double) -> Array[Array[WearableSample]]

Split accepted samples at timestamp gaps.

#
standard_deviation

fn standard_deviation(values : Array[Double]) -> Double

Return the sample standard deviation.

#
standard_spectral_bands

fn standard_spectral_bands() -> Array[SpectralBand]

Standard frequency bands used by short resting recordings.

#
stationarity_quality_score

fn stationarity_quality_score(intervals : Array[Double]) -> Double

Score local stationarity by comparing first and second half means.

#
successive_change_quality

fn successive_change_quality(intervals : Array[Double], threshold_ms : Double) -> Double

Return a threshold-based quality score for successive changes.

#
successive_differences

fn successive_differences(intervals : Array[Double]) -> Array[Double]

Return absolute beat-to-beat changes for a recording.

#
sum_values

fn sum_values(values : Array[Double]) -> Double

Sum a sequence without changing its order.

#
summarize_ambulatory

fn summarize_ambulatory(samples : Array[AmbulatorySample], thresholds : ActivityThresholds) -> AmbulatorySummary

Aggregate a synchronized sample day.

#
summarize_cohort

fn summarize_cohort(records : Array[BatchRecord]) -> CohortSummary

Aggregate all records and attach subject percentile ranks.

#
summarize_distribution

fn summarize_distribution(values : Array[Double]) -> DistributionStats

Return a full distribution summary for a sequence.

#
summarize_heart_rate

fn summarize_heart_rate(intervals : Array[Double], maximum_hr : Double) -> HeartRateSummary

Calculate a bounded heart-rate summary and time in five percentage zones.

#
summarize_recovery_weeks

fn summarize_recovery_weeks(records : Array[RecoveryDayRecord], baseline_window : Int) -> Array[RecoveryWeekSummary]

#
summarize_segments

fn summarize_segments(intervals : Array[Double], segment_size : Int, hop_size : Int, config : HrvConfig) -> Array[SegmentSummary]

Calculate a summary for every full segment in an RR stream.

#
summarize_session_analytics

fn summarize_session_analytics(observations : Array[SessionObservation], minimum_quality : Double) -> SessionAnalytics

Summarize a personal session history.

#
summarize_sleep_recovery

fn summarize_sleep_recovery(epochs : Array[SleepEpoch], baseline_rmssd : Double) -> SleepRecoverySummary

Build a complete overnight recovery summary.

#
summarize_subjects

fn summarize_subjects(records : Array[BatchRecord]) -> Array[SubjectSummary]

Aggregate records by subject.

#
summarize_time_domain_extended

fn summarize_time_domain_extended(intervals : Array[Double]) -> TimeDomainExtended

Return an extended summary for a cleaned RR sequence.

#
summarize_training_days

fn summarize_training_days(sessions : Array[WorkoutSession]) -> Array[TrainingDaySummary]

Group sessions by their ISO date while preserving input order.

#
summarize_training_load

fn summarize_training_load(daily_loads : Array[Double], acute_days : Int, chronic_days : Int) -> TrainingLoadSummary

Calculate acute/chronic load using recent and historical windows.

#
summarize_training_plan

fn summarize_training_plan(sessions : Array[WorkoutSession]) -> TrainingPlanMetrics

Calculate schedule-level load, trend, and recovery cost.

#
telemetry_export_csv

fn telemetry_export_csv(records : Array[TelemetryRecord]) -> String

#
telemetry_gap_count

fn telemetry_gap_count(records : Array[TelemetryRecord], maximum_gap_seconds : Double) -> Int

#
telemetry_latest_by_subject

fn telemetry_latest_by_subject(records : Array[TelemetryRecord]) -> Array[TelemetryRecord]

#
telemetry_notices_csv

fn telemetry_notices_csv(notices : Array[TelemetryStoreNotice]) -> String

#
telemetry_quality_histogram

fn telemetry_quality_histogram(records : Array[TelemetryRecord], buckets : Int) -> Array[Int]

#
telemetry_query_all

fn telemetry_query_all() -> TelemetryQuery

#
telemetry_query_subject

fn telemetry_query_subject(subject_id : String, limit : Int) -> TelemetryQuery

#
telemetry_query_window

fn telemetry_query_window(subject_id : String, start_seconds : Double, end_seconds : Double) -> TelemetryQuery

#
telemetry_record_is_valid

fn telemetry_record_is_valid(record : TelemetryRecord) -> Bool

#
telemetry_record_key

fn telemetry_record_key(record : TelemetryRecord) -> String

#
telemetry_record_row

fn telemetry_record_row(record : TelemetryRecord) -> Array[String]

#
telemetry_records_for_source

fn telemetry_records_for_source(records : Array[TelemetryRecord], source_id : String) -> Array[TelemetryRecord]

#
telemetry_records_for_subject

fn telemetry_records_for_subject(records : Array[TelemetryRecord], subject_id : String) -> Array[TelemetryRecord]

#
telemetry_store_feature_vector

fn telemetry_store_feature_vector(store : TelemetryStore) -> Array[Double]

#
telemetry_store_is_healthy

fn telemetry_store_is_healthy(store : TelemetryStore) -> Bool

#
telemetry_store_summary

fn telemetry_store_summary(store : TelemetryStore) -> TelemetrySummary

#
telemetry_summary

fn telemetry_summary(records : Array[TelemetryRecord]) -> TelemetrySummary

#
telemetry_window_coverage

fn telemetry_window_coverage(windows : Array[TelemetryWindow]) -> Double

Return the fraction of windows that contain a usable RR stream.

#
telemetry_window_sample_count

fn telemetry_window_sample_count(window : TelemetryWindow) -> Int

Return the number of usable cardiac samples in a window.

#
time_domain_feature_names

fn time_domain_feature_names() -> Array[String]

Return a stable list of feature names matching time_domain_feature_vector.

#
time_domain_feature_vector

fn time_domain_feature_vector(intervals : Array[Double]) -> Array[Double]

Build a compact feature vector for downstream models.

#
time_domain_is_usable

fn time_domain_is_usable(summary : TimeDomainExtended) -> Bool

Return whether an extended summary is numerically usable.

#
time_in_heart_rate_zone

fn time_in_heart_rate_zone(intervals : Array[Double], lower_bpm : Double, upper_bpm : Double) -> Double

Calculate the amount of time spent in a heart-rate zone.

#
to_csv

fn to_csv(grid : Array[Array[String]]) -> String

CSV Serializer. Escapes double quotes, commas, and newlines.

#
total_spectral_power

fn total_spectral_power(spectrum : Array[SpectrumBin]) -> Double

Return the total one-sided power.

#
training_load_entry_is_valid

fn training_load_entry_is_valid(entry : TrainingLoadEntry, config : LoadModelConfig) -> Bool

#
trend_baseline

fn trend_baseline(values : Array[Double], window_size : Int) -> Array[Double]

Estimate a rolling baseline with a centered median window.

#
trend_decomposition_is_usable

fn trend_decomposition_is_usable(decomposition : TrendDecomposition) -> Bool

Return whether the decomposition has aligned finite arrays.

#
trend_explained_variance

fn trend_explained_variance(values : Array[Double], trend : RegressionSummary) -> Double

Calculate variance explained by a fitted line.

#
trend_feature_vector

fn trend_feature_vector(decomposition : TrendDecomposition) -> Array[Double]

Return a trend feature vector.

#
turning_point_ratio

fn turning_point_ratio(values : Array[Double]) -> Double

Calculate the proportion of samples that are local turning points.

#
valid_duration_seconds

fn valid_duration_seconds(intervals : Array[Double], config : HrvConfig) -> Double

Return the total duration represented by valid intervals.

#
valid_features

fn valid_features(table : FeatureTable) -> Array[NamedFeature]

Return only valid features.

#
valid_intervals

fn valid_intervals(intervals : Array[Double], config : HrvConfig) -> Array[Double]

Return only values accepted by the configured physiological range.

#
validate_application_config

fn validate_application_config(config : ApplicationConfig) -> ConfigValidation

#
validate_intervals

fn validate_intervals(intervals : Array[Double], config : HrvConfig) -> IntervalValidation

Build a validation report without mutating the input.

#
validate_recording_protocol

fn validate_recording_protocol(intervals : Array[Double], config : HrvConfig, protocol : RecordingProtocol, dates : Array[String]) -> ProtocolValidation

Validate a recording against a protocol.

#
variance_value

fn variance_value(values : Array[Double]) -> Double

Sample variance. A sequence with fewer than two values has zero variance.

#
vector_distance

fn vector_distance(left : Array[Double], right : Array[Double]) -> Double

Calculate Euclidean distance between aligned vectors.

#
vector_squared_norm

fn vector_squared_norm(values : Array[Double]) -> Double

Calculate the squared norm of a vector.

#
vector_unit_norm

fn vector_unit_norm(values : Array[Double]) -> Array[Double]

Normalize a vector to unit norm.

#
wearable_finite

fn wearable_finite(value : Double) -> Bool

Check whether a floating-point value is usable in a telemetry record.

#
wearable_gap_detected

fn wearable_gap_detected(previous_timestamp : Double, current_timestamp : Double, maximum_gap_seconds : Double) -> Bool

Detect whether a gap exceeds the configured transport interval.

#
wearable_ingest_csv

fn wearable_ingest_csv(report : WearableIngestReport) -> String

Serialize a report suitable for a log line or a metrics endpoint.

#
wearable_ingest_feature_vector

fn wearable_ingest_feature_vector(report : WearableIngestReport) -> Array[Double]

Produce a compact quality vector for downstream model tables.

#
wearable_ingest_is_usable

fn wearable_ingest_is_usable(report : WearableIngestReport, minimum_samples : Int) -> Bool

Return whether an ingestion report has enough accepted cardiac events.

#
wearable_mean_quality

fn wearable_mean_quality(report : WearableIngestReport) -> Double

Return the average quality of accepted events.

#
wearable_quality_weight

fn wearable_quality_weight(value : Double) -> Double

Clamp quality to a finite unit interval for scoring.

#
wearable_rr_intervals

fn wearable_rr_intervals(report : WearableIngestReport) -> Array[Double]

Return the accepted RR stream in milliseconds.

#
wearable_sample_has_cardiac_value

fn wearable_sample_has_cardiac_value(sample : WearableSample) -> Bool

Return whether a sample carries at least one usable cardiac channel.

#
wearable_sample_is_valid

fn wearable_sample_is_valid(sample : WearableSample, config : WearableIngestConfig) -> Bool

Validate a sample against broad transport-level constraints.

#
wearable_sample_with_context

fn wearable_sample_with_context(sample : WearableSample, movement_g : Double, temperature_c : Double) -> WearableSample

Return a copy with optional movement and temperature channels attached.

#
wearable_samples_are_duplicate

fn wearable_samples_are_duplicate(left : WearableSample, right : WearableSample) -> Bool

Return whether two samples represent the same transport event.

#
wearable_timestamps

fn wearable_timestamps(report : WearableIngestReport) -> Array[Double]

Return accepted timestamps in seconds.

#
weighted_mean

fn weighted_mean(values : Array[Double], weights : Array[Double]) -> Double

Calculate a weighted mean for paired values. Extra values are ignored.

#
weighted_segment_rmssd

fn weighted_segment_rmssd(summaries : Array[SegmentSummary]) -> Double

Calculate a quality-weighted mean of segment RMSSD values.

#
weighted_signal_quality

fn weighted_signal_quality(components : SignalQualityComponents, weights : SignalQualityWeights) -> Double

Combine components using explicit weights.

#
weighted_sleep_hrv

fn weighted_sleep_hrv(epochs : Array[SleepEpoch]) -> (Double, Double)

Aggregate RR and RMSSD across epoch summaries using duration weights.

#
welch_periodogram

fn welch_periodogram(values : Array[Double], sample_rate_hz : Double, frame_size : Int, hop_size : Int, function : WindowFunction) -> Array[SpectrumBin]

Calculate the average spectrum across overlapping Welch frames.

#
window_coefficient

fn window_coefficient(function : WindowFunction, index : Int, length : Int) -> Double

Return the window coefficient for an index.

#
window_feature_vector

fn window_feature_vector(windows : Array[ScalarWindow]) -> Array[Double]

Convert scalar windows to a compact feature vector.

#
window_mean

fn window_mean(windows : Array[ScalarWindow]) -> Double

Return the mean of a window field.

#
window_mean_trend

fn window_mean_trend(windows : Array[ScalarWindow]) -> Double

Return the slope of window means.

#
window_quality_change

fn window_quality_change(left : WindowedAnalysis, right : WindowedAnalysis) -> Double

Compare two adjacent windows for a meaningful quality change.

#
window_rmssd_summary

fn window_rmssd_summary(windows : Array[WindowedAnalysis]) -> DistributionStats

Calculate the median and spread of window RMSSD values.

#
window_wearable_samples

fn window_wearable_samples(samples : Array[WearableSample], window_seconds : Double, step_seconds : Double, maximum_gap_seconds : Double) -> Array[TelemetryWindow]

Window accepted samples by duration and step.

#
windows_are_ordered

fn windows_are_ordered(windows : Array[ScalarWindow]) -> Bool

Return whether windows have monotonic, non-overlapping indices.

#
workout_load

fn workout_load(session : WorkoutSession) -> Double

Calculate the load of one session.

#
worst_quality_window

fn worst_quality_window(windows : Array[WindowedAnalysis]) -> WindowedAnalysis?

Return the window with the lowest quality.

#
worst_scalar_window

fn worst_scalar_window(windows : Array[ScalarWindow]) -> ScalarWindow?

Return the worst window by a scalar field.

#
z_scores

fn z_scores(values : Array[Double]) -> Array[Double]

Convert a sequence into z-scores. Constant sequences map to zero.