# thuhci/ringtool architecture

> Architecture diagram of the GitHub repository thuhci/ringtool, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/thuhci/ringtool
- Repository: https://github.com/thuhci/ringtool

## Overview

1. **Repository purpose and execution model**
   RingTool is a Python-based research toolkit for processing smart-ring physiological signals and benchmarking multiple estimation methods. The top-level entrypoint is `main.py`, which orchestrates runs from JSON configuration files rather than hard-coded pipelines. Most architecture diagrams should center on this config-driven execution path.

2. **Core data source and file contract**
   The system expects a dataset directory containing per-subject `.pkl` files with synchronized multimodal signals and labels. Each record can include PPG channels (`ir`, `red`, `bvp`), IMU axes (`ax`, `ay`, `az`), respiratory signals, and scalar targets such as HR, RR, SpO2, and blood pressure. This dataset boundary is the main input to the pipeline.

3. **Dataset loading and preprocessing boundary**
   The `dataset` package is the ingestion layer. `dataset/load_dataset.py` and `dataset/preprocess.py` likely handle reading the `.pkl` records, selecting channels, windowing, normalization, filtering, and feature preparation. This layer transforms raw sensor time series into model-ready tensors or signal segments, and it is shared by both physics-based and supervised branches.

4. **Two major analysis branches**
   The architecture splits into:
   - **Unsupervised / physics-based methods** in `unsupervised/`
   - **Supervised deep-learning methods** in `nets/` plus training logic in `trainer/`
   
   These branches operate on the same preprocessed inputs but produce estimates through very different mechanisms, which is an important architectural boundary.

5. **Physics-based signal processing subsystem**
   The `unsupervised` package contains task-specific implementations for HR, RR, and SpO2:
   - `unsupervised/hr/hr.py`
   - `unsupervised/rr/rr.py`
   - `unsupervised/spo2/spo2.py`
   
   These modules implement classical algorithms such as peak detection, FFT-based frequency estimation, and ratio-based SpO2 calculation. They are configuration-selected alternatives to ML models rather than intermediate preprocessing steps.

6. **Supervised model subsystem**
   The `nets` package contains reusable neural backbones for regression on physiological signals:
   - `resnet.py`
   - `inception_time.py`
   - `transformer.py`
   - `mamba2.py`
   
   Supporting files like `base_model.py` and `se_layer.py` provide shared model abstractions or building blocks. `nets/load_model.py` appears to map config choices to concrete model classes. This subsystem is the model layer in the architecture.

7. **Training, validation, and evaluation orchestration**
   The `trainer` package contains the training engine; `trainer/load_trainer.py` suggests a factory or selector for trainer variants. From the README, the training protocol includes subject-independent cross-validation, early stopping, best-epoch selection, and regression metrics such as MAE, RMSE, MAPE, and Pearson correlation. The trainer sits between preprocessed data and model execution.

8. **Experiment configuration and selection logic**
   The `config/` tree is a large experiment matrix organized by:
   - method family: `physical-based`, `supervised`, `only_test`
   - ring type: `ring1`, `ring2`
   - modality/target combinations: `hr`, `rr`, `spo2`, `bp`, plus variants like `ir`, `irimu`, `irredimu`
   - scenario splits: `all-scenes`, `motion-scenes`, `stationary-scenes`
   
   These JSON files are the main source of experiment metadata and determine which dataset slices, channels, models, and evaluation modes are run.

9. **Shared constants and model/dataset taxonomy**
   The `constants` package defines canonical enums and mappings for datasets, experiments, and models. This layer prevents the rest of the code from relying on ad hoc strings and provides the repository’s internal taxonomy for ring type, target task, and supported architectures.

10. **Utility and feature-engineering helpers**
   The `utils` package contains common functionality, including `accel_features.py` for accelerometer-derived features and general helpers in `utils.py`. `utils/rename_dir.py` suggests filesystem normalization or dataset organization support. These are supporting modules rather than primary architectural nodes, but they affect input preparation and reproducibility.

11. **Notification and operational integration**
   The `notifications` package adds an optional Slack notification boundary for long-running experiments. It is not part of core signal processing, but it is part of the runtime workflow for batch training jobs launched from `main.py`.

12. **Outputs, artifacts, and repository workflow**
   The repo produces multiple artifacts: logs, figures, visualizations, generated CSVs, and model outputs under folders like `logs/`, `csv/`, `img/`, `visualizations/`, and possibly `nets/` or `trainer/`-driven checkpoints. The `.github` workflows and scripts enforce repository hygiene, including config naming and CSV validation, which matters for keeping the experiment matrix consistent.

13. **External technology dependencies that shape architecture**
   The implementation is Python-centric and built around PyTorch. The README also calls out `mamba-ssm` and Triton, which matter because the Mamba backbone depends on them and can constrain the runtime/CUDA environment. This means the supervised branch is not just framework-agnostic Python; it has GPU/runtime coupling.

14. **How to draw the main system diagram**
   A clear diagram should show: raw ring dataset in `.pkl` files feeding a preprocessing layer, then branching into either physics-based algorithms or supervised training/inference. The supervised branch should show config-driven model selection, training/evaluation, and metric reporting. Optional side paths should include Slack notifications and generated artifacts/visualizations.

Main entry points: [`main.py`](https://github.com/thuhci/ringtool/blob/main/main.py) (Main entry), [`unsupervised`](https://github.com/thuhci/ringtool/tree/main/unsupervised) (Physics methods), [`dataset/preprocess.py`](https://github.com/thuhci/ringtool/blob/main/dataset/preprocess.py) (Preprocess), [`trainer/load_trainer.py`](https://github.com/thuhci/ringtool/blob/main/trainer/load_trainer.py) (Trainer)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime pipeline"]
  node_main(("Main entry<br/>entrypoint<br/>[main.py]"))
  node_dataset_boundary[("Ring data<br/>subject .pkl dataset")]
  node_load_dataset["Load data<br/>ingestion<br/>[load_dataset.py]"]
  node_preprocess["Preprocess<br/>signal prep<br/>[preprocess.py]"]
  node_physical{{"Physics methods<br/>unsupervised"}}
  node_hr_algo["HR calc<br/>peak/FFT<br/>[hr.py]"]
  node_rr_algo["RR calc<br/>peak/FFT<br/>[rr.py]"]
  node_spo2_algo["SpO2 calc<br/>ratio method<br/>[spo2.py]"]
  node_supervised{{"Supervised branch<br/>deep learning"}}
  node_model_factory["Model factory<br/>model selector<br/>[load_model.py]"]
  node_trainer["Trainer<br/>training engine<br/>[load_trainer.py]"]
  node_net_backbones{{"Backbones<br/>neural models"}}
end

subgraph group_experiments["Experiment matrix"]
  node_config["Configs<br/>experiment JSONs"]
  node_constants["Taxonomy<br/>shared enums"]
end

subgraph group_support["Support layers"]
  node_utils["Helpers<br/>utility layer"]
  node_notifications["Slack notify<br/>ops integration<br/>[slack.py]"]
  node_artifacts[("Artifacts<br/>outputs")]
  node_ci["Repo checks<br/>CI/scripts<br/>[.github]"]
end

node_main -->|"loads"| node_config
node_main -->|"uses"| node_constants
node_main -->|"starts"| node_load_dataset
node_load_dataset -->|"reads"| node_dataset_boundary
node_load_dataset -->|"passes"| node_preprocess
node_preprocess -->|"feeds"| node_physical
node_preprocess -->|"feeds"| node_supervised
node_physical -->|"selects"| node_hr_algo
node_physical -->|"selects"| node_rr_algo
node_physical -->|"selects"| node_spo2_algo
node_supervised -->|"selects"| node_model_factory
node_model_factory -->|"instantiates"| node_net_backbones
node_supervised -->|"runs"| node_trainer
node_trainer -->|"executes"| node_net_backbones
node_trainer -->|"writes"| node_artifacts
node_main -.->|"notifies"| node_notifications
node_ci -.->|"validates"| node_config
node_utils -.->|"supports"| node_preprocess
node_utils -.->|"supports"| node_trainer

click node_main "https://github.com/thuhci/ringtool/blob/main/main.py"
click node_config "https://github.com/thuhci/ringtool/tree/main/config"
click node_constants "https://github.com/thuhci/ringtool/tree/main/constants"
click node_load_dataset "https://github.com/thuhci/ringtool/blob/main/dataset/load_dataset.py"
click node_preprocess "https://github.com/thuhci/ringtool/blob/main/dataset/preprocess.py"
click node_physical "https://github.com/thuhci/ringtool/tree/main/unsupervised"
click node_hr_algo "https://github.com/thuhci/ringtool/blob/main/unsupervised/hr/hr.py"
click node_rr_algo "https://github.com/thuhci/ringtool/blob/main/unsupervised/rr/rr.py"
click node_spo2_algo "https://github.com/thuhci/ringtool/blob/main/unsupervised/spo2/spo2.py"
click node_supervised "https://github.com/thuhci/ringtool/tree/main/nets"
click node_model_factory "https://github.com/thuhci/ringtool/blob/main/nets/load_model.py"
click node_trainer "https://github.com/thuhci/ringtool/blob/main/trainer/load_trainer.py"
click node_net_backbones "https://github.com/thuhci/ringtool/tree/main/nets"
click node_utils "https://github.com/thuhci/ringtool/tree/main/utils"
click node_notifications "https://github.com/thuhci/ringtool/blob/main/notifications/slack.py"
click node_artifacts "https://github.com/thuhci/ringtool/tree/main/logs"
click node_ci "https://github.com/thuhci/ringtool/blob/main/.github"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_dataset_boundary,node_load_dataset,node_preprocess,node_physical,node_hr_algo,node_rr_algo,node_spo2_algo,node_supervised,node_model_factory,node_trainer,node_net_backbones toneBlue
class node_config,node_constants toneAmber
class node_utils,node_notifications,node_artifacts,node_ci toneMint
```

## Components

### Runtime pipeline

Config-driven execution from entrypoint through data, methods, and outputs.

- [Main entry](https://github.com/thuhci/ringtool/blob/main/main.py): entrypoint · Launches runs from JSON configs and coordinates the selected experiment path. · `main.py`
- **Ring data**: subject .pkl dataset · Per-subject synchronized multimodal signal records and scalar targets.
- [Load data](https://github.com/thuhci/ringtool/blob/main/dataset/load_dataset.py): ingestion · Reads subject records and constructs dataset slices for downstream processing. · `dataset/load_dataset.py`
- [Preprocess](https://github.com/thuhci/ringtool/blob/main/dataset/preprocess.py): signal prep · Channel selection, filtering, windowing, normalization, and feature preparation. · `dataset/preprocess.py`
- [Physics methods](https://github.com/thuhci/ringtool/tree/main/unsupervised): unsupervised · Classical estimation path for HR, RR, and SpO2 using signal processing rules. · `unsupervised`
- [HR calc](https://github.com/thuhci/ringtool/blob/main/unsupervised/hr/hr.py): peak/FFT · Heart-rate estimation via peak detection and frequency-domain methods. · `unsupervised/hr/hr.py`
- [RR calc](https://github.com/thuhci/ringtool/blob/main/unsupervised/rr/rr.py): peak/FFT · Respiration-rate estimation from respiratory or derived signals. · `unsupervised/rr/rr.py`
- [SpO2 calc](https://github.com/thuhci/ringtool/blob/main/unsupervised/spo2/spo2.py): ratio method · Oxygen-saturation estimation from red/IR channel relationships. · `unsupervised/spo2/spo2.py`
- [Supervised branch](https://github.com/thuhci/ringtool/tree/main/nets): deep learning · Neural regression path combining model selection, training, validation, and testing. · `nets`
- [Model factory](https://github.com/thuhci/ringtool/blob/main/nets/load_model.py): model selector · Maps config choices to a concrete backbone implementation. · `nets/load_model.py`
- [Trainer](https://github.com/thuhci/ringtool/blob/main/trainer/load_trainer.py): training engine · Runs optimization, validation, early stopping, best-epoch selection, and metrics. · `trainer/load_trainer.py`
- [Backbones](https://github.com/thuhci/ringtool/tree/main/nets): neural models · Reusable sequence regressors including ResNet, InceptionTime, Transformer, and Mamba2. · `nets`

### Experiment matrix

JSON configurations and taxonomy that select tasks, rings, scenes, and models.

- [Configs](https://github.com/thuhci/ringtool/tree/main/config): experiment JSONs · Method-family, ring, task, modality, and scene configuration matrix. · `config`
- [Taxonomy](https://github.com/thuhci/ringtool/tree/main/constants): shared enums · Canonical dataset, experiment, and model mappings used across the repo. · `constants`

### Support layers

Shared utilities, notifications, and repository hygiene.

- [Helpers](https://github.com/thuhci/ringtool/tree/main/utils): utility layer · Shared helpers for acceleration features, filesystem normalization, and common functions. · `utils`
- [Slack notify](https://github.com/thuhci/ringtool/blob/main/notifications/slack.py): ops integration · Optional Slack alerts for long-running experiment jobs. · `notifications/slack.py`
- [Artifacts](https://github.com/thuhci/ringtool/tree/main/logs): outputs · Logs, CSVs, images, figures, and visualizations produced by experiments. · `logs`
- [Repo checks](https://github.com/thuhci/ringtool/blob/main/.github): CI/scripts · Workflow and scripts that validate JSON naming and CSV outputs. · `.github`

## Connections

- Main entry → Configs: loads · Main reads experiment metadata from JSON configs.
- Main entry → Taxonomy: uses · Execution relies on shared dataset and model taxonomy.
- Main entry → Load data: starts · Entrypoint invokes the data ingestion layer.
- Load data → Ring data: reads · Loads per-subject multimodal .pkl records.
- Load data → Preprocess: passes · Raw records are transformed into model-ready inputs.
- Preprocess → Physics methods: feeds · Preprocessed signals can be routed to classical estimators.
- Preprocess → Supervised branch: feeds · Preprocessed signals can also feed supervised training and inference.
- Physics methods → HR calc: selects · Task config chooses HR estimation logic.
- Physics methods → RR calc: selects · Task config chooses RR estimation logic.
- Physics methods → SpO2 calc: selects · Task config chooses SpO2 estimation logic.
- Supervised branch → Model factory: selects · Config chooses the backbone implementation.
- Model factory → Backbones: instantiates · Factory builds the concrete neural architecture.
- Supervised branch → Trainer: runs · Training engine coordinates optimization and evaluation.
- Trainer → Backbones: executes · Trainer performs forward and backward passes through the model.
- Trainer → Artifacts: writes · Metrics, logs, figures, and outputs are persisted.
- Main entry → Slack notify: notifies · Optional operational alerts for batch runs.
- Repo checks → Configs: validates · Repository checks enforce configuration naming and CSV conventions.
- Helpers → Preprocess: supports · Utility functions contribute feature engineering and data handling.
- Helpers → Trainer: supports · Shared helpers are used in training and experiment execution.
