"""CAFE net primary production (Oregon State University)."""
from __future__ import annotations
import pathlib
import numpy as np
import pandas as pd
import xarray as xr
from seagrid.download import cache, http
from seagrid.sources.base import add_history
from seagrid.sources.families import HTTPSource
__all__ = ["CAFE", "read_hdf4"]
[docs]
def read_hdf4(path: pathlib.Path) -> xr.Dataset:
"""Read an Ocean Productivity HDF4 file, applying scale, offset and fill.
Parameters
----------
path : pathlib.Path
Returns
-------
xarray.Dataset
Variables on ``y``/``x`` in file order (north up).
"""
try:
from pyhdf.SD import SD, SDC
except ImportError as err: # a clean install
from seagrid.download.optional import missing
raise missing("pyhdf") from err
hdf = SD(str(path), SDC.READ)
try:
data_vars = {}
for name in hdf.datasets():
sds = hdf.select(name)
attrs = dict(sds.attributes())
data = np.asarray(sds[:], dtype="float64")
scale = attrs.pop("scale_factor", 1.0)
offset = attrs.pop("add_offset", 0.0)
fill = attrs.pop("Hole Value", None)
if fill is not None:
data = np.where(data == fill, np.nan, data)
data_vars[name] = xr.Variable(
("y", "x"), data * scale + offset, attrs=attrs
)
return xr.Dataset(data_vars, attrs=dict(hdf.attributes()))
finally:
hdf.end()
[docs]
class CAFE(HTTPSource):
"""CAFE net primary production from MODIS-Aqua R2022, monthly, 1/6°.
The server has gzipped HDF4 files named by the year and day of year of
the first day of the month; they are converted to netCDF on download
(lat ascending, ``lat``/``lon`` from the NASA 18 km grid).
Settings section ``[cafe]``. Silsbe et al. (2016),
doi:10.1002/2016GB005521.
Examples
--------
>>> import seagrid
>>> seagrid.get_source("cafe").filename("2020-02-15")
'cafe.2020032.nc'
"""
name = "cafe"
title = "CAFE net primary production, MODIS R2022 (Oregon State)"
family = "pp"
default_timetype = "monthly"
default_data_var = "npp"
def _remote_name(
self,
dtm: pd.Timestamp,
data_var: str | None,
timetype: str,
resolution: str | None,
) -> str:
return (
self._filename(dtm, data_var, timetype, resolution).removesuffix(".nc")
+ ".hdf.gz"
)
def _fetch(
self,
dtm: pd.Timestamp,
data_var: str | None,
timetype: str,
resolution: str | None,
dest: pathlib.Path,
) -> pathlib.Path:
gz = dest.parent / self._remote_name(dtm, data_var, timetype, resolution)
http.fetch(
self._remote_url(dtm, data_var, timetype, resolution),
gz,
timeout=float(self.settings.get("timeout", 60)),
progress=bool(self.settings.get("progress", False)),
force=True,
)
hdf = http.uncompress(gz)
try:
ds = read_hdf4(hdf).isel(y=slice(None, None, -1))
grid = self.grid(resolution)
ds = ds.rename({"y": "lat", "x": "lon"}).assign_coords(
lat=grid.lat, lon=grid.lon
)
add_history(ds, "converted from HDF4; flipped to latitude ascending")
tmp = cache.partial(dest)
ds.to_netcdf(tmp)
finally:
hdf.unlink(missing_ok=True)
return cache.finish(dest)