Lyapunov exponents: flowtracks.lyapunov¶
Overview¶
The module estimates how fast neighbouring fluid elements separate, from Lagrangian trajectories. Three estimators are provided, which answer different questions and should not be expected to agree:
Function |
Quantity |
Output |
|---|---|---|
|
mean exponential growth rate of pair separation (FTLE of pair dispersion) |
one number plus the growth curve |
|
FSLE: growth rate as a function of separation scale |
one value per length scale |
|
FTLE field on a grid, from the flow-map gradient |
3D field, with per-node diagnostics |
|
ridges (candidate LCS) of an FTLE field |
boolean mask on the same grid |
All three take a list of Trajectory objects
whose time() holds integer frame numbers, and return an
xarray.Dataset. Positions are in metres. The time between frames is
given by the argument dt [s].
The figures on this page are produced by examples/lyapunov_demo.py
(uv run python examples/lyapunov_demo.py). The real-data figures use the
tracers in data/tracers (500 fps, two-phase turbulence experiment, see
data/readme.txt).
Warning
Lyapunov exponents from PTV data are easy to compute and easy to get wrong. The numbers depend on the measurement noise, on which particles happen to be tracked for long enough, and on choices of scale and window made by the user. Read Cautions (please read) before quoting a value.
Quick start¶
from flowtracks.io import trajectories_ptvis
from flowtracks import lyapunov
trajs = trajectories_ptvis('data/tracers/ptv_is.%d', first=10001,
last=10200, frate=500, traj_min_len=8)
dt = 1 / 500
# Pair-based exponent: pairs that start 2-4 mm apart, fit lags 8..20.
ftle = lyapunov.finite_time_lyapunov(
trajs, r_min=2e-3, r_max=4e-3, dt=dt, max_lag=20, fit_lags=(8, 20),
min_overlap=8)
print(float(ftle.lyapunov), 'per second')
# Finite-size exponent, thresholds 2 mm * 1.3**n.
fsle = lyapunov.finite_size_lyapunov(
trajs, 2e-3, 4e-3, ratio=1.3, num_scales=8, dt=dt, min_overlap=8)
# Eulerian FTLE on a grid, window from frame 10050 to 10056.
import numpy as np
grid = (np.linspace(-0.01, 0.01, 17), np.linspace(-0.008, 0.008, 13),
np.linspace(-0.08, -0.06, 9))
field = lyapunov.eulerian_ftle(
trajs, grid, 10050, 10056, radius=6e-3, dt=dt, position_error=20e-6)
good = field.ftle.where(field.valid) # NaN where not trustworthy
Pair-based estimators¶
Method¶
Both pair-based estimators start from the same step (find_pairs()):
Every frame is scanned with a KD-tree. A pair of trajectories is accepted at the first frame in which both exist and their separation is within
[r_min, r_max]. That frame is the pair’s start,r(0) = r0.A pair is kept only if it shares at least
min_overlapframes from its start on.The separation
r(tau)is followed over the frames in which both trajectories exist (pair_separations()). Lagtauis the offset from the start frame.
Note that pair selection picks any two particles that happen to be close, not particles known to be neighbours for a reason. In a real flow that is the point (it is how pair dispersion is defined), but in a synthetic test it means unrelated particles must be kept far apart, or they enter as spurious pairs that do not separate (we found this the hard way: with 150 synthetic pairs packed in a 10 cm box, 95 spurious pairs appeared and biased the exponent from 5.0 to 3.3).
Finite-time exponent¶
For each lag the average of the logarithmic growth, \(\langle \ln
(r(\tau)/r_0) \rangle\), is taken over all pairs that still exist at that lag.
If the separation grows exponentially, \(r = r_0 e^{\lambda \tau}\), that
average is a straight line of slope \(\lambda\), and the exponent is the
least-squares slope over the window fit_lags.
Synthetic check (known \(\lambda = 5\ \mathrm{s^{-1}}\), 150 pairs, position noise 0.1 mm, 500 fps): the estimate is 5.0004 \(\mathrm{s^{-1}}\).
Panel (b) shows the curve and the fit; (c) shows that the FSLE of a pure exponential is flat and equal to \(\lambda\). Only two scales appear because these pairs start at 4-7 mm, and a pair cannot be timed from a threshold below its initial separation.
On the real tracers (\(r_0\) = 2-4 mm, 18253 pairs, fit window 8-20 frames = 16-40 ms):
Panel (b) is not a straight line from the start. For the first ~8 frames the mean log growth is flat or slightly negative: at these small scales and short times the relative motion is not an exponential separation, and measurement noise at small
r0also contributes. Fitting lags 1-6 gives about 1.1 \(\mathrm{s^{-1}}\); fitting lags 8-20 gives 5.9 \(\mathrm{s^{-1}}\). The window is the answer; choose it by looking at this curve, and report it.The number of pairs falls with lag (18253 at lag 0, 1779 at lag 20) because tracks end. The pairs at long lags are the ones whose tracks lived long.
Finite-size exponent¶
Thresholds \(\delta_n = r_{min}\rho^n\) are laid out, with
\(\rho\) = ratio. For each pair that starts below \(\delta_n\), the
first-passage times (linearly interpolated between frames) at which the
separation reaches \(\delta_n\) and \(\rho\delta_n\) are measured. Their
difference is \(T(\delta_n)\). Then
with the average over pairs that completed the amplification. Unlike the finite-time exponent it does not depend on a window, and is not tied to one initial separation. It is what to use to ask at which scale separation is exponential (\(\lambda\) is constant in \(\delta\)) and at which it is not.
The real-data result in panel (c) above is about 18-21 \(\mathrm{s^{-1}}\) at \(\delta\) = 2.6-7.4 mm. The number of pairs that completed the amplification is 772, 1175, 881, 182 and 20 at those scales, and only 2 at the last point (9.7 mm, value 13.7), which should be disregarded. This does not agree with the 5.9 \(\mathrm{s^{-1}}\) of the finite-time estimate, and it should not be expected to. The most likely reason is a selection effect specific to the FSLE with short tracks: a pair counts only if it was tracked long enough to complete the amplification, so pairs that separate slowly tend to drop out before they are counted. Treat the absolute FSLE values from short tracks as an upper bound until checked on longer data.
Parameters¶
r_minMust be well above the position error. Position noise is amplified in the ratio \(r/r_0\) at small separations, which biases the exponent. As a rule of thumb, take
r_minat least 20 times the position error.r_maxControls how many pairs there are. Larger gives more statistics but mixes scales; the finite-time exponent then averages over a range of \(r_0\).
max_lag/fit_lagsChoose the fit window from the curve (see above), not by default. The default window (lag 1 to the longest) is only appropriate if the curve is straight from the start, as in the synthetic case.
min_overlapPairs shorter than this are discarded. Raising it removes noisy short pairs but increases the survivorship bias.
Eulerian FTLE¶
Note
The Eulerian FTLE is the least robust estimator in this module, and the one most likely to produce attractive but meaningless pictures. The function is deliberately conservative: it returns NaN wherever a check fails, and returns diagnostics next to every value. Do not use the FTLE values without looking at the diagnostics.
Definition¶
Let \(\Phi_{t_0}^{t_0+T}\) be the flow map: it takes the position \(\mathbf{x}_0\) of a fluid particle at time \(t_0\) to its position \(\mathbf{x}_1\) at time \(t_0+T\). The deformation gradient is
and the right Cauchy-Green tensor is \(C = F^{\mathsf T} F\). The FTLE at \(\mathbf{x}_0\) is
the largest stretching rate of an infinitesimal material line that starts at \(\mathbf{x}_0\). A negative window (\(t_{end} < t_{start}\)) gives the backward FTLE. Ridges of the forward FTLE field are commonly used as indicators of repelling Lagrangian coherent structures, and ridges of the backward field as attracting ones. The field is “Eulerian” because it is reported on a fixed grid of initial positions \(\mathbf{x}_0\).
Properties worth keeping in mind (they are used in the diagnostics below):
For an incompressible flow, \(\det F = 1\), so \(\sigma_{\max} \ge 1\) and the exact FTLE is never negative.
For a short window, \(F \approx I + T\nabla\mathbf{u}\), and the FTLE tends to the largest eigenvalue of the strain-rate tensor \(S = \tfrac12(\nabla\mathbf{u}+\nabla\mathbf{u}^{\mathsf T})\). In that limit the result is not a Lagrangian-transport quantity at all, only the instantaneous strain rate; rotation does not contribute at first order.
FTLE is a property of a finite window. Changing \(t_0\) or \(T\) changes the field, and for unsteady flow there is no “true” value to converge to.
How it is estimated from PTV data¶
PTV does not measure the flow map on a grid. It measures positions of
scattered particles. eulerian_ftle() proceeds as follows:
Scattered flow map (
flow_map()). Keep only the trajectories that exist at botht_startandt_end. Their positions at these two frames are the pairs \((\mathbf{x}_0^{(i)}, \mathbf{x}_1^{(i)})\).Neighbourhoods. For every grid node \(\mathbf{g}\), collect the particles with \(|\mathbf{x}_0^{(i)}-\mathbf{g}| < R\) (
radius).Local linear fit. Fit, by weighted least squares,
\[\mathbf{x}_1^{(i)} \approx \mathbf{b} + F\,(\mathbf{x}_0^{(i)} - \mathbf{g}),\]with tricube weights \(w_i = (1-(r_i/R)^3)^3\). The fitted \(F\) is the deformation gradient at the node, and the offset \(\mathbf{b}\) is the (smoothed) displacement.
FTLE \(= \ln\sqrt{\lambda_{\max}(F^{\mathsf T}F)}/|T|\).
Validity checks and diagnostics (next section), evaluated per node.
Differentiating noisy scattered data is what makes this estimator delicate: \(F\) is a derivative of the measured map.
Validity checks¶
A node’s results are NaN, and valid is False, unless all of these hold:
n_points >= min_neighborsAt least
min_neighbors(default 12; the fit has 4 coefficients per component, so 5 is the absolute minimum) particles in the neighbourhood.condition <= max_conditionThe ratio of the largest to the smallest singular value of the (weighted, centred) neighbour offsets. A value near 1 means the neighbours surround the node isotropically. A large value means they lie in a plane, or on a line, and \(F\) is not determined in some direction. Default 10.
- centroid offset \(\le\)
max_offset\(\cdot R\) The weighted centroid of the neighbours must be close to the node. Where the data ends (edge of the measurement volume, or a hole without tracers), the fit extrapolates rather than interpolates, and the result is biased. For tricube weights a node exactly at a straight data edge has an offset of 0.27 \(R\), a node outside the data has more, and a full neighbourhood has about 0. Default 0.25, so nodes at or beyond the edge are rejected, as are very lopsided sparse neighbourhoods.
Diagnostics returned with the field¶
det_FFor incompressible flow it must be 1. Its distance from 1 is a measure of how wrong \(F\) is, caused by noise, by the flow map not being linear over \(R\), or by a poor neighbourhood. This is the most useful single check, and it is free. Mask FTLE values where ``det_F`` is far from 1 (for example, outside 0.8-1.2 for the example below), and make that criterion explicit in whatever you publish. Note that it is a necessary condition, not a sufficient one: a wrong \(F\) can still have \(\det F \approx 1\).
fit_residual_rms[m]The weighted RMS of the local-fit residuals. If it is much larger than the position error, the flow map is not linear at the scale \(R\) (or there is a data problem), and the FTLE is dominated by the model error.
ftle_noise_floor[1/s] (ifposition_erroris given)A first-order estimate of how much the FTLE is uncertain due to position noise alone. Computed from the fit itself: the covariance of the least squares coefficients, \(\sigma^2 M^{-1}(A^{\mathsf T}W^2A)M^{-1}\) with \(M=A^{\mathsf T}WA\), the typical error of one entry of \(F\), divided by \(|T|\). FTLE values not well above this floor are noise. This floor does not include the model error (see
fit_residual_rms), the survivorship bias, or errors inposition_erroritself, which is an input you must supply and justify.n_points,conditionAs above.
Validation on a known flow¶
The estimator was tested against the exact answer using a steady 2D Taylor-Green flow (cell width 20 mm, \(T\) = 0.4 s) seeded with 40000 random particles carrying 20 \(\mu\mathrm{m}\) position noise. The reference was computed from the exact flow map by finite differences. The nodes are on a plane through the seeded slab.
The three estimates differ only in radius, and show the central
trade-off of the method:
R = 1.5 mm. Spatial resolution is good and the ridges are sharp, but neighbourhoods are small and noisy, and 31% of the nodes (white) are rejected by the validity checks.
R = 3 mm. All nodes valid, RMS error 0.41 \(\mathrm{s^{-1}}\) against a ridge value of about 7. The ridge is already visibly wider and lower than the exact one. (The R = 1.5 mm RMS error, 0.22, is lower only because it is computed over the 69% of nodes that were not rejected; the comparison of errors across radii is not like for like.)
R = 6 mm. The field looks smooth and complete, which is exactly the danger: it is smeared, the ridge peak is underestimated by roughly a third, and the RMS error is the largest (0.75 \(\mathrm{s^{-1}}\)). A larger radius always gives a prettier picture, not a more accurate one.
The linear fit has a bias that grows with \(R\) (the flow map’s curvature, which for large \(T\) is concentrated exactly at the ridges) and a variance that grows as \(R\) shrinks. There is no setting that is right for all flows.
Real tracers¶
The same estimator on the real tracers (window 10050 to 10056, i.e. 6 frames = 12 ms, \(R\) = 6 mm, assumed position error 20 \(\mu\mathrm{m}\)):
What this shows, and what it does not:
Only 225 of 14035 trajectories span the 12 ms window, and 35% of the grid nodes (696 of 1989) pass the validity checks (median 21 particles in the neighbourhood). Panel (d): the longer the window, the fewer the survivors and valid nodes. Panel (a) has holes where the checks failed.
Panel (b): the median \(\det F\) is 1.00, with a spread of about 0.82-1.16 (5th-95th percentile). The incompressibility check is passed in the median, with a spread of order 15%. That is a reasonable sign, not a proof.
The median FTLE is about 10.8 \(\mathrm{s^{-1}}\) (5th-95th percentile 4.3-17.8), and it is almost independent of the window in panel (c), from 4 to 16 ms. This is what the theory above predicts for a window much shorter than any flow time scale: the value is essentially the largest strain rate, not a finite-time Lagrangian exponent. It carries no Lagrangian coherent structure information.
The noise floor is about 0.3 \(\mathrm{s^{-1}}\), so position noise at the assumed level is not the limiting factor. But the median
fit_residual_rmsis about 440 :math:`mumathrm{m}`, more than twenty times the assumed position error: the flow map is not well described by a linear fit over 6 mm. The dominant uncertainty is the model, not the noise, and the noise floor is therefore an optimistic bound.The real tracks are too short for anything but this near-instantaneous limit. To get actual finite-time FTLE ridges, much longer trajectories are needed (or stitching, see
flowtracks.stitching; stitching adds its own uncertainty, which is not propagated here).
Ridge extraction¶
Ridges of the forward (backward) FTLE field are the usual candidates for
repelling (attracting) Lagrangian coherent structures (LCS): the barriers that
organise transport. ftle_ridges() extracts them from the output of
eulerian_ftle().
Warning
An FTLE ridge is not the same thing as an LCS. It is neither necessary nor sufficient (a ridge can sit on a region of strong shear that no fluid crosses transversally, and a genuine LCS can be missed by a ridge criterion). It is a candidate. What is found also depends on the window, the radius, the smoothing and the thresholds. And the field underneath inherits every caution of the Eulerian FTLE above.
Definition¶
The second-derivative ridge definition is used. Let \(f\) be the (smoothed) FTLE field, \(H = \nabla\nabla f\) its Hessian and \(\mathbf{n}\) the eigenvector of \(H\) with the most negative eigenvalue \(\ell_{\min}\). A point is on a ridge if
that is, \(f\) is stationary and concave across the ridge. In 2D the ridges are curves, in 3D surfaces. They are found on the grid as follows:
Smoothing. The field is smoothed with a Gaussian (
smooth, in grid nodes), using only valid nodes (a normalised convolution, so holes do not pull the field toward zero). Differentiating twice amplifies noise, so some smoothing is required; it also widens ridges and can move them.Hessian. By finite differences on the grid (so the grid must be regular), giving \(\mathbf{n}\) and \(\ell_{\min}\) at every node.
Non-maximum suppression. The discrete form of \(\nabla f\cdot \mathbf{n}=0\): a node is kept if \(f\) there is not smaller than \(f\) one grid step away on either side along \(\mathbf{n}\) (linearly interpolated). This yields ridges one node thick.
Thresholds. Only nodes with \(\ell_{\min} < -\)
min_curvatureand \(f \ge\)min_ftleare kept. Without a threshold on \(f\), every weak maximum in the noise is a “ridge”. By defaultmin_ftleis a percentile (min_percentile) of the valid values: this is a choice about how much of the field you call a ridge, not a statement about the physics. Prefer to give an absolutemin_ftlethat you can justify (for instance from theftle_noise_floor).Border. The outermost layer of nodes never carries a ridge, because a maximum cannot be verified without neighbours on both sides. Before this was added, the test below produced false ridges along the grid edge.
Singleton dimensions are ignored, so a single plane of a 3D grid gives ridge lines, and a volume gives ridge surfaces.
Validation on a known flow¶
The same Taylor-Green setup as above: its separatrices (the lines where the
FTLE ridges must be) are known exactly, \(x, y \in \{0, L/2, L\}\) with
\(L\) = 40 mm. The full chain is exercised: noisy scattered particles, then
eulerian_ftle(), then ftle_ridges().
R = 3 mm and 6 mm: the ridge nodes (127 and 95) lie on the separatrices with a median error of 0.3 mm, a small fraction of the radius, and the cross is recovered.
R = 1.5 mm: only 25 scattered nodes, because 31% of the field is invalid (white): the neighbourhoods are too sparse. Few and fragmentary ridges are the result, not a poor extractor.
What is missed. The ridges stop short of the ends of the lines, where the FTLE falls below the threshold, and there is a gap at the crossing. At a crossing the Hessian has two equally negative eigenvalues, so the normal direction is not defined, and the criterion fails there. Ridge junctions are not captured by this method.
The automated tests (tests/test_lyapunov.py) check the extractor on
analytic fields (a line, a tilted line with noise, a cross, a plane in 3D, a
valley that must not be reported, fields with holes, flat and monotonic fields
that must give nothing), and the whole chain on the Taylor-Green flow: at least
95% of the ridge nodes within one radius of a separatrix, median error under
half a radius, and most of the interior separatrix nodes with a ridge nearby.
The real tracers give no ridges¶
On the real tracers (the 12 ms window and R = 6 mm of the Eulerian section) the extractor finds 1 ridge node. As a control, shuffling the FTLE values randomly over the same valid nodes, 50 times, gives on average 1.9 (range 0-6). So the result is indistinguishable from chance. This is the expected outcome: at that window the FTLE is essentially a strain rate (see above), and there is no coherent structure for the ridge to find. Ridges from such a field should not be reported. Control experiments of this kind (a shuffled or noise-only field through the same pipeline) are a good habit for any ridge claim.
Cautions (please read)¶
These apply to all three estimators unless stated.
- Measurement noise biases the exponent upward.
Zero-mean errors do not average out: the largest singular value of a matrix is a convex function of its entries, so errors in \(F\) increase \(\sigma_{\max}\) on average. Pair estimators have the same problem at small \(r_0\). The error is therefore not symmetric: noisy data produces larger exponents. Use
position_errorand keep the scales well above it.- Survivorship bias.
Every estimator here uses only the particles that were tracked for the whole window (or pair lifetime). Tracks are lost where the flow is most interesting: fast, strongly strained regions, high out-of-plane motion, or where the seeding is dense and ambiguous. The surviving sample is not a random sample of the flow, and the direction of the resulting bias is not known in general. The FSLE is especially exposed (see the real-data comparison above), and so is the Eulerian FTLE: the valid nodes are not a random subset of the grid either. Always report the number of trajectories used (it is stored in
attrs) and the fraction of valid nodes.- Only valid nodes mean something; coverage is not uniform.
Do not fill the NaN nodes in by interpolation, and do not average the field over the domain without saying what was excluded. The valid region is biased towards where the seeding is dense.
- The result depends on the window and on the radius.
The Eulerian FTLE depends on \(t_0\), on \(T\) and on \(R\); the pair estimators depend on the fit window and on
r_min/r_max. Show the dependence (as in panels (c) and (d) of the real-data figure) before claiming a value. A value that changes when the window changes is telling you something about the window.- A short window gives the strain rate, not a Lagrangian exponent.
See the definition section. Ridges and Lagrangian coherent structures only appear when \(T\) is long compared to the strain time-scale, i.e. when \(\lambda T\) is of order 1 or more. PTV trajectories are often shorter than that.
- The estimate is for the tracers, not necessarily for the fluid.
Inertial particles do not follow the flow map of the fluid. Use tracers.
- Time dependence.
For unsteady flow, FTLE ridges are not material barriers in a strict sense. They are indicators. The ridge extraction itself (e.g. ridge tracking, thresholds on \(\nabla\mathrm{FTLE}\)) is not done here and requires its own care.
- Ridges are candidates, and depend on the thresholds.
See the ridge section. Report
smooth,min_ftle(or the percentile) and the window. Run a control (shuffled or noise-only field) before interpreting a ridge, as done there for the real tracers.- No built-in notion of truth.
det_F,fit_residual_rmsand the noise floor catch several failure modes but not all. In particular, a smooth but wrong field (too large \(R\), in the validation figure) can pass every check. When possible, validate on a synthetic flow with the same seeding density, noise and track lengths as the real data, as done above.
Recommended workflow for the Eulerian FTLE¶
Count the trajectories that span your window (
flow_map) before doing anything else. If there are not at least a few hundred over the volume, stop.Pick \(R\) so that the neighbourhoods hold at least ~20-30 particles and so that \(R\) is clearly smaller than the structures you hope to see. Try three values of \(R\) and compare, as in the validation figure.
Look at
valid,det_Fandfit_residual_rmsbefore looking at the FTLE. Mask ondet_Fand state the criterion.Compare with
ftle_noise_floor.Repeat for several windows and several start frames.
Validate on synthetic data built to mimic your experiment.
Only then extract ridges, with an absolute threshold, and run a control.
Reference¶
Lyapunov-exponent estimates from Lagrangian trajectories (issue #65).
Three estimators are provided. They answer different questions and should not be expected to agree.
finite_time_lyapunov - the mean exponential growth rate of the separation
of close pairs, <ln(r(t)/r(0))> / t, fitted over a lag window (the
finite-time Lyapunov exponent, FTLE, of pair dispersion).
finite_size_lyapunov - the finite-size Lyapunov exponent (FSLE),
ln(rho) / <T(delta)> where T(delta) is the time for the separation to
grow from delta to rho * delta. Unlike the FTLE it does not depend on a
fit window or on one initial separation.
eulerian_ftle - the FTLE field on a regular grid, from the gradient of
the flow map. This one needs much more care than the pair-based estimators;
read its docstring and doc/lyapunov.rst before using it.
ftle_ridges - extracts the ridges (lines in 2D, surfaces in 3D) of an FTLE
field, the usual candidates for Lagrangian coherent structures. Ridges of a
noisy, threshold-dependent field are candidates only; see the documentation.
All take a list of Trajectory objects and
return an xarray.Dataset.
With 3D-PTV data the separations are noisy at small scales, so choose
r_min well above the position error, otherwise the exponent is biased high.
- flowtracks.lyapunov.find_pairs(trajects, r_min, r_max, min_overlap=2)[source]¶
Find pairs of trajectories that come within a given distance range.
For every pair of trajectories, the first frame in which both exist and the separation is in
[r_min, r_max]is taken as the pair’s start.Arguments
trajects: a list of Trajectory objects. Theirtime()must be integer frame numbers (floats holding integers are accepted).r_min, r_max: range of initial separations to accept, [m].min_overlap: the minimum number of common frames, including the first, that a pair must share from its start on, to be accepted.
Returns
pairs: (p, 2) int array, indices intotrajectsof each pair (first index < second index).start_frames: (p,) int array, the frame number at which each pair starts.
- flowtracks.lyapunov.pair_separations(trajects, pairs, start_frames, max_lag=None)[source]¶
Follow the separation of each pair from its start frame.
Returns
A list with one
(lags, r)tuple per pair:lagsare the integer frame offsets from the pair’s start (the first one is 0) andrthe separation at those frames, [m]. Only frames where both trajectories exist are included.
- flowtracks.lyapunov.finite_time_lyapunov(trajects, r_min, r_max, dt=1.0, max_lag=None, fit_lags=None, min_overlap=3)[source]¶
Finite-time Lyapunov exponent from the growth of pair separation.
For each lag
tauthe mean ofln(r(tau) / r(0))over all pairs that exist at that lag is computed; the exponent is the least-squares slope of that curve over the fit window.Arguments
trajects: list of Trajectory objects with integer frametime().r_min, r_max: range of initial pair separations, [m].dt: the time between frames, [s].max_lag: largest lag (in frames) to follow. None for no limit.fit_lags:(first, last)lags in frames, inclusive, defining the fit window. None uses all lags from 1 to the largest lag.min_overlap: minimal number of common frames for a pair to be used.
Returns
An xarray Dataset with the
lagdimension [s]:mean_log_growth(<ln(r/r0)>),npairs(pairs contributing at each lag). The fitted exponent [1/s] is in the scalar variablelyapunovandattrs.
- flowtracks.lyapunov.finite_size_lyapunov(trajects, r_min, r_max, ratio=1.5, num_scales=10, dt=1.0, min_overlap=3)[source]¶
Finite-size Lyapunov exponent (FSLE) from pair separation growth.
Thresholds
delta_n = r_min * ratio**nare laid out; for each pair the timeTtaken to go fromdelta_ntoratio * delta_nis measured (first-passage times, linearly interpolated between frames), averaged over pairs, andlambda(delta_n) = ln(ratio) / <T>.Arguments
trajects: list of Trajectory objects with integer frametime().r_min, r_max: range of initial separations used to select pairs, [m]. The thresholds start atr_min.ratio: the amplification factor between consecutive thresholds (> 1).num_scales: number of thresholds.dt: the time between frames, [s].min_overlap: minimal number of common frames for a pair to be used.
Returns
An xarray Dataset with dimension
delta[m]:fsle[1/s],mean_time([s],<T>) andcount(pairs that completed that amplification). Scales no pair completed are NaN.
- flowtracks.lyapunov.flow_map(trajects, t_start, t_end)[source]¶
The scattered flow map of a set of trajectories between two frames.
Only trajectories that exist at both frames contribute. This is a survivorship selection: it keeps the particles that were tracked for the whole window, which is not a random sample of the flow (see
doc/lyapunov.rst).Arguments
trajects: list of Trajectory objects with integer frametime().t_start, t_end: integer frame numbers.t_end < t_startis allowed (a backward map).
Returns
x0, x1: (n,3) arrays, the position of each surviving particle att_startand att_end, [m].ids: (n,) indices intotrajectsof those particles.
- flowtracks.lyapunov.eulerian_ftle(trajects, grid, t_start, t_end, radius, dt=1.0, min_neighbors=12, max_condition=10.0, max_offset=0.25, position_error=None)[source]¶
Eulerian finite-time Lyapunov exponent field from scattered trajectories.
Use with caution - see
doc/lyapunov.rstfor the full discussion. In short: the result is only meaningful where the diagnostics say so, it depends ont_start, the window length andradius, and it is computed from the particles that survived the whole window, which is a biased subset of the flow.Method
t_startto its positionx1att_end. At each grid node, the deformation gradientF = dPhi/dx0is estimated by a locally weighted linear least-squares fit ofx1againstx0over the particles whosex0is withinradiusof the node (tricube weights). ThenC = F^T Fis the right Cauchy-Green tensor and the exponent isFTLE = ln(sqrt(lambda_max(C))) / |T|, withT = (t_end - t_start)*dt.A negative window (
t_end < t_start) gives the backward FTLE.A node is reported (
valid) only if all three validity checks pass, otherwise its values are NaN. First, at leastmin_neighborsparticles must be withinradius.Second, the neighbourhood must not be degenerate: the ratio of the largest to the smallest singular value of the (weighted, centred) neighbour offsets must be at most
max_condition. This rejects flat or line-like clouds from whichFcannot be estimated.Third, the neighbourhood must surround the node: the weighted centroid of the neighbours must be within
max_offset * radiusof it. This rejects nodes at the edge of the data, where the fit would extrapolate. For tricube weights a node exactly at a straight data edge has an offset of 0.27, one lying outside the data has more, and a full neighbourhood has about 0.Arguments
trajects: list of Trajectory objects with integer frametime().grid:(x, y, z), three 1D arrays of node coordinates, [m].t_start, t_end: integer frame numbers of the beginning and the end of the flow map.radius: neighbourhood radius, [m]. There is no sensible default: it sets the spatial resolution, and must be chosen against the particle density and the flow scales.dt: the time between frames, [s].min_neighbors: minimal particles in a neighbourhood (at least 5 are needed to fit 4 coefficients per component; more is better).max_condition, max_offset: validity thresholds, see above.position_error: optional, the standard deviation of the measurement error of one position coordinate, [m]. If given, the output includesftle_noise_floor.
Returns
An xarray Dataset on the
(x, y, z)grid. Its variables are listed below;attrsrecord the parameters and the number of particles used.ftle: the exponent, [1/s]. NaN where the node is not valid.det_F:det(F). For an incompressible flow it must be 1; its distance from 1 is a built-in check of the whole estimate (noise, curvature, too large a radius). Treatftleas unreliable where it is far from 1.n_points: number of particles used at each node.fit_residual_rms: weighted RMS of the local linear-fit residuals, [m]. Large compared to the measurement error means the flow map is not linear overradius(reduce it) or the data are noisy.condition: the neighbourhood condition number described above.valid: boolean mask of the nodes that passed all the validity checks.ftle_noise_floor: only ifposition_erroris given. A first-order estimate of the FTLE uncertainty due to measurement noise, [1/s]. Values offtlethat are not well above it are noise.
- flowtracks.lyapunov.ftle_ridges(field, smooth=1.0, min_ftle=None, min_percentile=75.0, min_curvature=0.0)[source]¶
Extract the ridges of an FTLE field (second-derivative ridge definition).
Ridges are candidates, not proof. An FTLE ridge is neither necessary nor sufficient for a Lagrangian coherent structure (LCS), and what is found depends on the window, on the smoothing and on the thresholds. See
doc/lyapunov.rst.A node is on a ridge if the field has a local maximum across the ridge direction, in the following sense. Let
fbe the (smoothed) field,Hits Hessian andnthe eigenvector ofHwith the most negative eigenvaluel_min. A node is a ridge node when three conditions hold.First,
l_min < -min_curvature: the field is concave across the ridge.Second,
fat the node is not smaller thanfone grid step away on both sides alongn. This non-maximum suppression gives ridges one node thick, and is the discrete form of the conditiongrad(f).n = 0.Third,
f >= min_ftle: weak ridges in the low-FTLE background are noise.The outermost layer of grid nodes never carries a ridge, because the maximum across it cannot be verified there.
Arguments
field: the Dataset returned byeulerian_ftle(), or any Dataset with a variableftleand (optionally) a booleanvalid, on a regular grid. Dimensions of size smaller than 3 (such as a single plane in a 3D grid) are ignored, so a plane gives ridge lines and a volume gives ridge surfaces. At least two dimensions need 3 or more nodes.smooth: standard deviation of the Gaussian smoothing applied before differentiating, in grid nodes. Invalid nodes do not contribute. Differentiating twice amplifies noise, so some smoothing is normally necessary; it also moves and widens ridges. 0 disables it.min_ftle: the lowest FTLE at which to accept a ridge, [1/s]. If None, themin_percentilepercentile of the valid smoothed values is used.min_percentile: see above, in [0, 100].min_curvature: the minimal concavity-l_minaccepted, [1/s per m^2]. The default, 0, accepts any concave node.
Returns
An xarray Dataset on the same grid, with
ridge(boolean mask),ridge_strength(-l_min, [1/s per m^2], NaN where it could not be computed) andftle_smooth(the smoothed field that was used).attrsrecord the parameters and the threshold actually used.