Skip to content

0SiddharthKumar0/SomnoTherm-A-Physiological-ML-Decision-System

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 

Repository files navigation

SomnoTherm : AI-Driven Adaptive Sleep & Thermal Regulation System

A production-grade hybrid AI + deterministic control system for smart mattresses. Continuously infers physiological sleep state from embedded sensors and adapts thermal zones to prevent discomfort-driven micro-awakenings — without ever letting ML logic directly command hardware.


The Problem

Manual temperature settings are static. Sleep is not.

The body's thermal needs change continuously across sleep stages: core temperature drops during deep sleep, rises during REM, and responds to environmental drift throughout the night. A mattress set to a fixed temperature is comfortable at sleep onset and frequently wrong two hours later.

The result: users wake up due to thermal discomfort, adjust manually, and fall back asleep — often without remembering the event. These micro-awakenings fragment sleep architecture even when total duration looks normal.

The goal: predict and prevent discomfort before it causes arousal, using only passive physiological sensing — no wearables required, no user intervention during sleep.


Architecture

┌──────────────────────────────────────────────────────────────────────┐
│                         SENSING LAYER                                │
│  BCG sensors (HR, respiration, micro-movement)                       │
│  Pressure sensors (posture, restlessness)                            │
│  Environmental sensors (ambient temp, mattress surface temp)         │
│  Optional: wearable ring (PPG → HR, HRV) for training validation     │
└─────────────────────────────┬────────────────────────────────────────┘
                              │ Raw signals @ 1–5 Hz
                              ▼
┌──────────────────────────────────────────────────────────────────────┐
│                      SIGNAL PROCESSING LAYER                         │
│  Noise filtering · Sliding window segmentation (30s–3min windows)    │
│  Signal confidence scoring · Cross-sensor validation                 │
│  Fallback: if confidence < threshold → conservative mode             │
└─────────────────────────────┬────────────────────────────────────────┘
                              │ Clean windowed signals + confidence scores
                              ▼
┌──────────────────────────────────────────────────────────────────────┐
│                     FEATURE ENGINEERING LAYER                        │
│  HR trends & delta signals · HRV features (RMSSD, pNN50)             │
│  Respiration rate & stability · Movement frequency & magnitude       │
│  User-baseline deviation (personalized relative features)            │
└─────────────────────────────┬────────────────────────────────────────┘
                              │ Feature vectors
                              ▼
┌──────────────────────────────────────────────────────────────────────┐
│                       ML INFERENCE LAYER                             │
│                                                                      │
│  ┌─────────────────────────┐  ┌─────────────────────────────────┐    │
│  │  Sleep Stage Classifier │  │  Thermal Discomfort Predictor   │    │
│  │  (LSTM/GRU time-series) │  │  (probability of imminent       │    │
│  │  → AWAKE / LIGHT /      │  │   micro-awakening due to        │    │
│  │    DEEP / REM           │  │   thermal cause)                │    │
│  └────────────┬────────────┘  └──────────────┬──────────────────┘    │
│               │                               │                      │
└───────────────┼───────────────────────────────┼───────────────────────┘
                │ Probabilistic stage output     │ Discomfort probability
                └───────────────┬───────────────┘
                                │
                                ▼
┌──────────────────────────────────────────────────────────────────────┐
│                 SAFETY CONTROL LAYER (deterministic)                 │
│                                                                      │
│  ML NEVER directly commands hardware.                                │
│                                                                      │
│  This layer:                                                         │
│  · Enforces absolute temperature bounds (configurable per user)      │
│  · Enforces maximum rate of change (°C per minute)                   │
│  · Applies hysteresis to prevent oscillation                         │
│  · Overrides any ML recommendation that violates safety bounds       │
│  · Falls back to rule-based control if ML confidence drops           │
│                                                                      │
│  Manual override always takes absolute priority.                     │
└─────────────────────────────┬────────────────────────────────────────┘
                              │ Safe thermal actuator commands
                              ▼
┌──────────────────────────────────────────────────────────────────────┐
│                         HARDWARE LAYER                               │
│  Heating/cooling zone actuators · Mattress thermal zones             │
└──────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌──────────────────────────────────────────────────────────────────────┐
│                    PERSONALIZATION & AUDIT LAYER                     │
│  Per-user comfort band adaptation · Manual feedback integration      │
│  Full decision audit trail · Nightly session review                  │
└──────────────────────────────────────────────────────────────────────┘

Why Hybrid AI + Deterministic Control

Pure ML control is unsuitable for physical systems in direct contact with humans:

  • Small prediction errors → oscillation and inconsistent behavior (we saw this in early iterations)
  • No interpretability → impossible to audit or explain to safety reviewers
  • No hard guarantees → an ML model can always, in principle, produce an unsafe output

The hybrid architecture gives us the best of both: ML for pattern recognition across high-dimensional physiological signals, deterministic logic for safety guarantees. See DESIGN.md for the full rationale and the failure modes that drove this decision.


Key Design Decisions

Decision Choice Why
Sensor type BCG + pressure (no mandatory wearable) Passive sensing — zero friction for user
Signal processing Windowed with confidence scoring Raw BCG is too noisy; confidence gates ML input
ML architecture LSTM/GRU time-series Sleep stages are sequential, not independent frames
ML output Probabilities, not hard labels Allows confidence-gated control decisions
Hardware control Deterministic only ML cannot command actuators directly
Personalization Comfort bands only (not model weights) Stable online adaptation without training instability
Fallback Conservative rule-based control System degrades safely, not dangerously

Results (Pilot Deployments)

Metric Result
Reduction in thermal micro-awakenings ~45%
Sessions completed without manual adjustment >80%
System response time (sensing to actuator command) <1 second
Fallback activation rate <5% of windows

See RESULTS.md for measurement methodology.


Tech Stack

Layer Technology
ML models PyTorch (LSTM/GRU), scikit-learn
Signal processing NumPy, SciPy
API layer FastAPI
Database PostgreSQL
ORM SQLAlchemy
Edge runtime Python (designed for ARM-compatible deployment)
Containerization Docker + Docker Compose
Testing pytest

Project Structure

somnotherm/
├── app/
│   ├── core/
│   │   ├── signal_processor.py      # BCG noise filtering, windowing, confidence scoring
│   │   ├── feature_engineering.py   # HR deltas, HRV features, movement patterns
│   │   ├── sleep_stage_classifier.py # LSTM sleep stage inference
│   │   ├── discomfort_predictor.py  # Thermal discomfort probability model
│   │   ├── safety_controller.py     # Deterministic control with hard safety bounds
│   │   └── personalization.py       # Per-user comfort band adaptation
│   ├── api/
│   │   └── routes/
│   │       ├── sessions.py          # Sleep session management
│   │       ├── users.py             # User profiles and preferences
│   │       └── control.py          # Manual override and thermal commands
│   ├── db/
│   │   ├── session.py               # DB session management
│   │   └── models.py                # ORM models
│   └── services/
│       ├── session_service.py       # Session lifecycle orchestration
│       └── inference_service.py     # ML inference pipeline
├── data/
│   └── simulate/
│       └── sensor_simulator.py      # Synthetic sensor data generator
├── tests/
│   ├── test_signal_processor.py
│   ├── test_safety_controller.py
│   ├── test_feature_engineering.py
│   └── test_discomfort_predictor.py
├── docs/
│   ├── DESIGN.md                    # Architecture and design rationale
│   ├── RESULTS.md                   # Metrics and measurement methodology
│   └── API.md                       # REST API reference
├── scripts/
│   └── run_demo.py                  # End-to-end demo without hardware
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
└── .env.example

Running the Demo (No Hardware Required)

Prerequisites

  • Docker and Docker Compose

1. Clone and configure

git clone https://github.com/0SiddharthKumar0/somnotherm.git
cd somnotherm
cp .env.example .env

2. Start the stack

docker-compose up --build

This starts the API on http://localhost:8000 and PostgreSQL on port 5432.

3. Run the simulated demo

docker-compose exec app python scripts/run_demo.py

The demo simulates a full 8-hour sleep session using synthetic physiological signals, running the complete pipeline from sensor input through ML inference to thermal control commands. Watch the system detect sleep stage transitions and issue safe thermal adjustments in real time.

4. Explore the API

API docs: http://localhost:8000/docs


API Overview

Method Endpoint Description
POST /api/v1/sessions/ Start a sleep session
GET /api/v1/sessions/{id} Get session status and current stage
POST /api/v1/sessions/{id}/sensor-data Push sensor window
GET /api/v1/sessions/{id}/audit Full decision audit trail
POST /api/v1/control/override Manual temperature override
GET /api/v1/users/{id}/profile User comfort profile

Design Documentation

  • DESIGN.md — Architecture decisions, hybrid control rationale, failure modes that shaped the design
  • RESULTS.md — Metrics and measurement methodology
  • API.md — Full API reference

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages