seagrid.sources.base#

The DataSource base class: one interface for every data source.

A data source knows how to name, download, open and describe one product. The public methods here are the same for every source; a subclass only fills in hooks (_filename, _remote_url, _fetch, _postprocess, …). Shared behaviour therefore works for all of them: caching, an inventory of downloads, temporal aggregation (monthly or 8-day means from daily files), time series over a date range, bounding-box subsetting, grids and remote availability checks.

Module Attributes

AGGREGATABLE

Time types that can be built by averaging a finer native time type.

STATIC_DTM

The date used for static (time-invariant) products, whatever dtm is.

COORD_NAMES

Coordinate names mapped to seagrid's by rename_vars().

Functions

add_history(ds, text)

Append a line to ds.attrs["seagrid_history"] and return ds.

ascending_lat(ds[, lat])

Return ds with latitude ascending (south to north).

kelvin_to_celsius(ds, var)

Convert var from kelvin to degrees Celsius if its units say kelvin.

lon_to_180(ds[, lon])

Return ds with a 1-D longitude in -180–180, sorted ascending.

parse_date(value)

Parse a configured date, allowing "today" and relative dates.

rename_vars(ds[, names])

Rename variables and coordinates that are present, recording it.

snap_to_grid(ds, grid[, atol])

Replace rounded lat/lon coordinates with the exact grid ones.

Classes

DataSource([variant])

One data product, with the same interface for every source.

class seagrid.sources.base.DataSource(variant=None, **overrides)[source]#

Bases: object

One data product, with the same interface for every source.

Do not instantiate directly: use seagrid.get_source() or a subclass. Each subclass reads the settings section named by its name.

Parameters:
  • variant (str, optional) – Product variant, a key of the section’s variants table (e.g. "nrt"). Its keys replace the section’s keys.

  • **overrides – Settings that replace the configured ones for this object only, e.g. datadir="/scratch/ostia".

Variables:
  • name (str) – Registry name and settings section.

  • aliases (tuple of str) – Other names the source is registered under.

  • title (str) – Human-readable product name.

  • family (str) – "ocean_colour", "sst", "model", "static" or "pp".

  • default_data_var (str or None) – Variable used when none is given (required for sources with one variable per file).

  • default_timetype (str) – Time type used when none is given.

  • default_resolution (str or None) – Resolution used when none is given.

  • one_var_per_file (bool) – True if the variable chooses the file (e.g. NASA L3 products).

  • settings (mapping) – Read-only resolved settings of this source (and variant).

  • variant (str or None) – The selected variant.

Raises:

ValueError – If variant is not one of variants.

land_from: ClassVar[str] = 'gebco'#

"gebco" (GEBCO elevation on the source grid), "flags" (the GHRSST L4 mask variable) or "nan" (cells where a model’s surface field is missing; models have no clouds, so only land is missing).

Type:

Where landmask() takes land from

legacy_sections: ClassVar[tuple[str, ...]] = ()#

2.x settings sections of this source (e.g. "cmems-globgc"), read for credentials only, so existing .secrets.toml files keep working.

property variants: tuple[str, ...]#

Names of the product variants (e.g. ("nrt",)).

property data_vars: tuple[str, ...]#

Configured variables (data_vars setting).

property native_timetypes: tuple[str, ...]#

Time types available as files on the server (timetypes setting).

property timetypes: tuple[str, ...]#

the native ones plus those built by averaging.

Coarser time types in AGGREGATABLE are available whenever a finer one is native, e.g. "8day" and "monthly" from daily files.

Type:

All time types

property resolutions: tuple[str, ...]#

Configured spatial resolutions (resolutions setting).

describe()[source]#

Return a summary of the source for listings and documentation.

Returns:

dict – Name, title, family, variants, variables, time types, resolutions, time range of the default time type, DOI and reference URL.

Return type:

dict[str, Any]

time_range(timetype=None)[source]#

Return the first and last date of the configured time range.

Uses time_ranges[timetype] if set, else dtm_min/dtm_max (see parse_date(): "today" and relative dates such as "-720D" are allowed, for rolling archives). A latency setting (a pandas.Timedelta string such as "70D") ends the range that long before today, for products published with a delay.

Parameters:

timetype (str, optional) – Time type. Default default_timetype.

Returns:

start, end (pandas.Timestamp)

Raises:

ValueError – If the source has no configured time range.

Return type:

tuple[Timestamp, Timestamp]

dtm_vec(timetype=None, start=None, end=None)[source]#

Return the start of every time step in a range.

Parameters:
Returns:

pandas.DatetimeIndex

Return type:

DatetimeIndex

datadir(timetype=None, resolution=None)[source]#

Return the local directory of the cached files (not created).

Parameters:
  • timetype (str, optional) – Sources may keep different time types or resolutions in different directories.

  • resolution (str, optional) – Sources may keep different time types or resolutions in different directories.

Returns:

pathlib.Path

Return type:

Path

filename(dtm=None, data_var=None, *, timetype=None, resolution=None)[source]#

Return the file name of one time step.

Parameters:
  • dtm (str, pandas.Timestamp, numpy.datetime64 or datetime, optional) – Any time in the time step. Default: the first date of time_range() (cached after the first download).

  • data_var (str, optional) – Variable (chooses the file for sources with one variable per file).

  • timetype (str, optional) – Defaults: default_timetype, default_resolution.

  • resolution (str, optional) – Defaults: default_timetype, default_resolution.

Returns:

str

Return type:

str

local_path(dtm=None, data_var=None, *, timetype=None, resolution=None)[source]#

Return the path of the cached file of one time step.

Parameters are as for filename().

Returns:

pathlib.Path

Parameters:
Return type:

Path

remote_url(dtm=None, data_var=None, *, timetype=None, resolution=None)[source]#

Return the server URL of one time step.

Parameters are as for filename().

Returns:

str

Raises:

ValueError – For a time type built by averaging (it has no remote file).

Parameters:
Return type:

str

property inventory_db: Path#

The SQLite inventory of downloaded files (see seagrid.inventory).

download(dtm=None, data_var=None, *, timetype=None, resolution=None, force=False)[source]#

Download one time step, unless it is already cached.

For a time type built by averaging, the finer files are downloaded and the mean is computed and cached.

Parameters:
  • dtm (str, pandas.Timestamp, numpy.datetime64 or datetime, optional) – Any time in the time step. Default: the first date of time_range() (cached after the first download).

  • data_var (str, optional) – Variable.

  • timetype (str, optional) – Defaults: default_timetype, default_resolution.

  • resolution (str, optional) – Defaults: default_timetype, default_resolution.

  • force (bool, optional) – Download even if the file is cached. Default False.

Returns:

pathlib.Path – The cached file.

Raises:

seagrid.download.DownloadError – If the file cannot be downloaded.

Warns:

UserWarning – If dtm is outside the configured time range.

Return type:

Path

download_range(start, end, data_var=None, *, timetype=None, resolution=None, force=False, errors='raise')[source]#

Download every time step in a range.

Parameters:
Returns:

list of pathlib.Path – The files that were downloaded or already cached.

Return type:

list[Path]

check_remote(dtm=None, data_var=None, *, timetype=None, resolution=None)[source]#

Return True if the server has the file of one time step.

Nothing is downloaded.

Parameters are as for filename() (native time types only).

Returns:

bool

Raises:

seagrid.download.DownloadError – If the server cannot be reached.

Parameters:
Return type:

bool

downloaded(start=None, end=None, data_vars=None, *, timetype=None, resolution=None, show=True, force=False)[source]#

Report which time steps are cached.

Parameters:
Returns:

pandas.Series – Bool, indexed by time step.

Return type:

Series

open_dataset(dtm=None, data_var=None, *, timetype=None, resolution=None, force=False, lat_bounds=None, lon_bounds=None, **xr_kwargs)[source]#

Open one time step, downloading it first if it is not cached.

The result follows seagrid’s conventions: lat/lon coordinates with latitude ascending, SST in °C, a time coordinate, and the processing steps in attrs["seagrid_history"].

Parameters:
  • dtm (str, pandas.Timestamp, numpy.datetime64 or datetime, optional) – Any time in the time step. Default: the first date of time_range() (cached after the first download).

  • data_var (str, optional) – Return only this variable. Default: all variables (for sources with one variable per file, the default variable’s file).

  • timetype (str, optional) – Temporal resolution. Default default_timetype. Coarser time types than the native ones are computed as means.

  • resolution (str, optional) – Spatial resolution. Default default_resolution.

  • force (bool, optional) – Download again even if cached. Default False.

  • lat_bounds ((float, float), optional) – Bounding box. Default: the latmin/latmax/lonmin/ lonmax settings (global unless configured).

  • lon_bounds ((float, float), optional) – Bounding box. Default: the latmin/latmax/lonmin/ lonmax settings (global unless configured).

  • **xr_kwargs – Passed to xarray.open_dataset().

Returns:

xarray.Dataset

Raises:
Return type:

Dataset

open_dataarray(dtm=None, data_var=None, **kwargs)[source]#

Open one variable of one time step.

Parameters:
Returns:

xarray.DataArray

Return type:

DataArray

open_mfdataset(start, end, data_var=None, *, timetype=None, resolution=None, errors='raise', **kwargs)[source]#

Open every time step in a range as one dataset along time.

Parameters:
Returns:

xarray.Dataset

Raises:

FileNotFoundError – If no time step in the range could be opened.

Return type:

Dataset

grid(resolution=None)[source]#

Return the horizontal grid of the source.

The grid comes from the grid setting (a grid name, a regular grid or a pyresample area, optionally per resolution, see seagrid.grids.from_settings()), or from _grid().

Parameters:

resolution (str, optional) – Default default_resolution.

Returns:

seagrid.grids.Grid

Return type:

Grid

setup_grid(resolution=None, **kwargs)[source]#

Return grid(); the 2.x name, used by seagrid.match.Match.

Parameters:
  • resolution (str | None)

  • kwargs (Any)

Return type:

Grid

lats(resolution=None, *, cache=True)[source]#

Return the 2-D cell-centre latitudes of the source grid, in degrees.

Parameters:
  • resolution (str, optional) – Default default_resolution.

  • cache (bool, optional) – Keep the result for later calls (see clear_cache()). With False it is computed again and not kept. Default True.

Returns:

numpy.ndarray – Shape grid().shape; read-only when cached.

Return type:

ndarray[tuple[Any, …], dtype[float64]]

lons(resolution=None, *, cache=True)[source]#

Return the 2-D cell-centre longitudes of the source grid, in degrees.

Parameters and caching as in lats().

Parameters:
  • resolution (str | None)

  • cache (bool)

Return type:

ndarray[tuple[Any, …], dtype[float64]]

dx(resolution=None, *, cache=True)[source]#

Return the zonal cell width in metres.

Parameters and caching as in lats().

Parameters:
  • resolution (str | None)

  • cache (bool)

Return type:

ndarray[tuple[Any, …], dtype[float64]]

dy(resolution=None, *, cache=True)[source]#

Return the meridional cell height in metres.

Parameters and caching as in lats().

Parameters:
  • resolution (str | None)

  • cache (bool)

Return type:

ndarray[tuple[Any, …], dtype[float64]]

area(resolution=None, *, cache=True)[source]#

Return the cell area in m².

Parameters and caching as in lats().

Parameters:
  • resolution (str | None)

  • cache (bool)

Return type:

ndarray[tuple[Any, …], dtype[float64]]

geodir()[source]#

Return the directory where landmask() and friends are stored.

The geodir setting if the source’s section has one, else <datadir>/geo (geo_<variant> for a variant).

Returns:

pathlib.Path

Return type:

Path

landmask(resolution=None, *, cache=True)[source]#

Return the land mask of the source grid.

Land comes from the source itself where it has a land flag (land_from): the mask variable of the GHRSST L4 products (OSTIA, AVHRR OI, MUR), the missing cells of a model’s surface field (SMOC, CMEMS BGC, the carbonate system), or kmt for the models on their own grids. Otherwise it is GEBCO (downloaded on first use, about 7.5 GB), reduced to the land fraction of each cell: a cell is land if more than half of it is above sea level.

Parameters:
  • resolution (str, optional) – Default default_resolution.

  • cache (bool, optional) – Keep the mask in memory and store it as Zarr in geodir(), and use the stored mask next time. With False it is built again and neither kept nor stored. Default True.

Returns:

xarray.DataArray – Boolean on the source grid, True on land. Read-only when cached (use .copy() to modify it).

Return type:

DataArray

distance_from_land(resolution=None, *, cache=True)[source]#

Return the great-circle distance from each cell centre to land, in km.

Parameters:
  • resolution (str, optional) – Default default_resolution.

  • cache (bool, optional) – As in landmask() (both the mask and the distance).

Returns:

xarray.DataArray – float32 km on the source grid, 0 on land; NaN everywhere (with a warning) if the grid has no land.

Return type:

DataArray

clear_cache(*, disk=False)[source]#

Forget the geographic fields and grids kept in memory.

Parameters:

disk (bool, optional) – Also delete the stored land masks and distances in geodir(). Default False.

Return type:

None

longhurst_provinces(resolution=None, *, version=None, fill=True, cache=True)[source]#

Return the Longhurst province of every cell of the source grid.

The provinces (see seagrid.longhurst) are taken at each cell centre: from the 1/6° grid of the 2007 version, or from the polygons of the 1995 version. Their coastline is coarse, so some ocean cells near the coast fall in no province; with fill they take the nearest one, using landmask() to tell ocean from land.

Parameters:
  • resolution (str, optional) – Default default_resolution.

  • version ({"2007", "1995"}, optional) – Default "2007" (57 provinces). "1995" (54 provinces, other numbers) warns.

  • fill (bool, optional) – Give ocean cells outside every polygon the nearest province. Default True. Needs landmask() (which may download GEBCO).

  • cache (bool, optional) – Keep the result in memory and as Zarr in geodir(), as for landmask(). Default True.

Returns:

xarray.DataArray – int16 province numbers (1–57, or 1–54 for 1995; 0 on land and, without fill, outside every province). attrs["flag_values"] and attrs["flag_meanings"] give the province codes (spaces in codes such as NAST E become _).

Return type:

DataArray

longhurst_biomes(resolution=None, *, version=None, fill=True, cache=True)[source]#

Return the Longhurst biome of every cell (see longhurst_provinces()).

Returns:

xarray.DataArray – int16: 0 land, 1 Coastal, 2 Polar, 3 Trades, 4 Westerlies (seagrid.longhurst.BIOMES).

Parameters:
  • resolution (str | None)

  • version (str | None)

  • fill (bool)

  • cache (bool)

Return type:

DataArray

longhurst_basins(resolution=None, *, version=None, fill=True, cache=True)[source]#

Return the ocean basin of every cell (see longhurst_provinces()).

Returns:

xarray.DataArray – int16: 0 land, 1 Arctic, 2 Atlantic, 3 Indian, 4 Pacific, 5 Southern (seagrid.longhurst.BASINS).

Parameters:
  • resolution (str | None)

  • version (str | None)

  • fill (bool)

  • cache (bool)

Return type:

DataArray

regrid(target, dtm=None, data_var=None, *, method='bin', stat='mean', fill=False, **kwargs)[source]#

Open one time step and resample it onto another grid.

Parameters:
  • target (seagrid.grids.Grid, pyresample geometry or grid name) – Grid of the result, e.g. seagrid.grids.cbiomes_halfdeg().

  • dtm (str, pandas.Timestamp, numpy.datetime64 or datetime, optional) – Any time in the time step. Default: the first available date.

  • data_var (str, optional) – Only this variable. Default: all variables on the grid.

  • method ({"bin", "nearest"}, optional) – See seagrid.resample.regrid(). Default "bin".

  • stat ({"mean", "sum", "count", "min", "max"}, optional) – Statistic for method="bin". Default "mean".

  • fill (bool, optional) – Fill empty target cells by nearest neighbour. Default False.

  • **kwargs – Passed to open_dataset() (timetype, resolution).

Returns:

xarray.Dataset

Return type:

Dataset

match(lon, lat, time, data_var=None, *, nei=1, days_behind=0, days_ahead=0, max_distance=None, progress=False, **kwargs)[source]#

Return the value of the source at each of a set of observations.

Each time step is opened once for all observations in it.

Parameters:
  • lon (array_like) – Positions in decimal degrees.

  • lat (array_like) – Positions in decimal degrees.

  • time (array_like) – Time of each observation.

  • data_var (str, optional) – Variable. Default default_data_var.

  • nei (int, optional) – Use the nearest finite of the nei nearest cells. Default 1.

  • days_behind (int, optional) – Also sample days before and after (one column per day).

  • days_ahead (int, optional) – Also sample days before and after (one column per day).

  • max_distance (float, optional) – NaN for observations farther than this (metres) from a cell centre.

  • progress (bool, optional) – Show a progress bar. Default False.

  • **kwargs – Passed to open_dataset() (timetype, resolution).

Returns:

numpy.ndarray – One value per observation (see seagrid.match.Match.sample()).

Return type:

ndarray

Examples

>>> df["sst"] = ostia.match(df.lon, df.lat, df.index)
climatology(data_var=None, **kwargs)[source]#

Build (or read the cached) monthly climatology of a variable.

Parameters:
  • data_var (str, optional) – Variable. Default default_data_var.

  • **kwargs – grid (default: CBIOMES 0.5°), start, end, timetype, stat ("median" or "mean") and the other keywords of seagrid.climatology.build().

Returns:

xarray.DataArray – Dimensions (month, lat, lon).

Return type:

DataArray

seagrid.sources.base.add_history(ds, text)[source]#

Append a line to ds.attrs["seagrid_history"] and return ds.

Works on Datasets and DataArrays.

Parameters:
  • ds (XrObj)

  • text (str)

Return type:

XrObj

seagrid.sources.base.ascending_lat(ds, lat='lat')[source]#

Return ds with latitude ascending (south to north).

Parameters:
Return type:

Dataset

seagrid.sources.base.kelvin_to_celsius(ds, var)[source]#

Convert var from kelvin to degrees Celsius if its units say kelvin.

Parameters:
Return type:

Dataset

seagrid.sources.base.lon_to_180(ds, lon='lon')[source]#

Return ds with a 1-D longitude in -180–180, sorted ascending.

Examples

>>> ds = xr.Dataset(coords={"lon": [0.0, 90.0, 180.0, 270.0]})
>>> lon_to_180(ds).lon.values.tolist()
[-180.0, -90.0, 0.0, 90.0]
Parameters:
Return type:

Dataset

seagrid.sources.base.parse_date(value)[source]#

Parse a configured date, allowing "today" and relative dates.

Parameters:

value (str, pandas.Timestamp or datetime) – A date ("2010-01-01"), "today"/"now", or a signed pandas.Timedelta string relative to today ("-720D").

Returns:

pandas.Timestamp – Normalized to midnight.

Return type:

Timestamp

Examples

>>> parse_date("2010-01-01 12:00")
Timestamp('2010-01-01 00:00:00')
>>> parse_date("-1D") == pd.Timestamp.now().normalize() - pd.Timedelta(days=1)
True
seagrid.sources.base.rename_vars(ds, names=None)[source]#

Rename variables and coordinates that are present, recording it.

Parameters:
  • ds (xarray.Dataset)

  • names (mapping, optional) – {old: new}, in addition to COORD_NAMES (latitude/longitude to lat/lon).

Returns:

xarray.Dataset

Return type:

Dataset

Examples

>>> ds = xr.Dataset({"utotal": ("latitude", [1.0])}, {"latitude": [0.0]})
>>> list(rename_vars(ds, {"utotal": "uvel"}).variables)
['uvel', 'lat']
seagrid.sources.base.snap_to_grid(ds, grid, atol=1e-3)[source]#

Replace rounded lat/lon coordinates with the exact grid ones.

Files often store coordinates in float32, or with small rounding errors. If ds has the shape of grid and its coordinates agree within atol, they are replaced by the grid’s; if the shape matches but they disagree, a warning is issued and ds is returned unchanged.

Parameters:
Returns:

xarray.Dataset

Return type:

Dataset