Skip to content

Extending Diagnostic Models

Implementing a custom diagnostic model

This example will demonstrate how to extend Earth2Studio by implementing a custom diagnostic model and running it in a general workflow.

In this example you will learn:

  • API requirements of diagnostic models
  • Implementing a custom diagnostic model
  • Running this custom model in a workflow with built in prognostic

Custom Diagnostic

As discussed in the Diagnostic Models section of the user guide, Earth2Studio defines a diagnostic model through a simple interface [earth2studio.models.dx.base.DiagnosticModel][]. This can be used to help guide the required APIs needed to successfully create our own model.

In this example, lets consider a simple diagnostic that converts the surface temperature in Kelvin to Celsius to make it more readable for the average person.

Our diagnostic model has a base class of torch.nn.Module which allows us to get the required to(device) method for free.

import os

os.makedirs("outputs", exist_ok=True)
from dotenv import load_dotenv

load_dotenv()  # TODO: make common example prep function


import numpy as np
import torch
import xarray as xr

from earth2studio.utils.coords import coord_array, coord_array_like, handshake_dataarray
from earth2studio.utils.cupy import from_torch


class CustomDiagnostic(torch.nn.Module):
    """Custom dianostic model"""

    def __init__(self):
        super().__init__()

    def input_coords(self) -> xr.DataArray:
        """Input coordinate system of the prognostic model

        Returns
        -------
        xr.DataArray
            Allocation-free coordinate signature
        """
        return coord_array(
            ("batch", "variable", "lat", "lon"),
            {"variable": np.array(["t2m"])},
            dynamic=("batch",),
            grid="latlon-0.25deg",
        )

    def output_coords(self, input_coords: xr.DataArray) -> xr.DataArray:
        """Output coordinate system of the prognostic model

        Parameters
        ----------
        input_coords : xr.DataArray
            Input coordinate system to transform into output_coords

        Returns
        -------
        xr.DataArray
            Allocation-free coordinate signature
        """
        # Check input coordinates are valid
        handshake_dataarray(input_coords, self.input_coords())
        return coord_array_like(input_coords, {"variable": np.array(["t2m_c"])})

    def __call__(
        self,
        x: xr.DataArray,
    ) -> xr.DataArray:
        """Runs diagnostic model

        Parameters
        ----------
        x : xr.DataArray
            Input field carrying its coordinates and grid metadata
        """
        out_coords = self.output_coords(x)
        tensor, _ = x.e2s.to_torch()
        return from_torch(tensor - 273.15, out_coords)

Input/Output Coordinates

Defining the input/output coordinate systems is essential for any model in Earth2Studio since this is how both the package and users can learn what type of data the model expects. This requires the definition of input_coords and output_coords. Have a look at Data and Metadata for details on coordinate system.

For this diagnostic model, we simply define the input coordinates to be the global surface temperature specified in earth2studio/lexicon/base.py. The output is a custom variable t2m_c that represents the temperature in Celsius.

__call__ API

The call function is the main API of diagnostic models that have a tensor and coordinate system as input/output. This function first validates that the coordinate system is correct. Then both the input data tensor and also coordinate system are updated and returned.

Note

You may notice the batch_func decorator, which is used to make batched operations easier. For more details about this refer to the Batch Dimension section of the user guide.

Set Up

With the custom diagnostic model defined, the next step is to set up and run a workflow. We will use the built in workflow earth2studio.run.diagnostic.

Lets instantiate the components needed.

from dotenv import load_dotenv

load_dotenv()  # TODO: make common example prep function

from earth2studio.data import GFS
from earth2studio.io import ZarrBackend
from earth2studio.models.px import DLWP

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

# Diagnostic model
diagnostic = CustomDiagnostic()

# Create the data source
data = GFS()

# Create the IO handler, store in memory
io = ZarrBackend()
Console output8 lines
Downloading dlwp_cubesphere.zip: 0%|          | 0.00/67.2M [00:00<?, ?B/s]
Downloading dlwp_cubesphere.zip: 0%|          | 300k/67.2M [00:00<00:23, 3.05MB/s]
Downloading dlwp_cubesphere.zip: 4%|โ–         | 2.89M/67.2M [00:00<00:03, 17.2MB/s]
Downloading dlwp_cubesphere.zip: 22%|โ–ˆโ–ˆโ–       | 15.1M/67.2M [00:00<00:00, 67.3MB/s]
Downloading dlwp_cubesphere.zip: 42%|โ–ˆโ–ˆโ–ˆโ–ˆโ–     | 28.0M/67.2M [00:00<00:00, 94.2MB/s]
Downloading dlwp_cubesphere.zip: 61%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ    | 40.9M/67.2M [00:00<00:00, 109MB/s] 
Downloading dlwp_cubesphere.zip: 80%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ  | 54.0M/67.2M [00:00<00:00, 119MB/s]
Downloading dlwp_cubesphere.zip: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 67.2M/67.2M [00:00<00:00, 100MB/s]

Execute the Workflow

Running our workflow with a build in prognostic model and a custom diagnostic is the same as running a built in diagnostic.

import earth2studio.run as run

nsteps = 20
io = run.diagnostic(["2024-01-01"], nsteps, model, diagnostic, data, io)

print(io.root.tree())
Console output53 lines
2026-11-19 21:26:51.266 | INFO     | earth2studio.run:diagnostic:267 - Running diagnostic workflow!
2026-11-19 21:26:51.266 | INFO     | earth2studio.run:diagnostic:274 - Inference device: cuda

Fetching GFS data:   0%|          | 0/7 [00:00<?, ?it/s]
Fetching GFS data:  14%|โ–ˆโ–        | 1/7 [00:01<00:06,  1.08s/it]
Fetching GFS data:  29%|โ–ˆโ–ˆโ–Š       | 2/7 [00:01<00:02,  1.85it/s]
Fetching GFS data:  57%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‹    | 4/7 [00:01<00:00,  4.20it/s]
Fetching GFS data: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 7/7 [00:01<00:00,  5.05it/s]

Fetching GFS statistics: 0it [00:00, ?it/s]
Fetching GFS statistics: 0it [00:00, ?it/s]

Fetching GFS data:   0%|          | 0/7 [00:00<?, ?it/s]
Fetching GFS data:  14%|โ–ˆโ–        | 1/7 [00:00<00:01,  4.40it/s]
Fetching GFS data:  71%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–  | 5/7 [00:00<00:00, 14.82it/s]
Fetching GFS data: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 7/7 [00:00<00:00, 17.95it/s]

Fetching GFS statistics: 0it [00:00, ?it/s]
Fetching GFS statistics: 0it [00:00, ?it/s]
2026-11-19 21:26:53.319 | SUCCESS  | earth2studio.run:diagnostic:317 - Fetched data from GFS
2026-11-19 21:26:53.320 | INFO     | earth2studio.run:diagnostic:322 - Inference starting!


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

Running inference:  10%|โ–‰         | 2/21 [00:00<00:06,  3.11it/s]

Running inference:  19%|โ–ˆโ–‰        | 4/21 [00:00<00:02,  5.93it/s]

Running inference:  29%|โ–ˆโ–ˆโ–Š       | 6/21 [00:00<00:01,  8.61it/s]

Running inference:  38%|โ–ˆโ–ˆโ–ˆโ–Š      | 8/21 [00:00<00:01, 10.96it/s]

Running inference:  48%|โ–ˆโ–ˆโ–ˆโ–ˆโ–Š     | 10/21 [00:01<00:00, 12.89it/s]

Running inference:  57%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‹    | 12/21 [00:01<00:00, 14.64it/s]

Running inference:  71%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–  | 15/21 [00:01<00:00, 15.48it/s]

Running inference:  81%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ  | 17/21 [00:01<00:00, 16.33it/s]

Running inference:  90%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ | 19/21 [00:01<00:00, 16.79it/s]

Running inference: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 21/21 [00:01<00:00, 17.18it/s]
Running inference: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 21/21 [00:01<00:00, 12.41it/s]
2026-11-19 21:26:55.013 | SUCCESS  | earth2studio.run:diagnostic:352 - 
Inference complete
/
โ”œโ”€โ”€ lat (721,) float64
โ”œโ”€โ”€ lead_time (41,) timedelta64[ns]
โ”œโ”€โ”€ lon (1440,) float64
โ”œโ”€โ”€ t2m_c (1, 41, 721, 1440) float32
โ””โ”€โ”€ time (1,) datetime64[ns]

Post Processing

Let's plot the Celsius temperature field from our custom diagnostic model.

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

forecast = "2024-01-01"
variable = "t2m_c"

plt.close("all")

# Create a figure and axes with the specified projection
fig, ax = plt.subplots(
    1,
    5,
    figsize=(12, 4),
    subplot_kw={"projection": ccrs.Orthographic()},
    constrained_layout=True,
)

times = (
    io["lead_time"][:].astype("timedelta64[ns]").astype("timedelta64[h]").astype(int)
)
step = 4  # 24hrs
for i, t in enumerate(range(0, 20, step)):

    ctr = ax[i].contourf(
        io["lon"][:],
        io["lat"][:],
        io[variable][0, t],
        vmin=-10,
        vmax=30,
        transform=ccrs.PlateCarree(),
        levels=20,
        cmap="coolwarm",
    )
    ax[i].set_title(f"{times[t]}hrs")
    ax[i].coastlines()
    ax[i].gridlines()

plt.suptitle(f"{variable} - {forecast}")

cbar = plt.cm.ScalarMappable(cmap="coolwarm")
cbar.set_array(io[variable][0, 0])
cbar.set_clim(-10.0, 30)
cbar = fig.colorbar(cbar, ax=ax[-1], orientation="vertical", label="C", shrink=0.8)


plt.savefig("outputs/02_custom_diagnostic_dlwp_prediction.jpg")

Output from Extending Diagnostic Models


Execution profile

Runtime telemetry

Total runtime56.5 s

Execution environment

CPUAMD EPYC 9554 64-Core Processor
GPUNVIDIA H100 NVL ยท 93.6 GiB
System RAM58.4 GiB
PlatformLinux 6.8.0-147-generic
Python3.13.13
GPU driver / CUDADriver 595.99.02 ยท CUDA support 13.2