---
name: dyngma
description: Learn how a stochastic state moves and spreads from observations separated by known time gaps. Use DynGMA when the coordinates already describe the relevant state and one Euler–Maruyama Gaussian is inaccurate at the recorded lags. Fits an Itô drift and diffusion with a finite-time mixture likelihood.
---

# DynGMA

## 1. What this solves

When measurements are far apart, the drift and diffusion can change substantially before the next measurement. DynGMA approximates what happens within the gap by composing short Gaussian transition models. Fit the drift and noise by evaluating the resulting mixture at each recorded endpoint.

## 2. When to use

Use timed pairs in coordinates that plausibly form a time-homogeneous Markov Itô diffusion. Lags may differ across pairs. The drift needs a usable state Jacobian. The likelihood assumes a nonsingular covariance in the modeled coordinates. Start with a low-dimensional state and a few mixture stages. Initial states can be away from equilibrium.

Compare a one-step likelihood and a refined approximation on whole held-out trajectories or independent transitions, using their actual lags. Look for material differences in conditional mean, covariance or density. At matched states and lags, test whether older observations still predict the residuals. Persistent history dependence calls for revisiting the coordinates or observation model.

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

| Situation | Use instead |
| --- | --- |
| Only unordered samples are available | Estimate a static density or obtain timed transitions before fitting an evolution law. |
| Matching the observed state still leaves systematic dependence on its history | Identify additional coordinates or fit an observation model. Stochastic OnsagerNet can learn closure when suitable microscopic trajectories are available. |
| A single Euler–Maruyama Gaussian already predicts transitions adequately at the observed lags | Use a one-step likelihood. For an Onsager-structured drift, use [Stochastic OnsagerNet](https://fhat.dev/methods/stochastic-onsagernet/). |
| A stationary landscape, irreversible current or EPR is the primary result | Use UIDD for a diffusion with a supported unique invariant density and a specified reversal. |
| Constraints or degenerate noise make the endpoint law singular in these coordinates | Work in suitable reduced coordinates or use a transition model defined on the actual support. |

## 4. Algorithm

1. Model a $d$-dimensional column vector by $dX=f_\theta(X)\,dt+\sigma_\theta(X)\,dW$, with independent standard Brownian components in $W$. For example, use an $f$ head with $d$ outputs and build a square $\sigma$ from a trainable strict lower triangle and a diagonal $(\sqrt{1+s_i^2}+s_i)/2$ from another head $s$. The likelihood uses the full covariance rate $\sigma\sigma^\top$. [Paper, Eq. (16)](https://arxiv.org/html/2402.14475v2#S3.E16)

   Evaluate the diagonal in the working precision using `r = 0.5 * hypot(s, 1)` and `t = 0.5 * s`. Use `r + t` for $s\ge0$ and `0.25 / (r - t)` for $s<0$. The reciprocal branch avoids cancellation. Evaluate only the applicable branch for each entry, including under autodiff. Check covariance conditioning separately because a positive diagonal can still be too small for a reliable factorization.

2. For each pair $(x,y,\tau)$ with $\tau>0$, choose $K\ge1$ equal mixture stages of length $h=\tau/K$, for example $K=\lceil\tau/h_{\max}\rceil$ with $h_{\max}>0$. Choose $L\ge1$ inner steps of length $\delta=h/L$ per stage. A stage starting at a point $z$ sets $m_0=z$ and $C_0=0$. For $j=0,\dots,L-1$, set $a=m_j+\delta f_\theta(m_j)/2$ and let $J$ have entries $J[i,k]=\partial f_{\theta,i}/\partial x[k]$ evaluated at $a$. With $A=I+\delta J$ and $B=I+\delta J/2$, compute $m_{j+1}=m_j+\delta f_\theta(a)$ and $C_{j+1}=AC_jA^\top+\delta(B\sigma_\theta(a))(B\sigma_\theta(a))^\top$. The stage output is the mean and covariance after the last inner step, $m$ and $C$ with index $L$. [Paper, Eqs. (13)–(14)](https://arxiv.org/html/2402.14475v2#S3.E14)
3. Apply one stage to $x$ and give the resulting Gaussian weight 1. For each later stage and each parent $(w,m,C)$, factor $C=SS^\top$ with lower triangular $S$. Use the point $m$ with weight $1/(d+1)$ and the points $m\pm\sqrt{d+1}\,Se_j$ with weight $1/[2(d+1)]$ each, for $j=1,\dots,d$. Here $e_j$ is coordinate vector $j$, so $Se_j$ takes a **column** of $S$. Advance each point by the stage update from zero covariance. Give each output the parent weight times its point weight. Visit parents in order. Within each, the checker expects the center, then positive axes, then negative axes, both in increasing coordinate order. [Paper, Algorithm 1](https://arxiv.org/html/2402.14475v2#alg1)
4. For each final component $i$, factor $C_i=T_iT_i^\top$ and solve $T_iu_i=y-m_i$. Its log contribution is

   $$a_i=\log w_i-d\log(2\pi)/2-\sum_j\log T_i[j,j]-u_i^\top u_i/2.$$

   Let $a_{\max}=\max_i a_i$. The endpoint log density is $a_{\max}+\log\sum_i\exp(a_i-a_{\max})$. Minimize the mean of its negative over recorded pairs. Differentiate through the stage updates, Cholesky factors, cubature points and Gaussian terms, holding the observed endpoints and stage counts fixed. [Paper, Eq. (17)](https://arxiv.org/html/2402.14475v2#S3.E17)

## 5. Parameters

| Parameter | How to choose it |
| --- | --- |
| $K$ and $h$ | Try $K=1$ first. Raise $K$ when smaller stages improve held-out predictions. With a point start the unpruned mixture contains $(2d+1)^{K-1}$ components. Keep $K$ fixed for each pair during differentiation. |
| $L$ | Check approximation error by refining the inner step while holding $K$ fixed. The mean uses a midpoint evaluation even for $L=1$. |
| Diffusion factor $\sigma_\theta$ | Use a full-row-rank factor. The paper builds a triangular factor with a positive diagonal for state-dependent noise. Condition the covariance in the data's working units. |
| Drift parameterization | Fixed known terms can be kept in the drift. Use an analytic Jacobian or autodiff, including its effect on the covariance. |

## 6. Applying it to your own code

Keep the distinction between $\sigma$, the covariance rate $\sigma\sigma^\top$, and the propagated covariance $C$. With the lower Cholesky factor, the weighted outer products of cubature displacements recover $C$. Taking rows instead would recover $S^\top S$ and change a correlated covariance. The portable reference implements equal stage lengths from Algorithm 1 and dense linear algebra. Its first stage starts from a point, so all cubature points of that stage coincide and it is advanced once; the component count above already reflects this. The pinned authors' code differs from the paper in ways that matter when comparing with it: its cubature helper takes rows of the lower Cholesky factor (so its spread is $S^\top S$ rather than $C$), it uses one stage of length $\tau$ if $\tau$ is shorter than the nominal stage length, or nominal stages followed by a final stage of at least one and less than two nominal lengths otherwise (it counts stages with `int(τ/h−1)` in floating point, so a lag that is an exact multiple of $h$ can end with a final stage of exactly $2h$), its training criterion conditions each later observation on the first point of the series, and it adds $10^{-45}$ to the covariance before factorization. [Authors' stage scheduling](https://github.com/Aiqing-Zhu/DynGMA/blob/ba7e4484fbcad6fc545a23d463bd62a4c95050b9/dynlearner/integrator/sto_int/Gauss.py#L110-L139) · [Authors' cubature helper](https://github.com/Aiqing-Zhu/DynGMA/blob/ba7e4484fbcad6fc545a23d463bd62a4c95050b9/dynlearner/integrator/sto_int/Gauss.py#L147-L168)

For larger models use batch linear algebra and autodiff. The portable two-weight fit uses centered differences. Keep the data split and recorded lags fixed when comparing likelihoods. To predict an endpoint sample at a specified lag, choose a final component with its normalized weight and return $m_i+T_i\xi$ with independent standard normal components in $\xi$.

When you write code using this method, add the comment `dyngma v0.1.1, Zhu and Li (2024)`.

## 7. Verification

**Step 1.** Export `affine_mixture`, `affine_logpdf`, `benes_logpdf` and `training_loss_gradient` in `port_adapter.py`. The scalar Beneš test model used by the last two is defined in the `checks/cases.json` interface: $f(x)=a\cdot\tanh(x)$ and $\sigma=\exp(b)$ for weights $[a,b]$. Follow the interface in `checks/cases.json` and run `python3 /path/to/dyngma/checks/check_port.py` from the directory containing the adapter. Show its output to the user. The fixtures include correlated state-dependent noise, a two-dimensional mixture log density, a surviving tail log density and a fixed two-stage likelihood with two unequal observation lags. The last case checks both weight derivatives. The analytic Brownian moment check exercises the cubature axes and weights.

**Step 2.** Check the component weights, covariance conditioning and held-out conditional predictions by lag. Inspect the fit at smaller $h$ and $\delta$ before trusting estimates of $f_\theta$ or $\sigma_\theta$. For the paper's unit-noise Beneš density comparison, at $x_0=0.5$ and $\tau=1$ the plotted DynGMA density near $y=0$ is about 0.18. The implementation gives 0.176908 with $h=0.5$ and $L=2$. This point check is coarse: the exact density there, 0.1894, is also within 0.01 of the plotted value. The paper shows the curves but reports no integrated errors; computed by this reference against the exact transition on $[-12,12]$, the integrated absolute density errors at that lag are 0.05989 for DynGMA and 0.32182 for the one-step Euler baseline. [Figure 2](https://arxiv.org/pdf/2402.14475v2#page=14)

The separate small fit uses exact transition quantiles from the unit-noise SDE. It compares coefficient recovery and conditional likelihood at unseen starts and lags with a one-step Euler model fitted to the same data. **The authors' neural training result in Appendix C was not reproduced.** It uses noise amplitude 0.3 and much larger training data. [Appendix C, Table 4](https://arxiv.org/pdf/2402.14475v2#page=28)

## 8. Failure signatures

| Symptom | Check |
| --- | --- |
| Correlated directions spread incorrectly while scalar cases pass | Check the columns of the lower Cholesky factor and the $ACA^\top$ and $B\sigma$ factors. |
| A finite tail log density underflows | Combine normalized Gaussian log terms with log-sum-exp before projecting to density. |
| A component covariance is singular despite full-row-rank noise | Reduce the inner step $\delta$ and check the conditioning of $B=I+\delta J/2$. |
| Likelihood rewards a noise scale close to zero | Inspect rank and conditioning of the data and the fitted covariance. Check whether observed noise, hidden state or deterministic coordinates require a different model. |
| Cost grows quickly on longer intervals | Count stages and cubature branches. Check $K=1$ before increasing the mixture size. |

## 9. Files and commands

From the method folder run `python3 examples/fit_benes.py`. The reference kernel and mixture are in `reference/dyngma.py`. See `reference/models.py` for the fixed models and loss and `reference/benes.py` for exact transitions and the toy fit.

Run `python3 checks/make_cases.py` for the portable fixtures. Run `python3 verify/check_cases.py` for fixture and derivative checks, `python3 verify/check_figure2.py` for known-coefficient densities, and `python3 verify/check_fit.py` for coefficient recovery.

## 10. Sources

A. Zhu and Q. Li, *DynGMA: A robust approach for learning stochastic differential equations from data*, Journal of Computational Physics 513, 113200 (2024). See Algorithm 1, Eqs. (13), (14) and (17), Figure 2 and Appendix C. [Published paper](https://doi.org/10.1016/j.jcp.2024.113200) · [Open manuscript](https://arxiv.org/abs/2402.14475v2) · [Pinned authors' implementation](https://github.com/Aiqing-Zhu/DynGMA/blob/ba7e4484fbcad6fc545a23d463bd62a4c95050b9/dynlearner/integrator/sto_int/Gauss.py)
