Skip to content

Repository files navigation

FitAI Adaptive Control

Latent physiological state estimation and continuous optimal control for adaptive training

FitAI Adaptive Control is an experimental AI system that converts multimodal athlete measurements into a compact latent physiological state and uses that state as the basis for safe, adaptive training control.

The central idea is to move beyond static fitness prediction:

measure the athlete → infer the hidden physiological state → model its continuous dynamics → select a bounded training action → observe the response → update the state

Live web MVP · Technical repository

Important

FitAI is a research prototype, not a medical device, diagnostic system, or clinically validated score. The Bioenergetic Adaptation Index (BAI) is a learned latent representation and is not a direct measurement of mitochondrial function.

FitAI web MVP

Why FitAI is different

Most fitness applications evaluate visible measurements independently and return static recommendations. FitAI explores a closed-loop control architecture in which the AI system:

  1. combines physiological, performance, recovery, lifestyle, and optional image-derived information;
  2. infers structured hidden states rather than treating every measurement independently;
  3. models how the latent state changes under training load and uncertainty;
  4. balances expected adaptation against fatigue, stress, inflammation, and cardiovascular risk;
  5. recalculates the recommendation when new athlete measurements become available.

The long-term product vision is a personalized AI controller that learns each athlete's response to training over time.

Current system at a glance

Layer Implemented capability
Athlete assessment 23 structured physiological and performance measurements plus an optional body photo
Prediction Custom NumPy model producing eight fitness-related outputs
Image analysis OpenCV body-proportion estimation from an uploaded photo
Stress dynamics Seven-day stochastic emotional-drift simulation inspired by an Itô SDE
Training safety Recovery, inflammation, cardiovascular, and high-intensity training risk logic
Planning Weekly training-load and HIIT adjustment using recovery and risk indicators
Explainability Feature importance, perturbation analysis, sensitivity analysis, and physiological response visualizations
Monitoring Historical predictions, stability, drift, synthetic-reference comparison, and model-health indicators
Latent representation Six-branch hierarchical beta-VAE with a four-dimensional global BAI state
Optimal control Continuous stochastic latent dynamics, Hamiltonian, analytic bounded control, and HJB residual
Verification 64 automated tests, including 10 focused latent-HJB tests

End-to-end architecture

flowchart TD
    A["23 measurements + optional body photo"]
    B["Working assessment layer: prediction, photo analysis, stress drift, safety"]
    C["Six physiological beta-VAE branches"]
    D["24D local latent vector"]
    E["4D global BAI state z(t)"]
    F["Continuous stochastic latent dynamics"]
    G["Hamiltonian and HJB control"]
    H["Bounded training intensity u* in [0,1]"]
    I["New measurements and observed response"]

    A --> B
    A --> C
    C --> D --> E --> F --> G --> H
    B --> H
    H --> I --> A
Loading

This architecture contains two complementary layers:

  • the working product layer, which already demonstrates athlete onboarding, prediction, photo analysis, safety logic, planning, and monitoring;
  • the new adaptive-control research core, which provides the hierarchical latent state, continuous dynamics, and mathematical HJB control foundation.

The repository contains both layers. The live deployment demonstrates the athlete-assessment workflow and research dashboards; the new hierarchical VAE and continuous HJB core are present in main but are not yet connected to every web interface.


1. Working athlete-assessment MVP

Multimodal physiological input

The onboarding workflow combines 23 structured measurements:

  • age, height, weight, and waist circumference;
  • sleep, emotional stress, alcohol exposure, and daily calories;
  • resting heart rate, HRV, and systolic blood pressure;
  • CRP, testosterone, cortisol, and hemoglobin;
  • running, Cooper-test, push-up, pull-up, and burpee performance;
  • an experimental mitochondrial placeholder used only as a research feature.

An optional uploaded photo is processed separately by the OpenCV module.

Physiological signal flow

Custom NumPy prediction engine

The baseline prediction engine is implemented without a high-level deep-learning framework. Its architecture is:

23 inputs → 48-dimensional embedding → 32-neuron hidden layer → 8 outputs

It includes tanh activations, constrained outputs, momentum optimization, gradient clipping, normalization, early stopping, serialization, and permutation feature importance.

The model produces eight experimental outputs:

  1. daily calories;
  2. 1 km running time;
  3. Cooper-test distance;
  4. maximum pull-ups;
  5. burpee capacity;
  6. 10 km running time;
  7. waist-circumference change;
  8. testosterone projection.

Custom NumPy neural network

OpenCV body-proportion estimator

ml/photo_analysis.py processes an optional user photo and estimates:

  • shoulder, waist, and hip widths in image coordinates;
  • shoulder-to-waist and waist-to-hip ratios;
  • an experimental physique category;
  • a non-medical training suggestion.

The module uses grayscale conversion, Gaussian blur, Canny edges, contour detection, regional body slices, and ratio calculation. It is a prototype computer-vision feature, not a clinical body-composition measurement.

OpenCV body analysis

Stochastic emotional-drift model

FitAI includes a seven-day stochastic stress simulation inspired by an Itô differential equation:

$$dS_t = [\kappa(\theta-S_t)+\mu S_t+a(S_t)]dt+\sigma_{eff}(S_t)dW_t$$

The implementation models:

  • mean reversion toward a long-term stress level;
  • weak natural drift;
  • nonlinear alcohol-related drift;
  • alcohol-dependent volatility;
  • multiple stochastic trajectories and their mean forecast.

This is an experimental stress-dynamics model, not a psychological diagnosis.

Stochastic emotional drift

Risk-benefit and weekly training logic

The existing safety and planning modules estimate the trade-off between training stimulus and physiological cost. They use signals such as HRV, sleep, blood pressure, stress, CRP, age, alcohol exposure, and recent training load.

The current MVP can:

  • estimate a bounded training-risk score;
  • reduce high-intensity or high-heart-rate-oriented work when recovery or cardiovascular risk is elevated;
  • adjust weekly HIIT frequency;
  • calculate a conservative calorie deficit;
  • add recovery penalties for insufficient sleep, alcohol exposure, and high training load;
  • block training recommendations when hard safety conditions are triggered.

The current rule-based/discrete risk module remains part of the working MVP. It is distinct from the new continuous latent HJB engine described below.

Explainability and longitudinal monitoring

FitAI includes:

  • permutation feature importance;
  • relative perturbation analysis;
  • gradient-based sensitivity analysis;
  • prediction history and physiological trend charts;
  • stability mean, variance, and drift;
  • comparison with an independent synthetic physiological reference layer;
  • an experimental model-health indicator.

These tools are intended to reveal how model outputs react to changing inputs and to detect unstable behavior over repeated assessments.

Physiological response analysis

Dual-layer evaluation


2. New hierarchical latent architecture

From observable measurements to hidden physiological state

The central research hypothesis is that an athlete's condition cannot be represented adequately by isolated measurements alone. Recovery, fatigue, stress, metabolic adaptation, and performance interact through hidden processes that are only partially observable.

FitAI therefore learns a structured latent representation with six physiological subsystems:

  • Energy
  • Recovery
  • Stress
  • Muscle
  • Metabolism
  • Aging

Each subsystem has its own variational encoder and local reconstruction path. Every branch produces a four-dimensional local latent representation. The six outputs are concatenated into a 24-dimensional vector and passed into the global Bioenergetic Core.

23 physiological features
          ↓
six local variational encoders
          ↓
6 × 4D local states = 24D latent vector
          ↓
Bioenergetic Core
          ↓
4D global BAI state z(t)

Latent physiological states

Four-dimensional Bioenergetic Adaptation Index

The Bioenergetic Core defines a global posterior:

$$q(z\mid x)=\mathcal{N}\left(\mu(x),\operatorname{diag}(\sigma^2(x))\right)$$

Training combines:

  • six local reconstruction losses;
  • one global reconstruction loss;
  • KL regularization for every local latent state;
  • KL regularization for the global BAI state.

For reproducible evaluation and downstream control, inference uses the posterior mean:

$$z=\mu(x)$$

The four BAI coordinates are treated as generic learned axes. They are not assigned fixed physiological meanings until longitudinal identification and external validation are completed.

Reproducible VAE evaluation

Configuration:

Parameter Value
Engineered records 973
Structured features 23
Training samples 779
Validation samples 194
Beta 0.1
Maximum epochs 1000
Early-stopping patience 100
Random seed 42

Held-out deterministic results:

Metric Result
Normalized MSE 1.007890
Normalized MAE 0.829476
Mean R² -0.008582
Active BAI dimensions 4 / 4

BAI dimension standard deviations:

[0.286592, 0.230020, 0.296834, 0.228644]

All four global latent dimensions remain active. However, reconstruction performance is still close to a standardized mean baseline. The result demonstrates a functioning, non-collapsed research architecture—not production accuracy or clinical validity.

Reproducible artifacts:

ml/models/fitai_vae.pkl
ml/models/vae_validation_metrics.json

3. Continuous latent dynamics and HJB control

Controlled stochastic differential equation

The global BAI state is connected to a four-dimensional control-affine stochastic dynamical model:

$$dz_t=(Az_t+Bu_t+c)dt+\Sigma dW_t, \qquad u_t\in[0,1]$$

where:

  • z(t) is the learned four-dimensional latent state;
  • u(t) is normalized training intensity;
  • A describes interactions and natural latent-state evolution;
  • B describes the influence of training intensity;
  • c represents baseline drift;
  • Σ represents process uncertainty.

LatentDynamics.fit_from_transitions() provides an API for estimating A, B, c, and Σ from longitudinal tuples (z_t, u_t, z_{t+1}). Euler and RK4 integration are implemented for trajectory simulation.

Hamiltonian

For running cost L, value gradient ∇V, and Hessian ∇²V, the stochastic Hamiltonian is:

$$H(z,u)=L(z,u)+\nabla V(z)^T f(z,u) +\frac{1}{2}\operatorname{Tr}\left(\Sigma\Sigma^T\nabla^2V(z)\right)$$

The running cost represents a configurable balance between:

  • deviation from a desired latent state;
  • physiological risk and accumulated stress;
  • the expected benefit of an appropriate training stimulus;
  • the cost of excessive control intensity.

Continuous optimal training intensity

For control-affine dynamics and quadratic control cost, FitAI computes the minimizing action analytically:

$$u^*=\operatorname{clip}\left(-\frac{B^T\nabla V}{r},0,1\right)$$

This is a continuous control calculation. It does not enumerate a fixed grid of candidate intensities.

The engine also evaluates the HJB residual:

$$\frac{\partial V}{\partial t}+\min_{u\in[0,1]}H(z,u)$$

Hamilton–Jacobi–Bellman control concept

What is implemented and what remains

Implemented now:

  • hierarchical local and global latent representation;
  • deterministic BAI inference;
  • continuous control-affine stochastic dynamics;
  • estimation API for longitudinal transitions;
  • Euler and RK4 simulation;
  • quadratic running cost;
  • stochastic Hamiltonian including the Hessian trace term;
  • analytic bounded control in [0,1];
  • HJB residual evaluation;
  • automated unit tests.

Funded research milestones:

  • collect repeated real-world athlete measurements and training actions;
  • calibrate personalized dynamics from longitudinal data;
  • identify the temporal stability and semantics of BAI coordinates;
  • learn a value-function approximation;
  • integrate the continuous policy into the web product;
  • validate safety, policy stability, adherence, and coach-assessed usefulness in a supervised pilot.

4. Safety architecture

The optimization layer is subordinate to hard physiological restrictions:

flowchart TD
    A["Hard safety gates: recovery, inflammation, cardiovascular signals"]
    B["Latent-state policy and uncertainty checks"]
    C["Bounded recommendation"]
    D["Human review and observed response"]

    A --> B --> C --> D
Loading

The system is designed so that a learned control policy cannot override a hard safety restriction. Initial product positioning is performance and wellness support, not diagnosis or treatment. Any future clinical use would require appropriate clinical, ethical, legal, and regulatory validation.


5. Testing and reproducibility

The complete test suite currently contains 64 passing tests, including 10 focused tests for the latent HJB engine.

The HJB tests cover:

  • control-affine drift;
  • batch processing and control broadcasting;
  • RK4 integration against a known linear solution;
  • trajectory simulation;
  • recovery of known dynamics parameters from synthetic transitions;
  • analytic continuous Hamiltonian minimization;
  • control-bound enforcement;
  • stochastic Hessian trace calculation;
  • HJB residual calculation;
  • invalid-control rejection.

Run all tests:

python -m pytest -q

Expected result:

64 passed

Reproduce the VAE experiment:

python -m ml.vae.trainer
python -m ml.vae.evaluation

Core research files

ml/
├── bioenergetics/
│   ├── latent_states.py
│   └── bai.py
├── hjb/
│   ├── dynamics.py
│   └── hamiltonian.py
├── vae/
│   ├── encoder.py
│   ├── decoder.py
│   ├── model.py
│   ├── losses.py
│   ├── trainer.py
│   └── evaluation.py
├── emotional_drift.py
├── photo_analysis.py
├── training_optimizer.py
└── training_risk.py

tests/
└── test_latent_hjb.py

6. Run the web MVP

Local installation

git clone https://github.com/Mykhailo-888/FitAI-Adaptive-Control.git
cd FitAI-Adaptive-Control
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
python manage.py migrate
python manage.py runserver

Open:

http://127.0.0.1:8000/

Docker support is also included in the repository.

Technology

  • Python 3.11
  • Django
  • NumPy and pandas
  • OpenCV
  • PostgreSQL / SQLite
  • Docker
  • pytest
  • HTML, CSS, JavaScript, and Chart.js

7. Six-month product-validation plan

  1. Define a privacy-conscious longitudinal data and safety protocol with athletes and coaches.
  2. Onboard pilot partners and collect repeated measurements, training actions, recovery outcomes, and adverse-response flags.
  3. Calibrate the latent dynamics and evaluate BAI stability over time.
  4. Train and validate a bounded value-function approximation under hard safety gates.
  5. Integrate the adaptive policy into the web workflow and compare it with static recommendations.
  6. Produce pilot evidence, a commercialization plan, and a roadmap for larger validation.

Primary evaluation criteria will include calibration, uncertainty coverage, policy stability, safety-rule violations, adherence, user retention, and coach-assessed usefulness.

Funding objective

Funding would transform the current working software and tested mathematical prototype into a longitudinally calibrated product experiment. Immediate priorities are participant recruitment, privacy-compliant data infrastructure, wearable and measurement integration, model validation, safety review, UX integration, and a supervised field pilot.


Author

Mykhailo Velychko

Hesse, Germany

Project: FitAI Adaptive Control

Live MVP: fitai-research.onrender.com

About

Research MVP for latent physiological state estimation and continuous adaptive training control using a hierarchical beta-VAE and HJB optimization.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages