data.readers.grib.codes
Classes
Represent a GRIB message in a GRIB file. |
Module Contents
- class data.readers.grib.codes.GribField(path, offset, length, handle_manager=None, use_metadata_cache=False)
Bases:
earthkit.data.core.fieldlist.FieldRepresent a GRIB message in a GRIB file.
- Parameters:
path (
str) – Path to the GRIB fileoffset (
number) – File offset of the message (in bytes)length (
number) – Size of the message (in bytes)
- an_datetime()
- property array_backend
Return the array namespace of the field.
- Type:
ArrayBackend
- property array_namespace
Return the array namespace of the field.
- Type:
ArrayBackend
- base_datetime()
- batched(*args)
Return iterator for batches of data
- bounding_box()
Return the bounding box of the field.
- Return type:
- clone(**kwargs)
Create a new
ClonedFieldthe with updated values and/or metadata.- Parameters:
values (
array-likeorNone) – The values to be stored in the newClonedField. When it isNonethe resultingClonedFieldwill access the values from the original field.metadata (
dict,MetadataorNone) – If it is a dictionary, it is merged with**kwargsand interpreted in the same way as**kwargs. If it is aMetadataobject, it is used as the new metadata. In this case**kwargscannot be used.**kwargs (
dict, optional) – Keys and values to update the metadata with. Metadata values can also becallableswith the following positional arguments: original_field, key, original_metadata. The newClonedFieldwill contain a reference to the original metadata object and keys not present inkwargswill be accessed from the original field.
- Returns:
The new field with updated values and/or metadata keeping a reference to the original field.
- Return type:
ClonedField- Raises:
ValueError – If
metadatais aMetadataobject and**kwargsis not empty.
- copy(*, values=None, flatten=False, dtype=None, array_backend=None, array_namespace=None, device=None, metadata=None)
Create a new
ArrayFieldby copying the values and metadata.- Parameters:
values (
array-likeorNone) – The values to be stored in the newField. When it isNonethe values extracted from the original field by usingto_arraywithflatten,dtypeandarray_backendand copied to the new field.flatten (
bool) – Control the shape of the values when they are extracted from the original field. WhenTrue, flatten the array, otherwise the field’s shape is kept. Only used whenvaluesis not provided.dtype (
str,array.dtypeorNone) – Control the typecode or data-type of the values when they are extracted from the original field. IfNone, the default type used by the underlying data accessor is used. For GRIB it isfloat64. Only used whenvaluesis not provided.array_backend (
str,array_namespaceorNone) – Control the array namespace of the values when they are extracted from the original field. IfNone, the underlying array format of the field is used. Only used whenvaluesis not provided. Deprecated since version 0.19.0. Usearray_namespaceinstead. In versions before 0.19.0 anArrayBackendwas also accepted here, which is no longer the case.array_namespace (
str,array_namespaceorNone) – Control the array namespace of the values when they are extracted from the original field. When it isNonethe underlying array format of the field is used. New in version 0.19.0.device (
strorNone) – The device where the array will be allocated. When it isNonethe default device is used.metadata (
MetadataorNone) – The metadata to be stored in the newField. When it isNonea copy of the metadata of the original field is used.
- Return type:
ArrayField
- data(keys=('lat', 'lon', 'value'), flatten=False, dtype=None, index=None)
Return the values and/or the geographical coordinates for each grid point.
- Parameters:
keys (
str,listortuple) – Specifies the type of data to be returned. Any combination of “lat”, “lon” and “value” is allowed here.flatten (
bool) – When it is True a flat array per key is returned. Otherwise an array with the field’sshapeis returned for each key.dtype (
str,array.dtypeorNone) – Typecode or data-type of the arrays. When it isNonethe default type used by the underlying data accessor is used. For GRIB it isfloat64.index (
array indexing object, optional) – The index of the values and or the latitudes/longitudes to be extracted. When it is None all the values and/or coordinates are extracted.
- Returns:
An multi-dimensional array containing one array per key is returned (following the order in
keys). The underlying array format of the field is used. Whenkeysis a single value only the array belonging to the key is returned.- Return type:
array-like
Examples
/examples/grib_lat_lon_value.ipynb
>>> import earthkit.data >>> ds = earthkit.data.from_source("file", "docs/examples/test6.grib") >>> d = ds[0].data() >>> d.shape (3, 7, 12) >>> d[0, 0, 0] # first latitude 90.0 >>> d[1, 0, 0] # first longitude 0.0 >>> d[2, 0, 0] # first value 272.56417847 >>> d = ds[0].data(keys="lon") >>> d.shape (7, 12) >>> d[0, 0] # first longitude 0.0
- datetime()
Return the date and time of the field.
- Returns:
Dict with items “base_time” and “valid_time”.
- Return type:
dictofdatatime.datetime
Examples
>>> import earthkit.data >>> ds = earthkit.data.from_source("file", "tests/data/t_time_series.grib") >>> ds[4].datetime() {'base_time': datetime.datetime(2020, 12, 21, 12, 0), 'valid_time': datetime.datetime(2020, 12, 21, 18, 0)}
- default_encoder()
- describe(*args, **kwargs)
Generate a summary of the Field.
- dump(namespace=all, **kwargs)
Generate dump with all the metadata keys belonging to
namespace.In a Jupyter notebook it is represented as a tabbed interface.
- Parameters:
namespace (
str,list,tuple,Noneorall) –The namespace to dump. The following namespace values have a special meaning:
all: all the available namespaces will be used.- None or empty str: all the available keys will be used
(without a namespace qualifier)
**kwargs (
dict, optional) – Other keyword arguments used for testing only
- Returns:
Dict-like object with one item per namespace. In a Jupyter notebook represented as a tabbed interface to browse the dump contents.
- Return type:
NamespaceDump
Examples
- grid_points()
- grid_points_unrotated()
- group_by(*args)
Return iterator for batches of data grouped by metadata keys
- h_datetime()
- property handle
Get an object providing access to the low level GRIB message structure.
- Type:
CodesHandle
- indexing_datetime()
- abstract isel(*args, **kwargs)
- ls(*args, **kwargs)
Generate a list like summary using a set of metadata keys.
- Parameters:
*args (
tuple) – Positional arguments passed toFieldList.ls.**kwargs (
dict, optional) – Other keyword arguments passed toFieldList.ls.
- Returns:
DataFrame with one row.
- Return type:
Pandas DataFrame
- property mars_area
- property mars_grid
- message()
Return a buffer containing the encoded message.
- Return type:
bytes
- metadata(*keys, astype=None, remapping=None, patches=None, **kwargs)
Return metadata values from the field.
When called without any arguments returns a
Metadataobject.- Parameters:
*keys (
tuple) – Positional arguments specifying metadata keys. Can be empty, in this case all the keys from the specifiednamespacewill be used. (See examples below).astype (
type name,listortuple) – Return types forkeys. A single value is accepted and applied to all thekeys. Otherwise, must have same the number of elements askeys. Only used whenkeysis not empty.remapping (
dict, optional) –Creates new metadata keys from existing ones that we can refer to in
*argsand**kwargs. E.g. to define a new key “param_level” as the concatenated value of the “param” and “level” keys use:remapping={"param_level": "{param}{level}"}
**kwargs (
dict, optional) –Other keyword arguments:
- namespace:
str,list,tuple,Noneorall The namespace to choose the
keysfrom. Whenkeysis empty andnamespaceisallall the available namespaces will be used. Whenkeysis non emptynamespacecannot specify multiple values and it cannot beall. Whennamespaceis None or empty str all the available keys will be used (without a namespace qualifier).
- namespace:
- default: value, optional
Specifies the same default value for all the
keysspecified. Whendefaultis not present and a key is not found or its value is a missing valuemetadatawill raise KeyError.
- Returns:
when called without any arguments returns a
Metadataobject- when
keysis not empty: returns single value when
keysis a strotherwise returns the same type as that of
keys(listortuple)
- when
- when
keysis empty: when
namespaceis None or an empty str returns adictwith all the available keys and valueswhen
namespaceisstrreturns adictwith the keys and values in that namespaceotherwise returns a
dictwith one item per namespace (dict of dict)
- when
- Return type:
single value,list,tuple,dictorMetadata- Raises:
KeyError – If no
defaultis set and a key is not found in the message or it has a missing value.
Examples
>>> import earthkit.data >>> ds = earthkit.data.from_source("file", "docs/examples/test.grib")
Calling without arguments:
>>> r = ds[0].metadata() >>> r <earthkit.data.readers.grib.metadata.GribMetadata object at 0x164ace170> >>> r["name"] '2 metre temperature'
Getting keys with their native type:
>>> ds[0].metadata("param") '2t' >>> ds[0].metadata("param", "units") ('2t', 'K') >>> ds[0].metadata(("param", "units")) ('2t', 'K') >>> ds[0].metadata(["param", "units"]) ['2t', 'K'] >>> ds[0].metadata(["param"]) ['2t'] >>> ds[0].metadata("badkey") KeyError: 'badkey' >>> ds[0].metadata("badkey", default=None)
Prescribing key types:
>>> ds[0].metadata("centre", astype=int) 98 >>> ds[0].metadata(["paramId", "centre"], astype=int) [167, 98] >>> ds[0].metadata(["centre", "centre"], astype=[int, str]) [98, 'ecmf']
Using namespaces:
>>> ds[0].metadata(namespace="parameter") {'centre': 'ecmf', 'paramId': 167, 'units': 'K', 'name': '2 metre temperature', 'shortName': '2t'} >>> ds[0].metadata(namespace=["parameter", "vertical"]) {'parameter': {'centre': 'ecmf', 'paramId': 167, 'units': 'K', 'name': '2 metre temperature', 'shortName': '2t'}, 'vertical': {'typeOfLevel': 'surface', 'level': 0}} >>> r = ds[0].metadata(namespace=all) >>> r.keys() dict_keys(['default', 'ls', 'geography', 'mars', 'parameter', 'statistics', 'time', 'vertical']) >>> r = ds[0].metadata(namespace=None) >>> len(r) 186 >>> r["name"] '2 metre temperature'
- property offset
Gets the offset (in bytes) of the GRIB field within the GRIB file.
- Type:
number
- abstract order_by(*args, **kwargs)
Reorder the elements of the object.
- projection()
Return information about the projection.
- Return type:
Projection
Examples
>>> import earthkit.data >>> ds = earthkit.data.from_source("file", "docs/examples/test.grib") >>> ds.projection() <Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich >>> ds.projection().to_proj_string() '+proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to_meter=111319.4907932736 +no_defs +type=crs'
- property resolution
- property rotation
- save(filename, append=False, **kwargs)
Write the field into a file.
- Parameters:
filename (
str, optional) – The target file path, if not defined attempts will be made to detect the filenameappend (
bool, optional) – When it is true append data to the target file. Otherwise the target file be overwritten if already exists. Default is False**kwargs (
dict, optional) – Other keyword arguments passed towrite.
- abstract sel(*args, **kwargs)
Filter the object based on metadata.
- property shape
Get the shape of the field.
For structured grids the shape is a tuple in the form of (Nj, Ni) where:
ni: the number of gridpoints in i direction (longitude for a regular latitude-longitude grid)
nj: the number of gridpoints in j direction (latitude for a regular latitude-longitude grid)
For other grid types the number of gridpoints is returned as
(num,)- Type:
tuple
- to_array(flatten=False, dtype=None, array_backend=None, array_namespace=None, device=None, index=None)
Return the values stored in the field.
- Parameters:
flatten (
bool) – When it is True a flat array is returned. Otherwise an array with the field’sshapeis returned.dtype (
str,array.dtypeorNone) – Typecode or data-type of the array. When it isNonethe default type used by the underlying data accessor is used. For GRIB it isfloat64.array_backend (
str,array_namespaceorNone) – The array namespace to be used. When it isNonethe underlying array format of the field is used. Deprecated since version 0.19.0. Usearray_namespaceinstead. In versions before 0.19.0 anArrayBackendwas also accepted here, which is no longer the case.array_namespace (
str,array_namespaceorNone) – The array namespace to be used. When it isNonethe underlying array format of the field is used. New in version 0.19.0.device (
strorNone) – The device where the array will be allocated. When it isNonethe default device is used.index (
array indexing object, optional) – The index of the values and to be extracted. When it is None all the values are extracted
- Returns:
Field values.
- Return type:
array-array
- to_latlon(flatten=False, dtype=None, index=None)
Return the latitudes/longitudes of all the gridpoints in the field.
- Parameters:
flatten (
bool) – When it is True 1D arrays are returned. Otherwise arrays with the field’sshapeare returned.dtype (
str,array.dtypeorNone) – Typecode or data-type of the arrays. When it isNonethe default type used by the underlying data accessor is used. For GRIB it isfloat64.index (
array indexing object, optional) – The index of the latitudes/longitudes to be extracted. When it is None all the values are extracted.
- Returns:
Dictionary with items “lat” and “lon”, containing the arrays of the latitudes and longitudes, respectively. The underlying array format of the field is used.
- Return type:
dict
See also
- to_numpy(flatten=False, dtype=None, index=None)
Return the values stored in the field as an ndarray.
- Parameters:
flatten (
bool) – When it is True a flat ndarray is returned. Otherwise an ndarray with the field’sshapeis returned.dtype (
str,numpy.dtypeorNone) – Typecode or data-type of the array. When it isNonethe default type used by the underlying data accessor is used. For GRIB it isfloat64.index (
ndarray indexing object, optional) – The index of the values and to be extracted. When it is None all the values are extracted
- Returns:
Field values
- Return type:
ndarray
- abstract to_pandas(**kwargs)
Convert into a pandas dataframe
- to_points(flatten=False, dtype=None, index=None)
Return the geographical coordinates in the data’s original Coordinate Reference System (CRS).
- Parameters:
flatten (
bool) – When it is True 1D arrays are returned. Otherwise arrays with the field’sshapeare returned.dtype (
str,array.dtypeorNone) – Typecode or data-type of the arrays. When it isNonethe default type used by the underlying data accessor is used. For GRIB it isfloat64.index (
array indexing object, optional) – The index of the coordinates to be extracted. When it is None all the values are extracted.
- Returns:
Dictionary with items “x” and “y”, containing the arrays of the x and y coordinates, respectively. The underlying array format of the field is used.
- Return type:
dict- Raises:
ValueError – When the coordinates in the data’s original CRS are not available.
See also
- to_target(target, *args, **kwargs)
Write the field into a target object.
- Parameters:
target (
object) – The target object to write the field into.*args (
tuple) – Positional arguments used to specify the target object.**kwargs (
dict, optional) – Other keyword arguments used to write the field into the target object.
- to_xarray(*args, **kwargs)
Convert the Field into an Xarray Dataset.
- Parameters:
*args (
tuple) – Positional arguments passed toFieldList.to_xarray.**kwargs (
dict, optional) – Other keyword arguments passed toFieldList.to_xarray.
- Return type:
Xarray Dataset
- unique_values(*coords, remapping=None, patches=None, progress_bar=False)
Given a list of metadata attributes, such as date, param, levels, returns the list of unique values for each attributes
- valid_datetime()
- property values
Get the values stored in the field as a 1D array.
- Type:
array-like
- write(f, **kwargs)