-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdatamodel.py
More file actions
294 lines (220 loc) · 7.79 KB
/
datamodel.py
File metadata and controls
294 lines (220 loc) · 7.79 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
"""Submodule for data expression inside the package."""
__all__ = ["DataModel"]
# standard library
from dataclasses import dataclass, field, is_dataclass
from typing import (
Any,
Dict,
Hashable,
List,
Literal,
Optional,
Tuple,
Type,
Union,
cast,
)
# dependencies
import numpy as np
import xarray as xr
from typing_extensions import ParamSpec, get_type_hints
# submodules
from .typing import (
AnyDType,
AnyField,
AnyXarray,
DataClass,
Dims,
Role,
get_annotated,
get_dataclass,
get_dims,
get_dtype,
get_name,
get_role,
)
# type hints
PInit = ParamSpec("PInit")
AnyDataClass = Union[Type[DataClass[PInit]], DataClass[PInit]]
AnyEntry = Union["AttrEntry", "DataEntry"]
# runtime classes
class MissingType:
"""Singleton that indicates missing data."""
_instance = None
def __new__(cls) -> "MissingType":
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __repr__(self) -> str:
return "<MISSING>"
MISSING = MissingType()
@dataclass(frozen=True)
class AttrEntry:
"""Entry of an attribute (i.e. metadata)."""
name: Hashable
"""Name that the attribute is accessed by."""
tag: Literal["attr", "name"]
"""Function of the attribute (either attr or name)."""
type: Any = None
"""Type or type hint of the attribute."""
value: Any = MISSING
"""Actual value of the attribute."""
cast: bool = False
"""Whether the value is cast to the type."""
def __call__(self) -> Any:
"""Create an object according to the entry."""
if self.value is MISSING:
raise ValueError("Value is missing.")
return self.value
@dataclass(frozen=True)
class DataEntry:
"""Entry of a data variable."""
name: Hashable
"""Name that the attribute is accessed by."""
tag: Literal["coord", "data"]
"""Function of the data (either coord or data)."""
dims: Dims = cast(Dims, None)
"""Dimensions of the DataArray that the data is cast to."""
dtype: Optional[AnyDType] = None
"""Data type of the DataArray that the data is cast to."""
base: Optional[Type[DataClass[Any]]] = None
"""Base dataclass that converts the data to a DataArray."""
value: Any = MISSING
"""Actual value of the data."""
cast: bool = True
"""Whether the value is cast to the data type."""
def __post_init__(self) -> None:
"""Update the entry if a base dataclass exists."""
if self.base is None:
return
model = DataModel.from_dataclass(self.base)
setattr = object.__setattr__
setattr(self, "dims", model.data_vars[0].dims)
setattr(self, "dtype", model.data_vars[0].dtype)
if model.names:
setattr(self, "name", model.names[0].value)
def __call__(self, reference: Optional[AnyXarray] = None) -> xr.DataArray:
"""Create a DataArray object according to the entry."""
from .dataarray import asdataarray
if self.value is MISSING:
raise ValueError("Value is missing.")
if self.base is None:
return get_typedarray(self.value, self.dims, self.dtype, reference)
if is_dataclass(self.value):
return asdataarray(self.value, reference)
else:
return asdataarray(self.base(self.value), reference)
@dataclass(frozen=True)
class DataModel:
"""Data representation (data model) inside the package."""
entries: Dict[str, AnyEntry] = field(default_factory=dict)
"""Entries of data variable(s) and attribute(s)."""
@property
def attrs(self) -> List[AttrEntry]:
"""Return a list of attribute entries."""
return [v for v in self.entries.values() if v.tag == "attr"]
@property
def coords(self) -> List[DataEntry]:
"""Return a list of coordinate entries."""
return [v for v in self.entries.values() if v.tag == "coord"]
@property
def data_vars(self) -> List[DataEntry]:
"""Return a list of data variable entries."""
return [v for v in self.entries.values() if v.tag == "data"]
@property
def data_vars_items(self) -> List[Tuple[str, DataEntry]]:
"""Return a list of data variable entries with keys."""
return [(k, v) for k, v in self.entries.items() if v.tag == "data"]
@property
def names(self) -> List[AttrEntry]:
"""Return a list of name entries."""
return [v for v in self.entries.values() if v.tag == "name"]
@classmethod
def from_dataclass(cls, dataclass: AnyDataClass[PInit]) -> "DataModel":
"""Create a data model from a dataclass or its object."""
model = cls()
eval_dataclass(dataclass)
for field_value in dataclass.__dataclass_fields__.values():
value = getattr(dataclass, field_value.name, MISSING)
entry = get_entry(field_value, value)
if entry is not None:
model.entries[field_value.name] = entry
return model
# runtime functions
def eval_dataclass(dataclass: AnyDataClass[PInit]) -> None:
"""Evaluate field types of a dataclass."""
if not is_dataclass(dataclass):
raise TypeError("Not a dataclass or its object.")
field_values = dataclass.__dataclass_fields__.values()
# do nothing if field types are already evaluated
if not any(isinstance(field_value.type, str) for field_value in field_values):
return
# otherwise, replace field types with evaluated types
if not isinstance(dataclass, type):
dataclass = type(dataclass)
types = get_type_hints(dataclass, include_extras=True)
for field_value in field_values:
field_value.type = types[field_value.name]
def get_entry(field: AnyField, value: Any) -> Optional[AnyEntry]:
"""Create an entry from a field and its value."""
role = get_role(field.type)
name = get_name(field.type, field.name)
if role is Role.ATTR or role is Role.NAME:
return AttrEntry(
name=name,
tag=role.value,
value=value,
type=get_annotated(field.type),
)
if role is Role.COORD or role is Role.DATA:
try:
return DataEntry(
name=name,
tag=role.value,
base=get_dataclass(field.type),
value=value,
)
except TypeError:
return DataEntry(
name=name,
tag=role.value,
dims=get_dims(field.type),
dtype=get_dtype(field.type),
value=value,
)
def get_typedarray(
data: Any,
dims: Dims,
dtype: Optional[AnyDType],
reference: Optional[AnyXarray] = None,
) -> xr.DataArray:
"""Create a DataArray object with given dims and dtype.
Args:
data: Data to be converted to the DataArray object.
dims: Dimensions of the DataArray object.
dtype: Data type of the DataArray object.
reference: DataArray or Dataset object as a reference of shape.
Returns:
DataArray object with given dims and dtype.
"""
try:
data.__array__
except AttributeError:
data = np.asarray(data)
if dtype is not None:
data = data.astype(dtype, copy=False)
if data.ndim == len(dims):
dataarray = xr.DataArray(data, dims=dims)
elif data.ndim == 0 and reference is not None:
dataarray = xr.DataArray(data)
else:
raise ValueError(
"Could not create a DataArray object from data. "
f"Mismatch between shape {data.shape} and dims {dims}."
)
if reference is None:
return dataarray
else:
ddims = set(reference.dims) - set(dims)
reference = reference.isel({dim: 0 for dim in ddims})
return dataarray.broadcast_like(reference)