Skip to main content

Using Python

Installing the toolkit, running the examples, and calling it from your own code

How to install the NLSA Python toolkit on a laptop or GPU server, run the ENSO examples (including from the data shipped with the repository), run unattended on a server, and use the toolkit from your own scripts or notebooks.

What you need

Requirement Details
Python Version 3.13 or newer. The package metadata (pyproject.toml) requires 3.13; the README still says 3.12, but installation is refused on 3.12.
Operating system Linux or macOS. GPU acceleration needs Linux with an NVIDIA GPU.
GPU (optional) An NVIDIA GPU on Linux, with driver version 525 or newer. The JAX packages installed by pip include the CUDA libraries, so CUDA itself does not need to be installed. Everything also runs on a CPU, more slowly.
Memory The kernel matrix has N × N entries for N training samples: about 4 MB for the monthly ENSO examples (N ≈ 1,000) but 1.3 GB for 50 years of daily data (N ≈ 18,000) in single precision. See Choosing hyperparameters.
Data ERA5 files in NetCDF or GRIB format, or 14th Weather Squadron station files. The repository includes a small processed data set for the ENSO examples, so you can try the code without downloading ERA5.

Installation

Clone the repository and create a virtual environment inside its Python folder:

git clone https://github.com/dg227/NLSA.git
cd NLSA/Python
python3.13 -m venv venv
source venv/bin/activate
pip install --upgrade pip

Then install the toolkit together with its dependencies. The -e flag installs it in editable mode: changes you make to the code, or a later git pull, take effect without reinstalling.

pip install -e .
pip install cartopy "dask[array]"
pip install -e ".[cuda]"     # JAX 0.8.0 with CUDA 12
pip install cartopy "dask[array]"

With an NVIDIA driver of version 580 or newer you can instead install the most recent JAX built for CUDA 13, with pip install -e ".[cuda13]".

pip install -e ".[cuda,dev]"   # or ".[dev]" without a GPU
pip install cartopy "dask[array]"

The dev extra adds the test, lint and type-checking tools (pytest, ruff, mypy, pyright).

ImportantInstall cartopy and dask separately

Two packages that the climate code needs are not yet listed among the dependencies in pyproject.toml, so they are installed with the extra pip install line above:

  • cartopy, which nlsa_models.climate uses to draw maps. Every climate example imports it, and stops with ModuleNotFoundError: No module named 'cartopy' without it. The Lorenz 63 examples do not need it.
  • dask, which xarray needs to open the ERA5 files (the code opens all files in a folder at once, in parallel) and to project fields onto eigenfunctions.

Alternatively, add the xarray_complete extra of the toolkit, which installs both: pip install -e ".[xarray_complete]" or pip install -e ".[cuda,xarray_complete]".

Check that the installation works and see which devices JAX can use:

python -c "import jax; print(jax.devices())"

On a CPU-only machine this prints [CpuDevice(id=0)]; on a GPU machine it lists the GPUs, for example [CudaDevice(id=0), CudaDevice(id=1)].

When you open a new terminal later, activate the environment again with source venv/bin/activate (from the Python folder), and leave it with deactivate.

Running the examples

The example scripts are in Python/examples/. Run them from the Python folder, because results are saved and read relative to the folder the script is started from:

cd NLSA/Python
python examples/enso/kernel_analog_forecasting.py

python <script> --help prints the script’s description.

Each script is configured by editing it:

  1. Switches at the top of the file: which experiment to run, CPU or GPU, precision, which steps to compute or read from disk, and which plots to make. They are listed on the Setup and run control page.
  2. The function from_experiment(): the settings of each experiment (data, delay window, kernel, Koopman and forecast settings), written as parameter objects. They are documented block by block on the Calculation blocks pages.

The experiments in the scripts, and those planned for the MJO and the stations, are described on the Experiments page.

A first run with the data in the repository

The folder Python/examples/enso/data holds processed training and test data (monthly sea surface temperature over the Niño 3.4 region from ERA5, 1940–2025) for two Niño 3.4 configurations. With the edits below, both ENSO scripts run without any ERA5 files. The edits follow from the code but have not been tried out for this documentation; if a step fails, the error message usually names a missing file, which tells you which setting does not match the shipped data.

In examples/enso/kernel_analog_forecasting.py:

  1. Set the switches:

    EXPERIMENT: Experiment = Experiment.NINO34_FROM_ERA5_NINO34SST
    IDX_GPU: int | Sequence[int] | None = None   # None: CPU. Keep 0 on a GPU machine.
    EXTRACT_DATA_MODE = "read"                  # already the default
    PLOT_MODE = "save"
    LEAD_TIMES_PLT = [0, 3, 6, 12]
    INITIALIZATION_TIMES_PLT = [0, 12, 24]
  2. In from_experiment(), under case Experiment.NINO34_FROM_ERA5_NINO34SST:, add num_after=num_pred_steps, to both train_data_pars = DataPars(...) and test_data_pars = DataPars(...). The shipped data were prepared with these extra 24 months, and the forecast needs them (see Delay embedding).

  3. In the same block, replace the kernel_projection_pars = ProjectionPars(...) statement by kernel_projection_pars = None. The projection reads global SST from ERA5 files, which are not in the repository.

Keep CONE_KERNEL = True, as the shipped data include the velocities that the cone kernel needs. The script prints the skill table (normalized RMSE and anomaly correlation at leads 0–24 months) and saves the plots under examples/enso/data/.

In examples/enso/koopman_diffusion_regularization_kaf.py:

  1. Set the switches:

    EXPERIMENT: Experiment = Experiment.ENSO_FROM_ERA5_NINO34SST
    TUNE_KERNEL_MODE = "calcsave"     # default "read" needs results from an earlier run
    KERNEL_EIGEN_MODE = "calcsave"    # same
    PLOT_MODE = "save"
    WHICH_PLOTS = {"generator_spec", "koopman_eigen", "skill_scores"}
    KOOPMAN_EIGS_PLT = [1, 3, 5]

    Keep CONE_KERNEL = False and IDX_GPU = None (the defaults in this script).

  2. In from_experiment(), under case Experiment.ENSO_FROM_ERA5_NINO34SST:, replace koopman_projection_pars = ProjectionPars(...) by koopman_projection_pars = None (the projection needs ERA5 files).

The script prints the Koopman eigenvalue table (growth rate, energy, frequency in cycles per year, period in years), forecasts Koopman eigenfunction 3 with kernel analog forecasting, and prints the skill table.

The default experiments of the two scripts (ELNINO_2027_FROM_ERA5_NINO34SST and ENSO_FROM_ERA5_IPSST) read monthly ERA5 files from the paths set in from_experiment(). To run them, download the data (see ERA5 monthly data) and change era5.IO(input_path=...) or ERA5_MONTHLY_DATA_DIR to your folder.

Computing, saving and reading results

Each step of a script has a run mode switch (EXTRACT_DATA_MODE, TUNE_KERNEL_MODE, KERNEL_EIGEN_MODE, …) with three values:

Mode What happens
"calc" Compute the result; do not save it.
"calcsave" Compute the result and save it to disk.
"read" Read a result saved earlier by a "calcsave" run.

Results are saved in a tree of folders whose names spell out the settings (for example ns920_nd12_nb0_na24_vfd4 for the training samples), so runs with different settings never overwrite each other. The flip side is that "read" only finds a file if every setting that leads to it is the same as in the run that saved it. A typical pattern is to run the expensive steps (data extraction, kernel eigendecomposition, Koopman eigendecomposition) once with "calcsave", then switch them to "read" while you experiment with the later steps. Details are on the Setup and run control page.

Running unattended on a server

For runs on the campus server, from a scheduled job or over SSH without a display, change the switches that wait for a person:

MATPLOTLIB_BACKEND = "Agg"          # draw plots without a screen
PLOT_MODE = "save"                  # "show" waits for Enter after every plot
KERNEL_EIGS_PLT = [1, 2, 3]         # lists or None instead of "interactive",
LEAD_TIMES_PLT = [0, 6, 12]         # which asks for input at the prompt
INITIALIZATION_TIMES_PLT = None

Then start the script in the background and keep a log:

cd ~/NLSA/Python
source venv/bin/activate
nohup python examples/enso/kernel_analog_forecasting.py > enso_kaf.log 2>&1 &

To run it on a schedule, add a line to the crontab (crontab -e), calling the environment’s Python directly. For example, at 07:00 on the 10th of every month, after the monthly ERA5 fields are released:

0 7 10 * * cd $HOME/NLSA/Python && ./venv/bin/python examples/enso/kernel_analog_forecasting.py >> $HOME/logs/enso_kaf.log 2>&1

On a server with several GPUs, IDX_GPU selects the GPU (0, 1, …), or several with a list such as [0, 1]; the examples then split the training samples across the GPUs. The switch XLA_MEM_FRACTION (default "0.95") sets how much of each GPU’s memory JAX reserves when it starts; lower it if other jobs share the GPU.

To publish forecast figures on this website, copy the PNG files you want to show into the folder that scripts/publish_forecast.sh of the website repository reads (FORECAST_OUTPUT_DIR) and run that script, as described in the website’s README.

Using the toolkit from your own code

The example scripts are the most complete way to run an experiment, but the functions can also be called directly, from a script or a Jupyter notebook (JupyterLab is installed with the toolkit; start it with jupyter lab). The sketch below runs the whole kernel analog forecasting chain for the Niño 3.4 index. Each line corresponds to one calculation block, and the function signatures are those of version 0.4.

import jax.numpy as jnp
import numpy as np
import nlsa.jax.distance as dst
import nlsa.jax.kernels as knl
import nlsa.jax.scalars as scls
import nlsa_models.climate as clim
import nlsa_models.era5 as era5
from nlsa.jax.kernels import DmKernelPars, TunePars
from nlsa_models.climate import Climatology, Covariate, DataPars, Response, Time

# 1. Setup: CPU (use idx_gpu=0 for the first GPU), single precision
jax_env = clim.initialize_jax(idx_gpu=None, fp="f32")

# 2. Data: predictors = Nino 3.4 SST field, target = area-averaged Nino 3.4 anomaly
io5 = era5.IO(input_path="/path/to/era5/monthly", file_format="nc")
clim_period = ("1940-01-01", "2019-12-31")
num_steps = 24                                    # forecast leads 0-24 months


def make_data_pars(date_range):
    time = Time(date_range=date_range, sampling="monthly",
                custom_climatology_date_range=clim_period)
    sst_field = era5.DataSpecs(
        vars=[era5.Var.SST], domain=era5.nino34_domain(step_lon=4, step_lat=4),
        time=time, io=io5, climatology=Climatology(standardize=True))
    nino34 = era5.DataSpecs(
        vars=[era5.Var.SST], domain=era5.nino34_domain(sampling="area_averaged"),
        time=time, io=io5, climatology=Climatology(remove=True))
    # 3. Delay embedding: windows of 2*6 + 1 = 13 months
    return DataPars(covariate=Covariate(specs=(sst_field,)),
                    response=Response(specs=nino34),
                    num_half_delays=6, num_after=num_steps)


train_pars = make_data_pars(clim_period)
test_pars = make_data_pars(("2020-01-01", "2025-12-31"))
train = clim.extract_data_arrays(train_pars, dtype=np.dtype(np.float64)).to_device(
    dtype=jax_env.real_dtype)
test = clim.extract_data_arrays(test_pars, dtype=np.dtype(np.float64)).to_device(
    dtype=jax_env.real_dtype)
impl_l2 = clim.make_data_driven_l2_space(data_pars=train_pars, dtype=jax_env.real_dtype)
impl_l2_tst = clim.make_data_driven_l2_space(data_pars=test_pars, dtype=jax_env.real_dtype)

# 4. Kernel: tune the bandwidth, build the kernel, compute 512 eigenfunctions
scl_r = scls.scalar_field(jax_env.real_dtype)
tune_info = knl.tune_bandwidth(TunePars(), impl_l2, jnp.exp, dst.sqeuclidean, train)
kernel = knl.make_data_driven_rbf_kernel(scl_r, jnp.exp, dst.sqeuclidean,
                                         tune_info.bandwidth)
kernel_pars = DmKernelPars(normalization="fokkerplanck", eigensolver="eigh", num_eigs=512)
kernel_eigen = knl.compute_eigen(kernel_pars, impl_l2, kernel, train, tune_info.bandwidth,
                                 train_pars.num_samples, jax_env.real_dtype)

# 6. Forecasting: kernel analog forecast with all 512 eigenfunctions
coeffs = clim.compute_kaf_expansion_coeffs((train_pars, kernel_pars), impl_l2, train,
                                           kernel, kernel_eigen, num_steps, 512)
preds = knl.compute_kaf_preds(kernel_pars, impl_l2, train, kernel, kernel_eigen, coeffs,
                              impl_l2_tst, test, 512)

# 7. Skill: one value per lead time 0..num_steps
scores = clim.compute_skill_scores(test_pars, test, preds)
print(scores["accs"], scores["nrmses"])

preds has one row per initial time in the test period and one column per lead time (0 to num_steps). This sketch uses the plain Euclidean distance; the examples add a variable bandwidth function and the cone kernel, as shown on the Kernel page.

NoteAbout the code on these pages

The code excerpts were checked against the source of version 0.4 (names, arguments and their order) but have not been run as part of preparing this documentation. If you find a difference, the example scripts in the repository are the reference.

In an interactive session, after you edit a module of the toolkit, reload it without restarting Python:

import importlib
importlib.reload(clim)

Common problems

Message or symptom Cause and fix
ModuleNotFoundError: No module named 'cartopy' (or 'dask') Install them: pip install cartopy "dask[array]".
An error that JAX finds no gpu backend or platform IDX_GPU is set to a GPU index on a machine without a usable GPU, or JAX was installed without GPU support. Set IDX_GPU = None, or reinstall with pip install -e ".[cuda]".
FileNotFoundError for a .pkl, .h5 or .nc file A step is in "read" mode but no earlier "calcsave" run with the same settings exists. Run it once with "calcsave".
pip refuses to install, saying a different Python is required The toolkit needs Python 3.13 or newer.
The script stops and waits A plot switch is "show" or "interactive", which wait for keyboard input. See Running unattended on a server.
GPU out of memory in the kernel step Use the iterative eigensolver (eigensolver="eigsh" with DmKernelPars), set batch_size, or use fewer training samples. See Kernel.
The first run of a step is slow, later runs fast JAX compiles each function for the shapes of your data the first time it runs.