-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdataarray.py
More file actions
385 lines (304 loc) · 10 KB
/
dataarray.py
File metadata and controls
385 lines (304 loc) · 10 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""Submodule for DataArray creation."""
__all__ = ["AsDataArray", "asdataarray"]
# standard library
from functools import partial
from inspect import signature
from types import MethodType
from typing import (
Any,
Callable,
Optional,
Protocol,
TYPE_CHECKING,
Type,
TypeVar,
Union,
overload,
)
# dependencies
from typing_extensions import ParamSpec
# submodules
from .datamodel import DataModel
from .dataoptions import DataOptions
from .typing import AnyArray, AnyXarray, DataClass, Order, Shape, Sizes
from .util import lazy_import
# lazy imports of large modules
if TYPE_CHECKING:
import numpy as np
import xarray as xr
else:
np = lazy_import("numpy")
xr = lazy_import("xarray")
# private type hints
PInit = ParamSpec("PInit")
TDataArray = TypeVar("TDataArray", bound="xr.DataArray")
class OptionedClass(DataClass[PInit], Protocol[PInit, TDataArray]):
"""Type hint for dataclass objects with options."""
__dataoptions__: DataOptions[TDataArray]
if TYPE_CHECKING:
# runtime functions
@overload
def asdataarray(
dataclass: OptionedClass[PInit, TDataArray],
reference: Optional[AnyXarray] = None,
dataoptions: None = None,
) -> xr.DataArray: ...
@overload
def asdataarray(
dataclass: DataClass[PInit],
reference: Optional[AnyXarray] = None,
dataoptions: None = None,
) -> xr.DataArray: ...
@overload
def asdataarray(
dataclass: Any,
reference: Optional[AnyXarray] = None,
dataoptions: DataOptions[TDataArray] = DataOptions(xr.DataArray),
) -> xr.DataArray: ...
def asdataarray(
dataclass: Any,
reference: Optional[AnyXarray] = None,
dataoptions: Any = None,
) -> Any:
"""Create a DataArray object from a dataclass object.
Args:
dataclass: Dataclass object that defines typed DataArray.
reference: DataArray or Dataset object as a reference of shape.
dataoptions: Options for DataArray creation.
Returns:
DataArray object created from the dataclass object.
"""
if dataoptions is None:
try:
dataoptions = dataclass.__dataoptions__
except AttributeError:
dataoptions = DataOptions(xr.DataArray)
model = DataModel.from_dataclass(dataclass)
dataarray = dataoptions.factory(model.data_vars[0](reference))
for entry in model.coords:
if entry.name in dataarray.dims:
dataarray.coords[entry.name] = entry(dataarray)
for entry in model.coords:
if entry.name not in dataarray.dims:
dataarray.coords[entry.name] = entry(dataarray)
for entry in model.attrs:
dataarray.attrs[entry.name] = entry()
if model.names:
dataarray.name = model.names[0]()
return dataarray
# runtime classes
class classproperty:
"""Class property only for AsDataArray.new().
As a classmethod and a property can be chained together since Python 3.9,
this class will be removed when the support for Python 3.7 and 3.8 ends.
"""
def __init__(self, func: Any) -> None:
self.__func__ = func
if TYPE_CHECKING:
@overload
def __get__(
self,
obj: Any,
cls: Type[OptionedClass[PInit, TDataArray]],
) -> Callable[PInit, TDataArray]: ...
@overload
def __get__(
self,
obj: Any,
cls: Type[DataClass[PInit]],
) -> Callable[PInit, xr.DataArray]: ...
def __get__(self, obj: Any, cls: Any) -> Any:
return self.__func__(cls)
class AsDataArray:
"""Mix-in class that provides shorthand methods."""
@classproperty
def new(cls: Any) -> Any:
"""Create a DataArray object from dataclass parameters."""
sig = signature(cls.__init__) # type: ignore
sig = sig.replace(return_annotation=TDataArray)
def new(cls: Any, *args: Any, **kwargs: Any) -> Any:
return asdataarray(cls(*args, **kwargs))
setattr(new, "__doc__", cls.__init__.__doc__)
setattr(new, "__signature__", sig)
return MethodType(new, cls)
if TYPE_CHECKING:
@overload
@classmethod
def shaped(
cls: Type[OptionedClass[PInit, TDataArray]],
func: Callable[[Shape], AnyArray],
shape: Union[Shape, Sizes],
**kwargs: Any,
) -> TDataArray: ...
@overload
@classmethod
def shaped(
cls: Type[DataClass[PInit]],
func: Callable[[Shape], AnyArray],
shape: Union[Shape, Sizes],
**kwargs: Any,
) -> xr.DataArray: ...
@classmethod
def shaped(
cls: Any,
func: Callable[[Shape], AnyArray],
shape: Union[Shape, Sizes],
**kwargs: Any,
) -> Any:
"""Create a DataArray object from a shaped function.
Args:
func: Function to create an array with given shape.
shape: Shape or sizes of the new DataArray object.
kwargs: Args of the DataArray class except for data.
Returns:
DataArray object created from the shaped function.
"""
model = DataModel.from_dataclass(cls)
key, entry = model.data_vars_items[0]
if isinstance(shape, dict):
shape = tuple(shape[dim] for dim in entry.dims)
return asdataarray(cls(**{key: func(shape)}, **kwargs))
if TYPE_CHECKING:
@overload
@classmethod
def empty(
cls: Type[OptionedClass[PInit, TDataArray]],
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> TDataArray: ...
@overload
@classmethod
def empty(
cls: Type[DataClass[PInit]],
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> xr.DataArray: ...
@classmethod
def empty(
cls: Any,
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> Any:
"""Create a DataArray object without initializing data.
Args:
shape: Shape or sizes of the new DataArray object.
order: Whether to store data in row-major (C-style)
or column-major (Fortran-style) order in memory.
kwargs: Args of the DataArray class except for data.
Returns:
DataArray object without initializing data.
"""
func = partial(np.empty, order=order)
return cls.shaped(func, shape, **kwargs)
if TYPE_CHECKING:
@overload
@classmethod
def zeros(
cls: Type[OptionedClass[PInit, TDataArray]],
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> TDataArray: ...
@overload
@classmethod
def zeros(
cls: Type[DataClass[PInit]],
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> xr.DataArray: ...
@classmethod
def zeros(
cls: Any,
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> Any:
"""Create a DataArray object filled with zeros.
Args:
shape: Shape or sizes of the new DataArray object.
order: Whether to store data in row-major (C-style)
or column-major (Fortran-style) order in memory.
kwargs: Args of the DataArray class except for data.
Returns:
DataArray object filled with zeros.
"""
func = partial(np.zeros, order=order)
return cls.shaped(func, shape, **kwargs)
if TYPE_CHECKING:
@overload
@classmethod
def ones(
cls: Type[OptionedClass[PInit, TDataArray]],
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> TDataArray: ...
@overload
@classmethod
def ones(
cls: Type[DataClass[PInit]],
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> xr.DataArray: ...
@classmethod
def ones(
cls: Any,
shape: Union[Shape, Sizes],
order: Order = "C",
**kwargs: Any,
) -> Any:
"""Create a DataArray object filled with ones.
Args:
shape: Shape or sizes of the new DataArray object.
order: Whether to store data in row-major (C-style)
or column-major (Fortran-style) order in memory.
kwargs: Args of the DataArray class except for data.
Returns:
DataArray object filled with ones.
"""
func = partial(np.ones, order=order)
return cls.shaped(func, shape, **kwargs)
if TYPE_CHECKING:
@overload
@classmethod
def full(
cls: Type[OptionedClass[PInit, TDataArray]],
shape: Union[Shape, Sizes],
fill_value: Any,
order: Order = "C",
**kwargs: Any,
) -> TDataArray: ...
@overload
@classmethod
def full(
cls: Type[DataClass[PInit]],
shape: Union[Shape, Sizes],
fill_value: Any,
order: Order = "C",
**kwargs: Any,
) -> xr.DataArray: ...
@classmethod
def full(
cls: Any,
shape: Union[Shape, Sizes],
fill_value: Any,
order: Order = "C",
**kwargs: Any,
) -> Any:
"""Create a DataArray object filled with given value.
Args:
shape: Shape or sizes of the new DataArray object.
fill_value: Value for the new DataArray object.
order: Whether to store data in row-major (C-style)
or column-major (Fortran-style) order in memory.
kwargs: Args of the DataArray class except for data.
Returns:
DataArray object filled with given value.
"""
func = partial(np.full, fill_value=fill_value, order=order)
return cls.shaped(func, shape, **kwargs)