Skip to content

Commit

Permalink
Merge pull request #880 from dcs4cop/pont-879-coverages
Browse files Browse the repository at this point in the history
Implement OGC API - Coverages
  • Loading branch information
pont-us committed Sep 1, 2023
2 parents e604e85 + e6a452f commit b765ae6
Show file tree
Hide file tree
Showing 13 changed files with 1,054 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

### Enhancements

* Added a basic implementation of the draft version of OGC API - Coverages

### Fixes

### Other changes
Expand Down
3 changes: 2 additions & 1 deletion docs/source/webapi.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ API, clients can
* Get places (GeoJSON features including vector data) that can be associated
with xcube datasets;
* Perform compute operations on datasets, with the results calculated on
demand and presented as new, dynamically generated datasets.
demand and presented as new, dynamically generated datasets;
* Retrieve coverages backed by datasets using the OGC API - Coverages API.

Later versions of API will also allow for xcube dataset management including
generation, modification, and deletion of xcube datasets.
Expand Down
20 changes: 20 additions & 0 deletions test/webapi/ows/coverages/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# The MIT License (MIT)
# Copyright (c) 2023 by the xcube team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
188 changes: 188 additions & 0 deletions test/webapi/ows/coverages/expected.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
{
"id": "demo",
"type": "CoverageByDomainAndRange",
"envelope": {
"type": "EnvelopeByAxis",
"srsName": "EPSG:4326",
"axisLabels": [
"lat",
"bnds",
"lon",
"time"
],
"axis": [
{
"type": "RegularAxis",
"axisLabel": "lat",
"lowerBound": 52.49875,
"upperBound": 50.00125,
"resolution": 0.0024975000000000023,
"uomLabel": "degrees_north"
},
{
"type": "RegularAxis",
"axisLabel": "bnds",
"lowerBound": 0,
"upperBound": 1,
"resolution": 0.5,
"uomLabel": "degrees"
},
{
"type": "RegularAxis",
"axisLabel": "lon",
"lowerBound": 0.00125,
"upperBound": 4.99875,
"resolution": 0.00249875,
"uomLabel": "degrees_east"
},
{
"type": "RegularAxis",
"axisLabel": "time",
"lowerBound": 1484561361834255872,
"upperBound": 1485773193836892416,
"resolution": 242366400527308.8,
"uomLabel": "degrees"
}
]
},
"domainSet": {
"type": "DomainSet",
"generalGrid": {
"type": "GeneralGridCoverage",
"srsName": "EPSG:4326",
"axisLabels": [
"lat",
"bnds",
"lon",
"time"
],
"axis": [
{
"type": "RegularAxis",
"axisLabel": "lat",
"lowerBound": 52.49875,
"upperBound": 50.00125,
"resolution": 0.0024975000000000023,
"uomLabel": "degrees_north"
},
{
"type": "RegularAxis",
"axisLabel": "bnds",
"lowerBound": 0,
"upperBound": 1,
"resolution": 0.5,
"uomLabel": "degrees"
},
{
"type": "RegularAxis",
"axisLabel": "lon",
"lowerBound": 0.00125,
"upperBound": 4.99875,
"resolution": 0.00249875,
"uomLabel": "degrees_east"
},
{
"type": "RegularAxis",
"axisLabel": "time",
"lowerBound": 1484561361834255872,
"upperBound": 1485773193836892416,
"resolution": 242366400527308.8,
"uomLabel": "degrees"
}
],
"gridLimits": {
"type": "GridLimits",
"srsName": "http://www.opengis.net/def/crs/OGC/0/Index4D",
"axisLabels": [
"lat",
"bnds",
"lon",
"time"
],
"axis": [
{
"type": "IndexAxis",
"axisLabel": "lat",
"lowerBound": 0,
"upperBound": 1000
},
{
"type": "IndexAxis",
"axisLabel": "bnds",
"lowerBound": 0,
"upperBound": 2
},
{
"type": "IndexAxis",
"axisLabel": "lon",
"lowerBound": 0,
"upperBound": 2000
},
{
"type": "IndexAxis",
"axisLabel": "time",
"lowerBound": 0,
"upperBound": 5
}
]
}
}
},
"rangeSet": {
"type": "RangeSet",
"dataBlock": {
"type": "VDataBlock",
"values": [
"TODO"
]
}
},
"rangeType": {
"type": "DataRecord",
"field": [
{
"type": "Quantity",
"name": "c2rcc_flags",
"description": "C2RCC quality flags",
"encodingInfo": {
"dataType": "http://www.opengis.net/def/dataType/OGC/0/float64"
}
},
{
"type": "Quantity",
"name": "conc_chl",
"description": "Chlorophyll concentration",
"encodingInfo": {
"dataType": "http://www.opengis.net/def/dataType/OGC/0/float64"
}
},
{
"type": "Quantity",
"name": "conc_tsm",
"description": "Total suspended matter dry weight concentration",
"encodingInfo": {
"dataType": "http://www.opengis.net/def/dataType/OGC/0/float64"
}
},
{
"type": "Quantity",
"name": "kd489",
"description": "Irradiance attenuation coefficient at 489 nm",
"encodingInfo": {
"dataType": "http://www.opengis.net/def/dataType/OGC/0/float64"
}
},
{
"type": "Quantity",
"name": "quality_flags",
"description": "Classification and quality flags",
"encodingInfo": {
"dataType": "http://www.opengis.net/def/dataType/OGC/0/float64"
}
}
]
},
"metadata": {
"Conventions": "CF-1.7"
}
}
42 changes: 42 additions & 0 deletions test/webapi/ows/coverages/test_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# The MIT License (MIT)
# Copyright (c) 2023 by the xcube team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.


import unittest
from typing import Optional, Union, Mapping, Any

from test.webapi.helpers import get_api_ctx
from xcube.server.api import Context
from xcube.webapi.datasets.context import DatasetsContext
from xcube.webapi.ows.coverages.context import CoveragesContext


def get_coverages_ctx(
server_config: Optional[Union[str, Mapping[str, Any]]] = None
) -> CoveragesContext:
return get_api_ctx("ows.coverages", CoveragesContext, server_config)


class CoveragesContextTest(unittest.TestCase):
def test_ctx_ok(self):
ctx = get_coverages_ctx()
self.assertIsInstance(ctx.server_ctx, Context)
self.assertIsInstance(ctx.datasets_ctx, DatasetsContext)
126 changes: 126 additions & 0 deletions test/webapi/ows/coverages/test_controllers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# The MIT License (MIT)
# Copyright (c) 2023 by the xcube team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import json
import os
import tempfile
import unittest
from io import BytesIO
from pathlib import Path
import numpy as np
import xarray as xr
import rioxarray

from test.webapi.ows.coverages.test_context import get_coverages_ctx
from xcube.webapi.ows.coverages.controllers import (
get_coverage_as_json,
get_coverage_data,
get_crs_from_dataset,
dtype_to_opengis_datatype,
get_dataarray_description,
)


class CoveragesControllersTest(unittest.TestCase):
def test_get_coverage_as_json(self):
result = get_coverage_as_json(get_coverages_ctx().datasets_ctx, 'demo')
self.assertIsInstance(result, dict)
path = Path(__file__).parent / 'expected.json'
# with open(path, mode="w") as fp:
# json.dump(result, fp, indent=2)
with open(path, mode="r") as fp:
expected_result = json.load(fp)
self.assertEqual(expected_result, result)

def test_get_coverage_data_tiff(self):
query = dict(
bbox=['52,1,51,2'],
datetime=['2017-01-25'],
properties=['conc_chl'],
)
result = get_coverage_data(
get_coverages_ctx().datasets_ctx, 'demo', query, 'image/tiff'
)
with BytesIO(result) as fh:
da = rioxarray.open_rasterio(fh)
self.assertIsInstance(da, xr.DataArray)
self.assertEqual(('band', 'y', 'x'), da.dims)
self.assertEqual('Chlorophyll concentration', da.long_name)
self.assertEqual((1, 400, 400), da.shape)

def test_get_coverage_data_netcdf(self):
query = dict(
bbox=['52,1,51,2'],
datetime=['2017-01-25'],
properties=['conc_chl,kd489'],
)
result = get_coverage_data(
get_coverages_ctx().datasets_ctx,
'demo',
query,
'application/netcdf',
)
# We can't read this directly from memory: the netcdf4 engine only
# reads from filesystem paths, the h5netcdf engine (which can read
# from memory) isn't an xcube dependency, and the scipy engine only
# handles NetCDF 3.

with tempfile.TemporaryDirectory() as tempdir:
path = os.path.join(tempdir, 'out.nc')
with open(path, 'wb') as fh:
fh.write(result)
ds = xr.open_dataset(path)
self.assertEqual({'lat': 400, 'lon': 400, 'bnds': 2}, ds.dims)
self.assertEqual(['conc_chl', 'kd489'], list(ds.data_vars))
self.assertEqual(
[
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'time_bnds',
'conc_chl',
'kd489',
],
list(ds.variables),
)

def test_get_crs_from_dataset(self):
ds = xr.Dataset({'crs': ([], None, {'spatial_ref': '3035'})})
self.assertEqual('EPSG:3035', get_crs_from_dataset(ds))

def test_dtype_to_opengis_datatype(self):
expected = [
(
np.uint16,
'http://www.opengis.net/def/dataType/OGC/0/unsignedShort',
),
(np.int32, 'http://www.opengis.net/def/dataType/OGC/0/signedInt'),
(np.datetime64, 'http://www.opengis.net/def/bipm/UTC'),
(np.object_, ''),
]
for dtype, opengis in expected:
self.assertEqual(opengis, dtype_to_opengis_datatype(dtype))

def test_get_dataarray_description(self):
name = 'foo'
da = xr.DataArray(data=[], coords=[('x', [])], dims=['x'], name=name)
self.assertEqual(name, get_dataarray_description(da))
Loading

0 comments on commit b765ae6

Please sign in to comment.