JAX-EP is a fully differentiable cardiac EP solver and parameter-inversion framework built in JAX [1], enabling GPU-accelerated monodomain simulations and gradient-based inference of personalised tissue and cellular EP parameters. This repository contains the JAX-EP parameter-learning pipeline: recovering cell-kinetics and conductivity parameters from simulated omnipolar electrograms (EGMs) for two ionic models, the modified Mitchell–Schaeffer (mMS, five parameters) and the Courtemanche–Ramirez–Nattel (CRN, six parameters) models. The codebase progresses systematically from cellular-level validation through left-atrial (LA) forward simulation to parameter learning on a full 3D LA manifold.
This README communicates structural, mathematical, and execution information about the JAX-EP project. It serves as the primary technical documentation for repository visitors and contributors.
The repository is organized into four interconnected core components:
- 0D Cellular Validation: Verification of the JAX-based modified Mitchell-Schaeffer (mMS) [1] single-cell EP formulation against an independent openCARP reference trace to ensure core algorithmic and differentiability consistency.
- 2D Spatial Validation: Combined evaluation of the discrete spatial diffusion solver alongside localized ionic kinetics, benchmarked directly via conduction velocity profiles on an idealized 2D flat plate geometry.
- Fully Differentiable Monodomain Solver: Anisotropic Finite Element Method (FEM) propagation mechanics compiled via
jax.jitand accelerated on modern GPU architectures, showcased through high-performance Left Atrial (LA) forward simulations. - Parameter Inversion Pipeline: Benefiting from the differentiability of the JAX-EP monodomain solver, a dual-phase optimization pipeline combining multi-stage Nelder–Mead optimization with L-BFGS-B refinement using exact forward-mode gradients (
jax.jacfwd) was developed to recover cellular-kinetic and conductivity parameters (mMS: five; CRN: six) from clinically motivated omnipolar electrograms (EGMs).
JAX-EP brings scalable GPU-accelerated cardiac monodomain modelling to gradient-based parameter learning, exposing gradients of EP model outputs with respect to model parameters. It achieves:
- Accelerated Forward Models: Over 50x GPU-to-CPU simulation speedups using Custom Crank-Nicolson solver [4] and
jax.jit. - Stable Gradients: Leverages forward-mode automatic differentiation (
jax.jacfwd) and gradient checkpointing (jax.checkpoint) to navigate stiff, long-time ionic chains. - Automated Parameter Optimization: Blindly recovers hidden physiological settings using a multi-stage curriculum.
Traditional cardiac solvers lack efficient, native integration with machine learning or modern optimization tooling. By implementing the physics graph entirely within JAX, this framework allows researchers to:
- Perform high-throughput forward simulations on modern GPU hardware.
- Execute exact parameter estimation without relying on manual trial-and-error tuning curves.
- Maintain complete data tracking under strict blind optimization protocols.
All code blocks run out of a single integrated Python setup. Use the instructions below to configure and run the simulation suite.
Navigate to your project root folder and build the environment using the provided commands:
# Move to repository root
cd path_to_dir\Github_repo
# Create and activate environment
conda create --name jax_env python=3.10 -y
conda activate jax_env
# Install package dependencies
pip install -r requirements.txtEach component runs independently from within its own local subdirectory. Always ensure your environment is active before running scripts:
-
To run JAX-EP solver validation against carpentry bench (0D trace) and CARP 2D reference simulation [3]:
cd benchmark/0D_validation/ python 0D_differentiable_validation.pycd benchmark/2D_validation/ python benchmark2D.py -
To run LA tissue sample (3D cube) using JAX-EP solver and compare CPU/GPU performance (forward simulations), with either ionic model (
IONIC_MODEL=mMSorIONIC_MODEL=CRN):cd forward_model/ export IONIC_MODEL=mMS # or CRN python run_forward.py # activation map and conduction velocity python visualize_forward.py # 2D activation / CV figure python visualize_3d_plotly.py # interactive 3D view (+ CPU/GPU table) python run_cpu_gpu_comparison.py
-
To evaluate gradients using JAX-EP end-to-end differentiable simulations, i.e.
$\partial\mathcal{L}/\partial\theta$ :cd differentiability/3D_cube python run_differentiability_cpu_gpu.py cd differentiability/LA_patch python patch_differentiability_showcase.py
-
To learn parameters from EGM recordings
cd parameter_learning/0D_cellular python run_0D_parameter_recovery.py cd parameter_learning/1D_fiber python run_1D_egm_parameter_recovery.py cd parameter_learning/3D_LA python plot_gt_egm_9cliques.py (visualizing/plotting ground truth) python parameter_learning_patch_geometry.py (mMS, 5 parameters) python crn_parameter_learning_patch_geometry.py (CRN, 6 parameters)
- CS Pacing Forward: 46.2s GPU vs. 2608.2s CPU (56x Speedup)
- LAA Pacing Forward: 46.8s GPU vs. 2738.6s CPU (58x Speedup)
-
Full Jacobian Matrix (
$dAT/dG_{IL}$ ): 90.4s GPU vs. 5096.2s CPU (56x Speedup)
To ensure a comparable test with similar spatial and temporal resolution as compared to the patient LA mesh (dx = 0.351mm median edge length, DT = 0.1ms), the cube (19 × 19 × 1.5 mm, 18,432 nodes) uses dx = 0.2mm and DT = 0.1ms with N_T = 11,100 timesteps (1110 ms), paced from its entire left edge.
The ionic model is selected with a single switch, IONIC_MODEL = "mMS" or "CRN" (top of each script, or as an environment variable). Model-specific settings are in forward_model/cube_validation_3d/ionic_models.py:
| mMS | CRN | |
|---|---|---|
| Parameters | tau_in, tau_out, tau_open, tau_close, G_IL |
g_Na, g_to, g_Kr, g_CaL, g_K1 (multipliers of the nominal CRN values), G_IL |
| Nominal values | 0.3, 5.0, 120, 150, 0.35 | 1, 1, 1, 1, 1, 0.35 |
| Stimulus | 200 (normalised units), 2 ms | 40 pA/pF, 2 ms |
| Activation threshold | Vnorm = 0.13 | −40 mV |
| Conduction velocity (cube) | 0.47 m/s | 0.78 m/s |
| Metric | mMS CPU | mMS GPU | CRN CPU | CRN GPU |
|---|---|---|---|---|
| Forward simulation | 56.656 s | 1.287 s | 253.051 s | 3.639 s |
| GPU speed-up | 44.0× | 69.5× | ||
| Activated nodes | 18,432 | 18,432 | 18,432 | 18,432 |
| Activation-time range | 13.10–54.40 ms | 13.10–54.40 ms | 13.10–36.30 ms | 13.10–36.30 ms |
| Activation map agreement (max |AT difference|) | Identical (0.000 ms) | Identical (0.000 ms) | ||
Timings are warm (post-JIT) forward passes. GPU: NVIDIA A100-PCIE-40GB; CPU: the 8 cores allocated to the job on a 2 × 24-core Intel Xeon node. For both ionic models the GPU produced activation maps numerically identical to the CPU implementation, with a 44× (mMS) and 69.5× (CRN) reduction in forward simulation time.
| mMS | CRN |
![]() |
![]() |
Interactive 3D activation maps: forward_model/outputs/cube_3d_activation_mMS.html and cube_3d_activation_CRN.html.
A central feature of JAX-EP is its end-to-end differentiability, allowing gradients to be propagated through the complete cardiac electrophysiology simulation pipeline. This enables derivatives of simulated electrophysiological observables with respect to cellular and tissue parameters, providing the basis for gradient-based parameter inference and personalised electrophysiological model calibration.
Above differentiability results can be reproduced using run_differentiability_cpu_gpu.py, which uses a 3D cube representative of the full LA simulation, with matching spatial and temporal resolutions. The example uses a 3D tissue cube comprising 18,432 nodes and 36,860 elements, with a spatial resolution of dx = 0.2 mm, a time step of DT = 0.1 ms, and N_T = 11,100 time steps (total simulation time: 1110 ms). The script compares finite-difference (FD) gradients with reverse-mode (jax.grad) and forward-mode (jax.jacfwd) automatic differentiation, and includes the corresponding CPU/GPU benchmark.
For the tested ionic parameters (tau_in, tau_out, tau_open, tau_close) and longitudinal intracellular conductivity (G_IL), jax.jacfwd reproduced the finite-difference gradients with excellent agreement:
| Parameter | FD Gradient | jax.jacfwd |
Ratio |
|---|---|---|---|
tau_in |
-3.0118e-01 | -3.0116e-01 | 0.9999 |
tau_out |
1.8851e-02 | 1.8851e-02 | 1.0000 |
tau_open |
-6.1344e-10 | -6.2751e-10 | 1.0229 |
tau_close |
1.0544e-03 | 1.0544e-03 | 1.0000 |
G_IL |
-3.1939e-04 | -3.2335e-04 | 1.0124 |
The forward-mode derivatives were stable across all tested parameters, with the largest deviation from the finite-difference reference of approximately 2.3%. These gradient comparisons can be reproduced and visualised using plot_gradients.py.
In low-dimensional settings, reverse-mode differentiation (jax.grad) is used directly for parameter learning:
- 0D cell (
parameter_learning/0D_cellular/run_0D_parameter_recovery.py): the APD-restitution fit is driven byjax.gradwith Adam. - 1D fibre, 150 nodes (
parameter_learning/1D_fiber/run_1D_egm_parameter_recovery.py): Phases 1 and 2 usejax.value_and_gradwith Adam. For the final waveform-MSE refinement (Phase 3), the script switches to forward-mode gradients (jax.jvp) with L-BFGS-B, which converged more reliably. The 1D fibre is therefore the clearest example of the hand-over from reverse to forward mode (see 1D Fiber Scale Parameter Learning).
At higher dimensions (the 3D cube and the patient-specific LA patch, thousands of nodes over N_T = 11,100 time steps), jax.grad was not used for parameter learning. For mMS, direct reverse-mode differentiation produced severe gradient amplification through the stiff ionic dynamics: the resulting derivatives differed from the finite-difference reference by several orders of magnitude, making them unsuitable for stable parameter optimization in this configuration. This behaviour was observed consistently across both CPU and GPU executions, indicating that the issue originates from the differentiation of the stiff ionic time integration rather than the computational device. All 3D parameter learning therefore uses forward-mode gradients (jax.jacfwd).
The differentiability extends beyond the transmembrane voltage state to derived electrophysiological observables. A bipolar EGM configuration using two spatially separated electrode regions (0.3 mm inter electrode gap) was included in the benchmark. Forward-mode differentiation again reproduced the finite-difference gradients with close agreement, including for G_IL.
| Parameter | FD Gradient | jax.jacfwd |
Ratio |
|---|---|---|---|
tau_in |
9.7765e-03 | 9.7775e-03 | 1.0001 |
tau_out |
-8.7719e-05 | -8.7848e-05 | 1.0015 |
tau_open |
-2.1321e-09 | -2.1333e-09 | 1.0006 |
tau_close |
-1.5596e-06 | -1.5651e-06 | 1.0035 |
G_IL |
-1.2619e-02 | -1.2620e-02 | 1.0001 |
The bipolar EGM benchmark therefore provides an independent demonstration that gradients can be propagated through the simulation and EGM generation pipeline.
The differentiability benchmark also demonstrates the computational advantage of JAX-EP on GPU hardware. For the complete FD, jax.grad, and jax.jacfwd benchmark:
| Benchmark | CPU | GPU | GPU Speed-up |
|---|---|---|---|
Raw voltage (V² loss) |
1722.8 s | 45.6 s | 37.8× |
| Bipolar EGM | 1866.9 s | 45.9 s | 40.7× |
The GPU implementation therefore provides approximately 38–41× acceleration for the differentiability benchmark while retaining agreement with the reference finite-difference gradients.
The differentiability workflow was also tested on a representative patch extracted from the patient-specific MRI-derived LA anatomy used for the HD-grid omnipolar EGM simulations. The extracted patch contains 2,894 nodes and 5,572 elements and retains the same spatial and temporal discretisation used in the full LA simulation. The patch also includes the HD-grid electrode geometry and fibre information required to generate the simulated omnipolar EGMs.
The complete test can be reproduced using patch_differentiability_showcase.py with the provided patch_geometry.npz. The script generates the ground-truth omnipolar EGMs and compares finite-difference (FD), reverse-mode (jax.grad), and forward-mode (jax.jacfwd) derivatives for the five model parameters: tau_in, tau_out, tau_open, tau_close, and G_IL.
For the representative set3 case, jax.jacfwd remained stable for all five parameters and closely matched the FD reference:
| Parameter | FD Gradient | jax.jacfwd |
Ratio |
|---|---|---|---|
tau_in |
-2.6556e+03 | -2.6730e+03 | 1.0066 |
tau_out |
1.8406e+01 | 1.9386e+01 | 1.0533 |
tau_open |
2.6224e+00 | 2.6142e+00 | 0.9969 |
tau_close |
2.7259e+00 | 2.7538e+00 | 1.0103 |
G_IL |
-2.7231e+04 | -2.7209e+04 | 0.9992 |
Forward-mode derivatives agreed closely with the FD reference across all five parameters with mean absolute deviation ~1.5%, maximum ~5.3%. Both of these were found within the benchmark's stability criterion whereas reverse-mode jax.grad diverged from the FD reference by many orders of magnitude due to the stiff ionic dynamics
This example extends the differentiability test beyond the simplified 3D cube to a geometry extracted directly from the patient-specific LA anatomy, while retaining the simulated HD-grid omnipolar EGM generation pipeline. The patch test and outputs can be reproduced with patch_differentiability_showcase.py; the extracted geometry is provided as patch_geometry.npz.
Overall, these tests establish that JAX-EP provides a fully differentiable cardiac EP simulation pipeline, with forward-mode automatic differentiation providing stable gradients through the stiff ionic dynamics and derived EGM calculations. This differentiability forms the computational basis for the subsequent gradient-based parameter-learning and personalised EP inference framework.
Before performing spatially distributed parameter learning, JAX-EP was validated at the 0D cellular level through blind recovery of the four modified Mitchell–Schaeffer kinetic parameters: tau_in, tau_out, tau_open, and tau_close.
The optimizer was provided only with the target APD restitution curve and did not have access to the ground-truth parameter values. Parameter recovery was performed using GPU-accelerated JAX automatic differentiation on an NVIDIA Tesla P100.
Hardware: NVIDIA Tesla P100-PCIE-16GB
Backend: JAX / CUDA GPU
Optimization iterations: 200
The optimization reduced the restitution loss from 682.85 initially to 0.0833, producing an APD restitution curve that closely matched the ground truth.
Representative points across the S2 restitution range are shown below. The complete restitution curve is generated by the reproducible 0D parameter-learning script.
Across the complete restitution curve (S2 = 300–500 ms), the recovered model achieved a mean absolute APD error of 0.337 ms (0.18%), with a maximum error of 1.096 ms (0.94%).
Although the APD restitution curve was reproduced with high accuracy, the results also demonstrate an important property of inverse cellular modelling: APD restitution alone does not uniquely constrain all ionic parameters. In particular, tau_in and tau_out exhibited substantially different recovered values while producing an almost identical restitution curve.
This 0D experiment therefore provides two complementary validations: (i) JAX-EP can differentiate through the cellular dynamics and recover parameters that strongly influence restitution behaviour, and (ii) matching APD restitution does not necessarily imply unique recovery of the underlying ionic parameters. This motivates the use of better EP observables, including EGM morphology and activation-related features, in the subsequent 3D LA patient specific parameter-learning framework.
The 0D parameter-learning experiment can be reproduced using the corresponding script
'python run_1D_egm_parameter_recovery.pyin the parameter_learning/1D_fiber directory. The generated animation is saved as0D_parameter_recovery.gif`.
The fibre scale framework extends parameter learning from the isolated 0D cell to a 1D spatial fibre, introducing tissue propagation and bipolar EGM generation while retaining the four cellular kinetic parameters: tau_in, tau_out, tau_open, and tau_close.
A 1D fibre with 150 nodes is simulated using the modified Mitchell Schaeffer model with fixed spatial diffusion. Multiple parameter sets are sampled within physiological bounds informed by Corrado et al. [1]:
The search space was defined using bounds inspired by Corrado et al. [1]:
The three phase JAX based optimization uses (\parameter_learning\1D_fiber'run_1D_egm_parameter_recovery.py'):
- Phase 1: Adam optimization of the 0D APD restitution curve.
- Phase 2: Adam optimization of 1D EGM features, including activation recovery interval, activation timing, maximum slew rate, and EGM amplitude, with a reduced restitution loss.
- Phase 3: L BFGS B refinement using forward mode automatic differentiation through the 1D simulation, minimizing the combined bipolar EGM waveform MSE and APD restitution loss.
Bipolar EGMs proved to be an information rich target for constraining ionic parameters. Unlike the 0D restitution fit, which could reproduce APD restitution accurately without uniquely identifying the underlying parameters, the addition of spatial propagation and EGM morphology enabled perfect identification of the four ionic parameters within the tested regimes.
A limitation of this fibre scale experiment is that longitudinal conductivity G_IL is prescribed and not learned. This isolates ionic parameter recovery within the JAX based inversion framework but does not demonstrate simultaneous identification of ionic and tissue conductivity parameters.
The parameter-learning pipeline recovers cellular-kinetic and conductivity parameters from simulated omnipolar EGMs for two ionic models:
- mMS (5 parameters):
tau_in,tau_out,tau_open,tau_close,G_IL - CRN (6 parameters): multipliers of the nominal
g_Na,g_to,g_Kr,g_CaL,g_K1conductances, andG_IL
Both run under a strict blind protocol: the ground-truth parameter values used to generate the target EGMs are never exposed to the optimizer, which sees only the resulting S1 and S2 electrogram signals (S1 at 10 ms, S2 at a 500 ms coupling interval). (parameter_learning/plot_la_patch_9cliques_egm.py can be used to plot the clinical type Omnipolar EGMs simulated using our differentiable JAX-EP monodomain solver)
Parameter learning proceeds in two stages. Phase 1 uses Nelder Mead to fit the S2 electrogram mean squared error across all nine cliques (for mMS as a curriculum that sequentially adds centre clique shape derived features: S1 and S2 activation recovery interval, activation time, slew rate, and peak to peak amplitude, followed by the S1 electrogram mean squared error; for CRN with simplex restarts). Phase 2 refines the resulting fit using L BFGS B with exact gradients computed by forward mode autodiff (jax.jacfwd), minimising the combined S2 and S1 mean squared error, with the S1 term weighted at half the S2 term.
Simulation settings. Both models run on the same extracted patch (patch_geometry.npz, 2,894 nodes) with DT = 0.1 ms and four ionic sub-steps per half step, in float64. mMS uses β = 100 cm⁻¹. CRN uses β = 140 cm⁻¹ and a stimulus of 20 pA/pF, with two numerical changes for stable differentiation of the CRN model: the hard −40 mV switch in the INa h/j gates is replaced by a sigmoid blend of width 0.5 mV (CRN_SMOOTH_MV=0.5), and the removable 0/0 points of the rate functions are evaluated by their exact limits (CRN_SAFE_POLES=1).
The two phase strategy consistently recovered the underlying cellular and tissue parameters across all three tested physiological regimes for both ionic models:
| Ionic model | Set I MAPE | Set II MAPE | Set III MAPE | Mean MAPE |
|---|---|---|---|---|
| mMS (5 parameters) | 0.09% | 0.10% | 0.06% | 0.08% |
| CRN (6 parameters) | 0.02% | 0.03% | 0.01% | 0.02% |
All parameters were recovered to subpercent accuracy in every set, for both models.
| Case | Phase 1 Loss | Phase 2 Loss | CPU Wall Time | GPU Wall Time (NVIDIA Tesla T4) |
|---|---|---|---|---|
| set1 | 9.4e-5 | 1.2e-9 | 43.3 min | 7.1 min |
| set2 | 2.5e-5 | 9.3e-10 | 143.4 min | 17.0 min |
| set3 | 4.5e-5 | 4.1e-10 | 75.1 min | 4.1 min |
| Case | Ground truth [g_Na, g_to, g_Kr, g_CaL, g_K1, G_IL] |
Learned | MAPE |
|---|---|---|---|
| set1 | 1.15, 0.85, 1.15, 0.85, 1.20, 0.200 | 1.150, 0.850, 1.149, 0.850, 1.200, 0.2000 | 0.02% |
| set2 | 0.85, 1.15, 0.85, 1.15, 0.80, 0.200 | 0.851, 1.150, 0.851, 1.150, 0.800, 0.1999 | 0.03% |
| set3 | 1.10, 1.10, 0.90, 0.90, 0.90, 0.200 | 1.101, 1.100, 0.900, 0.900, 0.900, 0.2000 | 0.01% |
All CRN fits started from the nominal conductances (all multipliers 1.0) and G_IL = 0.225.
These results demonstrate near exact recovery of the target parameters from simulated omnipolar electrogram waveforms for both a phenomenological (mMS) and a detailed biophysical (CRN) ionic model. They can be reproduced from parameter_learning/3D_LA/ with parameter_learning_patch_geometry.py (mMS) and crn_parameter_learning_patch_geometry.py (CRN), which use the same extracted patch_geometry.npz geometry as the LA patch differentiability benchmark above and the target EGMs in egm_pipeline_for_jax_set1/2/3/.
| Feature | Details |
|---|---|
| Journal | Scientific Reports |
| Article Type | Research Article |
| Status | 🕒 Revised manuscript submitted — Under Review |
| Submission ID | af513ee8-0cb8-4b37-acaf-48f025f84f16 |
| Submission version | v3.1 (revised) |
Authors:
Ovais Ahmed Jaffery¹*, Mahmoud Ehnesh², H Valli¹, Gregory Slabaugh¹, Edward J. Vigmond⁴, Shouvik Haldar²,³, Caroline H. Roney¹
Affiliations:
- ¹ Queen Mary’s Digital Environment Research Institute (DERI), London, UK
- ² Cardiovascular Imaging Department, Royal Brompton & Harefield Hospitals, Guy’s and St Thomas’ NHS Foundation Trust, London, UK
- ³ National Heart and Lung Institute, Imperial College London, London, UK
- ⁴ IHU Liryc, The Heart Rhythm Disease Institute, Fondation Bordeaux Université, Pessac, France
*Corresponding author: o.jaffery@qmul.ac.uk
This repository provides the official implementation and computational framework described in our submitted study. JAX-EP leverages the high-performance computing capabilities of JAX to introduce a fully differentiable monodomain solver designed for cardiac electrophysiology. By tracking cellular dynamics across spatial dimensions with automatic differentiation, this framework unlocks efficient parameter-learning workflows and inverse modeling.
Note
The revised manuscript (submission version v3.1) has been submitted to Scientific Reports and is under review. The code in this repository contains representative examples with functional parameter learning, and updates will be pushed to match any further revisions. Clinical data from the HEAT-AF investigation [5] has been withheld from this repository to comply with patient privacy laws and data-sharing restrictions.
For individual component deep-dives, mathematical validations, structural nuances, and complete data formats, refer to the relevant text files located directly within each subfolder.
- R. Newbury et al., "A Review of Differentiable Simulators," in IEEE Access, vol. 12, pp. 98114-98132, 2024, doi: 10.1109/ACCESS.2024.3425448.
[1] Bradbury, J., Frostig, R., Hawkins, P., Johnson, M. J., Leary, C., Maclaurin, D., Necula, G., Paszke, A., VanderPlas, J., Wanderman-Milne, S. & Zhang, Q. (2018). JAX: composable transformations of Python+NumPy programs. Version 0.3.13. https://github.com/google/jax
[2] Corrado, C. & Niederer, S. A. (2016). A two-variable model robust to pacemaker behaviour for the dynamics of the cardiac action potential. Mathematical Biosciences, 281, 46–54.
[3] Plank, G., Loewe, A., Neic, A., Augustin, C., Huang, Y.-L., Gsell, M. A. F., Karabelas, E., Nothstein, M., Prassl, A. J., Sánchez, J. & others (2021). The openCARP simulation environment for cardiac electrophysiology. Computer Methods and Programs in Biomedicine, 208, 106223.
[4] Sundnes, J., Lines, G. T., Cai, X., Nielsen, B. F., Mardal, K.-A. & Tveito, A. (2007). Computing the Electrical Activity in the Heart. Springer, 1.
[5] Valli, H., Ehnesh, M., Coveney, S., Jones, D. G., Chen, Z., Hussain, W., Markides, V., Nanthakumar, K., Wong, T., Roney, C. & others. (2025). High Density Evaluation of the Arrhythmogenic Substrate in Atrial Fibrillation (HEAT-AF). Heart Rhythm O2.










