forked from intake/intake-esm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.py
285 lines (250 loc) · 10.4 KB
/
source.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import typing
import dask
import fsspec
import pandas as pd
import pydantic
import xarray as xr
from intake.source.base import DataSource, Schema
from .cat import Aggregation, DataFormat
from .utils import INTAKE_ESM_ATTRS_PREFIX, INTAKE_ESM_DATASET_KEY, INTAKE_ESM_VARS_KEY
class ESMDataSourceError(Exception):
pass
def _get_xarray_open_kwargs(data_format, xarray_open_kwargs=None):
xarray_open_kwargs = (xarray_open_kwargs or {}).copy()
_default_open_kwargs = {
'engine': 'zarr' if data_format == 'zarr' else 'netcdf4',
'chunks': {},
'backend_kwargs': {},
}
if not xarray_open_kwargs:
xarray_open_kwargs = _default_open_kwargs
else:
xarray_open_kwargs = {**_default_open_kwargs, **xarray_open_kwargs}
if (
xarray_open_kwargs['engine'] == 'zarr'
and 'storage_options' not in xarray_open_kwargs['backend_kwargs']
):
xarray_open_kwargs['backend_kwargs']['storage_options'] = {}
return xarray_open_kwargs
@dask.delayed
def _open_dataset(
urlpath,
varname,
*,
xarray_open_kwargs=None,
preprocess=None,
requested_variables=None,
additional_attrs=None,
expand_dims=None,
):
_can_be_local = fsspec.utils.can_be_local(urlpath)
storage_options = xarray_open_kwargs.get('backend_kwargs', {}).get('storage_options', {})
if xarray_open_kwargs['engine'] == 'zarr':
url = urlpath
elif _can_be_local:
url = fsspec.open_local(urlpath, **storage_options)
else:
url = fsspec.open(urlpath, **storage_options).open()
# Handle multi-file datasets with `xr.open_mfdataset()`
if '*' in url or isinstance(url, list):
# How should we handle concat_dim, and other xr.open_mfdataset kwargs?
xarray_open_kwargs.update(preprocess=preprocess)
xarray_open_kwargs.update(parallel=True)
ds = xr.open_mfdataset(url, **xarray_open_kwargs)
else:
ds = xr.open_dataset(url, **xarray_open_kwargs)
if preprocess is not None:
ds = preprocess(ds)
if varname and isinstance(varname, str):
varname = [varname]
if requested_variables:
if isinstance(requested_variables, str):
requested_variables = [requested_variables]
variable_intersection = set(requested_variables).intersection(set(varname))
variables = [variable for variable in variable_intersection if variable in ds.data_vars]
ds = ds[variables]
ds.attrs[INTAKE_ESM_VARS_KEY] = variables
else:
ds.attrs[INTAKE_ESM_VARS_KEY] = varname
ds = _expand_dims(expand_dims, ds)
ds = _update_attrs(additional_attrs, ds)
return ds
def _update_attrs(additional_attrs, ds):
additional_attrs = additional_attrs or {}
if additional_attrs:
additional_attrs = {
f'{INTAKE_ESM_ATTRS_PREFIX}/{key}': value for key, value in additional_attrs.items()
}
ds.attrs = {**ds.attrs, **additional_attrs}
return ds
def _expand_dims(expand_dims, ds):
if expand_dims:
for variable in ds.attrs[INTAKE_ESM_VARS_KEY]:
edims = {}
for dim, crd in expand_dims.items():
if dim in ds[variable].dims and ds.dims[dim] != len(crd):
# Dimension already exist and has the same length
if dim in ds.coords:
# Raise if values are different
if not all(ds[dim] == crd):
raise ValueError(
f'Conflicting values for coordinate {dim} in dataset and catalog.'
)
else: # No values, simply assign what was given by the catalog
ds[dim] = crd
else: # Dimension does not exist : expand.
# If it does exist but has a different size, expand_dims will raise.
edims[dim] = crd
ds[variable] = ds[variable].expand_dims(**edims)
return ds
class ESMDataSource(DataSource):
version = '1.0'
container = 'xarray'
name = 'esm_datasource'
partition_access = True
@pydantic.validate_arguments
def __init__(
self,
key: pydantic.StrictStr,
records: typing.List[typing.Dict[str, typing.Any]],
variable_column_name: pydantic.StrictStr,
path_column_name: pydantic.StrictStr,
data_format: typing.Optional[DataFormat],
format_column_name: typing.Optional[pydantic.StrictStr],
*,
aggregations: typing.Optional[typing.List[Aggregation]] = None,
requested_variables: typing.List[str] = None,
preprocess: typing.Callable = None,
storage_options: typing.Dict[str, typing.Any] = None,
xarray_open_kwargs: typing.Dict[str, typing.Any] = None,
xarray_combine_by_coords_kwargs: typing.Dict[str, typing.Any] = None,
intake_kwargs: typing.Dict[str, typing.Any] = None,
):
"""An intake compatible Data Source for ESM data.
Parameters
----------
key: str
The key of the data source.
records: list of dict
A list of records, each of which is a dictionary
mapping column names to values.
variable_column_name: str
The column name of the variable name.
path_column_name: str
The column name of the path.
data_format: DataFormat
The data format of the data.
aggregations: list of Aggregation, optional
A list of aggregations to apply to the data.
requested_variables: list of str, optional
A list of variables to load.
preprocess: callable, optional
A preprocessing function to apply to the data.
storage_options: dict, optional
fsspec parameters passed to the backend file-system such as Google Cloud Storage,
Amazon Web Service S3.
xarray_open_kwargs: dict, optional
Keyword arguments to pass to :py:func:`~xarray.open_dataset` function.
xarray_combine_by_coords_kwargs: dict, optional
Keyword arguments to pass to :py:func:`~xarray.combine_by_coords` function.
intake_kwargs: dict, optional
Additional keyword arguments are passed through to the :py:class:`~intake.source.base.DataSource` base class.
"""
intake_kwargs = intake_kwargs or {}
super().__init__(**intake_kwargs)
self.key = key
self.storage_options = storage_options or {}
self.preprocess = preprocess
self.requested_variables = requested_variables or []
self.path_column_name = path_column_name
self.variable_column_name = variable_column_name
self.aggregations = aggregations
self.df = pd.DataFrame.from_records(records)
self.xarray_open_kwargs = xarray_open_kwargs
self.xarray_combine_by_coords_kwargs = dict(combine_attrs='drop_conflicts')
if xarray_combine_by_coords_kwargs is None:
xarray_combine_by_coords_kwargs = {}
self.xarray_combine_by_coords_kwargs = {
**self.xarray_combine_by_coords_kwargs,
**xarray_combine_by_coords_kwargs,
}
self._ds = None
if data_format is not None:
self.df['_data_format_'] = data_format.value
else:
self.df = self.df.rename(columns={format_column_name: '_data_format_'})
def __repr__(self) -> str:
return f'<{type(self).__name__} (name: {self.key}, asset(s): {len(self.df)})>'
def _get_schema(self) -> Schema:
if self._ds is None:
self._open_dataset()
metadata = {'dims': {}, 'data_vars': {}, 'coords': ()}
self._schema = Schema(
datashape=None,
dtype=None,
shape=None,
npartitions=None,
extra_metadata=metadata,
)
return self._schema
def _open_dataset(self):
"""Open dataset with xarray"""
try:
datasets = [
_open_dataset(
record[self.path_column_name],
record[self.variable_column_name],
xarray_open_kwargs=_get_xarray_open_kwargs(
record['_data_format_'], self.xarray_open_kwargs
),
preprocess=self.preprocess,
expand_dims={
agg.attribute_name: (
[record[agg.attribute_name]]
if not isinstance(record[agg.attribute_name], tuple)
else record[agg.attribute_name]
)
for agg in self.aggregations
if agg.type.value == 'join_new'
},
requested_variables=self.requested_variables,
additional_attrs=record.to_dict(),
)
for _, record in self.df.iterrows()
]
datasets = dask.compute(*datasets)
if len(datasets) == 1:
self._ds = datasets[0]
else:
datasets = sorted(
datasets,
key=lambda ds: tuple(
f'{INTAKE_ESM_ATTRS_PREFIX}/{agg.attribute_name}'
for agg in self.aggregations
),
)
with dask.config.set(
{'scheduler': 'single-threaded', 'array.slicing.split_large_chunks': True}
): # Use single-threaded scheduler
datasets = [
ds.set_coords(set(ds.variables) - set(ds.attrs[INTAKE_ESM_VARS_KEY]))
for ds in datasets
]
self._ds = xr.combine_by_coords(
datasets, **self.xarray_combine_by_coords_kwargs
)
self._ds.attrs[INTAKE_ESM_DATASET_KEY] = self.key
except Exception as exc:
raise ESMDataSourceError(
f"""Failed to load dataset with key='{self.key}'
You can use `cat['{self.key}'].df` to inspect the assets/files for this key.
"""
) from exc
def to_dask(self):
"""Return xarray object (which will have chunks)"""
self._load_metadata()
return self._ds
def close(self):
"""Delete open files from memory"""
self._ds = None
self._schema = None