-
Notifications
You must be signed in to change notification settings - Fork 21
/
flavour.py
472 lines (371 loc) · 14.5 KB
/
flavour.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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# (C) Copyright 2024 Anemoi contributors.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
import logging
from .coordinates import DateCoordinate
from .coordinates import EnsembleCoordinate
from .coordinates import LatitudeCoordinate
from .coordinates import LevelCoordinate
from .coordinates import LongitudeCoordinate
from .coordinates import ScalarCoordinate
from .coordinates import StepCoordinate
from .coordinates import TimeCoordinate
from .coordinates import UnsupportedCoordinate
from .coordinates import XCoordinate
from .coordinates import YCoordinate
from .coordinates import is_scalar
from .grid import MeshedGrid
from .grid import MeshProjectionGrid
from .grid import UnstructuredGrid
from .grid import UnstructuredProjectionGrid
LOG = logging.getLogger(__name__)
class CoordinateGuesser:
def __init__(self, ds):
self.ds = ds
self._cache = {}
@classmethod
def from_flavour(cls, ds, flavour):
if flavour is None:
return DefaultCoordinateGuesser(ds)
else:
return FlavourCoordinateGuesser(ds, flavour)
def guess(self, c, coord):
if coord not in self._cache:
self._cache[coord] = self._guess(c, coord)
return self._cache[coord]
def _guess(self, c, coord):
name = c.name
standard_name = getattr(c, "standard_name", "").lower()
axis = getattr(c, "axis", "")
long_name = getattr(c, "long_name", "").lower()
units = getattr(c, "units", "")
d = self._is_longitude(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_latitude(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_x(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_y(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_time(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_step(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_date(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_level(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
d = self._is_number(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
)
if d is not None:
return d
if c.shape in ((1,), tuple()):
return ScalarCoordinate(c)
LOG.warning(
f"Coordinate {coord} not supported\n{axis=}, {name=},"
f" {long_name=}, {standard_name=}, units\n\n{c}\n\n{type(c.values)} {c.shape}"
)
return UnsupportedCoordinate(c)
def grid(self, coordinates, variable):
lat = [c for c in coordinates if c.is_lat]
lon = [c for c in coordinates if c.is_lon]
if len(lat) == 1 and len(lon) == 1:
return self._lat_lon_provided(lat, lon, variable)
x = [c for c in coordinates if c.is_x]
y = [c for c in coordinates if c.is_y]
if len(x) == 1 and len(y) == 1:
return self._x_y_provided(x, y, variable)
raise NotImplementedError(f"Cannot establish grid {coordinates}")
def _check_dims(self, variable, x_or_lon, y_or_lat):
x_dims = set(x_or_lon.variable.dims)
y_dims = set(y_or_lat.variable.dims)
variable_dims = set(variable.dims)
if not (x_dims <= variable_dims) or not (y_dims <= variable_dims):
raise ValueError(
f"Dimensions do not match {variable.name}{variable.dims} !="
f" {x_or_lon.name}{x_or_lon.variable.dims} and {y_or_lat.name}{y_or_lat.variable.dims}"
)
variable_dims = tuple(v for v in variable.dims if v in (x_dims | y_dims))
if x_dims == y_dims:
# It's unstructured
return variable_dims, True
if len(x_dims) == 1 and len(y_dims) == 1:
# It's a mesh
return variable_dims, False
raise ValueError(
f"Cannot establish grid for {variable.name}{variable.dims},"
f" {x_or_lon.name}{x_or_lon.variable.dims},"
f" {y_or_lat.name}{y_or_lat.variable.dims}"
)
def _lat_lon_provided(self, lat, lon, variable):
lat = lat[0]
lon = lon[0]
dim_vars, unstructured = self._check_dims(variable, lon, lat)
if (lat.name, lon.name, dim_vars) in self._cache:
return self._cache[(lat.name, lon.name, dim_vars)]
if unstructured:
grid = UnstructuredGrid(lat, lon, dim_vars)
else:
grid = MeshedGrid(lat, lon, dim_vars)
self._cache[(lat.name, lon.name, dim_vars)] = grid
return grid
def _x_y_provided(self, x, y, variable):
x = x[0]
y = y[0]
dim_vars, unstructured = self._check_dims(variable, x, y)
if (x.name, y.name, dim_vars) in self._cache:
return self._cache[(x.name, y.name, dim_vars)]
grid_mapping = variable.attrs.get("grid_mapping", None)
if grid_mapping is not None:
print(f"grid_mapping: {grid_mapping}")
print(self.ds[grid_mapping])
if grid_mapping is None:
LOG.warning(f"No 'grid_mapping' attribute provided for '{variable.name}'")
LOG.warning("Trying to guess...")
PROBE = {
"prime_meridian_name",
"reference_ellipsoid_name",
"crs_wkt",
"horizontal_datum_name",
"semi_major_axis",
"spatial_ref",
"inverse_flattening",
"semi_minor_axis",
"geographic_crs_name",
"GeoTransform",
"grid_mapping_name",
"longitude_of_prime_meridian",
}
candidate = None
for v in self.ds.variables:
var = self.ds[v]
if not is_scalar(var):
continue
if PROBE.intersection(var.attrs.keys()):
if candidate:
raise ValueError(f"Multiple candidates for 'grid_mapping': {candidate} and {v}")
candidate = v
if candidate:
LOG.warning(f"Using '{candidate}' as 'grid_mapping'")
grid_mapping = candidate
else:
LOG.warning("Could not fine a candidate for 'grid_mapping'")
if grid_mapping is None:
if "crs" in self.ds[variable].attrs:
grid_mapping = self.ds[variable].attrs["crs"]
LOG.warning(f"Using CRS {grid_mapping} from variable '{variable.name}' attributes")
if grid_mapping is None:
if "crs" in self.ds.attrs:
grid_mapping = self.ds.attrs["crs"]
LOG.warning(f"Using CRS {grid_mapping} from global attributes")
grid = None
if grid_mapping is not None:
grid_mapping = dict(self.ds[grid_mapping].attrs)
if unstructured:
grid = UnstructuredProjectionGrid(x, y, grid_mapping)
else:
grid = MeshProjectionGrid(x, y, grid_mapping)
if grid is not None:
self._cache[(x.name, y.name, dim_vars)] = grid
return grid
LOG.error("Could not fine a candidate for 'grid_mapping'")
raise NotImplementedError(f"Unstructured grid {x.name} {y.name}")
class DefaultCoordinateGuesser(CoordinateGuesser):
def __init__(self, ds):
super().__init__(ds)
def _is_longitude(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "longitude":
return LongitudeCoordinate(c)
if long_name == "longitude" and units == "degrees_east":
return LongitudeCoordinate(c)
if name == "longitude": # WeatherBench
return LongitudeCoordinate(c)
def _is_latitude(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "latitude":
return LatitudeCoordinate(c)
if long_name == "latitude" and units == "degrees_north":
return LatitudeCoordinate(c)
if name == "latitude": # WeatherBench
return LatitudeCoordinate(c)
def _is_x(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "projection_x_coordinate":
return XCoordinate(c)
if name == "x":
return XCoordinate(c)
def _is_y(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "projection_y_coordinate":
return YCoordinate(c)
if name == "y":
return YCoordinate(c)
def _is_time(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "time":
return TimeCoordinate(c)
# That is the output of `cfgrib` for forecasts
if name == "time" and standard_name != "forecast_reference_time":
return TimeCoordinate(c)
def _is_date(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "forecast_reference_time":
return DateCoordinate(c)
if name == "forecast_reference_time":
return DateCoordinate(c)
def _is_step(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "forecast_period":
return StepCoordinate(c)
if long_name == "time elapsed since the start of the forecast":
return StepCoordinate(c)
if name == "prediction_timedelta": # WeatherBench
return StepCoordinate(c)
def _is_level(self, c, *, axis, name, long_name, standard_name, units):
if standard_name == "atmosphere_hybrid_sigma_pressure_coordinate":
return LevelCoordinate(c, "ml")
if long_name == "height" and units == "m":
return LevelCoordinate(c, "height")
if standard_name == "air_pressure" and units == "hPa":
return LevelCoordinate(c, "pl")
if name == "level":
return LevelCoordinate(c, "pl")
if name == "vertical" and units == "hPa":
return LevelCoordinate(c, "pl")
if standard_name == "depth":
return LevelCoordinate(c, "depth")
if name == "vertical" and units == "hPa":
return LevelCoordinate(c, "pl")
def _is_number(self, c, *, axis, name, long_name, standard_name, units):
if name in ("realization", "number"):
return EnsembleCoordinate(c)
class FlavourCoordinateGuesser(CoordinateGuesser):
def __init__(self, ds, flavour):
super().__init__(ds)
self.flavour = flavour
def _match(self, c, key, values):
if key not in self.flavour["rules"]:
return None
rules = self.flavour["rules"][key]
if not isinstance(rules, list):
rules = [rules]
for rule in rules:
ok = True
for k, v in rule.items():
if isinstance(v, str) and values.get(k) != v:
ok = False
if ok:
return rule
return None
def _is_longitude(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "longitude", locals()):
return LongitudeCoordinate(c)
def _is_latitude(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "latitude", locals()):
return LatitudeCoordinate(c)
def _is_x(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "x", locals()):
return XCoordinate(c)
def _is_y(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "y", locals()):
return YCoordinate(c)
def _is_time(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "time", locals()):
return TimeCoordinate(c)
def _is_step(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "step", locals()):
return StepCoordinate(c)
def _is_date(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "date", locals()):
return DateCoordinate(c)
def _is_level(self, c, *, axis, name, long_name, standard_name, units):
rule = self._match(c, "level", locals())
if rule:
# assert False, rule
return LevelCoordinate(
c,
self._levtype(
c,
axis=axis,
name=name,
long_name=long_name,
standard_name=standard_name,
units=units,
),
)
def _levtype(self, c, *, axis, name, long_name, standard_name, units):
if "levtype" in self.flavour:
return self.flavour["levtype"]
raise NotImplementedError(f"levtype for {c=}")
def _is_number(self, c, *, axis, name, long_name, standard_name, units):
if self._match(c, "number", locals()):
return DateCoordinate(c)