Skip to main content

Lagrangian Gradient Regression (LGR)

A modular Python package for estimating flow-map Jacobians from sparse Lagrangian trajectory data and computing Lagrangian Coherent Structure (LCS) diagnostics.

Reference

Harms, T. D., Brunton, S. L., & McKeon, B. J. (2024). Lagrangian gradient regression for the detection of coherent structures from sparse trajectory data. R. Soc. Open Sci. 11, 240586.

The nonlinear estimators (higher-order polynomial libraries, Gaussian-process local models and the composed higher derivatives of the flow map) are described in Nonlinear Lagrangian Gradient Regression (in preparation). The code and data that reproduce that paper's figures are in Nonlinear-LGR-Paper.

Installation

pip install lagrangian-gradient-regression

The package is imported as lgr. It is distributed under its full name because the name lgr on PyPI belongs to an unrelated project; do not pip install lgr. Python 3.12 or newer.

Optional extras: [ocean] for the gridded ocean-data readers and [jax] for the JAX backend.

To work on the library itself, install from a clone:

git clone https://github.com/TannerHarms/Lagrangian-Gradient-Regression.git
cd Lagrangian-Gradient-Regression
pip install -e ".[dev]"

Quick Start

LGR works on a plain (n_particles, n_times, dim) array of positions. Nothing else is required — no wrapper objects, no DataFrame.

import numpy as np
from lgr import (
    fit_library_deformation, compute_lcs_metrics, estimate_error,
)
from lgr.flows import DoubleGyre

# 1. Trajectories: any (n_particles, n_times, dim) array will do.
flow = DoubleGyre()
ics = np.random.rand(500, 2) * [2, 1]          # random seeds in [0,2]x[0,1]
times = np.linspace(0, 10, 101)
positions = flow.integrate_trajectories(ics, times)

# 2. Fit local deformation gradients. `order=1` is standard LGR; raising it
#    fits a richer local flow map and differentiates that at the tracer,
#    which is what reduces finite-neighbourhood bias on sparse data.
fit = fit_library_deformation(positions, times=times, order=2, k_neighbors=20)

fit.F                       # (n_particles, n_intervals, dim, dim)
fit.valid                   # which fits passed the rank/conditioning gates
fit.normalized_dof_residual # residual, comparable across polynomial orders
fit.hessian                 # the second derivative, free once order >= 2

# 3. LCS diagnostics from the deformation gradients.
metrics = compute_lcs_metrics(fit.to_deformation_result(), metrics=("ftle",))
metrics.ftle                # (n_particles, n_intervals)

Missing observations are supported directly — leave them as NaN and they are excluded from every neighbourhood:

positions[10, 40:50] = np.nan     # this tracer is simply not seen for a while

Kernel weighting, a Gaussian-process local model, and uncertainty are all one argument away:

from lgr import fit_anchored_gp_deformation, WEIGHT_KERNELS

fit_library_deformation(positions, times=times, order=2, k_neighbors=20,
                        weights="gaussian", bandwidth=0.7)
gp = fit_anchored_gp_deformation(positions, times=times, k_neighbors=20)
gp.F_variance               # posterior variance of the gradient

Package Architecture

src/lgr/
├── array_api.py        # TrajectoryData, neighbour search, fit_deformation, metrics
├── regression/         # local estimators: batched kernels, weights, libraries, GP
├── metrics/            # LCS diagnostics (FTLE, LAVD, DRA, vorticity, uncertainty)
├── flows/              # analytical flows + batched integration and composition
├── interpolation/      # scattered-to-grid interpolation
├── plotting/           # colormaps, fields, trajectories, paper figure style
├── preprocessing/      # trajectory and Jacobian cleaning
└── core/               # legacy Particle/DataFrame pipeline (see below)

The array-first API above is the supported path. The Particle / generate_dataframe / compute_jacobians pipeline in lgr.core predates it and is retained for existing scripts; it is slower, holds the whole history in a pandas frame, and does not expose the nonlinear estimators. New code should use lgr.PRIMARY_API.

Extension Points

Every major subsystem is built around an abstract base class so new components can be added without modifying existing code:

Extension Point ABC Example Subclasses
Jacobian estimation RegressionKernel PseudoinverseRegression, GaussianKernelRegression
Local libraries LocalBasis PolynomialBasis
LCS metrics LagrangianMetric FTLEMetric, LAVDMetric, DRAMetric, VorticityMetric
Flow models FlowBase DoubleGyre, BickleyJet, ABCFlow
Interpolation Interpolator GridDataInterpolator, RBFInterpolator

Examples

Jupyter notebook demonstrations are in the examples/ directory:

  • LCS_from_velocity_gradients.ipynb — FTLE from known analytical velocity gradients
  • LGR_on_Random_Sparse_Data.ipynb — Full LGR pipeline on sparse/random particle data
  • nonlinear_order_benchmark_paper_example.ipynb — Paper figure workflow for nonlinear polynomial and GP regression comparisons

Experiment Artifacts

The experiment scripts generate NPZ/JSON artifacts, run the array-first LGR workflow, and create static figures without changing package source code:

python scripts/experiments/generate_dataset.py --config configs/experiments/datasets/linear3d_random_tiny.json --output-dir artifacts/datasets
python scripts/experiments/run_lgr_experiment.py --config configs/experiments/models/array_lgr_default.json --dataset artifacts/datasets/analytic3d_linear3d_random_tiny_seed0.npz --output-dir artifacts/results
python scripts/experiments/make_figures.py --config configs/experiments/figures/default_report.json --results artifacts/results/analytic3d_linear3d_random_tiny_seed0_array_lgr_default.npz --output-dir artifacts/figures

Synthetic LPT artifacts and nonlinear model configs are included:

python scripts/experiments/generate_dataset.py --config configs/experiments/datasets/synthetic_lpt_double_gyre_tiny.json --output-dir artifacts/datasets
python scripts/experiments/run_lgr_experiment.py --config configs/experiments/models/array_lgr_polynomial_order2.json --dataset artifacts/datasets/synthetic_lpt_double_gyre_random_tiny_seed0.npz --output-dir artifacts/results
python scripts/experiments/run_lgr_experiment.py --config configs/experiments/models/array_lgr_model_selection.json --dataset artifacts/datasets/synthetic_lpt_double_gyre_random_tiny_seed0.npz --output-dir artifacts/results

Slurm and Flux launcher templates are in configs/experiments/launchers/.

Running Tests

pytest

License

MIT License — see LICENSE for details.

Metadata

Release files for lagrangian-gradient-regression 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lagrangian-gradient-regression 0.1.0
File Size Uploaded Provenance Actions
lagrangian_gradient_regression-0.1.0.tar.gz 270.4 kB With provenance Details for lagrangian_gradient_regression-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lagrangian-gradient-regression 0.1.0
File Interpreter ABI Platform Actions
lagrangian_gradient_regression-0.1.0-py3-none-any.whl Python 3 none any Details for lagrangian_gradient_regression-0.1.0-py3-none-any.whl

Total release size: 514.8 kB

Release files / lagrangian_gradient_regression-0.1.0.tar.gz

Download URL lagrangian_gradient_regression-0.1.0.tar.gz
Size 270.4 kB
Tags Source
SHA-256 checksum
How to use checksums
d5811327213b36fa3927d43cb3e1dbacba43be7ece5f537281161a05fc188c5b
BLAKE2b-256 checksum
How to use checksums
a18f1dc43fb8b00d23693879db8f433bf0759d4a8024a3b34e3bd182992ef071
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / lagrangian_gradient_regression-0.1.0-py3-none-any.whl

Download URL lagrangian_gradient_regression-0.1.0-py3-none-any.whl
Size 244.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7a5ae9e7d89f4413b8c7eefbdebdf40ff2c97ee749f4d5c332c78a3d6d8ca17d
BLAKE2b-256 checksum
How to use checksums
7bc405b24830457bf2ec72ca56f8c7c132ea7a1f67866373a14148adfcefa888
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for lagrangian-gradient-regression 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for lagrangian_gradient_regression-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page