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
|
Time types that can be built by averaging a finer native time type. |
|
The date used for static (time-invariant) products, whatever dtm is. |
|
Coordinate names mapped to seagrid's by |
Functions
|
Append a line to |
|
Return ds with latitude ascending (south to north). |
|
Convert var from kelvin to degrees Celsius if its units say kelvin. |
|
Return ds with a 1-D longitude in -180–180, sorted ascending. |
|
Parse a configured date, allowing |
|
Rename variables and coordinates that are present, recording it. |
|
Replace rounded |
Classes
|
One data product, with the same interface for every source. |
- class seagrid.sources.base.DataSource(variant=None, **overrides)[source]#
Bases:
objectOne 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 itsname.- Parameters:
variant (
str, optional) – Product variant, a key of the section’svariantstable (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 (
tupleofstr) – 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 (
strorNone) – 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 (
strorNone) – 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).
- Raises:
ValueError – If variant is not one of
variants.
- land_from: ClassVar[str] = 'gebco'#
"gebco"(GEBCO elevation on the source grid),"flags"(the GHRSST L4maskvariable) 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.tomlfiles keep working.
- property native_timetypes: tuple[str, ...]#
Time types available as files on the server (
timetypessetting).
- property timetypes: tuple[str, ...]#
the native ones plus those built by averaging.
Coarser time types in
AGGREGATABLEare available whenever a finer one is native, e.g."8day"and"monthly"from daily files.- Type:
All time types
- time_range(timetype=None)[source]#
Return the first and last date of the configured time range.
Uses
time_ranges[timetype]if set, elsedtm_min/dtm_max(seeparse_date():"today"and relative dates such as"-720D"are allowed, for rolling archives). Alatencysetting (apandas.Timedeltastring such as"70D") ends the range that long before today, for products published with a delay.- Parameters:
timetype (
str, optional) – Time type. Defaultdefault_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:
timetype (
str, optional) – Time type. Defaultdefault_timetype.start (
str,pandas.Timestamp,numpy.datetime64ordatetime, optional) – Range. Default:time_range(), ending no later than today.end (
str,pandas.Timestamp,numpy.datetime64ordatetime, optional) – Range. Default:time_range(), ending no later than today.
- Returns:
- Return type:
DatetimeIndex
- datadir(timetype=None, resolution=None)[source]#
Return the local directory of the cached files (not created).
- Parameters:
- Returns:
- Return type:
- 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.datetime64ordatetime, optional) – Any time in the time step. Default: the first date oftime_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:
- Return type:
- 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:
- Parameters:
- Return type:
- 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:
- Raises:
ValueError – For a time type built by averaging (it has no remote file).
- Parameters:
- Return type:
- 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.datetime64ordatetime, optional) – Any time in the time step. Default: the first date oftime_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:
- download_range(start, end, data_var=None, *, timetype=None, resolution=None, force=False, errors='raise')[source]#
Download every time step in a range.
- Parameters:
start (
str,pandas.Timestamp,numpy.datetime64ordatetime) – Range (inclusive).end (
str,pandas.Timestamp,numpy.datetime64ordatetime) – Range (inclusive).data_var (
str, optional) – As fordownload().timetype (
str, optional) – As fordownload().resolution (
str, optional) – As fordownload().force (
bool, optional) – Download even cached files.errors (
{"raise", "warn", "ignore"}, optional) – What to do when one time step fails. Default"raise".
- Returns:
listofpathlib.Path– The files that were downloaded or already cached.- Return type:
- 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:
- Raises:
seagrid.download.DownloadError – If the server cannot be reached.
- Parameters:
- Return type:
- downloaded(start=None, end=None, data_vars=None, *, timetype=None, resolution=None, show=True, force=False)[source]#
Report which time steps are cached.
- Parameters:
start (
str,pandas.Timestamp,numpy.datetime64ordatetime, optional) – Range. Default:time_range(), ending no later than today.end (
str,pandas.Timestamp,numpy.datetime64ordatetime, optional) – Range. Default:time_range(), ending no later than today.data_vars (
listofstr, optional) – Variables that must all be cached. Default: the default variable (sources with one variable per file) or["all"].timetype (
str, optional) – As fordownload().resolution (
str, optional) – As fordownload().show (
bool, optional) – Print a summary (seeseagrid.inventory.summary()).force (
bool, optional) – Check every file on disk, not trusting the inventory.
- 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/loncoordinates with latitude ascending, SST in °C, atimecoordinate, and the processing steps inattrs["seagrid_history"].- Parameters:
dtm (
str,pandas.Timestamp,numpy.datetime64ordatetime, optional) – Any time in the time step. Default: the first date oftime_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. Defaultdefault_timetype. Coarser time types than the native ones are computed as means.resolution (
str, optional) – Spatial resolution. Defaultdefault_resolution.force (
bool, optional) – Download again even if cached. Default False.lat_bounds (
(float,float), optional) – Bounding box. Default: thelatmin/latmax/lonmin/lonmaxsettings (global unless configured).lon_bounds (
(float,float), optional) – Bounding box. Default: thelatmin/latmax/lonmin/lonmaxsettings (global unless configured).**xr_kwargs – Passed to
xarray.open_dataset().
- Returns:
- Raises:
ValueError – For an unknown time type or resolution.
seagrid.download.DownloadError – If the file cannot be downloaded.
- Return type:
- open_dataarray(dtm=None, data_var=None, **kwargs)[source]#
Open one variable of one time step.
- Parameters:
dtm (
str,pandas.Timestamp,numpy.datetime64ordatetime, optional) – Any time in the time step. Default: the first date oftime_range()(cached after the first download).data_var (
str, optional) – Variable. Defaultdefault_data_var, else the first ofdata_vars.**kwargs – Passed to
open_dataset().
- Returns:
- Return type:
- 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:
start (
str,pandas.Timestamp,numpy.datetime64ordatetime) – Range (inclusive).end (
str,pandas.Timestamp,numpy.datetime64ordatetime) – Range (inclusive).data_var (
str, optional) – As foropen_dataset().timetype (
str, optional) – As foropen_dataset().resolution (
str, optional) – As foropen_dataset().errors (
{"raise", "warn", "ignore"}, optional) – What to do when a time step cannot be opened.**kwargs – Passed to
open_dataset().
- Returns:
- Raises:
FileNotFoundError – If no time step in the range could be opened.
- Return type:
- grid(resolution=None)[source]#
Return the horizontal grid of the source.
The grid comes from the
gridsetting (a grid name, a regular grid or a pyresample area, optionally per resolution, seeseagrid.grids.from_settings()), or from_grid().- Parameters:
resolution (
str, optional) – Defaultdefault_resolution.- Returns:
- Return type:
- setup_grid(resolution=None, **kwargs)[source]#
Return
grid(); the 2.x name, used byseagrid.match.Match.
- lats(resolution=None, *, cache=True)[source]#
Return the 2-D cell-centre latitudes of the source grid, in degrees.
- Parameters:
resolution (
str, optional) – Defaultdefault_resolution.cache (
bool, optional) – Keep the result for later calls (seeclear_cache()). With False it is computed again and not kept. Default True.
- Returns:
numpy.ndarray– Shapegrid().shape; read-only when cached.- Return type:
- 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().
- dx(resolution=None, *, cache=True)[source]#
Return the zonal cell width in metres.
Parameters and caching as in
lats().
- dy(resolution=None, *, cache=True)[source]#
Return the meridional cell height in metres.
Parameters and caching as in
lats().
- area(resolution=None, *, cache=True)[source]#
Return the cell area in m².
Parameters and caching as in
lats().
- geodir()[source]#
Return the directory where
landmask()and friends are stored.The
geodirsetting if the source’s section has one, else<datadir>/geo(geo_<variant>for a variant).- Returns:
- Return type:
- 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): themaskvariable of the GHRSST L4 products (OSTIA, AVHRR OI, MUR), the missing cells of a model’s surface field (SMOC, CMEMS BGC, the carbonate system), orkmtfor 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:
- Returns:
xarray.DataArray– Boolean on the source grid, True on land. Read-only when cached (use.copy()to modify it).- Return type:
- 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) – Defaultdefault_resolution.cache (
bool, optional) – As inlandmask()(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:
See also
- 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, usinglandmask()to tell ocean from land.- Parameters:
resolution (
str, optional) – Defaultdefault_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. Needslandmask()(which may download GEBCO).cache (
bool, optional) – Keep the result in memory and as Zarr ingeodir(), as forlandmask(). Default True.
- Returns:
xarray.DataArray– int16 province numbers (1–57, or1–54for 1995; 0 on land and, without fill, outside every province).attrs["flag_values"]andattrs["flag_meanings"]give the province codes (spaces in codes such asNAST Ebecome_).- Return type:
- longhurst_biomes(resolution=None, *, version=None, fill=True, cache=True)[source]#
Return the Longhurst biome of every cell (see
longhurst_provinces()).
- longhurst_basins(resolution=None, *, version=None, fill=True, cache=True)[source]#
Return the ocean basin of every cell (see
longhurst_provinces()).
- 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 geometryorgrid name) – Grid of the result, e.g.seagrid.grids.cbiomes_halfdeg().dtm (
str,pandas.Timestamp,numpy.datetime64ordatetime, 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) – Seeseagrid.resample.regrid(). Default"bin".stat (
{"mean", "sum", "count", "min", "max"}, optional) – Statistic formethod="bin". Default"mean".fill (
bool, optional) – Fill empty target cells by nearest neighbour. Default False.**kwargs – Passed to
open_dataset()(timetype,resolution).
- Returns:
- Return type:
See also
- 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. Defaultdefault_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 (seeseagrid.match.Match.sample()).- Return type:
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. Defaultdefault_data_var.**kwargs –
grid(default: CBIOMES 0.5°),start,end,timetype,stat("median"or"mean") and the other keywords ofseagrid.climatology.build().
- Returns:
xarray.DataArray– Dimensions(month, lat, lon).- Return type:
See also
- 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).
- seagrid.sources.base.kelvin_to_celsius(ds, var)[source]#
Convert var from kelvin to degrees Celsius if its units say kelvin.
- 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]
- seagrid.sources.base.parse_date(value)[source]#
Parse a configured date, allowing
"today"and relative dates.- Parameters:
value (
str,pandas.Timestampordatetime) – A date ("2010-01-01"),"today"/"now", or a signedpandas.Timedeltastring 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 toCOORD_NAMES(latitude/longitudetolat/lon).
- Returns:
- Return type:
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/loncoordinates 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:
ds (
xarray.Dataset)grid (
seagrid.grids.Grid)atol (
float, optional) – Tolerance in degrees. Default 1e-3.
- Returns:
- Return type: