目录

moonbit-hrvkit

moonbit-hrvkit is a high-performance, target-independent Heart Rate Variability (HRV) analysis toolkit written in MoonBit. It is designed for sports scientists, developers, and bio-hackers interested in recovery monitoring and training status analysis.

The toolkit is completely pure and compatible with all MoonBit backends (wasm-gc, js, and native), requiring no system-specific FFI or runtime imports.


Features

1. RR Interval Cleaning (Ectopic Beat Handling)

Wearable heart rate sensors can suffer from signal drops, muscle noise, and ectopic beats. This library implements medical-grade preprocessing to clean raw RR intervals:

  • Range Filter: Automatically flags and filters out physiologically implausible beats (default: outside [300, 2000] ms, corresponding to [30, 200] bpm).
  • Karlsson Local Median Filter: Runs a 5-point local median filter. If any beat deviates from the local median by more than a threshold (default: 20%), it is flagged as ectopic.
  • Correction Modes:
    • Remove: Exclude ectopic beats completely from subsequent analysis.
    • InterpolateLocalMedian: Replace ectopic beats with the local median of surrounding valid beats.
    • InterpolateLinear: Linearly interpolate the values of ectopic beats using adjacent valid beats.

2. HRV Time-Domain Indicators

Computes standard time-domain metrics widely used in recovery tracking:

  • Mean RR: The average duration of valid RR intervals (ms).
  • Mean Heart Rate (HR): The average heart rate (bpm).
  • SDNN: The standard deviation of normal-to-normal (NN) intervals (ms), reflecting overall autonomic nervous system activity.
  • RMSSD: The root mean square of successive differences (ms), reflecting parasympathetic (vagal) activity. This is the primary indicator used for daily recovery tracking.
  • pNN50: The percentage of successive interval differences greater than 50 ms.
  • pNN(custom): Custom threshold support (e.g. pNN20).

3. Morning baseline and Trend Analysis

For daily recovery tracking, one-off measurements are highly variable. This library computes baseline trends using historical morning measurements:

  • 7-Day Rolling Baseline: Calculates the rolling mean (μ\mu) and standard deviation (σ\sigma) of RMSSD over the past 7 measurements.
  • Normal Range: Computes a personalized normal range defined as μ±0.75σ\mu \pm 0.75 \sigma (standard deviation coefficient is configurable).
  • Status Classification:
    • Low: RMSSD is below the normal range (indicates high stress, under-recovery).
    • High: RMSSD is above the normal range (indicates stable recovery or parasympathetic hyperactivity).
    • Normal: RMSSD is within the normal range (indicates stable adaptive state).
  • Recovery Score: A normalized score between 0 and 100 representing where today’s measurement stands relative to the baseline.

4. Custom CSV and JSON formats

  • Custom CSV Parser & Serializer: A state-machine-based CSV parser supporting comma separators, optional double quotes, and escaped quotes.
  • JSON Serialization: Complete support for ToJson and FromJson traits on all metrics and trends.

Directory Structure

.
├── moon.mod                  # Module metadata
├── moon.pkg                  # Root package config
├── LICENSE                   # Apache 2.0 License
├── README.md                 # Project documentation
├── pkg.generated.mbti        # Generated public interface definitions
├── hrvkit.mbt                # Core data models and configurations
├── cleaning.mbt              # RR intervals cleaning and interpolation logic
├── indicators.mbt            # SDNN, RMSSD, and pNN computation
├── morning.mbt               # Rolling baseline trends and recovery score calculations
├── parser.mbt                # CSV state-machine parsing/serialization and domain mapping
├── hrvkit_test.mbt           # Unit test suite covering all features
└── cmd
    └── main
        ├── main.mbt          # CLI entry point
        ├── moon.pkg          # Executable package config
        └── pkg.generated.mbti

Installation & Setup

  1. Make sure you have the latest MoonBit toolchain (v0.10.3 or higher) installed:
    moon version --all
  2. Clone the repository and run type check:
    moon check
  3. Run unit tests:
    moon test

Command Line Interface (CLI) Usage

Run the tool using moon run cmd/main -- [options].

Options

  • --action <clean|metrics|trends>: Select analysis action.
  • --format <json|csv>: Input/Output format (default: csv).
  • --cleaning <remove|median|linear>: Correction method for ectopic beats (default: remove).
  • --data <data_string>: Inline CSV or JSON formatted data.

Examples

1. Clean RR Intervals (JSON)

moon run cmd/main -- --action clean --data "[800, 802, 1500, 200, 798]" --format json

Output:

{"cleaned":[800,802],"quality":{"total_beats":5,"valid_beats":2,"ectopic_beats":3,"clean_ratio":0.4,"is_low_quality":true}}

2. Compute HRV Metrics (CSV)

moon run cmd/main -- --action metrics --data "800, 802, 798, 805, 801" --format csv

Output:

metric,value
mean_rr,801.2
mean_hr,74.88766849725411
sdnn,2.588435821108957
rmssd,4.6097722286464435
pnn50,0
pnn_custom,0
total_beats,5
valid_beats,5
ectopic_beats,0
clean_ratio,1
is_low_quality,false
moon run cmd/main -- --action trends --format csv --data "date,rmssd,sdnn,rr_mean
2026-08-01,50.0,60.0,800.0
2026-08-02,52.0,62.0,810.0
2026-08-03,48.0,58.0,790.0
2026-08-04,51.0,61.0,800.0
2026-08-05,50.0,60.0,800.0
2026-08-06,53.0,63.0,820.0
2026-08-07,49.0,59.0,795.0
2026-08-08,30.0,40.0,750.0"

Output:

date,rmssd,rolling_avg,rolling_sd,normal_lower,normal_upper,status,recovery_score
2026-08-01,50,50,5,46.25,53.75,Normal,90
2026-08-02,52,50,5,46.25,53.75,Normal,95.33333333333333
2026-08-03,48,51,1.4142135623730951,49.9393398282209,52.0606601717791,Low,76.88931165152865
2026-08-04,51,50,2,48.5,51.5,Normal,96.66666666666667
2026-08-05,50.25,50.25,1.707825127659933,48.96913115425505,51.53086884574495,Normal,90
2026-08-06,53,50.2,1.4832396974191326,49.08757022693565,51.31242977306435,High,93.42465753424658
2026-08-07,49,50.666666666666664,1.7511900715418252,49.3532741130103,51.98005922032303,Low,79.42661893309499
2026-08-08,30,50.42857142857143,1.7182494136847429,49.13988436830787,51.71725848883499,Low,48.8406180373809

License

This project is licensed under the Apache License 2.0. See LICENSE for details.

关于

moonbit-hrvkit 是一个完全用 MoonBit 编写的、跨平台且独立的心率变异性(HRV)指标计算与分析工具箱。

80.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802047560号