seagrid.sources.model.ocean_model#

Daily ocean-model output on the model’s own grid (GLORYS, ECCO2, Scripps GoG).

ModelSource is the base of the sources tracmass reads velocities from. It adds to DataSource:

  • open_dataset(dtm) without data_var opens the velocities (and with tracers=True temperature and salinity) together, downloading the missing files of the day in parallel (ModelSource.fetch_day());

  • grid_definition(): the model’s cell metrics (dxv, dyu, dxdy, dzt, kmt), built once and cached as Zarr;

  • landmask() and distance_to_land() on the model’s T-cells;

  • mask_fill() for the fill values some servers leave in land cells.

Model data keep the model’s layout, which differs from seagrid’s conventions for gridded products: dimensions are z/y/x (and the staggered dimensions of the model where velocities sit on cell faces), and each variable keeps the coordinates of its own grid points. Each source’s docstring describes its layout.

Settings#

variables

Table {key: [file_key, name_in_file]}: the seagrid name of each variable, the part of the remote file name or URL that selects it, and its name in the file.

velocity_vars, tracer_vars

Variables ModelSource.open_dataset() opens without data_var (tracers with tracers=True).

grid_definition

File name of the cached grid definition (Zarr) in datadir().

timestep

Time step of the model output, a pandas.Timedelta string; stored as attrs["timestep"].

retries, retry_wait

Default attempts per day in ModelSource.download_range(), and the seconds between them.

Module Attributes

FILL_THRESHOLD

Values at or above this magnitude are fill values (the netCDF default fill value 9.96921e36 that some OPeNDAP servers leave undecoded in land cells).

Classes

ModelSource([variant])

Daily ocean-model output on the model grid, one variable per file.

OpendapModelSource([variant])

Model output read over OPeNDAP, one day and variable per Zarr store.

seagrid.sources.model.ocean_model.FILL_THRESHOLD = 1e+30#

Values at or above this magnitude are fill values (the netCDF default fill value 9.96921e36 that some OPeNDAP servers leave undecoded in land cells).

class seagrid.sources.model.ocean_model.ModelSource(variant=None, **overrides)[source]#

Bases: DataSource

Daily ocean-model output on the model grid, one variable per file.

See the module docstring for the settings. Subclasses implement _build_grid_definition() and the usual naming and fetch hooks.

Parameters:
  • variant (str | None)

  • overrides (Any)

has_fill_values: ClassVar[bool] = False#

True if land cells hold fill values that mask_fill() replaces.

property variables: dict[str, tuple[str, str]]#

{key: (file_key, name_in_file)} from the variables setting.

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

Variables open_dataset() opens by default.

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

Variables added by open_dataset(tracers=True).

property timestep: Timedelta#

Time step of the model output.

open_dataset(dtm=None, data_var=None, *, tracers=False, mask=True, force=False, dask=True, **kwargs)[source]#

Open one day, downloading the files first if they are not cached.

Parameters:
  • dtm (str, pandas.Timestamp, numpy.datetime64 or datetime, optional) – Day. Default: the first available date.

  • data_var (str, optional) – One variable. Default: velocity_vars together.

  • tracers (bool, optional) – Without data_var, add tracer_vars. Default False.

  • mask (bool, optional) – Replace fill values in land cells (mask_fill()). Default True. False leaves them, for callers that cut out a region first and mask only that (masking a whole Zarr chunk to keep a small part of it is several times slower).

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

  • dask (bool, optional) – Open lazily with the files’ own chunks. Default True.

  • **kwargs – Passed to seagrid.sources.DataSource.open_dataset().

Returns:

xarray.Dataset – The variables on the model grid, with attrs["timestep"].

Return type:

Dataset

mask_fill(da)[source]#

Replace fill values (land) in one variable, lazily.

Velocities (velocity_vars and wvel) become 0 (no flow through land), other variables NaN.

Parameters:

da (xarray.DataArray) – A variable from open_dataset(), named by its key.

Returns:

xarray.DataArray – Same shape and dask chunks.

Return type:

DataArray

fetch_day(dtm, data_vars, *, force=False)[source]#

Download the missing files of several variables of one day.

Parameters:
Returns:

list of str – The variables that were downloaded.

Return type:

list[str]

download_range(start, end=None, data_var=None, *, data_vars=None, force=False, retries=None, retry_wait=None, errors='warn', **kwargs)[source]#

Download every day from start to end, skipping cached days.

A day that fails is tried again retries times, retry_wait seconds apart, and then skipped, so a long download survives a flaky server and can simply be started again.

Parameters:
  • start (str, pandas.Timestamp, numpy.datetime64 or datetime) – First day.

  • end (str, pandas.Timestamp, numpy.datetime64 or datetime, optional) – Last day (inclusive). Default: start only.

  • data_var (str, optional) – One variable (the same as data_vars=[data_var]).

  • data_vars (iterable of str, optional) – Variables. Default velocity_vars.

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

  • retries (int, optional) – Extra attempts per day. Default: the retries setting (3).

  • retry_wait (float, optional) – Seconds between attempts. Default: the retry_wait setting (60).

  • errors ({"warn", "raise", "ignore"}, optional) – What to do with a day that still fails. Default "warn".

  • **kwargs – Ignored (accepted for compatibility with seagrid.sources.DataSource.download_range()).

Returns:

list of pandas.Timestamp – Days that failed after all attempts.

Return type:

list[Timestamp]

downloaded(start=None, end=None, data_vars=None, **kwargs)[source]#

Report which days are cached.

As seagrid.sources.DataSource.downloaded(), with data_vars defaulting to velocity_vars.

Parameters:
Return type:

Series

property grid_definition_path: Path#

The cached grid definition (Zarr).

grid_definition(dask=True, force=False)[source]#

Return the model’s cell metrics, built once and cached as Zarr.

Parameters:
  • dask (bool, optional) – Open the cache lazily with its own chunks. Default True.

  • force (bool, optional) – Build again and overwrite the cache. Default False.

Returns:

xarray.Dataset – dxv (zonal width of the north face, m), dyu (meridional height of the east face, m), dxdy (area, m²), dzt (thickness, m, 0 below the sea floor) and kmt (number of ocean levels, 0 on land), with lon/lat coordinates.

Return type:

Dataset

landmask(k=1, *, cache=True)[source]#

Return the land mask on the model’s T-cells.

Parameters:
  • k (int, optional) – 1-based model level. Default 1 (surface): land is kmt == 0. Deeper, the sea floor counts as land too (kmt < k).

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

Returns:

xarray.DataArray – Boolean (y, x), True on land, with lon/lat.

Return type:

DataArray

distance_from_land(k=1, *, cache=True)[source]#

Return the distance (km) from each T-cell centre to the nearest land cell.

Parameters:
  • k (int, optional) – 1-based model level whose land mask is used (see landmask()). Default 1.

  • cache (bool, optional) – Keep the mask and the distance in memory and as Zarr in geodir(). Default True.

Returns:

xarray.DataArray – float32 (y, x) great-circle distance in km, 0 on land; NaN everywhere (with a warning) if the grid has no land.

Return type:

DataArray

Notes

Distances run between cell centres. On a regional grid land outside the domain is unknown, so distances near open boundaries can be too large.

distance_to_land(k=1, *, cache=True)[source]#

Return distance_from_land() (the tracmass name).

Parameters:
Return type:

DataArray

class seagrid.sources.model.ocean_model.OpendapModelSource(variant=None, **overrides)[source]#

Bases: ModelSource

Model output read over OPeNDAP, one day and variable per Zarr store.

Subclasses implement _open_day(), which opens the remote dataset lazily and returns one day of one variable. Settings: chunks (dask chunks of the remote read), opendap_timeout ([connect, read] seconds per request) and compute_retries (attempts after a connection that drops in the middle of a transfer, default 0).

Parameters:
  • variant (str | None)

  • overrides (Any)

fetch_day(dtm, data_vars, *, force=False)[source]#

Download the missing files of several variables of one day, in parallel.

The OPeNDAP connections are opened concurrently and all writes run in one dask computation. Parameters and return value as for ModelSource.fetch_day().

Parameters:
Return type:

list[str]