Skip to main content

Code structure

How the packages and modules are organized, and how an experiment script is put together

Layout of the NLSA Python toolkit: the nlsa and nlsa_models packages, their modules, the data flow from input files to forecasts, the anatomy of an example script, and the design conventions of the code.

Repository layout

The Python toolkit lives in the Python/ folder of the NLSA repository.

NLSA/
├── Python/
│   ├── pyproject.toml           package metadata and dependencies (version 0.4)
│   ├── README.md, CHANGELOG.md
│   ├── src/
│   │   ├── nlsa/                algorithms, independent of any data set
│   │   │   ├── kernels.py       kernel parameters, normalizations, tuning criterion
│   │   │   ├── koopman.py       Koopman parameters, eigenvalue tables, plots
│   │   │   ├── eofs.py          extended EOF parameters
│   │   │   ├── qmda.py          building blocks for quantum mechanical data assimilation
│   │   │   ├── io_actions.py    saving, reading, timing and plotting wrappers
│   │   │   └── jax/             implementations in JAX
│   │   │       ├── kernels/     bandwidth tuning, eigensolvers, eigenbases, kernel analog forecasting
│   │   │       ├── koopman/     generator and integral-transform eigenproblems, Koopman forecasts
│   │   │       ├── eofs/        extended EOF analysis
│   │   │       ├── delays.py    delay embedding, finite differences, quadrature weights
│   │   │       ├── distance.py  Euclidean and cone distances
│   │   │       ├── stats.py     skill scores
│   │   │       └── sharding.py  splitting arrays across several GPUs
│   │   └── nlsa_models/         data sets and models
│   │       ├── climate.py       the climate pipeline: data, embedding, forecasts, skill, plots
│   │       ├── era5.py          ERA5 reanalysis: variables, domains, file settings
│   │       ├── ws44.py          14th Weather Squadron station records
│   │       ├── lorenz63.py      the Lorenz 63 system
│   │       ├── core.py          JAX setup and the skill-score container
│   │       ├── estcp.py         an earlier, self-contained version of the climate pipeline
│   │       └── cesm2.py         CESM2 climate model output (earlier work)
│   └── examples/
│       ├── enso/                ENSO scripts, processed data, example figures
│       └── lorenz63/            Lorenz 63 scripts
├── MATLAB/                      the MATLAB implementation, including QMDA
└── pubs/                        code for three published papers (Froyland et al. 2021,
                                 Freeman et al. 2023, Lintner et al. 2023)

Two packages

The toolkit is split into two Python packages with different jobs:

  • nlsa holds the mathematics: kernels, their normalization and eigendecomposition, Koopman operators, forecasting, skill scores. It knows nothing about climate data. The top-level modules (nlsa.kernels, nlsa.koopman) define the parameter classes and the parts that do not depend on the array library; the subpackage nlsa.jax implements the computations with JAX. Users import from nlsa.jax.kernels and nlsa.jax.koopman, which also re-export the parameter classes.
  • nlsa_models connects the mathematics to particular data: it reads ERA5 files and station records, removes climatologies, builds delay-embedded samples, and makes the plots. All climate experiments share nlsa_models.climate; era5.py and ws44.py describe the data sources.

The older modules nlsa_models.estcp and nlsa_models.cesm2, and the NumPy and Numba versions in nlsa.numpy and nlsa.numba, are not used by the current examples.

Modules used by the climate examples

Modules and their main classes and functions
Module Role Main contents
nlsa_models.core
(through climate)
JAX environment initialize_jax, JaxEnv, initialize_matplotlib, SkillScores
nlsa_models.era5
as era5
ERA5 data Domain, IO, DataSpecs, Var; nino34_domain, indo_pacific_domain, global_domain
nlsa_models.ws44
as ws44
Station data DataSpecs, Station, Var, IO, and HighLat… versions for Pituffik
nlsa_models.climate
as clim
Climate pipeline Time, Climatology, Covariate, Response, DataPars, ProjectionPars; extract_data_arrays, make_data_driven_l2_space, compute_kaf_expansion_coeffs, compute_skill_scores, compute_eigenfunction_projections, plotting functions
nlsa.jax.distance
as dst
Distances sqeuclidean, make_sqcone
nlsa.jax.kernels
as knl
Kernels TunePars, ConePars, DmKernelPars, BsKernelPars, TuneInfo, KernelEigen; tune_bandwidth, make_data_driven_bandwidth_function, make_data_driven_rbf_kernel, compute_eigen, compute_kaf_preds
nlsa.jax.koopman
as koop
Koopman operators KoopmanParsDiff, KoopmanParsTransf, KoopmanEigen; compute_generator_matrix, compute_diffusion_regularized_generator_eigen, evaluate_eigenfunction, compute_koopman_preds
nlsa.jax.scalars
as scls
Number types scalar_field
nlsa.io_actions
(by name)
Saving and reading IO, pickleit, h5it, npyit, netcdfit, plotit, plotem, timeit
nlsa.jax.sharding
(by name)
Several GPUs NamedSharder

From data to forecasts

The calculation runs through the same steps in every experiment. The diagram shows the main objects and the functions that produce them; each step is a calculation block.

flowchart TD
  A["ERA5 files, station records"] -->|"clim.extract_data_arrays"| B["NPData<br/>time, covariate, response"]
  B -->|".to_device"| C["Data<br/>arrays on CPU or GPU"]
  C -->|"clim.make_data_driven_l2_space<br/>(delay embedding)"| D["impl_l2<br/>delay-embedded samples"]
  D -->|"knl.tune_bandwidth"| E["TuneInfo<br/>bandwidth"]
  E -->|"knl.make_data_driven_rbf_kernel<br/>knl.compute_eigen"| F["KernelEigen<br/>kernel eigenfunctions"]
  F -->|"clim.compute_kaf_expansion_coeffs<br/>knl.compute_kaf_preds"| G["Forecasts<br/>initial time × lead time"]
  F -->|"koop.compute_generator_matrix<br/>koop.compute_diffusion_regularized_generator_eigen"| H["KoopmanEigen<br/>Koopman eigenfunctions"]
  H -->|"koop.evaluate_eigenfunction"| I["Koopman index<br/>time series"]
  I -->|"kernel analog forecast"| G
  G -->|"clim.compute_skill_scores"| J["SkillScores<br/>NRMSE, ACC"]
  F -->|"clim.compute_eigenfunction_projections"| K["Spatial modes"]
  H -->|"clim.compute_eigenfunction_projections"| K

Data flow in the climate examples. Boxes are objects; arrows are labelled with the functions that compute them.

Anatomy of an example script

The two ENSO scripts follow the same plan, which a new experiment script should also follow.

Part of the script What it does
1. Imports The modules in the table above, with their short names (clim, knl, koop, …).
2. Switches Constants in capitals: EXPERIMENT, IDX_GPU, FP, run modes, plot settings. See Setup and run control.
3. JAX and Matplotlib setup jax_env = clim.initialize_jax(...) and clim.initialize_matplotlib(...), run when the script starts.
4. Parameter classes of the script PredPars (forecast settings), TrainPars (everything about training: data, tuning, kernel, cone, Koopman, forecast), TestPars (test data), and Pars, which bundles them with optional projections.
5. from_experiment() A match statement with one case per experiment, which builds all the parameter objects and, for several GPUs, the sharding layout.
6. Wrapped computations Each computation is wrapped with saving or reading (pickleit, h5it, …), which follows the run-mode switch, and with timing (timeit). Plot functions are wrapped with plotit or plotem.
7. main() Runs the steps in order: data, kernel tuning, kernel eigenfunctions, projections, Koopman analysis, forecasts, plots, skill scores. Before each step it extends the output folder path (io /= str(...)).

The parameter objects nest, so one object describes a whole experiment. For the kernel analog forecasting script:

Pars
├── train: TrainPars
│   ├── data: DataPars ─────────── covariate: Covariate ── specs: (era5.DataSpecs, …)
│   │                              response: Response ─── specs: era5.DataSpecs
│   │                              num_half_delays, num_after, velocity settings, …
│   ├── bw_tune: TunePars          tuning of the variable-bandwidth function
│   ├── cone: ConePars             cone kernel (or None)
│   ├── tune: TunePars             tuning of the kernel bandwidth
│   ├── kernel: DmKernelPars       normalization, eigensolver, number of eigenfunctions
│   └── pred: PredPars             forecast steps, eigenfunctions used
├── test: TestPars
│   ├── data: DataPars             same embedding settings, test period
│   └── num_pred_steps
└── kernel_projection: ProjectionPars (or None)

The Koopman script adds koopman: KoopmanParsDiff to TrainPars, koopman_projection to Pars, and its PredPars names the Koopman eigenfunction to forecast.

Conventions in the code

Parameters are immutable dataclasses. Every parameter class (Time, DataPars, TunePars, DmKernelPars, KoopmanParsDiff, …) is a frozen dataclass: once created it cannot be changed, so a set of results always matches the parameters that produced it. Each class also defines a short text form, for example str(TunePars()) is nb128_loglim-3_loglim3_dimNone_scl1, and these strings name the output folders.

Results are named tuples. The results of the expensive steps (NPData, TuneInfo, KernelEigen, KoopmanEigen) are named tuples of arrays, which can be saved to disk and read back.

Functions that build functions. Many functions take parameters and return another function, which is applied to the data later. For example, clim.make_data_driven_l2_space(data_pars, dtype) returns impl_l2, and impl_l2(data) is the space of functions on the delay-embedded training samples, with its inner product. Kernels and distances are likewise passed around as functions of two points. JAX then compiles a whole step, such as the bandwidth tuning, into one program for the size of the data, and the same code runs on a CPU, one GPU or several.

Data-driven functions take the data as their first argument. A kernel built by knl.make_data_driven_rbf_kernel is called as kernel(data, x, y): the data are needed because normalizations and the variable bandwidth are computed from the training samples.

Eigenfunctions are numbered from 0. Eigenfunction 0 of a normalized kernel is the constant function. Options that select eigenfunctions accept an integer, a tuple or a list (see the conventions).

Type annotations throughout. The code uses the generic syntax of Python 3.12 and later (class DataPars[T: TimeSampling]), which is one reason for the Python version requirement. The annotations are checked with mypy and pyright.

Several GPUs

When IDX_GPU lists more than one GPU, the scripts split (“shard”) the training samples across the GPUs. The layout is described by the classes L2FnAlgebraShardings, KernelEigenShardings, GeneratorShardings and KoopmanEigenShardings, built in from_experiment() with a NamedSharder. With one GPU or a CPU the defaults (no sharding) are used, and nothing needs to be set.

MATLAB and the published-paper code

The MATLAB/ folder contains the original implementation of the same methods, in maintenance mode. It includes the full quantum mechanical data assimilation (QMDA) algorithm (MATLAB/nlsa/utils/forecasting/qmda.m), which is not yet in the Python toolkit; see Forecasting. The pubs/ folder holds the code behind three papers: Koopman analysis of climate data (Froyland et al. 2021), QMDA (Freeman et al. 2023), and the Koopman MJO index (Lintner et al. 2023).

Known issues in version 0.4

These points were found while preparing this documentation. They do not affect the results of the example experiments as configured, but they matter when changing settings or setting up new experiments.

Installation

  • cartopy (imported by nlsa_models.climate) and dask (used by xarray to open the ERA5 files) are not listed in the dependencies of pyproject.toml.
  • The README says Python 3.12 or above; pyproject.toml requires 3.13 or above.

Options that have no effect

  • DataPars.delay_embedding_mode is not read by the climate pipeline; make_data_driven_l2_space and the other builders take their own delay_embedding_mode argument.
  • laplacian_method of KoopmanParsDiff and KoopmanParsTransf enters only the folder name; the Laplace eigenvalues are always computed with "log".
  • KoopmanParsDiff.dt and the dt of the KAF script’s PredPars are not used in the computation.
  • The switch JAX_CACHE_DIR is not passed to initialize_jax, so the compilation cache is not used.

Example scripts

  • The experiment NINO34_FROM_ERA5_NINO34SST of the KAF script does not set num_after, which the forecast needs; the data shipped in the repository were prepared with num_after=24 for training and test data.
  • The docstring of the KAF script refers to the experiment ENSO_FROM_ERA5_NINO34SST, which belongs to the Koopman script; the docstring of the Koopman script says the data for ENSO_FROM_ERA5_IPSST are included, but examples/enso/data contains only Niño 3.4 data.
  • The test periods of the ENSO experiments overlap their training periods.

Data

  • "zonally_averaged" sampling coarsens longitude by step_lat before averaging over all longitudes, so the step has no effect.
  • For ERA5 data, rolling_mode="forward" leaves the last rolling_window − 1 dates without values.
  • Area, zonal and meridional averages are not weighted by grid-cell area.
  • The reader expects a time coordinate; ERA5 NetCDF files from the current Climate Data Store name it valid_time.
  • The docstring of era5.Var.AVG_TNLWRF says “Outgoing longwave radiation”; the ERA5 variable is the net longwave flux at the top of the atmosphere, the negative of the OLR.
  • Several station descriptions in ws44.Station contain typos (for example KABQ given as AZ, KLSV as NM and KVNY as “XA”); the corrected names are on the Data page.

References

Freeman, D. C., D. Giannakis, B. Mintz, A. Ourmazd, and J. Slawinska. 2023. “Data Assimilation in Operator Algebras.” Proceedings of the National Academy of Sciences 120 (8): e2211115120. https://doi.org/10.1073/pnas.2211115120.
Froyland, G., D. Giannakis, B. R. Lintner, M. Pike, and J. Slawinska. 2021. “Spectral Analysis of Climate Dynamics with Operator-Theoretic Approaches.” Nature Communications 12: 6570. https://doi.org/10.1038/s41467-021-26357-x.
Lintner, B. R., D. Giannakis, M. Pike, and J. Slawinska. 2023. “Identification of the Madden–Julian Oscillation with Data-Driven Koopman Spectral Analysis.” Geophysical Research Letters 50: e2023GL102743. https://doi.org/10.1029/2023GL102743.