You can run this notebook in Binder, in Colab, in Deepnote or in Kaggle.

Save data to GRIB

Here is an example of generating custom GRIB using climetlab.

To generate a GRIB, CliMetLab providesthe function cml.new_grib_output(), requiring the following arguments:

  • A numpy array containing the data to save.

  • An object containing a template for the GRIB metadata, such as a CliMetLab source

  • (Optional) A dictionary of metadata to override the template metadata.

Using this function is similar to open(path) in python, as shown below:

A template for the GRIB metadata

import climetlab as cml

s = cml.load_source(
    variable=["2t", "msl"],
    area=[50, -50, 20, 50],

template = s[0]  # temperature template

An numpy array with the data:

import numpy as np
import math

def generate_numpy_field(shape, ref=273.15, offset1=0, offset2=0):
    f = np.zeros(shape=shape, dtype=np.float64)
    for i in range(f.shape[0]):
        for j in range(f.shape[1]):
            f[i, j] = (
                + (math.sin((i + offset1) / 45.0) + math.sin((j + offset2) / 90.0)) * 15
    return f

arr = generate_numpy_field(template.shape)

Let us plot the generated field for inspection. Notice how cml.plot_map() also uses the template to find the metadata required to plot the field as a temperature field.

cml.plot_map(arr, metadata=template)

Write to GRIB

Method 1

Compare to the usual python code:

f = open(path)
output = cml.new_grib_output("test1.grib", template=template)
cml.plot_map(cml.load_source("file", "test1.grib"))

Write to GRIB

Method 2

The template can also be added in the .write() method instead of the cml.new_grib_output() function:

output = cml.new_grib_output("test2.grib")
output.write(arr, template=template)
cml.plot_map(cml.load_source("file", "test2.grib"))

Method 3

Compare to the usual python code:

with open(path) as f:
with cml.new_grib_output("test3.grib", template=template) as output:
cml.plot_map(cml.load_source("file", "test3.grib"))

Once a GRIB output has been open, several fields can be written to it, as follows:

with cml.new_grib_output("test4.grib", template=template) as output:
    for i in range(24):
        f = generate_numpy_field(template.shape, offset1=i, offset2=i)
        output.write(f, metadata={"time": i})
test4 = cml.load_source("file", "test4.grib")

assert len(test4) == 24