Earth2Studio is now OSS!

Single Variable Perturbation Method#

Intermediate ensemble inference using a custom perturbation method.

This example will demonstrate how to run a an ensemble inference workflow with a custom perturbation method that only applies noise to a specific variable.

In this example you will learn:

  • How to extend an existing pertubration method

  • How to instantiate a built in prognostic model

  • Creating a data source and IO object

  • Running a simple built in workflow

  • Extend a built-in method using custom code.

  • Post-processing results

Set Up#

All workflows inside Earth2Studio require constructed components to be handed to them. In this example, we will use the built in ensemble workflow earth2studio.run.ensemble().

def ensemble(
    time: list[str] | list[datetime] | list[np.datetime64],
    nsteps: int,
    nensemble: int,
    prognostic: PrognosticModel,
    data: DataSource,
    io: IOBackend,
    perturbation_method: PerturbationMethod,
    batch_size: Optional[int] = None,
    output_coords: CoordSystem = OrderedDict({}),
    device: Optional[torch.device] = None,
) -> IOBackend:
    """Ensemble workflow

    Parameters
    ----------
    time : list[str] | list[datetime] | list[np.datetime64]
        List of string, datetimes or np.datetime64
    nsteps : int
        Number of forecast steps
    nensemble : int
        Number of ensemble members to run inference for.
    prognostic : PrognosticModel
        Prognostic models
    data : DataSource
        Data source
    io : IOBackend
        IO object
    perturbation_method : PerturbationMethod
        Method to perturb the initial condition to create an ensemble.
    batch_size: Optional[int], optional
        Number of ensemble members to run in a single batch,
        by default None.
    device : Optional[torch.device], optional
        Device to run inference on, by default None

    Returns
    -------
    IOBackend
        Output IO object
    """

We need the following:

from typing import List, Union

from dotenv import load_dotenv

load_dotenv()  # TODO: make common example prep function

import numpy as np
import torch

from earth2studio.data import GFS
from earth2studio.io import ZarrBackend
from earth2studio.models.px import DLWP
from earth2studio.perturbation import PerturbationMethod, SphericalGaussian
from earth2studio.run import ensemble
from earth2studio.utils.type import CoordSystem

# Load the default model package which downloads the check point from NGC
package = DLWP.load_default_package()
model = DLWP.load_model(package)

# Create the data source
data = GFS()

The perturbation method in Running Ensemble Inference is naive because it applies the same noise amplitude to every variable. We can create a custom wrapper that only applies the perturbation method to a particular variable instead.

class ApplyToVariable:
    """Apply a perturbation to only a particular variable."""

    def __init__(self, pm: PerturbationMethod, variable: Union[str, List[str]]):
        self.pm = pm
        if isinstance(variable, str):
            variable = [variable]
        self.variable = variable

    @torch.inference_mode()
    def __call__(
        self,
        x: torch.Tensor,
        coords: CoordSystem,
    ) -> tuple[torch.Tensor, CoordSystem]:
        # Construct perturbation
        dx, coords = self.pm(x, coords)
        # Find variable in data
        ind = np.in1d(coords["variable"], self.variable)
        dx[..., ~ind, :, :] = 0.0
        return dx, coords


# Generate a new noise amplitude that specifically targets 't2m' with a 1 K noise amplitude
avsg = ApplyToVariable(SphericalGaussian(noise_amplitude=1.0), "t2m")

# Create the IO handler, store in memory
chunks = {"ensemble": 1, "time": 1}
io = ZarrBackend(file_name="outputs/04_ensemble_avsg.zarr", chunks=chunks)

Execute the Workflow#

With all components initialized, running the workflow is a single line of Python code. Workflow will return the provided IO object back to the user, which can be used to then post process. Some have additional APIs that can be handy for post-processing or saving to file. Check the API docs for more information.

For the forecast we will predict for 10 steps (for FCN, this is 60 hours) with 8 ensemble members which will be ran in 2 batches with batch size 4.

nsteps = 10
nensemble = 8
batch_size = 4
io = ensemble(
    ["2024-01-01"],
    nsteps,
    nensemble,
    model,
    data,
    io,
    avsg,
    batch_size=batch_size,
    output_coords={"variable": np.array(["t2m", "tcwv"])},
)
2024-04-19 00:28:43.807 | INFO     | earth2studio.run:ensemble:157 - Running ensemble inference!
2024-04-19 00:28:43.807 | INFO     | earth2studio.run:ensemble:165 - Inference device: cuda
2024-04-19 00:28:43.814 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:151 - Fetching GFS index file: 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:   0%|          | 0/7 [00:00<?, ?it/s]

2024-04-19 00:28:44.298 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: t850 at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:   0%|          | 0/7 [00:00<?, ?it/s]
Fetching GFS for 2023-12-31 18:00:00:  14%|█▍        | 1/7 [00:04<00:26,  4.42s/it]

2024-04-19 00:28:48.717 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z1000 at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:  14%|█▍        | 1/7 [00:04<00:26,  4.42s/it]
Fetching GFS for 2023-12-31 18:00:00:  29%|██▊       | 2/7 [00:05<00:12,  2.49s/it]

2024-04-19 00:28:49.858 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z700 at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:  29%|██▊       | 2/7 [00:05<00:12,  2.49s/it]
Fetching GFS for 2023-12-31 18:00:00:  43%|████▎     | 3/7 [00:06<00:06,  1.69s/it]

2024-04-19 00:28:50.591 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z500 at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:  43%|████▎     | 3/7 [00:06<00:06,  1.69s/it]
Fetching GFS for 2023-12-31 18:00:00:  57%|█████▋    | 4/7 [00:06<00:03,  1.29s/it]

2024-04-19 00:28:51.264 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z300 at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:  57%|█████▋    | 4/7 [00:06<00:03,  1.29s/it]
Fetching GFS for 2023-12-31 18:00:00:  71%|███████▏  | 5/7 [00:07<00:02,  1.11s/it]

2024-04-19 00:28:52.054 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: tcwv at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:  71%|███████▏  | 5/7 [00:07<00:02,  1.11s/it]
Fetching GFS for 2023-12-31 18:00:00:  86%|████████▌ | 6/7 [00:08<00:00,  1.06it/s]

2024-04-19 00:28:52.686 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: t2m at 2023-12-31 18:00:00

Fetching GFS for 2023-12-31 18:00:00:  86%|████████▌ | 6/7 [00:08<00:00,  1.06it/s]
Fetching GFS for 2023-12-31 18:00:00: 100%|██████████| 7/7 [00:08<00:00,  1.26it/s]
Fetching GFS for 2023-12-31 18:00:00: 100%|██████████| 7/7 [00:08<00:00,  1.27s/it]
2024-04-19 00:28:53.180 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:151 - Fetching GFS index file: 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:   0%|          | 0/7 [00:00<?, ?it/s]

2024-04-19 00:28:53.288 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: t850 at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:   0%|          | 0/7 [00:00<?, ?it/s]

2024-04-19 00:28:53.307 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z1000 at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:   0%|          | 0/7 [00:00<?, ?it/s]

2024-04-19 00:28:53.326 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z700 at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:   0%|          | 0/7 [00:00<?, ?it/s]
Fetching GFS for 2024-01-01 00:00:00:  43%|████▎     | 3/7 [00:00<00:01,  3.97it/s]

2024-04-19 00:28:54.043 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z500 at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:  43%|████▎     | 3/7 [00:00<00:01,  3.97it/s]

2024-04-19 00:28:54.062 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: z300 at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:  43%|████▎     | 3/7 [00:00<00:01,  3.97it/s]
Fetching GFS for 2024-01-01 00:00:00:  71%|███████▏  | 5/7 [00:01<00:00,  2.90it/s]

2024-04-19 00:28:54.927 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: tcwv at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:  71%|███████▏  | 5/7 [00:01<00:00,  2.90it/s]

2024-04-19 00:28:54.947 | DEBUG    | earth2studio.data.gfs:fetch_gfs_dataarray:197 - Fetching GFS grib file for variable: t2m at 2024-01-01 00:00:00

Fetching GFS for 2024-01-01 00:00:00:  71%|███████▏  | 5/7 [00:01<00:00,  2.90it/s]
Fetching GFS for 2024-01-01 00:00:00: 100%|██████████| 7/7 [00:01<00:00,  4.17it/s]
2024-04-19 00:28:54.996 | SUCCESS  | earth2studio.run:ensemble:177 - Fetched data from GFS
2024-04-19 00:28:55.001 | INFO     | earth2studio.run:ensemble:196 - Starting 8 Member Ensemble Inference with             2 number of batches.

Total Ensemble Batches:   0%|          | 0/2 [00:00<?, ?it/s]

Running batch 0 inference:   0%|          | 0/11 [00:00<?, ?it/s]

Running batch 0 inference:   9%|▉         | 1/11 [00:00<00:02,  3.39it/s]

Running batch 0 inference:  18%|█▊        | 2/11 [00:00<00:03,  2.60it/s]

Running batch 0 inference:  27%|██▋       | 3/11 [00:01<00:03,  2.51it/s]

Running batch 0 inference:  36%|███▋      | 4/11 [00:01<00:02,  2.34it/s]

Running batch 0 inference:  45%|████▌     | 5/11 [00:02<00:02,  2.25it/s]

Running batch 0 inference:  55%|█████▍    | 6/11 [00:02<00:02,  2.12it/s]

Running batch 0 inference:  64%|██████▎   | 7/11 [00:03<00:01,  2.02it/s]

Running batch 0 inference:  73%|███████▎  | 8/11 [00:03<00:01,  1.90it/s]

Running batch 0 inference:  82%|████████▏ | 9/11 [00:04<00:01,  1.84it/s]

Running batch 0 inference:  91%|█████████ | 10/11 [00:04<00:00,  1.76it/s]

Running batch 0 inference: 100%|██████████| 11/11 [00:05<00:00,  1.72it/s]


Total Ensemble Batches:  50%|█████     | 1/2 [00:08<00:08,  8.46s/it]

Running batch 4 inference:   0%|          | 0/11 [00:00<?, ?it/s]

Running batch 4 inference:   9%|▉         | 1/11 [00:00<00:02,  3.36it/s]

Running batch 4 inference:  18%|█▊        | 2/11 [00:00<00:03,  2.71it/s]

Running batch 4 inference:  27%|██▋       | 3/11 [00:01<00:03,  2.54it/s]

Running batch 4 inference:  36%|███▋      | 4/11 [00:01<00:02,  2.36it/s]

Running batch 4 inference:  45%|████▌     | 5/11 [00:02<00:02,  2.28it/s]

Running batch 4 inference:  55%|█████▍    | 6/11 [00:02<00:02,  2.15it/s]

Running batch 4 inference:  64%|██████▎   | 7/11 [00:03<00:01,  2.06it/s]

Running batch 4 inference:  73%|███████▎  | 8/11 [00:03<00:01,  1.95it/s]

Running batch 4 inference:  82%|████████▏ | 9/11 [00:04<00:01,  1.88it/s]

Running batch 4 inference:  91%|█████████ | 10/11 [00:04<00:00,  1.81it/s]

Running batch 4 inference: 100%|██████████| 11/11 [00:05<00:00,  1.75it/s]


Total Ensemble Batches: 100%|██████████| 2/2 [00:16<00:00,  8.32s/it]
Total Ensemble Batches: 100%|██████████| 2/2 [00:16<00:00,  8.34s/it]
2024-04-19 00:29:11.684 | SUCCESS  | earth2studio.run:ensemble:242 - Ensemble Inference complete

Post Processing#

The last step is to post process our results.

Notice that the Zarr IO function has additional APIs to interact with the stored data.

import cartopy.crs as ccrs
import matplotlib.pyplot as plt

forecast = "2024-01-01"


def plot_(axi, data, title, cmap):
    """Convenience function for plotting pcolormesh."""
    # Plot the field using pcolormesh
    im = axi.pcolormesh(
        io["lon"][:],
        io["lat"][:],
        data,
        transform=ccrs.PlateCarree(),
        cmap=cmap,
    )
    plt.colorbar(im, ax=axi, shrink=0.6, pad=0.04)
    # Set title
    axi.set_title(title)
    # Add coastlines and gridlines
    axi.coastlines()
    axi.gridlines()


for variable, cmap in zip(["t2m", "tcwv"], ["coolwarm", "Blues"]):
    step = 4  # lead time = 24 hrs

    plt.close("all")
    # Create a Robinson projection
    projection = ccrs.Robinson()

    # Create a figure and axes with the specified projection
    fig, (ax1, ax2, ax3) = plt.subplots(
        nrows=1, ncols=3, subplot_kw={"projection": projection}, figsize=(16, 3)
    )

    plot_(
        ax1,
        io[variable][0, 0, step],
        f"{forecast} - Lead time: {6*step}hrs - Member: {0}",
        cmap,
    )
    plot_(
        ax2,
        io[variable][1, 0, step],
        f"{forecast} - Lead time: {6*step}hrs - Member: {1}",
        cmap,
    )
    plot_(
        ax3,
        np.std(io[variable][:, 0, step], axis=0),
        f"{forecast} - Lead time: {6*step}hrs - Std",
        cmap,
    )

    plt.savefig(f"outputs/04_{forecast}_{variable}_{step}_ensemble.jpg")
2024-01-01 - Lead time: 24hrs - Member: 0, 2024-01-01 - Lead time: 24hrs - Member: 1, 2024-01-01 - Lead time: 24hrs - Std

Total running time of the script: (2 minutes 25.064 seconds)

Gallery generated by Sphinx-Gallery