erddapy 3.2.1__tar.gz → 3.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {erddapy-3.2.1 → erddapy-3.3.0}/PKG-INFO +1 -1
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/__init__.py +0 -2
- erddapy-3.3.0/erddapy/core/griddap.py +88 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/core/interfaces.py +3 -7
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/core/url.py +74 -39
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/erddapy.py +51 -59
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/multiple_server_search.py +22 -32
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/servers/servers.py +1 -4
- erddapy-3.3.0/erddapy/xarray_erddap.py +51 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/pyproject.toml +26 -25
- {erddapy-3.2.1 → erddapy-3.3.0}/requirements-dev.txt +2 -0
- erddapy-3.2.1/erddapy/core/griddap.py +0 -90
- erddapy-3.2.1/erddapy/xarray_erddap.py +0 -93
- {erddapy-3.2.1 → erddapy-3.3.0}/CHANGES.txt +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/LICENSE.txt +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/MANIFEST.in +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/README.md +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/core/__init__.py +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/core/netcdf.py +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/servers/__init__.py +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy/servers/erddaps.json +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/erddapy.egg-info/SOURCES.txt +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/requirements.txt +0 -0
- {erddapy-3.2.1 → erddapy-3.3.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: erddapy
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.3.0
|
|
4
4
|
Summary: Python interface for ERDDAP
|
|
5
5
|
Maintainer-email: Alex Kerney <akerney@gmri.org>, Callum Rollo <c.rollo@outlook.com>, Filipe Fernandes <ocefpaf+erddapy@gmail.com>
|
|
6
6
|
License: Copyright 2017 Filipe Fernandes
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Griddap handling."""
|
|
2
|
+
|
|
3
|
+
import xml.etree.ElementTree as ET
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from collections.abc import Hashable
|
|
8
|
+
|
|
9
|
+
from erddapy.core.url import urlopen
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _griddap_get_constraints(
|
|
13
|
+
dataset_url: str,
|
|
14
|
+
step: int,
|
|
15
|
+
) -> tuple[dict, list, list]:
|
|
16
|
+
"""Fetch metadata of griddap dataset and set initial constraints.
|
|
17
|
+
|
|
18
|
+
Step size is applied to all dimensions.
|
|
19
|
+
"""
|
|
20
|
+
xmlns = "https://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2"
|
|
21
|
+
|
|
22
|
+
ncml_url = f"{dataset_url}.ncml"
|
|
23
|
+
res = urlopen(ncml_url)
|
|
24
|
+
xml = res.read().decode("utf-8")
|
|
25
|
+
root = ET.fromstring(xml) # noqa: S314
|
|
26
|
+
|
|
27
|
+
variables = root.findall(f"{{{xmlns}}}variable")
|
|
28
|
+
dimensions = root.findall(f"{{{xmlns}}}dimension")
|
|
29
|
+
|
|
30
|
+
dimension_names = [dimension.attrib["name"] for dimension in dimensions]
|
|
31
|
+
variable_names = [variable.attrib["name"] for variable in variables]
|
|
32
|
+
variable_names = list(set(variable_names).difference(dimension_names))
|
|
33
|
+
|
|
34
|
+
constraints_dict: dict[Hashable, str] = {}
|
|
35
|
+
|
|
36
|
+
ns = {"nc": "https://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2"}
|
|
37
|
+
|
|
38
|
+
for dimension_name in dimension_names:
|
|
39
|
+
element = root.find(
|
|
40
|
+
path=f'nc:variable[@name="{dimension_name}"]/nc:attribute[@name="actual_range"]',
|
|
41
|
+
namespaces=ns,
|
|
42
|
+
)
|
|
43
|
+
if element is None:
|
|
44
|
+
msg = (
|
|
45
|
+
f"Could not find actual_range for dimension {dimension_name}."
|
|
46
|
+
)
|
|
47
|
+
raise ValueError(msg)
|
|
48
|
+
actual_range = element.attrib["value"]
|
|
49
|
+
range_min, range_max = actual_range.split()
|
|
50
|
+
if dimension_name == "time":
|
|
51
|
+
range_min = range_max
|
|
52
|
+
|
|
53
|
+
constraints_dict[f"{dimension_name}>="] = range_min
|
|
54
|
+
constraints_dict[f"{dimension_name}<="] = range_max
|
|
55
|
+
constraints_dict[f"{dimension_name}_step"] = str(step)
|
|
56
|
+
|
|
57
|
+
return constraints_dict, dimension_names, variable_names
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _griddap_check_constraints(
|
|
61
|
+
user_constraints: dict,
|
|
62
|
+
original_constraints: dict,
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Validate user constraints against the dataset."""
|
|
65
|
+
if user_constraints.keys() != original_constraints.keys():
|
|
66
|
+
msg = (
|
|
67
|
+
"keys in e.constraints have changed. Re-run e.griddap_initialize",
|
|
68
|
+
)
|
|
69
|
+
raise ValueError(msg)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _griddap_check_variables(
|
|
73
|
+
user_variables: list[str] | tuple[str],
|
|
74
|
+
original_variables: list[str] | tuple[str],
|
|
75
|
+
) -> None:
|
|
76
|
+
"""Check user has not requested variables that do not exist in dataset."""
|
|
77
|
+
invalid_variables: list[str] = []
|
|
78
|
+
invalid_variables.extend(
|
|
79
|
+
variable
|
|
80
|
+
for variable in user_variables
|
|
81
|
+
if variable not in original_variables
|
|
82
|
+
)
|
|
83
|
+
if invalid_variables:
|
|
84
|
+
msg = (
|
|
85
|
+
f"variables {invalid_variables} are not present in dataset. "
|
|
86
|
+
"Re-run e.griddap_initialize"
|
|
87
|
+
)
|
|
88
|
+
raise ValueError(msg)
|
|
@@ -19,10 +19,6 @@ if TYPE_CHECKING:
|
|
|
19
19
|
import xarray as xr
|
|
20
20
|
|
|
21
21
|
|
|
22
|
-
OptionalStr = str | None
|
|
23
|
-
OptionalDict = dict | None
|
|
24
|
-
|
|
25
|
-
|
|
26
22
|
def to_pandas(
|
|
27
23
|
url: str,
|
|
28
24
|
requests_kwargs: dict | None = None,
|
|
@@ -45,8 +41,8 @@ def to_pandas(
|
|
|
45
41
|
|
|
46
42
|
def to_ncCF( # noqa: N802
|
|
47
43
|
url: str,
|
|
48
|
-
protocol:
|
|
49
|
-
requests_kwargs:
|
|
44
|
+
protocol: str | None = None,
|
|
45
|
+
requests_kwargs: dict | None = None,
|
|
50
46
|
) -> netCDF4.Dataset:
|
|
51
47
|
"""Convert a URL to a netCDF4 Dataset.
|
|
52
48
|
|
|
@@ -66,7 +62,7 @@ def to_ncCF( # noqa: N802
|
|
|
66
62
|
|
|
67
63
|
def to_xarray(
|
|
68
64
|
url: str,
|
|
69
|
-
response:
|
|
65
|
+
response: str | None = "opendap",
|
|
70
66
|
requests_kwargs: dict | None = None,
|
|
71
67
|
xarray_kwargs: dict | None = None,
|
|
72
68
|
) -> xr.Dataset:
|
|
@@ -1,22 +1,64 @@
|
|
|
1
1
|
"""URL handling."""
|
|
2
2
|
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
3
|
import copy
|
|
6
4
|
import datetime
|
|
7
5
|
import functools
|
|
8
6
|
import io
|
|
9
7
|
from collections import OrderedDict
|
|
10
|
-
from typing import BinaryIO
|
|
8
|
+
from typing import TYPE_CHECKING, Any, BinaryIO
|
|
11
9
|
from urllib import parse
|
|
12
10
|
|
|
13
11
|
import requests
|
|
14
12
|
from pandas import to_datetime
|
|
15
13
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from xarray.backends.common import T_PathFileOrDataStore
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _is_netcdf(url: str) -> bool:
|
|
19
|
+
"""Check if it .nc .ncCF, or ncCFMA URL.
|
|
20
|
+
|
|
21
|
+
Parameters
|
|
22
|
+
----------
|
|
23
|
+
url : str or unicode
|
|
24
|
+
ERDDAP netcdf-like URL
|
|
25
|
+
|
|
26
|
+
Returns
|
|
27
|
+
-------
|
|
28
|
+
isnetcdf : bool
|
|
29
|
+
True is `url` can be opened by xarray otherwise False.
|
|
30
|
+
|
|
31
|
+
"""
|
|
32
|
+
isnetcdf = False
|
|
33
|
+
if any(
|
|
34
|
+
ext in url for ext in (".nc?", ".ncCF?", ".ncCFMA?")
|
|
35
|
+
) or url.endswith(
|
|
36
|
+
(".nc", ".ncCF", ".ncCFMA"),
|
|
37
|
+
):
|
|
38
|
+
isnetcdf = True
|
|
39
|
+
return isnetcdf
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _is_url(url: "T_PathFileOrDataStore") -> bool:
|
|
43
|
+
"""Check if it is a valid ERDDAP URL.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
url : str or unicode
|
|
48
|
+
ERDDAP netcdf-like URL
|
|
49
|
+
|
|
50
|
+
Returns
|
|
51
|
+
-------
|
|
52
|
+
isurl : bool
|
|
53
|
+
True is `url` is a valid ERDDAP URL otherwise False.
|
|
54
|
+
|
|
55
|
+
"""
|
|
56
|
+
isurl = False
|
|
57
|
+
if not isinstance(url, str):
|
|
58
|
+
return False
|
|
59
|
+
if url.startswith(("http://", "https://")) and "/erddap" in url:
|
|
60
|
+
isurl = True
|
|
61
|
+
return isurl
|
|
20
62
|
|
|
21
63
|
|
|
22
64
|
def quote_url(url: str) -> str:
|
|
@@ -63,7 +105,7 @@ def _clean_response(response: str) -> str:
|
|
|
63
105
|
|
|
64
106
|
|
|
65
107
|
@functools.lru_cache(maxsize=128)
|
|
66
|
-
def _urlopen(url: str, auth: tuple | None = None, **kwargs:
|
|
108
|
+
def _urlopen(url: str, auth: tuple | None = None, **kwargs: Any) -> BinaryIO:
|
|
67
109
|
timeout = kwargs.pop("timeout", 60)
|
|
68
110
|
response = requests.get(
|
|
69
111
|
url,
|
|
@@ -112,7 +154,7 @@ def urlopen(
|
|
|
112
154
|
return data
|
|
113
155
|
|
|
114
156
|
|
|
115
|
-
def check_url_response(url: str, **kwargs:
|
|
157
|
+
def check_url_response(url: str, **kwargs: Any) -> str:
|
|
116
158
|
"""Shortcut to `raise_for_status` instead of fetching the whole content.
|
|
117
159
|
|
|
118
160
|
One should only use this is passing URLs that are known to work is
|
|
@@ -125,7 +167,7 @@ def check_url_response(url: str, **kwargs: dict) -> str:
|
|
|
125
167
|
return url
|
|
126
168
|
|
|
127
169
|
|
|
128
|
-
def _distinct(url: str, *, distinct:
|
|
170
|
+
def _distinct(url: str, *, distinct: bool = False) -> str:
|
|
129
171
|
"""Sort all of the rows in the results table.
|
|
130
172
|
|
|
131
173
|
Starting with the first requested variable,
|
|
@@ -153,8 +195,8 @@ def _format_search_string(server: str, query: str) -> str:
|
|
|
153
195
|
)
|
|
154
196
|
|
|
155
197
|
|
|
156
|
-
def _multi_urlopen(url: str) -> BinaryIO:
|
|
157
|
-
"""Simpler
|
|
198
|
+
def _multi_urlopen(url: str) -> BinaryIO | None:
|
|
199
|
+
"""Simpler URL openner to work with multiprocessing."""
|
|
158
200
|
try:
|
|
159
201
|
data = urlopen(url, requests_kwargs={"timeout": 120})
|
|
160
202
|
except (
|
|
@@ -166,7 +208,7 @@ def _multi_urlopen(url: str) -> BinaryIO:
|
|
|
166
208
|
return data
|
|
167
209
|
|
|
168
210
|
|
|
169
|
-
def _quote_string_constraints(kwargs: dict) -> dict:
|
|
211
|
+
def _quote_string_constraints(kwargs: dict[str, str]) -> dict[str, str]:
|
|
170
212
|
"""Quote constraints of String variables.
|
|
171
213
|
|
|
172
214
|
The right-hand-side value must be surrounded by double quotes if they are
|
|
@@ -186,9 +228,10 @@ def _format_constraints_url(kwargs: dict) -> str:
|
|
|
186
228
|
return "".join([f"&{k}{v}" for k, v in kwargs.items()])
|
|
187
229
|
|
|
188
230
|
|
|
189
|
-
def _check_substrings(constraint:
|
|
231
|
+
def _check_substrings(constraint: str) -> bool:
|
|
190
232
|
"""Extend the OPeNDAP with extra strings."""
|
|
191
|
-
|
|
233
|
+
# The `now` doesn't need this check, it works both quoted and unquoted.
|
|
234
|
+
substrings = ["now+", "now-", "min(", "max("]
|
|
192
235
|
return any(
|
|
193
236
|
True for substring in substrings if substring in str(constraint)
|
|
194
237
|
)
|
|
@@ -203,8 +246,8 @@ def _is_quoted(url: str) -> bool:
|
|
|
203
246
|
def parse_dates(
|
|
204
247
|
date_time: datetime.datetime | str,
|
|
205
248
|
*,
|
|
206
|
-
dayfirst:
|
|
207
|
-
yearfirst:
|
|
249
|
+
dayfirst: bool = False,
|
|
250
|
+
yearfirst: bool = False,
|
|
208
251
|
) -> float:
|
|
209
252
|
"""Parse dates to ERDDAP internal format.
|
|
210
253
|
|
|
@@ -235,10 +278,10 @@ def get_search_url( # noqa: PLR0913
|
|
|
235
278
|
server: str,
|
|
236
279
|
response: str = "html",
|
|
237
280
|
search_for: str | None = None,
|
|
238
|
-
protocol: str = "tabledap",
|
|
281
|
+
protocol: str | None = "tabledap",
|
|
239
282
|
items_per_page: int = 1_000_000,
|
|
240
283
|
page: int = 1,
|
|
241
|
-
**kwargs:
|
|
284
|
+
**kwargs: Any,
|
|
242
285
|
) -> str:
|
|
243
286
|
"""Build the search URL for the `server` endpoint provided.
|
|
244
287
|
|
|
@@ -388,8 +431,8 @@ def get_search_url( # noqa: PLR0913
|
|
|
388
431
|
|
|
389
432
|
def get_info_url(
|
|
390
433
|
server: str,
|
|
391
|
-
dataset_id:
|
|
392
|
-
response:
|
|
434
|
+
dataset_id: str | None,
|
|
435
|
+
response: str | None,
|
|
393
436
|
) -> str:
|
|
394
437
|
"""Build the info URL for the `server` endpoint.
|
|
395
438
|
|
|
@@ -413,8 +456,8 @@ def get_info_url(
|
|
|
413
456
|
def get_categorize_url(
|
|
414
457
|
server: str,
|
|
415
458
|
categorize_by: str,
|
|
416
|
-
value:
|
|
417
|
-
response:
|
|
459
|
+
value: str | None,
|
|
460
|
+
response: str | None,
|
|
418
461
|
) -> str:
|
|
419
462
|
"""Build the categorize URL for the `server` endpoint.
|
|
420
463
|
|
|
@@ -439,16 +482,16 @@ def get_categorize_url(
|
|
|
439
482
|
return url
|
|
440
483
|
|
|
441
484
|
|
|
442
|
-
def get_download_url( # noqa: PLR0913
|
|
485
|
+
def get_download_url( # noqa: PLR0913
|
|
443
486
|
server: str,
|
|
444
487
|
*,
|
|
445
|
-
dataset_id:
|
|
446
|
-
protocol:
|
|
447
|
-
variables:
|
|
448
|
-
dim_names:
|
|
449
|
-
response:
|
|
450
|
-
constraints:
|
|
451
|
-
distinct:
|
|
488
|
+
dataset_id: str,
|
|
489
|
+
protocol: str,
|
|
490
|
+
variables: list[str] | tuple[str] | None = None,
|
|
491
|
+
dim_names: list[str] | tuple[str] | None = None,
|
|
492
|
+
response: str = "html",
|
|
493
|
+
constraints: dict[Any, Any] | None = None,
|
|
494
|
+
distinct: bool = False,
|
|
452
495
|
) -> str:
|
|
453
496
|
"""Build the download URL.
|
|
454
497
|
|
|
@@ -486,14 +529,6 @@ def get_download_url( # noqa: PLR0913, C901
|
|
|
486
529
|
url (str): the download URL for the `response` chosen.
|
|
487
530
|
|
|
488
531
|
"""
|
|
489
|
-
if not dataset_id:
|
|
490
|
-
msg = f"Please specify a valid `dataset_id`, got {dataset_id}"
|
|
491
|
-
raise ValueError(msg)
|
|
492
|
-
|
|
493
|
-
if not protocol:
|
|
494
|
-
msg = f"Please specify a valid `protocol`, got {protocol}"
|
|
495
|
-
raise ValueError(msg)
|
|
496
|
-
|
|
497
532
|
if (
|
|
498
533
|
protocol == "griddap"
|
|
499
534
|
and constraints is not None
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import functools
|
|
6
6
|
import hashlib
|
|
7
7
|
from pathlib import Path
|
|
8
|
-
from typing import TYPE_CHECKING
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
9
|
from urllib.request import urlretrieve
|
|
10
10
|
|
|
11
11
|
import pandas as pd
|
|
@@ -21,7 +21,7 @@ from erddapy.core.url import (
|
|
|
21
21
|
_clean_response,
|
|
22
22
|
_distinct,
|
|
23
23
|
_format_constraints_url,
|
|
24
|
-
|
|
24
|
+
_is_url,
|
|
25
25
|
_sort_url,
|
|
26
26
|
download_formats,
|
|
27
27
|
get_categorize_url,
|
|
@@ -31,7 +31,7 @@ from erddapy.core.url import (
|
|
|
31
31
|
parse_dates,
|
|
32
32
|
urlopen,
|
|
33
33
|
)
|
|
34
|
-
from erddapy.servers
|
|
34
|
+
from erddapy.servers import servers
|
|
35
35
|
|
|
36
36
|
# Objects used by downstream packages
|
|
37
37
|
__all__ = [
|
|
@@ -39,7 +39,6 @@ __all__ = [
|
|
|
39
39
|
"_check_substrings",
|
|
40
40
|
"_distinct",
|
|
41
41
|
"_format_constraints_url",
|
|
42
|
-
"_quote_string_constraints",
|
|
43
42
|
"parse_dates",
|
|
44
43
|
"urlopen",
|
|
45
44
|
]
|
|
@@ -49,11 +48,6 @@ if TYPE_CHECKING:
|
|
|
49
48
|
import netCDF4.Dataset
|
|
50
49
|
import xarray as xr
|
|
51
50
|
|
|
52
|
-
OptionalBool = bool | None
|
|
53
|
-
OptionalDict = dict | None
|
|
54
|
-
OptionalList = list[str] | tuple[str] | None
|
|
55
|
-
OptionalStr = str | None
|
|
56
|
-
|
|
57
51
|
|
|
58
52
|
class ERDDAP:
|
|
59
53
|
"""Creates an ERDDAP instance for a specific server endpoint.
|
|
@@ -99,31 +93,19 @@ class ERDDAP:
|
|
|
99
93
|
to get a list of the shortcuts available servers:
|
|
100
94
|
|
|
101
95
|
>>> from erddapy import servers
|
|
102
|
-
>>>
|
|
103
|
-
{'
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
'NERACOOS': 'https://www.neracoos.org/erddap/',
|
|
109
|
-
'NGDAC': 'https://gliders.ioos.us/erddap/',
|
|
110
|
-
'PacIOOS': 'https://pae-paha.pacioos.hawaii.edu/erddap/',
|
|
111
|
-
'SECOORA': 'https://erddap.secoora.org/erddap/',
|
|
112
|
-
'NCEI': 'https://ecowatch.ncddc.noaa.gov/erddap/',
|
|
113
|
-
'OSMC': 'https://osmc.noaa.gov/erddap/',
|
|
114
|
-
'UAF': 'https://upwell.pfeg.noaa.gov/erddap/',
|
|
115
|
-
'ONC': 'https://dap.onc.uvic.ca/erddap/',
|
|
116
|
-
'BMLSC': 'http://bmlsc.ucdavis.edu:8080/erddap/',
|
|
117
|
-
'RTECH': 'https://meteo.rtech.fr/erddap/',
|
|
118
|
-
'IFREMER': 'https://www.ifremer.fr/erddap/',
|
|
119
|
-
'UBC': 'https://salishsea.eos.ubc.ca/erddap/'}
|
|
96
|
+
>>> servers()
|
|
97
|
+
{'voto': Server(description='Voice of the Ocean', url='https://erddap.observations.voiceoftheocean.org/erddap/'),
|
|
98
|
+
'cswc': Server(description='CoastWatch West Coast Node', url='https://coastwatch.pfeg.noaa.gov/erddap/'),
|
|
99
|
+
...,
|
|
100
|
+
'noaa oceanview': Server(description='NOAA Oceanview', url='https://oceanview.pfeg.noaa.gov/erddap/'),
|
|
101
|
+
'cfrf': Server(description='Commercial Fisheries Research Foundation', url='https://erddap.ondeckdata.com/erddap/')}
|
|
120
102
|
|
|
121
103
|
"""
|
|
122
104
|
|
|
123
105
|
def __init__(
|
|
124
106
|
self: ERDDAP,
|
|
125
107
|
server: str,
|
|
126
|
-
protocol:
|
|
108
|
+
protocol: str | None = None,
|
|
127
109
|
response: str = "html",
|
|
128
110
|
) -> None:
|
|
129
111
|
"""Instantiate main class attributes.
|
|
@@ -135,8 +117,13 @@ class ERDDAP:
|
|
|
135
117
|
response: default is HTML.
|
|
136
118
|
|
|
137
119
|
"""
|
|
138
|
-
if server
|
|
139
|
-
|
|
120
|
+
if not _is_url(server):
|
|
121
|
+
_servers = servers()
|
|
122
|
+
if server.lower() in _servers:
|
|
123
|
+
server = _servers[server.lower()].url
|
|
124
|
+
else:
|
|
125
|
+
msg = f"Cannot initialize {server=}."
|
|
126
|
+
raise ValueError(msg)
|
|
140
127
|
self.server = server.rstrip("/")
|
|
141
128
|
self.protocol = protocol
|
|
142
129
|
self.response = response
|
|
@@ -147,19 +134,19 @@ class ERDDAP:
|
|
|
147
134
|
self.auth: tuple | None = None
|
|
148
135
|
|
|
149
136
|
self.constraints: dict | None = None
|
|
150
|
-
self.variables:
|
|
151
|
-
self.dim_names:
|
|
137
|
+
self.variables: list[str] | tuple[str] | None = None
|
|
138
|
+
self.dim_names: list[str] | tuple[str] | None = None
|
|
152
139
|
|
|
153
140
|
self._get_variables = functools.lru_cache(maxsize=128)(
|
|
154
141
|
self._get_variables_uncached,
|
|
155
142
|
)
|
|
156
143
|
# Caching the last dataset_id and variables list request for
|
|
157
144
|
# quicker access, will be overridden when requesting a new dataset_id.
|
|
158
|
-
self._dataset_id:
|
|
145
|
+
self._dataset_id: str | None = None
|
|
159
146
|
self._variables: dict = {}
|
|
160
147
|
|
|
161
148
|
@property
|
|
162
|
-
def dataset_id(self) -> str:
|
|
149
|
+
def dataset_id(self) -> str | None:
|
|
163
150
|
"""dataset_id property."""
|
|
164
151
|
return self._dataset_id
|
|
165
152
|
|
|
@@ -170,7 +157,7 @@ class ERDDAP:
|
|
|
170
157
|
|
|
171
158
|
def griddap_initialize(
|
|
172
159
|
self: ERDDAP,
|
|
173
|
-
dataset_id:
|
|
160
|
+
dataset_id: str | None = None,
|
|
174
161
|
step: int = 1,
|
|
175
162
|
) -> None:
|
|
176
163
|
"""Fetch metadata of dataset and initialize constraints and variables.
|
|
@@ -200,9 +187,9 @@ class ERDDAP:
|
|
|
200
187
|
|
|
201
188
|
def get_search_url(
|
|
202
189
|
self: ERDDAP,
|
|
203
|
-
response:
|
|
204
|
-
search_for:
|
|
205
|
-
protocol:
|
|
190
|
+
response: str | None = None,
|
|
191
|
+
search_for: str | None = None,
|
|
192
|
+
protocol: str | None = None,
|
|
206
193
|
items_per_page: int = 1_000_000,
|
|
207
194
|
page: int = 1,
|
|
208
195
|
**kwargs: dict,
|
|
@@ -263,8 +250,8 @@ class ERDDAP:
|
|
|
263
250
|
|
|
264
251
|
def get_info_url(
|
|
265
252
|
self: ERDDAP,
|
|
266
|
-
dataset_id:
|
|
267
|
-
response:
|
|
253
|
+
dataset_id: str | None = None,
|
|
254
|
+
response: str | None = None,
|
|
268
255
|
) -> str:
|
|
269
256
|
"""Build the info URL for the `server` endpoint.
|
|
270
257
|
|
|
@@ -291,8 +278,8 @@ class ERDDAP:
|
|
|
291
278
|
def get_categorize_url(
|
|
292
279
|
self: ERDDAP,
|
|
293
280
|
categorize_by: str,
|
|
294
|
-
value:
|
|
295
|
-
response:
|
|
281
|
+
value: str | None = None,
|
|
282
|
+
response: str | None = None,
|
|
296
283
|
) -> str:
|
|
297
284
|
"""Build the categorize URL for the `server` endpoint.
|
|
298
285
|
|
|
@@ -315,13 +302,13 @@ class ERDDAP:
|
|
|
315
302
|
def get_download_url( # noqa: PLR0913
|
|
316
303
|
self: ERDDAP,
|
|
317
304
|
*,
|
|
318
|
-
dataset_id:
|
|
319
|
-
protocol:
|
|
320
|
-
variables:
|
|
321
|
-
dim_names:
|
|
322
|
-
response:
|
|
323
|
-
constraints:
|
|
324
|
-
distinct:
|
|
305
|
+
dataset_id: str | None = None,
|
|
306
|
+
protocol: str | None = None,
|
|
307
|
+
variables: list[str] | tuple[str] | None = None,
|
|
308
|
+
dim_names: list[str] | tuple[str] | None = None,
|
|
309
|
+
response: str | None = None,
|
|
310
|
+
constraints: dict[str, Any] | None = None,
|
|
311
|
+
distinct: bool = False,
|
|
325
312
|
) -> str:
|
|
326
313
|
"""Build the download URL for the `server` endpoint.
|
|
327
314
|
|
|
@@ -417,7 +404,10 @@ class ERDDAP:
|
|
|
417
404
|
"""
|
|
418
405
|
response = kw.pop("response", "csvp")
|
|
419
406
|
distinct = kw.pop("distinct", False)
|
|
420
|
-
url = self.get_download_url(
|
|
407
|
+
url = self.get_download_url(
|
|
408
|
+
response=str(response),
|
|
409
|
+
distinct=bool(distinct),
|
|
410
|
+
)
|
|
421
411
|
return to_pandas(
|
|
422
412
|
url,
|
|
423
413
|
requests_kwargs=requests_kwargs,
|
|
@@ -426,13 +416,13 @@ class ERDDAP:
|
|
|
426
416
|
|
|
427
417
|
def to_ncCF( # noqa: N802
|
|
428
418
|
self: ERDDAP,
|
|
429
|
-
protocol:
|
|
419
|
+
protocol: str | None = None,
|
|
430
420
|
**kw: dict,
|
|
431
421
|
) -> netCDF4.Dataset:
|
|
432
422
|
"""Load the data request into a CF compliant netCDF4-python object."""
|
|
433
423
|
distinct = kw.pop("distinct", False)
|
|
434
424
|
protocol = protocol or self.protocol
|
|
435
|
-
url = self.get_download_url(response="ncCF", distinct=distinct)
|
|
425
|
+
url = self.get_download_url(response="ncCF", distinct=bool(distinct))
|
|
436
426
|
return to_ncCF(url, protocol=protocol, requests_kwargs={**kw})
|
|
437
427
|
|
|
438
428
|
def to_xarray(
|
|
@@ -451,7 +441,7 @@ class ERDDAP:
|
|
|
451
441
|
else:
|
|
452
442
|
response = "ncCF"
|
|
453
443
|
distinct = kw.pop("distinct", False)
|
|
454
|
-
url = self.get_download_url(response=response, distinct=distinct)
|
|
444
|
+
url = self.get_download_url(response=response, distinct=bool(distinct))
|
|
455
445
|
if requests_kwargs:
|
|
456
446
|
requests_kwargs = {"auth": self.auth, **requests_kwargs}
|
|
457
447
|
else:
|
|
@@ -463,7 +453,7 @@ class ERDDAP:
|
|
|
463
453
|
xarray_kwargs={**kw},
|
|
464
454
|
)
|
|
465
455
|
|
|
466
|
-
def to_iris(self: ERDDAP, **kw:
|
|
456
|
+
def to_iris(self: ERDDAP, **kw: Any) -> iris.cube.CubeList:
|
|
467
457
|
"""Load the data request into an iris.cube.CubeList.
|
|
468
458
|
|
|
469
459
|
Accepts any `iris.load_raw` keyword arguments.
|
|
@@ -475,7 +465,7 @@ class ERDDAP:
|
|
|
475
465
|
|
|
476
466
|
def _get_variables_uncached(
|
|
477
467
|
self: ERDDAP,
|
|
478
|
-
dataset_id:
|
|
468
|
+
dataset_id: str | None = None,
|
|
479
469
|
) -> dict:
|
|
480
470
|
if not dataset_id:
|
|
481
471
|
dataset_id = self.dataset_id
|
|
@@ -504,7 +494,7 @@ class ERDDAP:
|
|
|
504
494
|
|
|
505
495
|
def get_var_by_attr(
|
|
506
496
|
self: ERDDAP,
|
|
507
|
-
dataset_id:
|
|
497
|
+
dataset_id: str | None = None,
|
|
508
498
|
**kwargs: dict,
|
|
509
499
|
) -> list[str]:
|
|
510
500
|
"""Return a variable based on its attributes.
|
|
@@ -544,11 +534,13 @@ class ERDDAP:
|
|
|
544
534
|
for vname in variables:
|
|
545
535
|
var = variables[vname]
|
|
546
536
|
for k, v in kwargs.items():
|
|
537
|
+
# Attributes must always be a string.
|
|
538
|
+
_k = str(k)
|
|
547
539
|
if callable(v):
|
|
548
|
-
has_value_flag = v(var.get(
|
|
540
|
+
has_value_flag = v(var.get(_k, None))
|
|
549
541
|
if not has_value_flag:
|
|
550
542
|
break
|
|
551
|
-
elif var.get(
|
|
543
|
+
elif var.get(_k) == v:
|
|
552
544
|
has_value_flag = True
|
|
553
545
|
else:
|
|
554
546
|
has_value_flag = False
|
|
@@ -560,7 +552,7 @@ class ERDDAP:
|
|
|
560
552
|
def download_file(
|
|
561
553
|
self: ERDDAP,
|
|
562
554
|
file_type: str,
|
|
563
|
-
) ->
|
|
555
|
+
) -> Path:
|
|
564
556
|
"""Download the dataset to a file in a user specified format."""
|
|
565
557
|
file_type = file_type.lstrip(".")
|
|
566
558
|
if file_type not in download_formats:
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
"""Multiple Server Search."""
|
|
2
2
|
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
3
|
import multiprocessing
|
|
4
|
+
from typing import Any
|
|
6
5
|
|
|
7
6
|
import pandas as pd
|
|
8
7
|
|
|
@@ -19,12 +18,10 @@ from erddapy.core.url import (
|
|
|
19
18
|
)
|
|
20
19
|
from erddapy.servers.servers import servers
|
|
21
20
|
|
|
22
|
-
OptionalList = list | None
|
|
23
|
-
OptionalBool = bool | None
|
|
24
21
|
OptionalStr = str | None
|
|
25
22
|
|
|
26
23
|
|
|
27
|
-
def _format_results(dfs: dict[str, pd.DataFrame]) -> pd.DataFrame:
|
|
24
|
+
def _format_results(dfs: list[dict[str, pd.DataFrame]]) -> pd.DataFrame:
|
|
28
25
|
"""Format dictionary of results into a Pandas dataframe."""
|
|
29
26
|
# we return None for bad server, so we need to filter them here
|
|
30
27
|
return pd.concat(
|
|
@@ -36,7 +33,7 @@ def fetch_results(
|
|
|
36
33
|
url: str,
|
|
37
34
|
key: str,
|
|
38
35
|
protocol: str,
|
|
39
|
-
) -> dict[str, pd.DataFrame]:
|
|
36
|
+
) -> dict[str, pd.DataFrame] | None:
|
|
40
37
|
"""Fetch search results from multiple servers.
|
|
41
38
|
|
|
42
39
|
If the server fails to response this function returns None
|
|
@@ -64,10 +61,10 @@ def fetch_results(
|
|
|
64
61
|
def search_servers(
|
|
65
62
|
query: str,
|
|
66
63
|
*,
|
|
67
|
-
servers_list:
|
|
68
|
-
parallel:
|
|
64
|
+
servers_list: list | None = None,
|
|
65
|
+
parallel: bool | None = False,
|
|
69
66
|
protocol: OptionalStr = "tabledap",
|
|
70
|
-
) -> pd.
|
|
67
|
+
) -> pd.DataFrame:
|
|
71
68
|
"""Search all servers for a query string.
|
|
72
69
|
|
|
73
70
|
Returns a dataframe of details for all matching datasets
|
|
@@ -81,16 +78,12 @@ def search_servers(
|
|
|
81
78
|
if protocol not in ("tabledap", "griddap"):
|
|
82
79
|
msg = f"Protocol must be tabledap or griddap, got {protocol}"
|
|
83
80
|
raise ValueError(msg)
|
|
84
|
-
if servers_list:
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
urls = {
|
|
91
|
-
key: _format_search_string(server.url, query)
|
|
92
|
-
for key, server in servers.items()
|
|
93
|
-
}
|
|
81
|
+
if servers_list is None:
|
|
82
|
+
servers_list = [v.url for k, v in servers().items()]
|
|
83
|
+
|
|
84
|
+
urls = {
|
|
85
|
+
server: _format_search_string(server, query) for server in servers_list
|
|
86
|
+
}
|
|
94
87
|
if parallel:
|
|
95
88
|
num_cores = multiprocessing.cpu_count()
|
|
96
89
|
if not joblib:
|
|
@@ -110,11 +103,11 @@ def search_servers(
|
|
|
110
103
|
|
|
111
104
|
|
|
112
105
|
def advanced_search_servers(
|
|
113
|
-
servers_list:
|
|
106
|
+
servers_list: list | None = None,
|
|
114
107
|
*,
|
|
115
|
-
parallel:
|
|
108
|
+
parallel: bool | None = False,
|
|
116
109
|
protocol: OptionalStr = "tabledap",
|
|
117
|
-
**kwargs:
|
|
110
|
+
**kwargs: Any,
|
|
118
111
|
) -> pd.DataFrame:
|
|
119
112
|
"""Search multiple ERDDAP servers.
|
|
120
113
|
|
|
@@ -130,16 +123,13 @@ def advanced_search_servers(
|
|
|
130
123
|
msg = f"Protocol must be tabledap or griddap, got {protocol}"
|
|
131
124
|
raise ValueError(msg)
|
|
132
125
|
response = "csv"
|
|
133
|
-
if servers_list:
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
key: get_search_url(server.url, response=response, **kwargs)
|
|
141
|
-
for key, server in servers.items()
|
|
142
|
-
}
|
|
126
|
+
if servers_list is None:
|
|
127
|
+
servers_list = [v.url for k, v in servers().items()]
|
|
128
|
+
|
|
129
|
+
urls = {
|
|
130
|
+
server: get_search_url(server, response=response, **kwargs)
|
|
131
|
+
for server in servers_list
|
|
132
|
+
}
|
|
143
133
|
|
|
144
134
|
if parallel:
|
|
145
135
|
num_cores = multiprocessing.cpu_count()
|
|
@@ -17,7 +17,7 @@ class Server(NamedTuple):
|
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
@functools.lru_cache(maxsize=128)
|
|
20
|
-
def
|
|
20
|
+
def servers() -> dict:
|
|
21
21
|
"""Download a new server list from awesome-erddap.
|
|
22
22
|
|
|
23
23
|
First we try to load the latest list from GitHub.
|
|
@@ -38,6 +38,3 @@ def servers_list() -> dict:
|
|
|
38
38
|
for k, row in df_servers.iterrows()
|
|
39
39
|
if row["short_name"]
|
|
40
40
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
servers = servers_list()
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""ERDDAPyBackendEntrypoint."""
|
|
2
|
+
|
|
3
|
+
import urllib.parse
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
|
|
6
|
+
import xarray as xr
|
|
7
|
+
from xarray.backends.common import T_PathFileOrDataStore
|
|
8
|
+
|
|
9
|
+
from erddapy.core.interfaces import to_xarray
|
|
10
|
+
from erddapy.core.url import _is_netcdf, _is_url
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _make_opendap(url: str) -> str:
|
|
14
|
+
parts = urllib.parse.urlparse(url)
|
|
15
|
+
opendap_url = urllib.parse.urlunparse(
|
|
16
|
+
[parts.scheme, parts.netloc, parts.path, "", "", ""],
|
|
17
|
+
)
|
|
18
|
+
return opendap_url.split(".nc")[0]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ERDDAPyBackendEntrypoint(xr.backends.BackendEntrypoint):
|
|
22
|
+
"""Erddapy backend entrypoint for xarray."""
|
|
23
|
+
|
|
24
|
+
def open_dataset(
|
|
25
|
+
self,
|
|
26
|
+
filename_or_obj: T_PathFileOrDataStore,
|
|
27
|
+
*,
|
|
28
|
+
drop_variables: str | Iterable[str] | None = None, # noqa: ARG002
|
|
29
|
+
) -> xr.Dataset:
|
|
30
|
+
"""Open ERDDAP URLs as xarray datasets."""
|
|
31
|
+
return open_erddap_dataset(filename_or_obj)
|
|
32
|
+
|
|
33
|
+
open_dataset_parameters = ("filename_or_obj", "drop_variables")
|
|
34
|
+
|
|
35
|
+
description = "Load ERDDAP URLs in xarray."
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def open_erddap_dataset(filename_or_obj: T_PathFileOrDataStore) -> xr.Dataset:
|
|
39
|
+
"""Open an ERDDAP URL with a netcdf-like response as an xarray object."""
|
|
40
|
+
if not _is_url(filename_or_obj):
|
|
41
|
+
msg = f"Expected an ERDDAP URL, got {filename_or_obj!r}."
|
|
42
|
+
raise ValueError(msg)
|
|
43
|
+
|
|
44
|
+
url = str(filename_or_obj)
|
|
45
|
+
if _is_netcdf(url):
|
|
46
|
+
response = "nc"
|
|
47
|
+
else:
|
|
48
|
+
filename_or_obj = _make_opendap(url)
|
|
49
|
+
response = "opendap"
|
|
50
|
+
|
|
51
|
+
return to_xarray(url, response=response)
|
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
[build-system]
|
|
2
2
|
build-backend = "setuptools.build_meta"
|
|
3
|
-
requires = [
|
|
4
|
-
"setuptools>=42",
|
|
5
|
-
"setuptools-scm",
|
|
6
|
-
"wheel",
|
|
7
|
-
]
|
|
3
|
+
requires = [ "setuptools>=42", "setuptools-scm" ]
|
|
8
4
|
|
|
9
5
|
[project]
|
|
10
6
|
name = "erddapy"
|
|
@@ -43,46 +39,51 @@ dynamic.dependencies = { file = [
|
|
|
43
39
|
] }
|
|
44
40
|
|
|
45
41
|
[tool.setuptools_scm]
|
|
42
|
+
tag_regex = "^(?P<prefix>v)?(?P<version>[^\\+]+)(?P<suffix>.*)?$"
|
|
46
43
|
write_to = "erddapy/_version.py"
|
|
47
44
|
write_to_template = "__version__ = '{version}'"
|
|
48
|
-
|
|
45
|
+
|
|
46
|
+
[tool.interrogate]
|
|
47
|
+
fail-under = 85
|
|
48
|
+
ignore-init-method = true
|
|
49
|
+
ignore-init-module = false
|
|
50
|
+
ignore-magic = false
|
|
51
|
+
ignore-semiprivate = false
|
|
52
|
+
ignore-private = false
|
|
53
|
+
ignore-module = false
|
|
54
|
+
exclude = [
|
|
55
|
+
"docs",
|
|
56
|
+
"tests",
|
|
57
|
+
]
|
|
58
|
+
color = true
|
|
59
|
+
verbose = 1
|
|
60
|
+
quiet = false
|
|
49
61
|
|
|
50
62
|
[tool.check-manifest]
|
|
51
63
|
ignore = [
|
|
52
64
|
"*.yml",
|
|
53
65
|
".coveragerc",
|
|
54
|
-
"Makefile",
|
|
55
66
|
"docs",
|
|
56
67
|
"docs/*",
|
|
68
|
+
"Makefile",
|
|
57
69
|
"notebooks",
|
|
58
70
|
"notebooks/*",
|
|
59
71
|
"tests",
|
|
60
72
|
"tests/*",
|
|
61
73
|
]
|
|
62
74
|
|
|
75
|
+
[tool.mypy]
|
|
76
|
+
ignore_missing_imports = true
|
|
77
|
+
warn_unreachable = true
|
|
78
|
+
warn_unused_configs = true
|
|
79
|
+
|
|
63
80
|
[tool.pytest]
|
|
64
81
|
ini_options.markers = [
|
|
65
|
-
"web: marks tests require connection (deselect with '-m \"not web\"')",
|
|
66
82
|
"serial: marks tests that cannot be run in parallel (deselect with '-m \"not serial\"')",
|
|
83
|
+
"web: marks tests require connection (deselect with '-m \"not web\"')",
|
|
67
84
|
]
|
|
68
85
|
ini_options.filterwarnings = [
|
|
69
86
|
"error:::erddapy.*",
|
|
70
|
-
"ignore::UserWarning",
|
|
71
87
|
"ignore::RuntimeWarning",
|
|
88
|
+
"ignore::UserWarning",
|
|
72
89
|
]
|
|
73
|
-
|
|
74
|
-
[tool.interrogate]
|
|
75
|
-
ignore-init-method = true
|
|
76
|
-
ignore-init-module = false
|
|
77
|
-
ignore-magic = false
|
|
78
|
-
ignore-semiprivate = false
|
|
79
|
-
ignore-private = false
|
|
80
|
-
ignore-module = false
|
|
81
|
-
fail-under = 85
|
|
82
|
-
exclude = [
|
|
83
|
-
"docs",
|
|
84
|
-
"tests",
|
|
85
|
-
]
|
|
86
|
-
verbose = 1
|
|
87
|
-
quiet = false
|
|
88
|
-
color = true
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
"""Griddap handling."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import pandas as pd
|
|
6
|
-
|
|
7
|
-
from erddapy.core.url import urlopen
|
|
8
|
-
|
|
9
|
-
OptionalList = list[str] | tuple[str] | None
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def _griddap_get_constraints(
|
|
13
|
-
dataset_url: str,
|
|
14
|
-
step: int,
|
|
15
|
-
) -> tuple[dict, list, list]:
|
|
16
|
-
"""Fetch metadata of griddap dataset and set initial constraints.
|
|
17
|
-
|
|
18
|
-
Step size is applied to all dimensions.
|
|
19
|
-
"""
|
|
20
|
-
dds_url = f"{dataset_url}.dds"
|
|
21
|
-
url = urlopen(dds_url)
|
|
22
|
-
data = url.read().decode()
|
|
23
|
-
dims, *variables = data.split("GRID")
|
|
24
|
-
dim_list = dims.split("[")[:-1]
|
|
25
|
-
dim_names, variable_names = [], []
|
|
26
|
-
for dim in dim_list:
|
|
27
|
-
dim_name = dim.split(" ")[-1]
|
|
28
|
-
dim_names.append(dim_name)
|
|
29
|
-
for var in variables:
|
|
30
|
-
phrase, *__ = var.split("[")
|
|
31
|
-
var_name = phrase.split(" ")[-1]
|
|
32
|
-
variable_names.append(var_name)
|
|
33
|
-
table = pd.DataFrame(
|
|
34
|
-
{"dimension name": [], "min": [], "max": [], "length": []},
|
|
35
|
-
)
|
|
36
|
-
for dim in dim_names:
|
|
37
|
-
url = f"{dataset_url}.csvp?{dim}"
|
|
38
|
-
data = pd.read_csv(url).to_numpy()
|
|
39
|
-
data_start = data[-1][0] if dim == "time" else data[0][0]
|
|
40
|
-
|
|
41
|
-
meta = pd.DataFrame(
|
|
42
|
-
[
|
|
43
|
-
{
|
|
44
|
-
"dimension name": dim,
|
|
45
|
-
"min": data_start,
|
|
46
|
-
"max": data[-1][0],
|
|
47
|
-
"length": len(data),
|
|
48
|
-
},
|
|
49
|
-
],
|
|
50
|
-
)
|
|
51
|
-
table = pd.concat([table, meta])
|
|
52
|
-
table = table.set_index("dimension name", drop=True)
|
|
53
|
-
constraints_dict = {}
|
|
54
|
-
for dim, data in table.iterrows():
|
|
55
|
-
constraints_dict[f"{dim}>="] = data["min"]
|
|
56
|
-
constraints_dict[f"{dim}<="] = data["max"]
|
|
57
|
-
constraints_dict[f"{dim}_step"] = step
|
|
58
|
-
|
|
59
|
-
return constraints_dict, dim_names, variable_names
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def _griddap_check_constraints(
|
|
63
|
-
user_constraints: dict,
|
|
64
|
-
original_constraints: dict,
|
|
65
|
-
) -> None:
|
|
66
|
-
"""Validate user constraints against the dataset."""
|
|
67
|
-
if user_constraints.keys() != original_constraints.keys():
|
|
68
|
-
msg = (
|
|
69
|
-
"keys in e.constraints have changed. Re-run e.griddap_initialize",
|
|
70
|
-
)
|
|
71
|
-
raise ValueError(msg)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
def _griddap_check_variables(
|
|
75
|
-
user_variables: OptionalList = None,
|
|
76
|
-
original_variables: OptionalList = None,
|
|
77
|
-
) -> None:
|
|
78
|
-
"""Check user has not requested variables that do not exist in dataset."""
|
|
79
|
-
invalid_variables = []
|
|
80
|
-
invalid_variables.extend(
|
|
81
|
-
variable
|
|
82
|
-
for variable in user_variables
|
|
83
|
-
if variable not in original_variables
|
|
84
|
-
)
|
|
85
|
-
if invalid_variables:
|
|
86
|
-
msg = (
|
|
87
|
-
f"variables {invalid_variables} are not present in dataset. "
|
|
88
|
-
"Re-run e.griddap_initialize"
|
|
89
|
-
)
|
|
90
|
-
raise ValueError(msg)
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
"""ERDDAPyBackendEntrypoint."""
|
|
2
|
-
|
|
3
|
-
import urllib.parse
|
|
4
|
-
|
|
5
|
-
import xarray as xr
|
|
6
|
-
|
|
7
|
-
from erddapy.core.interfaces import to_xarray
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def _is_netcdf(url: str) -> bool:
|
|
11
|
-
"""Check if it .nc .ncCF, or ncCFMA URL.
|
|
12
|
-
|
|
13
|
-
Parameters
|
|
14
|
-
----------
|
|
15
|
-
url : str or unicode
|
|
16
|
-
ERDDAP netcdf-like URL
|
|
17
|
-
|
|
18
|
-
Returns
|
|
19
|
-
-------
|
|
20
|
-
isnetcdf : bool
|
|
21
|
-
True is `url` can be opened by xarray otherwise False.
|
|
22
|
-
|
|
23
|
-
"""
|
|
24
|
-
isnetcdf = False
|
|
25
|
-
if any(
|
|
26
|
-
ext in url for ext in (".nc?", ".ncCF?", ".ncCFMA?")
|
|
27
|
-
) or url.endswith(
|
|
28
|
-
(".nc", ".ncCF", ".ncCFMA"),
|
|
29
|
-
):
|
|
30
|
-
isnetcdf = True
|
|
31
|
-
return isnetcdf
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
def _is_url(url: str) -> bool:
|
|
35
|
-
"""Check if it is a valid ERDDAP URL.
|
|
36
|
-
|
|
37
|
-
Parameters
|
|
38
|
-
----------
|
|
39
|
-
url : str or unicode
|
|
40
|
-
ERDDAP netcdf-like URL
|
|
41
|
-
|
|
42
|
-
Returns
|
|
43
|
-
-------
|
|
44
|
-
isurl : bool
|
|
45
|
-
True is `url` is a valid ERDDAP URL otherwise False.
|
|
46
|
-
|
|
47
|
-
"""
|
|
48
|
-
isurl = False
|
|
49
|
-
if not isinstance(url, str):
|
|
50
|
-
isurl = False
|
|
51
|
-
if url.startswith(("http://", "https://")) and "/erddap/" in url:
|
|
52
|
-
isurl = True
|
|
53
|
-
return isurl
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def _make_opendap(url: str) -> str:
|
|
57
|
-
parts = urllib.parse.urlparse(url)
|
|
58
|
-
opendap_url = urllib.parse.urlunparse(
|
|
59
|
-
[parts.scheme, parts.netloc, parts.path, "", "", ""],
|
|
60
|
-
)
|
|
61
|
-
return opendap_url.split(".nc")[0]
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
class ERDDAPyBackendEntrypoint(xr.backends.BackendEntrypoint):
|
|
65
|
-
"""Erddapy backend entrypoint for xarray."""
|
|
66
|
-
|
|
67
|
-
def open_dataset(
|
|
68
|
-
self,
|
|
69
|
-
filename_or_obj: str,
|
|
70
|
-
*,
|
|
71
|
-
drop_variables: list | None = None, # noqa: ARG002
|
|
72
|
-
) -> xr.Dataset:
|
|
73
|
-
"""Open ERDDAP URLs as xarray datasets."""
|
|
74
|
-
return open_erddap_dataset(filename_or_obj)
|
|
75
|
-
|
|
76
|
-
open_dataset_parameters = ("filename_or_obj", "drop_variables")
|
|
77
|
-
|
|
78
|
-
description = "Load ERDDAP URLs in xarray."
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def open_erddap_dataset(filename_or_obj: str) -> xr.Dataset:
|
|
82
|
-
"""Open an ERDDAP URL with a netcdf-like response as an xarray object."""
|
|
83
|
-
if not _is_url(filename_or_obj):
|
|
84
|
-
msg = f"Expected an ERDDAP URL, got {filename_or_obj}."
|
|
85
|
-
raise ValueError(msg)
|
|
86
|
-
|
|
87
|
-
if _is_netcdf(filename_or_obj):
|
|
88
|
-
response = "nc"
|
|
89
|
-
else:
|
|
90
|
-
filename_or_obj = _make_opendap(filename_or_obj)
|
|
91
|
-
response = "opendap"
|
|
92
|
-
|
|
93
|
-
return to_xarray(filename_or_obj, response=response)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|