Skip to main content

2. Data

Reading ERA5 fields and station records, and turning them into predictors and a target

The data block of the NLSA Python toolkit: data specifications for ERA5 reanalysis and 14th Weather Squadron station records, time settings, climatology removal, smoothing and standardization, spatial sampling, file requirements, and the Lorenz 63 test data.

Every experiment has predictors and a target. The predictors (called covariates in the code, class Covariate) describe the state of the system at the time a forecast is made. The target (response, class Response) is the quantity to forecast, or to verify against.

Both are made of data specifications: an era5.DataSpecs for a reanalysis field or a ws44.DataSpecs for station records. A data specification says which variables to read, over which domain or at which stations, for which period, from which files, and how to remove the climatology and standardize. For example, the predictors of the Niño 3.4 forecasts:

sst_field = era5.DataSpecs(
    vars=[era5.Var.SST],                                   # sea surface temperature
    domain=era5.nino34_domain(step_lon=4, step_lat=4),     # every 4th grid point
    time=Time(date_range=("1940-01-01", "2019-12-31"), sampling="monthly",
              custom_climatology_date_range=("1940-01-01", "2019-12-31")),
    io=era5.IO(input_path="/storage/data/era5/monthly_1940-2025_nc", file_format="nc"),
    climatology=Climatology(remove=False, standardize=True),
)
predictors = Covariate(specs=(sst_field,))

Processing steps

clim.extract_data_arrays(data_pars) reads the predictors and the target of a DataPars object and returns them as arrays. For each ERA5 data specification, clim.read_gridded_dataset does the following, in this order:

  1. Open the files. All files in the folder io.input_path with the extension io.file_format are opened together as one data set, sorted by latitude, and cut to the domain.
  2. Spatial sampling. Grid points are kept, thinned, averaged in blocks or averaged over the domain, as set by Domain.sampling (see below).
  3. Climatology. If Climatology.remove is set, the mean of each calendar month (monthly data) or of each day of the year (daily data) over the climatology period is subtracted.
  4. Smoothing. If Time.rolling_window is set, a running mean over that many samples is applied.
  5. Standardization. If Climatology.standardize is set, the data are centred and scaled with statistics from the climatology period (see Standardization).
  6. Dates. The period Time.date_range is selected.

The arrays are then assembled: all grid points of all variables become the columns of one array, with one row per time; columns with any missing value are dropped (for example land points of a sea surface temperature field); and the arrays of the different data specifications of the predictors are placed side by side. If DataPars.velocity_covariate is set, the rate of change of every column is computed with a central finite difference and stored alongside (see Delay embedding).

TipThe climatology period comes from the training data

Steps 3–5 use the climatology period, and the dates are selected only at the end. So the climatology period can lie outside the date range, and the test data can (and should) use the climatology of the training period: give both the same custom_climatology_date_range. The files must then cover both the dates and the climatology period.

Time settings

Time (nlsa_models.climate, defined in src/nlsa_models/climate.py)
Option Type or values Default Description
date_range tuple[str, str] required First and last date ("YYYY-MM-DD") of the data. For training data this is the training period, for test data the test period.
sampling "monthly" or "daily" required Time sampling: "monthly" or "daily".
rolling_window int or None None Length, in samples, of a running mean applied after the climatology is removed. None means no smoothing.
rolling_mode "forward" or "backward" or "center" "center" Alignment of the running-mean window: "center" (centred), "backward" (the current and previous samples) or "forward" (the current and following samples).
custom_climatology_date_range tuple[str, str] or None None Period used to compute the climatology and the standardization statistics. If None, date_range is used. Set it to the training period for both training and test data, so that test anomalies use the training climatology.

The running mean uses the samples that are available near the ends of the record (min_periods=1), so the first and last values are averages over fewer samples. One exception: for ERA5 data with rolling_mode="forward", the last rolling_window − 1 dates of the files get no value, so the files must extend at least that far beyond the end of date_range.

Climatology and standardization

Climatology (nlsa_models.climate, defined in src/nlsa_models/climate.py)
Option Type or values Default Description
remove bool False Subtract the mean annual cycle (the average for each calendar month, or each day of the year for daily data) computed over the climatology period.
standardize bool False Rescale the data using statistics from the climatology period (see Standardization above).

Standardization

Standardization puts the predictors on a common scale. The mean is taken over the climatology period, separately at each grid point (after any climatology removal and smoothing). The scaling depends on the data:

Data Scaling
ERA5, "pointwise" sampling Each variable is divided by the square root of its total variance, summed over all grid points and averaged over time. The field as a whole has unit variance, and the relative amplitudes of the grid points are kept.
ERA5, any other sampling Each grid point or average is divided by its own standard deviation.
Station records Each variable of each station is scaled to zero mean and unit variance.

For a pointwise field \(x(s, t)\) at grid points \(s\), with means \(\bar x(s)\) over the climatology period of \(T_c\) samples,

\[ \tilde x(s, t) = \frac{x(s, t) - \bar x(s)}{\Big[\frac{1}{T_c} \sum_{t} \sum_{s'} \big(x(s', t) - \bar x(s')\big)^2\Big]^{1/2}}. \]

This matters when predictors are combined. A pointwise ERA5 field contributes one unit of variance per variable however many grid points it has, while each station variable, and each grid point of a coarsened field, contributes one unit. Since the kernel compares predictors through their total distance, these weights decide how much each block of predictors counts.

ERA5 reanalysis

Domain and spatial sampling

Domain (nlsa_models.era5, defined in src/nlsa_models/era5.py)
Option Type or values Default Description
sampling "pointwise" or "coarsened" or "area_averaged" or "meridionally_averaged" or "zonally_averaged" required How grid points are used: "pointwise", "coarsened", "area_averaged", "meridionally_averaged" or "zonally_averaged" (see Spatial sampling).
min_lon float or None None Western edge of the domain, in degrees east (0–360).
max_lon float or None None Eastern edge of the domain, in degrees east (0–360).
min_lat float or None None Southern edge of the domain, in degrees north.
max_lat float or None None Northern edge of the domain, in degrees north.
step_lon int or None None Step in grid points along longitude: keep every step_lon-th point ("pointwise") or average blocks of step_lon points ("coarsened").
step_lat int or None None Step in grid points along latitude, as for step_lon.
Spatial sampling options (era5.Domain.sampling)
sampling Result Role of step_lon, step_lat
"pointwise" The field at every grid point Keep every step_lon-th longitude and step_lat-th latitude; with ERA5’s 0.25° grid, 4 gives a 1° grid.
"coarsened" Averages over blocks of grid points Block size; at least one step must be given.
"area_averaged" One value per time: the average over the domain Not used.
"meridionally_averaged" A profile in longitude: the average over latitude If step_lon is given, blocks of step_lon longitudes are averaged first.
"zonally_averaged" A profile in latitude: the average over longitude No effect on the result. (The code coarsens longitude by step_lat before averaging over all longitudes.)

Averages are plain means over grid points, not weighted by the area of the grid cells. This makes little difference near the equator but gives more weight to high latitudes in large domains. Domains are cut with min_lon < max_lon in degrees east from 0 to 360, so a domain cannot cross the 0° meridian.

Three domains are predefined; all accept the sampling, step_lon and step_lat arguments:

Predefined domains in nlsa_models.era5
Function Longitudes Latitudes Used for
era5.nino34_domain() 190°E–240°E (170°W–120°W) 5°S–5°N Niño 3.4 predictors and index
era5.indo_pacific_domain() 28°E–290°E 60°S–20°N Indo-Pacific SST for Koopman modes
era5.global_domain() 0°–360°E 90°S–90°N Spatial patterns (projections)

For other regions, create the domain directly, for example the MJO target box: era5.Domain(sampling="area_averaged", min_lon=120, max_lon=150, min_lat=-5, max_lat=5).

Files

IO (nlsa_models.era5, defined in src/nlsa_models/era5.py)
Option Type or values Default Description
input_path str or Path or None None Folder with the ERA5 files. All files with the chosen extension in the folder are opened together as one data set.
file_format "grib" or "nc" "nc" File format: "nc" (NetCDF) or "grib".

The code expects:

  • One data set per folder. Every file with the given extension in the folder is opened, and the files are combined along time.

  • Coordinates named time, latitude and longitude, with longitudes from 0° to 360°. ERA5 NetCDF files from the current Copernicus Climate Data Store name the time coordinate valid_time instead; rename it once after downloading:

    import xarray as xr
    ds = xr.open_dataset("era5_sst_monthly.nc")
    ds = ds.rename({"valid_time": "time"}).drop_vars(["expver", "number"], errors="ignore")
    ds.to_netcdf("era5_sst_monthly_time.nc")
  • One value per month or per day, without gaps. The number of samples is computed from the dates, so missing months or days would misalign the data.

  • Coverage of both the date range and the climatology period.

GRIB files (file_format="grib") are read with cfgrib, which is installed with the toolkit.

Data specification and variables

DataSpecs (nlsa_models.era5, defined in src/nlsa_models/era5.py)
Option Type or values Default Description
vars Sequence[Var] required ERA5 variables to read (see the variable table).
domain Domain required Spatial domain and spatial sampling, as an era5.Domain.
time Time required Period, time sampling and smoothing, as a climate.Time.
io IO required Location and format of the files, as an era5.IO.
climatology Climatology Climatology() Anomaly and standardization settings, as a climate.Climatology.
Var (nlsa_models.era5)
Member Value Description
AVG_TNLWRF "avg_tnlwrf" Mean top net long-wave radiation flux. This is the outgoing longwave radiation with a negative sign, since ERA5 counts downward fluxes as positive.
MSL "msl" Mean sea level pressure.
SST "sst" Sea surface temperature.
SP "sp" Surface pressure.
CAPE "cape" Convective available potential energy.
TCWV "tcwv" Total column water vapor.
T2M "t2m" 2 meter temperature.
TSR "tsr" Top net shortwave (solar) radiation.
TTR "ttr" Top net longwave (thermal) radiation.
CP "cp" Convective precipitation.
LSP "lsp" Large-scale precipitation.
TENV "10v" 10-meter V wind component.
SSRO "ssro" Subsurface runoff
LAI_HV "lai_hv" Leaf area index, high vegetation.
LAI_LW "lai_lv" Leaf area index, low vegetation.

The value of each member is the name of the variable in the files. To use another ERA5 variable, add a member to era5.Var with its name in your files.

Station records

The station records of the U.S. Air Force 14th Weather Squadron are read by nlsa_models.ws44, which has two sets of classes: one for the stations of the southwestern United States and the western Pacific, and one (HighLat…) for Pituffik Space Base in Greenland, whose records come in a different format. For each station and variable, the reader fills missing days by linear interpolation (and prints how many were filled), averages to months if sampling="monthly", then removes the climatology, smooths, standardizes and selects the dates, as for ERA5 data.

Southwestern United States and western Pacific

IO (nlsa_models.ws44, defined in src/nlsa_models/ws44.py)
Option Type or values Default Description
input_path str or Path or None None Folder with one <STATION>_dailystats.csv file per station.
file_format "csv" "csv" File format; only "csv" is supported.
DataSpecs (nlsa_models.ws44, defined in src/nlsa_models/ws44.py)
Option Type or values Default Description
vars Sequence[Var] required Station variables, as ws44.Var members (columns of the daily-statistics files).
stations Sequence[Station] required Stations, as ws44.Station members (ICAO codes). Each station adds its variables as columns of the predictor vector.
time Time required Period, time sampling and smoothing, as a climate.Time. Monthly sampling averages the daily values.
io IO required Location of the files, as a ws44.IO.
climatology Climatology Climatology() Anomaly and standardization settings, as a climate.Climatology.

The files are named <ICAO code>_dailystats.csv (for example KEDW_dailystats.csv), one per station, with columns YEAR, MO and DAY for the date and one column per variable, named by the values below. Units follow the names: temperature in °C, wind in m/s, precipitation in inches.

Var (nlsa_models.ws44)
Member Value Description
TEMP_C_MAX "temp_c_max" Max temperature.
TEMP_C_MIN "temp_c_min" Min temperature.
TEMP_C_MEAN "temp_c_mean" Mean temperature.
SLP_MAX "slp_max" Max sea level pressure.
SLP_MIN "slp_min" Min sea level pressure.
SLP_MEAN "slp_mean" Mean sea level pressure.
STP_MAX "stp_max" Max station pressure.
STP_MIN "stp_min" Min station pressure.
STP_MEAN "stp_mean" Mean station pressure.
U_WIND_MPS_MEAN "u_wind_mps_mean" Mean zonal winds.
V_WIND_MPS_MEAN "v_wind_mps_mean" Mean meridional winds.
DAILY_PRECIP_IN "daily_precip_in" Precipitation.
Station (nlsa_models.ws44)
Code Station
KABQ Albuquerque International Sunport (Kirtland AFB), NM
KBLH Blythe Airport, CA
KBUR Hollywood Burbank Airport, CA
KCDS Childress Municipal Airport, TX
KCNM Cavern City Air Terminal, NM
KCRQ McClellan-Palomar Airport, CA
KCVN Clovis Regional Airport, NM
KCVS Cannon AFB, NM
KDAG Barstow-Daggett Airport, CA
KDLF Laughlin AFB, TX
KDMA Davis–Monthan AFB, AZ
KDMN Deming Municipal Airport, NM
KDRT Del Rio International Airport, TX
KDUG Bisbee Douglas International Airport, AZ
KEDW Edwards AFB, CA
KELP El Paso International Airport, TX
KFHU Libby Army Airfield, AZ
KGDP Guadalupe Pass Weather Station, TX
KHHR Hawthorne Municipal Airport, CA
KHMN Holloman AFB, NM
KHOB Lea County Regional Airport, NM
KINK Winkler County Airport, TX
KIPL Imperial County Airport, CA
KIWA Phoenix–Mesa Gateway Airport (former Williams AFB), AZ
KLAX Los Angeles International Airport, CA
KLBB Lubbock, TX
KLGB Long Beach Airport, CA
KLPC Lompoc Airport, CA
KLRU Las Cruces International Airport, NM
KLSV Nellis AFB, NV
KLUF Luke AFB, AZ
KMAF Midland International Air & Space Port, TX
KMRF Marfa Municipal, TX
KNJK El Centro NAF, CA
KNSI San Nicolas Island NOLF, CA
KNTD Point Mugu NAS, CA
KNYL Marine Corps Air Station, Yuma, AZ
KNZY North Island NAS, CA
KONT Ontario International Airport, CA
KOXR Oxnard Airport, CA
KPHX Phoenix Sky Harbor International Airport, AZ
KPRC Prescott Regional Airport, AZ
KPSP Palm Springs International Airport, CA
KRIV March Air Reserve Base, CA
KROW Roswell International Air Center, NM
KREE Reese AFB, TX
KSAD Safford Regional Airport, AZ
KSAN San Diego International Airport, CA
KSBA Santa Barbara Municipal Airport, CA
KSMX Santa Maria Public Airport, CA
KSDB Sandberg Airstrip, CA
KSEE Gillespie Field, CA
KSUU Travis Air Force Base, CA
KSJT San Angelo Regional Airport (Mathis Field), TX
KSMO Santa Monica Municipal Airport, CA
KSNA John Wayne Airport, CA
KSRR Sierra Blanca Regional Airport, NM
KTCS Truth or Consequences Municipal Airport, NM
KTUS Tucson International Airport, AZ
KTRM Jacqueline Cochran Regional Airport, CA
KWJF General William J. Fox Airfield, CA
KVBG Vandenberg Space Force Base, CA
KVNY Van Nuys Airport, CA
PGUA Andersen AFB, Guam
PKWA Bucholz Army Airfield, Kwajalein Atoll, Marshall Islands
PWAK Wake Island Airfield, Wake Atoll

To add a station, add its ICAO code to ws44.Station and put its file in the data folder.

Pituffik, Greenland

HighLatIO (nlsa_models.ws44, defined in src/nlsa_models/ws44.py)
Option Type or values Default Description
input_path str or Path or None None Folder with one subfolder per station; all CSV files in a station’s subfolder are merged on their obs_date column.
file_format "csv" "csv" File format; only "csv" is supported.
HighLatDataSpecs (nlsa_models.ws44, defined in src/nlsa_models/ws44.py)
Option Type or values Default Description
vars Sequence[HighLatVar] required Variables, as ws44.HighLatVar members.
stations Sequence[HighLatStation] required Stations, as ws44.HighLatStation members (currently BGTL, Pituffik Space Base).
time Time required Period, time sampling and smoothing, as a climate.Time.
io HighLatIO required Location of the files, as a ws44.HighLatIO.
climatology Climatology Climatology() Anomaly and standardization settings, as a climate.Climatology.

The records are in a subfolder named after the station, BGTL/, which may contain several CSV files. Each file has an obs_date column, a platformid column (dropped on reading) and variable columns named by the values below; the files are merged on obs_date.

HighLatVar (nlsa_models.ws44)
Member Value Description
MAXTEMP "maxtemp" Max temperature.
MINTEMP "mintemp" Min temperature.
MEANTEMP "meantemp" Mean temperature.
MAXSLP "maxslp" Max sea level pressure.
MINSLP "minslp" Min sea level pressure.
MEANSLP "meanslp" Mean sea level pressure.
MAXSTP "maxstp" Max station pressure.
MINSTP "minstp" Min station pressure.
MEANSTP "meanstp" Mean station pressure.
AVG_U_WIND "avg_u_wind" Mean zonal winds.
AVG_V_WIND "avg_v_wind" Mean meridional winds.
PRECIP_IN "precip_in" Precipitation.
HighLatStation (nlsa_models.ws44)
Code Station
BGTL Pituffik Space Base (formerly Thule Air Base), Greenland

Predictors and target

Covariate (nlsa_models.climate, defined in src/nlsa_models/climate.py)
Option Type or values Default Description
specs sequence of era5.DataSpecs, ws44.DataSpecs or ws44.HighLatDataSpecs required One or more data specifications (ERA5 or station). Their columns are joined side by side into the predictor vector.
Response (nlsa_models.climate, defined in src/nlsa_models/climate.py)
Option Type or values Default Description
specs era5.DataSpecs (area-averaged), ws44.DataSpecs or ws44.HighLatDataSpecs required One data specification for the quantity to forecast: an ERA5 field with "area_averaged" sampling (for example the Niño 3.4 index) or a station variable.

The predictors and the target are combined in a DataPars object, one for the training period and one for the test period. Its first two fields are:

DataPars (nlsa_models.climate, defined in src/nlsa_models/climate.py)
Option Type or values Default Description
covariate Covariate required Predictors, as a climate.Covariate.
response Response required Forecast target, as a climate.Response.

The other fields of DataPars set up the delay embedding; they are described in the next block.

Result

clim.extract_data_arrays(data_pars, dtype) returns an NPData object of NumPy arrays, which to_device(dtype, shardings) copies to the CPU or GPU as a Data object of JAX arrays:

Data containers in nlsa_models.climate
Object Field Contents
NPData time Dates of all samples in the period (a pandas DatetimeIndex)
covariate Predictors: one row per date and one column per grid point and variable; with velocities, an array of shape (dates, 2, columns) holding the values and their rates of change
response Target: one value per date
Data covariate, response The same arrays, on the device, in the precision of the run

Lorenz 63

For the Lorenz 63 examples the data are not read from files but simulated: nlsa_models.lorenz63 integrates the Lorenz 63 equations with the standard parameters (σ = 10, ρ = 28, β = 8/3) with an adaptive Runge–Kutta solver (Diffrax), discards a spin-up period, and samples the trajectory at intervals dt. Its DataPars class combines the data and the embedding settings:

DataPars (nlsa_models.lorenz63, defined in src/nlsa_models/lorenz63.py)
Option Type or values Default Description
covariate "x" or "y" or "z" or "xy" or "xyz" required Components of the Lorenz 63 state used as predictors: "x", "y", "z", "xy" or "xyz".
response "x" or "y" or "z" required Component to forecast: "x", "y" or "z".
dt float required Sampling interval, in model time units.
x0 tuple[float, float, float] required Initial condition of the simulated trajectory.
num_spinup int required Samples discarded at the start of the simulation, so that the trajectory is on the attractor.
num_samples int required Number of samples left after spin-up, delay embedding and finite differences (set directly here, unlike the climate pipeline where it follows from the dates).
num_half_delays int 0 As for the climate DataPars.
delay_embedding_mode "explicit" or "on_the_fly" "on_the_fly" As for the climate DataPars.
num_before int 0 As for the climate DataPars.
num_after int 0 As for the climate DataPars.
velocity_covariate bool False As for the climate DataPars.
velocity_fd_order 2 or 4 or 6 or 8 or None None As for the climate DataPars.
eval_batch_size int or None None As for the climate DataPars.