Skip to content

Commit

Permalink
Add netcdf output to xarray provider
Browse files Browse the repository at this point in the history
  • Loading branch information
barbuz committed Aug 27, 2024
1 parent f1a5ff7 commit 9f72bf7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pygeoapi/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1122,6 +1122,19 @@ def describe_collections(self, request: Union[APIRequest, Any],
'title': title_,
'href': f"{self.get_collections_url()}/{k}/coverage?f={collection_data_format['name']}" # noqa
})

# Hardcode netcdf format for xarray provider
if (collection_data['name'] == 'xarray' and
collection_data_format['name'] == 'zarr'):
title_ = l10n.translate('Coverage data as', request.locale)
title_ = f"{title_} {F_NETCDF}"
collection['links'].append({
'type': FORMAT_TYPES[F_NETCDF],
'rel': f'{OGC_RELTYPES_BASE}/coverage',
'title': title_,
'href': f"{self.get_collections_url()}/{k}/coverage?f={F_NETCDF}" # noqa
})

if dataset is not None:
LOGGER.debug('Creating extended coverage metadata')
try:
Expand Down
19 changes: 19 additions & 0 deletions pygeoapi/provider/xarray_.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,9 @@ def query(self, properties=[], subsets={}, bbox=[], bbox_crs=4326,
elif format_ == 'zarr':
LOGGER.debug('Returning data in native zarr format')
return _get_zarr_data(data)
elif format_ == 'netcdf':
LOGGER.debug('Returning data in netcdf format')
return _get_netcdf_data(data)
else: # return data in native format
with tempfile.NamedTemporaryFile() as fp:
LOGGER.debug('Returning data in native NetCDF format')
Expand Down Expand Up @@ -582,6 +585,22 @@ def _get_zarr_data(data):
return fh.read()


def _get_netcdf_data(data: xarray.Dataset):
"""
Returns bytes to read from netcdf file
:param data: Xarray dataset of coverage data
:returns: byte array of netcdf data
"""

with tempfile.NamedTemporaryFile() as fp:
data.to_netcdf(
fp.name
) # we need to pass a string to be able to use the "netcdf4" engine
fp.seek(0)
return fp.read()


def _convert_float32_to_float64(data):
"""
Converts DataArray values of float32 to float64
Expand Down

0 comments on commit 9f72bf7

Please sign in to comment.