---
name: onsagernet
description: Learn a deterministic evolution law from time-ordered state pairs in a dissipative physical system. Retain a lower-bounded energy, a dissipative operator, conservative motion and an optional external drive. Use deterministic OnsagerNet when the state or a resolved low-dimensional representation is available.
---

# Learn a deterministic vector field with an energy balance

## 1. What this solves

Fit an autonomous ODE to observed changes of state. Splitting its velocity into dissipative, conservative and driven parts gives an energy balance that a port can check at any state. Yu et al. apply this to oscillators, Lorenz dynamics and reduced convection models.

## 2. When to use

- The input is a collection of ordered vector pairs and positive time gaps. Repeated states under the same conditions have effectively deterministic rates.
- The chosen coordinates resolve the relevant evolution. For high-dimensional data on a low-dimensional manifold, §III.C of the paper couples the ODE to an autoencoder with metric regularization. The example here starts with resolved coordinates.
- Dissipation and an optional constrained drive make sense in these units. Hold out complete trajectories or operating conditions when assessing prediction.

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

| Observation or task | Better fit |
| --- | --- |
| Repeated increments have intrinsic stochastic spread | Fit an Itô diffusion, with a stochastic closure if extra coordinates are needed. |
| Need a uniquely normalized stationary landscape or entropy production | Use timed trajectories and a diffusion model that identifies the stationary density and current. Independent snapshots alone leave the current undetermined. |
| A known ODE only needs a trajectory | Use the time-integration category. |
| The same state has different futures depending on earlier history | Add a measured or learned closure coordinate and validate at several lags. |

## 4. Algorithm

Use Eqs. (3), (9)–(12) and Architecture 1. A shared feature map provides heads for a lift, a matrix and optionally a drive. The portable reference uses one tanh feature layer. Write `hidden = tanh(A*x+b)`, `lift = B*hidden+c+skip*x`, and reshape the affine matrix-head output row by row to a square matrix. Take its lower triangle, including the diagonal, as L and its strict upper triangle as R.

1. Set V = liftᵀlift/2 + β xᵀx. Differentiate with respect to the state, including the linear skip. The gradient is J_liftᵀ lift + 2βx.
2. Assemble M = LLᵀ + αI and W = R − Rᵀ. The vector field is f = −(M+W)∇V + F. The reference supports an affine drive F. Fix it to zero for an unforced system.
3. For each pair (x,y,τ), integrate f with n Heun substeps h = τ/n. At each substep compute a = f(x), b = f(x+h a), then update x by h(a+b)/2. Reevaluate all heads at both stages.
4. Minimize the mean over pairs of ||prediction − y||²/τ². Backpropagate through the state gradient and both stages of every step. The paper uses gradient-based training. The small CPU fit uses centered parameter differences and BFGS.

The continuous-time identity is ∇Vᵀf = −||Lᵀ∇V||² − α||∇V||² + ∇VᵀF. With the drive set to zero it guarantees dissipation only along the continuous-time solution. A numerical rollout can increase energy. For example, for x′ = −x, V = x²/2 and x(0) = 1, a single Heun step of size 3 raises V from 0.5 to 3.125. Choose a rollout method and check energy changes as the step is reduced. [Time integration](https://fhat.dev/categories/time-integration/)

## 5. Parameters

Use nonnegative α and β. The forced-system bounds in Theorem 1 use coercivity and additional growth conditions on the drive. Positive floors can impose artificial damping on conservative components. The oscillator example uses zero floors. Choose feature width, number of substeps and the capacity of the drive on trajectory-level holdouts. Halve the substep size to check numerical bias.

## 6. Applying it to your own code

Keep the time unit with each pair. A normalized state changes the metric in which forces and energies are expressed. The same f can admit several choices of V, M and W. Fix a physical scale or document alignment before comparing learned and physical energy. For a larger model use autodiff and batched operations with the same axis conventions. `reference/onsager.py` accepts arbitrary state size and width, and `spring.py` shows how to train selected weights from observations. Equation (10) uses half the squared lift. The authors’ PyTorch forward uses a whole squared lift and separate biases on both lift maps. To transfer those weights into the paper convention, combine the biases, multiply lift weights and combined bias by √2, and retain β. The architecture check reproduces 120 trainable parameters for the unforced 2D width-12 network and 356 for the forced 3D width-20 network. [Author implementation](https://github.com/yuhj1998/OnsagerNet/blob/32cbb31116cf4244b340497d739a86eb7de9e7a2/Langevin/ode_net.py#L335)

Record `onsagernet v0.1.0, Yu et al. 2021` with the port.

## 7. Verification

1. Export the four functions specified in `checks/cases.json` from `port_adapter.py` in your working directory. Run `python3 /path/to/onsagernet/checks/check_port.py` and show the output. The fixed `spring_loss_gradient` case checks both the loss and its derivatives with respect to all three trainable weights of a one-hidden-unit model. For weights [s, a, c], its lift is s q + a tanh(q), its kinetic energy is v²/2, and its friction is c². Two observed pairs have different time gaps and each uses two Heun substeps. Differentiate the loss with the endpoints held fixed. The verifier cross-checks all three derivatives by complex-step differentiation of an independently written rollout.
2. On new trajectories check signed velocities, energy rate and rollout error at several step sizes. The reference trains three weights on the §IV.A spring, whose exact stiffness 4 and damping 3 lie in its model class. The kinetic scale is fixed. Its unaligned relative energy error is 7.1×10⁻⁷ on held-out states. **We did not reproduce the authors’ Figure 3 result of 0.0063** for their larger network after energy alignment. The local experiment checks coefficient recovery on a smaller model. [Paper, §IV.A and Figure 3](https://arxiv.org/pdf/2009.02327v3#page=10) · [Authors’ Figure 3 training script](https://github.com/yuhj1998/OnsagerNet/blob/32cbb31116cf4244b340497d739a86eb7de9e7a2/Langevin/paper_fig3.sh)

## 8. Failure signatures

Growing unforced energy at the field level suggests a sign error or an indefinite mobility. Good energy decay with motion rotating the wrong way suggests a transposed skew head. Rising error as sample intervals grow can signal unresolved dynamics or too few Heun substeps. A changing energy scale across equivalent fits is a reason to test the field and state the chosen gauge.

## 9. Files and commands

From the method folder run `python3 examples/fit_spring.py`, `python3 verify/check_spring.py` and `python3 verify/check_cases.py`. Run `python3 verify/check_architecture.py` for the published model sizes and the energy-scale conversion. `checks/make_cases.py` prints the portable fixtures. The three learned coefficients in the example control the linear and tanh parts of the potential and the friction factor.

## 10. Sources

Yu, Tian, E and Li, *OnsagerNet*, Physical Review Fluids 6, 114402 (2021). The spring setup, energy alignment and network definitions follow §§III–IV.A. [Published paper](https://doi.org/10.1103/PhysRevFluids.6.114402) · [Open manuscript](https://arxiv.org/abs/2009.02327v3)
