---
name: stochastic-onsagernet
description: "Keep a measured observable and learn which additional coordinates predict its random evolution. Use time-ordered microscopic measurements and known short lags to fit Stochastic OnsagerNet, a reduced Itô diffusion."
---

# Stochastic OnsagerNet

## 1. What this solves

A measured extension can have the same value for two configurations that stretch at different rates. Keep the observable, learn extra coordinates from each microscopic configuration and fit a conditional distribution for their next joint state. The result supplies a drift, a noise amplitude and a potential for the drift.

## 2. When to use

To learn closure, use short time-resolved microscopic trajectory pairs with a known elapsed time and a chosen observable available at both endpoints. For already resolved stochastic coordinates, keep the coordinate map fixed and fit the transition likelihood. The state should plausibly admit a time-homogeneous Markov diffusion over the lags of interest. Include enough independent paths to estimate conditional variation. Split by trajectory before centering or fitting. The dense reference targets small reduced states.

## 3. When not to use (and what to use instead)

| Situation | Use instead |
| --- | --- |
| Only an unordered collection of configurations | Obtain time-ordered data to learn rates. Static density estimation answers a different question. |
| Already-closed deterministic coordinates, negligible process noise | Use deterministic OnsagerNet. |
| The aim is a stationary density and a quantitative steady-state entropy production | For a confined diffusion with a supported unique invariant density, use UIDD on time-ordered data. |
| Only one recorded observable and unresolved memory, no microscopic configurations | Collect additional channels or test a delay-coordinate model and validate temporal residuals. |

## 4. Algorithm

1. Reserve whole trajectories for testing and calculate the chosen observable. Form the covariance of centered training vectors. For positive leading eigenvalues λ and corresponding orthonormal **rows** U, set P = diag(λ⁻¹ᐟ²)U and P† = Uᵀdiag(λ¹ᐟ²). The portable PCA accepts already-centered samples and divides by the number of samples. Use a single shared training mean for an autonomous coordinate map. The toy closure fit uses a fixed calibrated projection and keeps the observable in its original units.

   The paper centers microscopic configurations separately at each training time snapshot. This needs synchronized trajectories and makes the reduced coordinate map implicitly time-dependent. Apply the same time-indexed statistics to held-out paths and keep the time origin when mapping predictions back. The notebook also standardizes the measured extension with the training mean and standard deviation, while PCA whitens the closure coordinates. For scale, the published fast-group mean extension starts near 56 and ends near 247 in the original units. [Paper, Methods](https://www.nature.com/articles/s43588-023-00581-5) · [Authors’ preprocessing and training notebook](https://github.com/MLDS-NUS/DeepLearningCustomThermodynamics/blob/c068669704d37b22202f9318755a2de383342f63/reproduction/OnsagerNet.ipynb)
2. For centered x compute h = Px + e(x), z = [observable, h] and x̃ = P†h + d(h). The residual networks e and d can be nonlinear. Feed only h to the decoder. The PCA reconstruction for comparison is P†Px. These are Eqs. (17–18).
3. Use a lower-bounded scalar potential V(z), M = LLᵀ + αI with α ≥ 0 and W = −Wᵀ. The drift is f = −(M+W)∇V. Learn a separate Brownian amplitude σ(z), with full row rank for the likelihood, in dz = f dt + σ dB (Eq. 5). Take L from the lower triangle of the square network output and R from its strict upper triangle, then set W=R−Rᵀ. The notebook applies a final tanh before taking the triangles, so the entries of L and R drawn from that output lie in (−1, 1). The portable drift takes W after antisymmetrization. The published potential is V=‖U(z)+Γz‖²/2 + β‖z‖² with learned U, Γ and positive β. The paper uses a positive mobility floor α. The reference also permits α=0 when the mobility factor supplies the desired dissipation. The toy fit fixes the observable’s quadratic energy scale and learns the curvature along the hidden coordinate.
4. Encode both ends of each pair with the same parameters. At the start evaluate f, A = σσᵀ and r = z′−z−Δt f. For d state variables the normalized Gaussian negative log likelihood is [d log(2πΔt) + log det A + rᵀA⁻¹r/Δt]/2. Its derivative with respect to f is −A⁻¹r. Use a Cholesky solve. The paper drops additive constants independent of trainable parameters.
5. Write E = ‖x−x̃‖² and B = ‖x−P†Px‖². Add ρ[E + ρ₁ max(0, log E − log B)] to the per-pair likelihood, then average and optimize. The reference follows Eq. (19), with log arguments floored at 10⁻¹⁵ in the working units. The paper describes joint training at ρ = 0.01 and fine-tuning the dynamics at ρ = 0 with the encoder and decoder frozen. The notebook averages its diagonal-noise loss over samples and coordinates. Its reconstruction terms use logs of pooled mean-square errors, weighting the positive log-ratio by 100 and the log reconstruction error by 0.001. [Authors’ training notebook](https://github.com/MLDS-NUS/DeepLearningCustomThermodynamics/blob/c068669704d37b22202f9318755a2de383342f63/reproduction/OnsagerNet.ipynb)
6. Predict ensembles by stepping z forward with independent Gaussian increments σ(z)√Δt ξ. Score conditional means and covariances as well as multistep distributions on held-out paths. Itô's formula gives the mean potential rate E[−∇VᵀM∇V + tr(A∇²V)/2] under the usual integrability conditions. A rising potential along one path is compatible with the model. [Published paper, Methods and Theorem 2](https://pmc.ncbi.nlm.nih.gov/articles/PMC10808076/)

## 5. Parameters

| Parameter | Choice |
| --- | --- |
| Closure dimension | Start with few coordinates. Increase while held-out conditional increments or ensemble predictions improve. Whitening needs positive retained eigenvalues. |
| Δt | Use physical elapsed time for each pair. Test shorter lags to detect Euler bias or measurement noise. |
| ρ, ρ₁ | Inspect reconstruction and transition likelihood separately. Scale input channels consistently. Excessive reconstruction weighting can retain variables irrelevant to prediction. |
| α and σ | α controls deterministic dissipation. Set the diffusion parameterization from conditional increments and check covariance eigenvalues. |

## 6. Applying it to your own code

Port the encoder, the loss and the drift as separate functions. In a neural implementation, differentiate V with respect to z and allow training gradients through both encoded endpoints. Concatenate the chosen observable before the learned coordinates. Return the **normalized** likelihood for the portable interface. If measurement noise is appreciable, estimate its contribution or fit an observation model before interpreting σ.

The toy problem uses a calibrated measuring channel as the linear skip, balanced innovations with exact first two moments and single tanh residuals. It fits both coordinate maps and the potential, mobility, skew and diffusion parameters jointly, then freezes the maps and refines the dynamics. The supplied PCA routine fits general training-centered samples. For a larger model, compute the leading training components using an SVD and fit residual heads with automatic differentiation.

When writing generated code add the comment `stochastic-onsagernet v0.1.0, Chen et al. (2024)`.

## 7. Verification

**Step 1.** Implement the six operations specified in `checks/cases.json`, expose them from `port_adapter.py` in your working directory and run `python3 /path/to/stochastic-onsagernet/checks/check_port.py`. Show its output to the user. The fixtures include correlated diffusion, a nonunit lag, both branches of the reconstruction penalty, PCA scale and a signed drift. The fixed `closure_loss_gradient` case checks the normalized transition and reconstruction loss and its derivatives with respect to the encoder scale, potential curvature and noise scale. Differentiate through both encoded endpoints. The independent property check differentiates the likelihood with respect to drift.

**Step 2.** Compare an observable-only model with the augmented state on the same held-out starts and forecast horizons. Undo any extension standardization and score increments, ensemble spread and relaxation statistics in the same observable units. Whiten one-step innovations with each pair’s model-predicted covariance Δt σσᵀ, or its observable block for cross-model comparisons. Check the whitened covariance and lag correlations. The synthetic closure example fits short pairs whose balanced innovations match the first two Gaussian moments by construction. It checks parameter recovery and observable conditional mean and spread at new starting states.

Supplementary Table 2 reports a **0.388%** relative L² error for the fast group’s mean extension with all 610 training trajectories. The offline check recomputes **0.388077%** directly from the published Figure 2 ensemble means. Reproducing the authors’ training and predictions is outside this check. [Supplementary Table 2](https://pmc.ncbi.nlm.nih.gov/articles/instance/10808076/bin/43588_2023_581_MOESM1_ESM.pdf)

## 8. Failure signatures

| Symptom | Check |
| --- | --- |
| Drift fits but ensembles are too narrow | Check the √Δt amplitude, the σσᵀ product, and whether process noise was inadvertently treated as observation error. |
| Latent likelihood improves while closure coordinates and their noise shrink | A flexible encoder can collapse its hidden coordinates. Scaling k hidden coordinates and their noise by c shifts the negative log likelihood by k log c, which tends to −∞ as c approaches zero. Monitor the final closure variance and constrain its scale. PCA whitening only fixes the linear skip, which the residual can cancel. Compare encoders and dimensions using predictions in the same observable space. Latent likelihood is only comparable in a fixed coordinate system and dimension. |
| Entire ensembles drift in a different direction | Check coordinate ordering and the orientation of W on a signed state. |
| Estimated potential gives a poor equilibrium histogram | This model independently learns mobility and diffusion. A Gibbs stationary law needs additional structure. |

## 9. Files and commands

From the skill directory run `python3 examples/learn_closure.py` for a joint fit. The example prints the expected values in its neighboring text file. `reference/stochastic.py` implements the loss and structure, `reference/pca.py` fits the linear maps, and `reference/closure_demo.py` defines the instrument and fitted model.

Run `python3 checks/make_cases.py` to emit the portable JSON. Run `python3 verify/check_cases.py`, `python3 verify/check_pca.py`, `python3 verify/check_closure.py` and `python3 verify/check_figure2.py` for the fixture, training and source evidence.

## 10. Sources

- X. Chen, B. W. Soh, Z.-E. Ooi, E. Vissol-Gaudin, H. Yu, K. S. Novoselov, K. Hippalgaonkar and Q. Li, *Constructing custom thermodynamics using deep learning*, Nature Computational Science 4, 66–85 (2024). [Paper](https://doi.org/10.1038/s43588-023-00581-5)
- The CSV is an adaptation of Chen et al.’s Figure 2 Source Data. For each of the 1,001 time columns in sheets `Z1_fast_true` and `Z1_fast_pred`, it stores the mean of 500 paths rounded to ten decimal places. The first spreadsheet row contains indices. Original workbook SHA-256 is `4d4d18b1acbd47291b2b00641b90ceb2867a8682a02b7d349357e43bd0f7b023`. [Source workbook](https://media.springernature.com/full/springer-static/esm/art%3A10.1038%2Fs43588-023-00581-5/MediaObjects/43588_2023_581_MOESM4_ESM.xlsx) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · [Authors’ fast-group analysis](https://github.com/MLDS-NUS/DeepLearningCustomThermodynamics/blob/c068669704d37b22202f9318755a2de383342f63/reproduction/prediction/predict_fast.ipynb)
