/
dataset.py
638 lines (586 loc) · 22.5 KB
/
dataset.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#
# Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors:
# Alessandro Amici - B-Open - https://bopen.eu
#
import collections
import datetime
import json
import logging
import typing as T
import attr
import numpy as np
from . import __version__
from . import cfmessage
from . import messages
LOG = logging.getLogger(__name__)
#
# Edition-independent keys in ecCodes namespaces. Documented in:
# https://software.ecmwf.int/wiki/display/ECC/GRIB%3A+Namespaces
#
GLOBAL_ATTRIBUTES_KEYS = ['edition', 'centre', 'centreDescription', 'subCentre']
DATA_ATTRIBUTES_KEYS = [
'paramId',
'shortName',
'units',
'name',
'cfName',
'cfVarName',
'dataType',
'missingValue',
'numberOfPoints',
'totalNumber',
'numberOfDirections',
'numberOfFrequencies',
'typeOfLevel',
'NV',
'stepUnits',
'stepType',
'gridType',
'gridDefinitionDescription',
]
GRID_TYPE_MAP = {
'regular_ll': [
'Nx',
'iDirectionIncrementInDegrees',
'iScansNegatively',
'longitudeOfFirstGridPointInDegrees',
'longitudeOfLastGridPointInDegrees',
'Ny',
'jDirectionIncrementInDegrees',
'jPointsAreConsecutive',
'jScansPositively',
'latitudeOfFirstGridPointInDegrees',
'latitudeOfLastGridPointInDegrees',
],
'rotated_ll': [
'Nx',
'Ny',
'angleOfRotationInDegrees',
'iDirectionIncrementInDegrees',
'iScansNegatively',
'jDirectionIncrementInDegrees',
'jPointsAreConsecutive',
'jScansPositively',
'latitudeOfFirstGridPointInDegrees',
'latitudeOfLastGridPointInDegrees',
'latitudeOfSouthernPoleInDegrees',
'longitudeOfFirstGridPointInDegrees',
'longitudeOfLastGridPointInDegrees',
'longitudeOfSouthernPoleInDegrees',
],
'reduced_ll': [
'Ny',
'jDirectionIncrementInDegrees',
'jPointsAreConsecutive',
'jScansPositively',
'latitudeOfFirstGridPointInDegrees',
'latitudeOfLastGridPointInDegrees',
],
'regular_gg': [
'Nx',
'iDirectionIncrementInDegrees',
'iScansNegatively',
'longitudeOfFirstGridPointInDegrees',
'longitudeOfLastGridPointInDegrees',
'N',
'Ny',
],
'rotated_gg': [
'Nx',
'Ny',
'angleOfRotationInDegrees',
'iDirectionIncrementInDegrees',
'iScansNegatively',
'jPointsAreConsecutive',
'jScansPositively',
'latitudeOfFirstGridPointInDegrees',
'latitudeOfLastGridPointInDegrees',
'latitudeOfSouthernPoleInDegrees',
'longitudeOfFirstGridPointInDegrees',
'longitudeOfLastGridPointInDegrees',
'longitudeOfSouthernPoleInDegrees',
'N',
],
'lambert': [
'LaDInDegrees',
'LoVInDegrees',
'iScansNegatively',
'jPointsAreConsecutive',
'jScansPositively',
'latitudeOfFirstGridPointInDegrees',
'latitudeOfSouthernPoleInDegrees',
'longitudeOfFirstGridPointInDegrees',
'longitudeOfSouthernPoleInDegrees',
'DyInMetres',
'DxInMetres',
'Latin2InDegrees',
'Latin1InDegrees',
'Ny',
'Nx',
],
'reduced_gg': ['N', 'pl'],
'sh': ['M', 'K', 'J'],
}
GRID_TYPE_KEYS = sorted(set(k for _, ks in GRID_TYPE_MAP.items() for k in ks))
ENSEMBLE_KEYS = ['number']
VERTICAL_KEYS = ['level']
DATA_TIME_KEYS = ['dataDate', 'dataTime', 'endStep']
ALL_REF_TIME_KEYS = ['time', 'step', 'valid_time', 'verifying_time', 'forecastMonth']
SPECTRA_KEYS = ['directionNumber', 'frequencyNumber']
ALL_HEADER_DIMS = ENSEMBLE_KEYS + VERTICAL_KEYS + DATA_TIME_KEYS + ALL_REF_TIME_KEYS + SPECTRA_KEYS
ALL_KEYS = sorted(GLOBAL_ATTRIBUTES_KEYS + DATA_ATTRIBUTES_KEYS + GRID_TYPE_KEYS + ALL_HEADER_DIMS)
COORD_ATTRS = {
# geography
'latitude': {'units': 'degrees_north', 'standard_name': 'latitude', 'long_name': 'latitude'},
'longitude': {'units': 'degrees_east', 'standard_name': 'longitude', 'long_name': 'longitude'},
# vertical
'depthBelowLand': {
'units': 'm',
'positive': 'down',
'long_name': 'soil depth',
'standard_name': 'depth',
},
'depthBelowLandLayer': {
'units': 'm',
'positive': 'down',
'long_name': 'soil depth',
'standard_name': 'depth',
},
'hybrid': {
'units': '1',
'positive': 'down',
'long_name': 'hybrid level',
'standard_name': 'atmosphere_hybrid_sigma_pressure_coordinate',
},
'heightAboveGround': {
'units': 'm',
'positive': 'up',
'long_name': 'height above the surface',
'standard_name': 'height',
},
'isobaricInhPa': {
'units': 'hPa',
'positive': 'down',
'stored_direction': 'decreasing',
'standard_name': 'air_pressure',
'long_name': 'pressure',
},
'isobaricInPa': {
'units': 'Pa',
'positive': 'down',
'stored_direction': 'decreasing',
'standard_name': 'air_pressure',
'long_name': 'pressure',
},
'isobaricLayer': {
'units': 'Pa',
'positive': 'down',
'standard_name': 'air_pressure',
'long_name': 'pressure',
},
# ensemble
'number': {
'units': '1',
'standard_name': 'realization',
'long_name': 'ensemble member numerical id',
},
# time
'step': {
'units': 'hours',
'standard_name': 'forecast_period',
'long_name': 'time since forecast_reference_time',
},
'time': {
'units': 'seconds since 1970-01-01T00:00:00',
'calendar': 'proleptic_gregorian',
'standard_name': 'forecast_reference_time',
'long_name': 'initial time of forecast',
},
'valid_time': {
'units': 'seconds since 1970-01-01T00:00:00',
'calendar': 'proleptic_gregorian',
'standard_name': 'time',
'long_name': 'time',
},
'verifying_time': {
'units': 'seconds since 1970-01-01T00:00:00',
'calendar': 'proleptic_gregorian',
'standard_name': 'time',
'long_name': 'time',
},
'forecastMonth': {'units': '1', 'long_name': 'months since forecast_reference_time'},
}
class DatasetBuildError(ValueError):
def __str__(self):
return str(self.args[0])
def enforce_unique_attributes(index, attributes_keys, filter_by_keys={}):
# type: (messages.FileIndex, T.Sequence[str], dict) -> T.Dict[str, T.Any]
attributes = collections.OrderedDict() # type: T.Dict[str, T.Any]
for key in attributes_keys:
values = index[key]
if len(values) > 1:
fbks = []
for value in values:
fbk = {key: value}
fbk.update(filter_by_keys)
fbks.append(fbk)
raise DatasetBuildError("multiple values for key %r" % key, key, fbks)
if values and values[0] not in ('undef', 'unknown'):
attributes['GRIB_' + key] = values[0]
return attributes
@attr.attrs(eq=False)
class Variable(object):
dimensions = attr.attrib(type=T.Tuple[str, ...])
data = attr.attrib(type=np.ndarray)
attributes = attr.attrib(default={}, type=T.Dict[str, T.Any], repr=False)
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
equal = (self.dimensions, self.attributes) == (other.dimensions, other.attributes)
return equal and np.array_equal(self.data, other.data)
def expand_item(item, shape):
expanded_item = []
for i, size in zip(item, shape):
if isinstance(i, list):
expanded_item.append(i)
elif isinstance(i, np.ndarray):
expanded_item.append(i.tolist())
elif isinstance(i, slice):
expanded_item.append(list(range(i.start or 0, i.stop or size, i.step or 1)))
elif isinstance(i, int):
expanded_item.append([i])
else:
raise TypeError("Unsupported index type %r" % type(i))
return tuple(expanded_item)
@attr.attrs()
class OnDiskArray(object):
stream = attr.attrib()
shape = attr.attrib(type=T.Tuple[int, ...])
offsets = attr.attrib(repr=False, type=T.Dict[T.Tuple[T.Any, ...], T.List[int]])
missing_value = attr.attrib()
geo_ndim = attr.attrib(default=1, repr=False)
dtype = np.dtype('float32')
def build_array(self):
# type: () -> np.ndarray
"""Helper method used to test __getitem__"""
array = np.full(self.shape, fill_value=np.nan, dtype='float32')
with open(self.stream.path, 'rb') as file:
for header_indexes, offset in self.offsets.items():
# NOTE: fill a single field as found in the message
message = self.stream.message_from_file(file, offset=offset[0])
values = message.message_get('values', float)
array.__getitem__(header_indexes).flat[:] = values
array[array == self.missing_value] = np.nan
return array
def __getitem__(self, item):
header_item = expand_item(item[: -self.geo_ndim], self.shape)
array_field_shape = tuple(len(l) for l in header_item) + self.shape[-self.geo_ndim :]
array_field = np.full(array_field_shape, fill_value=np.nan, dtype='float32')
with open(self.stream.path, 'rb') as file:
for header_indexes, offset in self.offsets.items():
try:
array_field_indexes = [
it.index(ix) for it, ix in zip(header_item, header_indexes)
]
except ValueError:
continue
# NOTE: fill a single field as found in the message
message = self.stream.message_from_file(file, offset=offset[0])
values = message.message_get('values', float)
array_field.__getitem__(tuple(array_field_indexes)).flat[:] = values
array = array_field[(Ellipsis,) + item[-self.geo_ndim :]]
array[array == self.missing_value] = np.nan
for i, it in reversed(list(enumerate(item[: -self.geo_ndim]))):
if isinstance(it, int):
array = array[(slice(None, None, None),) * i + (0,)]
return array
GRID_TYPES_DIMENSION_COORDS = {'regular_ll', 'regular_gg'}
GRID_TYPES_2D_NON_DIMENSION_COORDS = {
'rotated_ll',
'rotated_gg',
'lambert',
'lambert_azimuthal_equal_area',
'albers',
'polar_stereographic',
}
def build_geography_coordinates(
index, # type: messages.FileIndex
encode_cf, # type: T.Sequence[str]
errors, # type: str
log=LOG, # type: logging.Logger
):
# type: (...) -> T.Tuple[T.Tuple[str, ...], T.Tuple[int, ...], T.Dict[str, Variable]]
first = index.first()
geo_coord_vars = collections.OrderedDict() # type: T.Dict[str, Variable]
grid_type = index.getone('gridType')
if 'geography' in encode_cf and grid_type in GRID_TYPES_DIMENSION_COORDS:
geo_dims = ('latitude', 'longitude') # type: T.Tuple[str, ...]
geo_shape = (index.getone('Ny'), index.getone('Nx')) # type: T.Tuple[int, ...]
latitudes = np.array(first['distinctLatitudes'])
geo_coord_vars['latitude'] = Variable(
dimensions=('latitude',), data=latitudes, attributes=COORD_ATTRS['latitude'].copy()
)
if latitudes[0] > latitudes[-1]:
geo_coord_vars['latitude'].attributes['stored_direction'] = 'decreasing'
geo_coord_vars['longitude'] = Variable(
dimensions=('longitude',),
data=np.array(first['distinctLongitudes']),
attributes=COORD_ATTRS['longitude'],
)
elif 'geography' in encode_cf and grid_type in GRID_TYPES_2D_NON_DIMENSION_COORDS:
geo_dims = ('y', 'x')
geo_shape = (index.getone('Ny'), index.getone('Nx'))
try:
geo_coord_vars['latitude'] = Variable(
dimensions=('y', 'x'),
data=np.array(first['latitudes']).reshape(geo_shape),
attributes=COORD_ATTRS['latitude'],
)
geo_coord_vars['longitude'] = Variable(
dimensions=('y', 'x'),
data=np.array(first['longitudes']).reshape(geo_shape),
attributes=COORD_ATTRS['longitude'],
)
except KeyError: # pragma: no cover
if errors != 'ignore':
log.warning('ecCodes provides no latitudes/longitudes for gridType=%r', grid_type)
else:
geo_dims = ('values',)
geo_shape = (index.getone('numberOfPoints'),)
# add secondary coordinates if ecCodes provides them
try:
latitude = first['latitudes']
geo_coord_vars['latitude'] = Variable(
dimensions=('values',), data=np.array(latitude), attributes=COORD_ATTRS['latitude']
)
longitude = first['longitudes']
geo_coord_vars['longitude'] = Variable(
dimensions=('values',),
data=np.array(longitude),
attributes=COORD_ATTRS['longitude'],
)
except KeyError: # pragma: no cover
if errors != 'ignore':
log.warning('ecCodes provides no latitudes/longitudes for gridType=%r', grid_type)
return geo_dims, geo_shape, geo_coord_vars
def encode_cf_first(data_var_attrs, encode_cf=('parameter', 'time'), time_dims=('time', 'step')):
coords_map = ENSEMBLE_KEYS[:]
param_id = data_var_attrs.get('GRIB_paramId', 'undef')
data_var_attrs['long_name'] = 'original GRIB paramId: %s' % param_id
data_var_attrs['units'] = '1'
if 'parameter' in encode_cf:
if 'GRIB_cfName' in data_var_attrs:
data_var_attrs['standard_name'] = data_var_attrs['GRIB_cfName']
if 'GRIB_name' in data_var_attrs:
data_var_attrs['long_name'] = data_var_attrs['GRIB_name']
if 'GRIB_units' in data_var_attrs:
data_var_attrs['units'] = data_var_attrs['GRIB_units']
if 'time' in encode_cf:
if set(time_dims).issubset(ALL_REF_TIME_KEYS):
coords_map.extend(time_dims)
else:
raise ValueError("time_dims %r not a subset of %r" % (time_dims, ALL_REF_TIME_KEYS))
else:
coords_map.extend(DATA_TIME_KEYS)
coords_map.extend(VERTICAL_KEYS)
coords_map.extend(SPECTRA_KEYS)
return coords_map
def build_variable_components(
index,
encode_cf=(),
filter_by_keys={},
log=LOG,
errors='warn',
squeeze=True,
read_keys=[],
time_dims=('time', 'step'),
):
data_var_attrs_keys = DATA_ATTRIBUTES_KEYS[:]
data_var_attrs_keys.extend(GRID_TYPE_MAP.get(index.getone('gridType'), []))
data_var_attrs_keys.extend(read_keys)
data_var_attrs = enforce_unique_attributes(index, data_var_attrs_keys, filter_by_keys)
coords_map = encode_cf_first(data_var_attrs, encode_cf, time_dims)
coord_name_key_map = {}
coord_vars = collections.OrderedDict()
for coord_key in coords_map:
values = index[coord_key]
if len(values) == 1 and values[0] == 'undef':
log.info("missing from GRIB stream: %r" % coord_key)
continue
coord_name = coord_key
if (
'vertical' in encode_cf
and coord_key == 'level'
and 'GRIB_typeOfLevel' in data_var_attrs
):
coord_name = data_var_attrs['GRIB_typeOfLevel']
coord_name_key_map[coord_name] = coord_key
attributes = {
'long_name': 'original GRIB coordinate for key: %s(%s)' % (coord_key, coord_name),
'units': '1',
}
attributes.update(COORD_ATTRS.get(coord_name, {}).copy())
data = np.array(sorted(values, reverse=attributes.get('stored_direction') == 'decreasing'))
dimensions = (coord_name,)
if squeeze and len(values) == 1:
data = data[0]
dimensions = ()
coord_vars[coord_name] = Variable(dimensions=dimensions, data=data, attributes=attributes)
header_dimensions = tuple(d for d, c in coord_vars.items() if not squeeze or c.data.size > 1)
header_shape = tuple(coord_vars[d].data.size for d in header_dimensions)
geo_dims, geo_shape, geo_coord_vars = build_geography_coordinates(index, encode_cf, errors)
dimensions = header_dimensions + geo_dims
shape = header_shape + geo_shape
coord_vars.update(geo_coord_vars)
offsets = collections.OrderedDict()
for header_values, offset in index.offsets:
header_indexes = [] # type: T.List[int]
for dim in header_dimensions:
header_value = header_values[index.index_keys.index(coord_name_key_map.get(dim, dim))]
header_indexes.append(coord_vars[dim].data.tolist().index(header_value))
offsets[tuple(header_indexes)] = offset
missing_value = data_var_attrs.get('missingValue', 9999)
data = OnDiskArray(
stream=index.filestream,
shape=shape,
offsets=offsets,
missing_value=missing_value,
geo_ndim=len(geo_dims),
)
if 'time' in coord_vars and 'step' in coord_vars:
# add the 'valid_time' secondary coordinate
dims, time_data = cfmessage.build_valid_time(
coord_vars['time'].data, coord_vars['step'].data,
)
attrs = COORD_ATTRS['valid_time']
coord_vars['valid_time'] = Variable(dimensions=dims, data=time_data, attributes=attrs)
data_var_attrs['coordinates'] = ' '.join(coord_vars.keys())
data_var = Variable(dimensions=dimensions, data=data, attributes=data_var_attrs)
dims = collections.OrderedDict((d, s) for d, s in zip(dimensions, data_var.data.shape))
return dims, data_var, coord_vars
def dict_merge(master, update):
for key, value in update.items():
if key not in master:
master[key] = value
elif master[key] == value:
pass
else:
raise DatasetBuildError(
"key present and new value is different: "
"key=%r value=%r new_value=%r" % (key, master[key], value)
)
def build_dataset_attributes(index, filter_by_keys, encoding):
attributes = enforce_unique_attributes(index, GLOBAL_ATTRIBUTES_KEYS, filter_by_keys)
attributes['Conventions'] = 'CF-1.7'
if 'GRIB_centreDescription' in attributes:
attributes['institution'] = attributes['GRIB_centreDescription']
attributes_namespace = {
'cfgrib_version': __version__,
'cfgrib_open_kwargs': json.dumps(encoding),
'eccodes_version': messages.eccodes_version,
'timestamp': datetime.datetime.now().isoformat().partition('.')[0],
}
history_in = (
'{timestamp} GRIB to CDM+CF via '
'cfgrib-{cfgrib_version}/ecCodes-{eccodes_version} with {cfgrib_open_kwargs}'
)
attributes['history'] = history_in.format(**attributes_namespace)
return attributes
def build_dataset_components(
index,
errors='warn',
encode_cf=('parameter', 'time', 'geography', 'vertical'),
squeeze=True,
log=LOG,
read_keys=[],
time_dims=('time', 'step'),
):
dimensions = collections.OrderedDict()
variables = collections.OrderedDict()
filter_by_keys = index.filter_by_keys
for param_id in index['paramId']:
var_index = index.subindex(paramId=param_id)
try:
dims, data_var, coord_vars = build_variable_components(
var_index,
encode_cf,
filter_by_keys,
errors=errors,
squeeze=squeeze,
read_keys=read_keys,
time_dims=time_dims,
)
except DatasetBuildError as ex:
# NOTE: When a variable has more than one value for an attribute we need to raise all
# the values in the file, not just the ones associated with that variable. See #54.
key = ex.args[1]
error_message = "multiple values for unique key, try re-open the file with one of:"
fbks = []
for value in index[key]:
fbk = {key: value}
fbk.update(filter_by_keys)
fbks.append(fbk)
error_message += "\n filter_by_keys=%r" % fbk
raise DatasetBuildError(error_message, key, fbks)
short_name = data_var.attributes.get('GRIB_shortName', 'paramId_%d' % param_id)
var_name = data_var.attributes.get('GRIB_cfVarName', 'unknown')
if 'parameter' in encode_cf and var_name not in ('undef', 'unknown'):
short_name = var_name
try:
dict_merge(variables, coord_vars)
dict_merge(variables, {short_name: data_var})
dict_merge(dimensions, dims)
except ValueError:
if errors == 'ignore':
pass
elif errors == 'raise':
raise
else:
log.exception("skipping variable: paramId==%r shortName=%r", param_id, short_name)
encoding = {
'source': index.filestream.path,
'filter_by_keys': filter_by_keys,
'encode_cf': encode_cf,
}
attributes = build_dataset_attributes(index, filter_by_keys, encoding)
return dimensions, variables, attributes, encoding
@attr.attrs()
class Dataset(object):
"""
Map a GRIB file to the NetCDF Common Data Model with CF Conventions.
"""
dimensions = attr.attrib(type=T.Dict[str, int])
variables = attr.attrib(type=T.Dict[str, Variable])
attributes = attr.attrib(type=T.Dict[str, T.Any])
encoding = attr.attrib(type=T.Dict[str, T.Any])
def open_fileindex(
path, grib_errors='warn', indexpath='{path}.{short_hash}.idx', index_keys=ALL_KEYS
):
stream = messages.FileStream(path, message_class=cfmessage.CfMessage, errors=grib_errors)
return stream.index(index_keys, indexpath=indexpath)
def open_file(
path,
grib_errors='warn',
indexpath='{path}.{short_hash}.idx',
filter_by_keys={},
read_keys=[],
**kwargs
):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
index_keys = sorted(ALL_KEYS + read_keys)
index = open_fileindex(path, grib_errors, indexpath, index_keys).subindex(filter_by_keys)
return Dataset(*build_dataset_components(index, read_keys=read_keys, **kwargs))