Metadata-Version: 2.5
Name: lagrangian-gradient-regression
Version: 0.1.0
Summary: Lagrangian Gradient Regression for the detection of Lagrangian Coherent Structures from sparse trajectory data.
Project-URL: Repository, https://github.com/TannerHarms/Lagrangian-Gradient-Regression
Project-URL: Paper, https://doi.org/10.1098/rsos.240586
Project-URL: Issues, https://github.com/TannerHarms/Lagrangian-Gradient-Regression/issues
Author: Tanner Harms
License: MIT
License-File: LICENSE
Keywords: FTLE,coherent structures,fluid dynamics,gradient regression,lagrangian
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.12
Requires-Dist: matplotlib>=3.6
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=1.5
Requires-Dist: scikit-learn>=1.1
Requires-Dist: scipy>=1.9
Requires-Dist: sympy>=1.11
Provides-Extra: cuda
Requires-Dist: jax[cuda12]>=0.4; (platform_system == 'Linux') and extra == 'cuda'
Provides-Extra: dev
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Provides-Extra: gpu
Requires-Dist: jax[cuda12]>=0.4; (platform_system == 'Linux') and extra == 'gpu'
Provides-Extra: jax
Requires-Dist: jax>=0.4; extra == 'jax'
Provides-Extra: ocean
Requires-Dist: netcdf4>=1.6; extra == 'ocean'
Requires-Dist: requests>=2.28; extra == 'ocean'
Requires-Dist: xarray>=2022.9; extra == 'ocean'
Provides-Extra: rocm
Requires-Dist: jax[rocm]>=0.4; (platform_system == 'Linux') and extra == 'rocm'
Description-Content-Type: text/markdown

# 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](https://doi.org/10.1098/rsos.240586). *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](https://github.com/TannerHarms/Nonlinear-LGR-Paper).

## Installation

```bash
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:

```bash
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.

```python
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:

```python
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:

```python
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:

```bash
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:

```bash
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

```bash
pytest
```

## License

MIT License — see [LICENSE](https://github.com/TannerHarms/Lagrangian-Gradient-Regression/blob/main/LICENSE) for details.
