Skip to main content

Physics-constrained Neural DEs for chemical reactor digital twins

Project description

ReactorTwin

Physics-Constrained Neural Differential Equations for Chemical Reactor Digital Twins

PyPI version Python 3.10+ License: MIT CI Documentation Code style: ruff


Overview

ReactorTwin is a framework for building digital twins of chemical reactors using Neural Differential Equations with hard physics constraints. It combines:

  • 5 Neural DE variants: Standard, Latent, Augmented, SDE, CDE
  • 4 reactor types: CSTR, Batch, Semi-batch, PFR (plug flow with Method of Lines)
  • 7 hard conservation laws: Mass, energy, thermodynamics, stoichiometry, port-Hamiltonian, GENERIC, positivity
  • 6 kinetics models: Arrhenius, Michaelis-Menten, Power Law, Langmuir-Hinshelwood, Reversible, Monod
  • Digital twin features: EKF state estimation, 4-level fault detection, MPC control, online adaptation, meta-learning
  • 10-page Streamlit dashboard for interactive simulation and analysis

Key differentiator: Architectural projection onto constraint manifolds ensures physical laws are satisfied exactly, not approximately.


Quick Start

Installation

# Clone repository
git clone https://github.com/ktubhyam/reactor-twin.git
cd reactor-twin

# Install with all dependencies
pip install -e ".[all]"

# Or minimal install
pip install -e .

30-Second Example

from reactor_twin import CSTRReactor, ArrheniusKinetics, NeuralODE
import torch

# Define CSTR with A -> B kinetics
reactor = CSTRReactor(
    name="my_cstr",
    num_species=2,
    params={"V": 100, "F": 10, "C_feed": [1.0, 0.0], "T_feed": 350},
    kinetics=ArrheniusKinetics(
        name="A_to_B",
        num_reactions=1,
        params={"k0": [1e10], "Ea": [50000], "stoich": [[-1, 1]]},
    ),
)

# Train Neural ODE to learn dynamics
model = NeuralODE(state_dim=2, solver="dopri5", adjoint=True)
predictions = model(z0=torch.randn(32, 2), t_span=torch.linspace(0, 10, 50))

# Predictions are 1000x faster than scipy integration!

Run the full quickstart: python examples/00_quickstart.py


Features

Neural DE Variants

Variant Use Case Status
Neural ODE Standard continuous-time dynamics ✅ Complete
Latent Neural ODE High-dimensional systems (encoder/decoder) ✅ Complete
Augmented Neural ODE Topology-breaking expressivity ✅ Complete
Neural SDE Uncertainty quantification (stochastic) ✅ Complete
Neural CDE Irregular sensor data ✅ Complete

Reactor Types

Reactor Description Status
CSTR Continuous stirred-tank reactor ✅ Complete
Batch Time-varying volume for gas-phase reactions ✅ Complete
Semi-batch Continuous feed + batch (pharmaceutical) ✅ Complete
PFR Plug flow with Method of Lines discretization ✅ Complete

Kinetics Models

Model Use Case Status
Arrhenius Standard temperature-dependent reactions ✅ Complete
Michaelis-Menten Enzyme-catalyzed reactions ✅ Complete
Power Law Empirical rate expressions ✅ Complete
Langmuir-Hinshelwood Heterogeneous catalysis ✅ Complete
Reversible Equilibrium-limited reactions ✅ Complete
Monod Microbial growth kinetics ✅ Complete

Physics Constraints

Constraint Hard Mode Soft Mode Status
Positivity Softplus/ReLU projection Penalty ✅ Complete
Mass Balance Stoichiometric projection Penalty ✅ Complete
Energy Balance Soft mode only Penalty ✅ Complete
Thermodynamics Entropy/Gibbs/equilibrium Penalty ✅ Complete
Stoichiometry Predict rates not species Penalty ✅ Complete
Port-Hamiltonian Structure-preserving N/A ✅ Complete
GENERIC Reversible-irreversible coupling Penalty ✅ Complete

Digital Twin Features

Feature Description Status
State Estimation EKF with Neural ODE fusion, autograd Jacobians ✅ Complete
Fault Detection 4-level: SPC, residual, isolation, ML classification ✅ Complete
MPC Control Gradient-based with constraint handling ✅ Complete
Online Adaptation Replay buffer + Elastic Weight Consolidation ✅ Complete
Meta-Learning Reptile for cross-reactor transfer ✅ Complete

Benchmark Systems

System Type Status
Exothermic A→B Non-isothermal CSTR ✅ Complete
Van de Vusse Series-parallel CSTR ✅ Complete
Bioreactor Monod growth kinetics ✅ Complete
Consecutive A→B→C Selectivity optimization ✅ Complete
Parallel A→B, A→C Yield optimization ✅ Complete

Architecture

Plugin-Based Design

ReactorTwin uses a registry system for extensibility without modifying library code:

from reactor_twin import REACTOR_REGISTRY, AbstractReactor

# Register custom reactor
@REACTOR_REGISTRY.register("my_reactor")
class MyCustomReactor(AbstractReactor):
    def ode_rhs(self, t, y, u):
        # Your reactor equations
        return dydt

# Use anywhere
reactor = REACTOR_REGISTRY.get("my_reactor")(...)

Project Structure

reactor-twin/
├── src/reactor_twin/
│   ├── core/           # Neural DE Engine (Neural ODE, Latent, SDE, CDE)
│   ├── physics/        # 7 hard/soft constraints
│   ├── reactors/       # 4 reactor types + 5 kinetics models + 5 benchmarks
│   ├── training/       # Training engine + losses + data generation
│   ├── digital_twin/   # EKF, fault detection, MPC, online adaptation, meta-learning
│   └── dashboard/      # 10-page Streamlit app
├── tests/              # Test suite
├── examples/           # Runnable examples
└── pyproject.toml      # Package configuration

See PROJECT_STRUCTURE.md for complete architecture details.


Dashboard

Launch the interactive Streamlit dashboard:

pip install -e ".[dashboard]"
reactor-twin-dashboard
# Or: streamlit run src/reactor_twin/dashboard/app.py

10 pages: Reactor Simulator, Phase Portraits, Bifurcation Diagrams, RTD Analysis, Parameter Sweeps, Sensitivity Analysis, Pareto Optimization, Fault Monitoring, Model Validation, Latent Space Explorer.


Benchmarks

Accuracy (vs ground truth):

  • CSTR exothermic: RMSE < 5% (target), < 1% (stretch)
  • PFR 1D: RMSE < 8% (target), < 3% (stretch)

Physics Compliance:

  • Mass balance error: < 10^-8 (hard), < 10^-3 (soft)
  • Positivity violations: 0 (hard), < 0.1% (soft)

Speed:

  • Single trajectory: < 5 ms (100x faster than scipy)
  • Parameter sweep (10K conditions): < 5 s (1000x faster)
  • MPC optimization: < 100 ms (real-time capable)

Development

Setup

# Install development dependencies
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install

Testing

# Run tests
pytest

# With coverage
pytest --cov=reactor_twin --cov-report=html

Linting & Formatting

# Lint with ruff
ruff check src/

# Format with ruff
ruff format src/

# Type check with mypy
mypy src/

Roadmap

  • Phase 1 (Weeks 1-2): Core Neural ODE + CSTR benchmark ✅
  • Phase 2 (Weeks 3-4): 7 physics constraints + training infrastructure ✅
  • Phase 3 (Weeks 5-6): Advanced DEs (Latent/Augmented/SDE/CDE) ✅
  • Phase 4 (Weeks 7-8): Batch, Semi-batch, PFR + 4 kinetics + 3 benchmarks ✅
  • Phase 5 (Weeks 9-10): Digital twin features + 10-page dashboard ✅
  • Phase 6 (Weeks 11-12): Tests, examples, docs, PyPI release ✅

See ROADMAP.md for details.


Citation

If you use ReactorTwin in your research, please cite:

@software{reactortwin2026,
  author = {Karthikeyan, Tubhyam},
  title = {ReactorTwin: Physics-Constrained Neural Differential Equations for Chemical Reactor Digital Twins},
  year = {2026},
  url = {https://github.com/ktubhyam/reactor-twin}
}

License

MIT License - see LICENSE for details.


Contact

Tubhyam Karthikeyan Email: takarthikeyan25@gmail.com GitHub: @ktubhyam Website: tubhyam.dev


Acknowledgments

Built on:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

reactor_twin-0.1.0.tar.gz (125.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

reactor_twin-0.1.0-py3-none-any.whl (126.3 kB view details)

Uploaded Python 3

File details

Details for the file reactor_twin-0.1.0.tar.gz.

File metadata

  • Download URL: reactor_twin-0.1.0.tar.gz
  • Upload date:
  • Size: 125.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for reactor_twin-0.1.0.tar.gz
Algorithm Hash digest
SHA256 5c2cdf95340b5c8edde939fced9a91570a9e6325d06896d10e1f9f09d4b0e10e
MD5 7fe95e3f22c2fe8d27469f611e3023ef
BLAKE2b-256 4c756a36ccc633e39a2b69840049836348b22bd5f657aff5be05ae49d51950bc

See more details on using hashes here.

Provenance

The following attestation bundles were made for reactor_twin-0.1.0.tar.gz:

Publisher: release.yml on ktubhyam/reactor-twin

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file reactor_twin-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: reactor_twin-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 126.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for reactor_twin-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b6d6b5cad41e23279f7ec395623f748c91db4e285614b28abee841f8c2d17316
MD5 8f5eeda2b52dcec735cebe5964671121
BLAKE2b-256 12046a9cde7231f22c389ce94e388d715998961b66567b5b9c5186c134e0d888

See more details on using hashes here.

Provenance

The following attestation bundles were made for reactor_twin-0.1.0-py3-none-any.whl:

Publisher: release.yml on ktubhyam/reactor-twin

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page