Skip to content

Running Diagnostic Inference

Basic prognostic + diagnostic inference workflow.

This example will demonstrate how to run a deterministic inference workflow that couples a prognostic model with a diagnostic model. This diagnostic model will predict a new atmospheric quantity from the predicted fields of the prognostic.

In this example you will learn:

  • How to instantiate a prognostic model
  • How to instantiate a diagnostic model
  • Creating a data source and IO object
  • Running the built in diagnostic workflow
  • Post-processing results

Set Up

For this example, the built in diagnostic workflow earth2studio.run.diagnostic will be used.

# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.

"""Built-in forecast workflows and work-item runners.

A :class:`~earth2studio.run.runner.Runner` executes one
:class:`~earth2studio.run.runner.WorkItem`. The built-ins are
:class:`PrognosticRunner`, which rolls out one prognostic model, and
:class:`DiagnosticRunner`, which applies diagnostics to source data. Coupled
runners live with the coupler, never here. :class:`Pipeline` drives any runner
over many items: distribution across ranks, resume, scoring, and IO.
"""

from collections import OrderedDict
from datetime import datetime
from math import ceil
from typing import cast

import numpy as np
import torch
import xarray as xr
from loguru import logger
from tqdm import tqdm  # type: ignore[import-untyped]

from earth2studio.data import DataSource, ForecastSource, fetch_data
from earth2studio.io.base import IOBackend
from earth2studio.models.dx import DiagnosticModel
from earth2studio.models.px import PrognosticModel
from earth2studio.perturbation import Perturbation
from earth2studio.run._fields import (  # noqa: F401 - re-exported helpers
    _dimension_coords,
    _io_template,
    _lead_times,
    _map_field,
    _require_analysis_time_input,
    _require_unforced,
    _rollout,
    _with_lead_time,
    map_field,
)
from earth2studio.run.pipeline import Pipeline, Scorer
from earth2studio.run.reduce import LeadReduction, LeadWindow
from earth2studio.run.runner import (
    DataRequest,
    DiagnosticRunner,
    PrognosticRunner,
    Runner,
)
from earth2studio.run.work import ProgressStore, WorkItem, work_items
from earth2studio.utils.checkpoint import (
    Checkpoint,
    CheckpointSession,
    NullCheckpoint,
)
from earth2studio.utils.coords import CoordSystem
from earth2studio.utils.time import to_time_array

logger.remove()
logger.add(lambda msg: tqdm.write(msg, end=""), colorize=True)

__all__ = [
    "DataRequest",
    "DiagnosticRunner",
    "LeadReduction",
    "LeadWindow",
    "Pipeline",
    "PrognosticRunner",
    "ProgressStore",
    "Runner",
    "Scorer",
    "WorkItem",
    "work_items",
    "map_field",
    "deterministic",
    "diagnostic",
    "ensemble",
]


def deterministic(
    time: list[str] | list[datetime] | list[np.datetime64],
    nsteps: int,
    prognostic: PrognosticModel,
    data: DataSource,
    io: IOBackend,
    output_coords: CoordSystem = OrderedDict({}),
    device: torch.device | None = None,
    verbose: bool = True,
    checkpoint: Checkpoint | CheckpointSession | NullCheckpoint = NullCheckpoint(),
) -> IOBackend:
    """Built in deterministic workflow.
    This workflow creates a determinstic inference pipeline to produce a forecast
    prediction using a prognostic model.

    Parameters
    ----------
    time : list[str] | list[datetime] | list[np.datetime64]
        List of string, datetimes or np.datetime64
    nsteps : int
        Number of forecast steps
    prognostic : PrognosticModel
        Prognostic model
    data : DataSource
        Data source
    io : IOBackend
        IO object
    output_coords: CoordSystem, optional
        IO output coordinate system override, by default OrderedDict({})
    device : torch.device, optional
        Device to run inference on, by default None
    verbose : bool, optional
        Print inference progress, by default True
    checkpoint : Checkpoint, optional
        Checkpoint manager or checkpoint session used to record and resume workflow
        progress, by default no checkpoint

    Returns
    -------
    IOBackend
        Output IO object
    """
    logger.info("Running simple workflow!")
    _require_unforced(prognostic, "deterministic")
    # Load model onto the device
    device = (
        device
        if device is not None
        else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    )
    logger.info(f"Inference device: {device}")
    prognostic = prognostic.to(device)
    prognostic_ic = cast(xr.DataArray, prognostic.input_coords())
    _require_analysis_time_input(prognostic_ic)
    time = to_time_array(time)

    # Set up IO backend
    template = _io_template(
        prognostic.output_coords(prognostic_ic),
        nsteps,
        leading={"time": np.asarray(time)},
        output_coords=output_coords,
    )
    io.add_array(template)

    with checkpoint as ckpt:
        restart_step = None
        if ckpt.exists and ckpt.write_count > 0:
            if ckpt.catalog.level < 2:
                logger.warning(
                    "deterministic received checkpoint level "
                    f"{ckpt.catalog.level}; component state may not be "
                    "complete enough to resume a rollout. Re-running from "
                    "lead time zero."
                )
            else:
                restart_step = ckpt.write_count - 1
                if restart_step >= nsteps:
                    logger.success("\nInference complete")
                    return io

        # Fetch data from data source and load onto device
        x = fetch_data(
            source=data,
            time=time,
            variable=prognostic_ic.coords["variable"].values,
            lead_time=prognostic_ic.coords["lead_time"].values,
            device=device,
        )

        logger.success(f"Fetched data from {data.__class__.__name__}")

        # Map lat and lon if needed
        x = map_field(x, prognostic_ic)
        # Create prognostic iterator
        model = _rollout(prognostic, x, restart_step is None)

        logger.info("Inference starting!")
        initial_progress = 0 if restart_step is None else restart_step + 1
        with tqdm(
            total=nsteps + 1,
            initial=initial_progress,
            desc="Running inference",
            position=1,
            disable=(not verbose),
        ) as pbar:
            for local_step, x in enumerate(model):
                step = (
                    local_step
                    if restart_step is None
                    else restart_step + local_step + 1
                )

                x = cast(xr.DataArray, x)
                current_lead_time = x.coords["lead_time"].values[-1]
                # Subselect domain/variables as indicated in output_coords
                x = map_field(x, output_coords)
                io.write(x)
                ckpt.write(lead_time=current_lead_time)
                pbar.update(1)
                if step == nsteps:
                    break

        ckpt.flush()

    io.flush()
    logger.success("\nInference complete")
    return io


def diagnostic(
    time: list[str] | list[datetime] | list[np.datetime64],
    nsteps: int,
    prognostic: PrognosticModel,
    diagnostic: DiagnosticModel,
    data: DataSource | ForecastSource,
    io: IOBackend,
    output_coords: CoordSystem = OrderedDict({}),
    device: torch.device | None = None,
    verbose: bool = True,
    checkpoint: Checkpoint | CheckpointSession | NullCheckpoint = NullCheckpoint(),
) -> IOBackend:
    """Built in diagnostic workflow.
    This workflow creates a determinstic inference pipeline that couples a prognostic
    model with a diagnostic model.

    Parameters
    ----------
    time : list[str] | list[datetime] | list[np.datetime64]
        List of string, datetimes or np.datetime64
    nsteps : int
        Number of forecast steps
    prognostic : PrognosticModel
        Prognostic model
    diagnostic: DiagnosticModel
        Diagnostic model, must be on same coordinate axis as prognostic
    data : DataSource | ForecastSource
        Data source
    io : IOBackend
        IO object
    output_coords: CoordSystem, optional
        IO output coordinate system override, by default OrderedDict({})
    device : torch.device, optional
        Device to run inference on, by default None
    verbose : bool, optional
        Print inference progress, by default True
    checkpoint : Checkpoint, optional
        Checkpoint manager or checkpoint session used to record and resume workflow
        progress, by default no checkpoint

    Returns
    -------
    IOBackend
        Output IO object
    """
    logger.info("Running diagnostic workflow!")
    _require_unforced(prognostic, "diagnostic")
    device = (
        device
        if device is not None
        else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    )
    logger.info(f"Inference device: {device}")
    prognostic = prognostic.to(device)
    diagnostic = diagnostic.to(device)

    prognostic_ic = cast(xr.DataArray, prognostic.input_coords())
    _require_analysis_time_input(prognostic_ic)
    diagnostic_ic = cast(xr.DataArray, diagnostic.input_coords())
    time = to_time_array(time)

    prognostic_oc = prognostic.output_coords(prognostic_ic)
    diagnostic_oc = diagnostic.output_coords(map_field(prognostic_oc, diagnostic_ic))
    template = _io_template(
        diagnostic_oc,
        nsteps,
        leading={"time": np.asarray(time)},
        output_coords=output_coords,
        lead_time=_lead_times(prognostic_oc, nsteps),
    )
    io.add_array(template)

    with checkpoint as ckpt:
        restart_step = None
        if ckpt.exists and ckpt.write_count > 0:
            if ckpt.catalog.level < 2:
                logger.warning(
                    "diagnostic received checkpoint level "
                    f"{ckpt.catalog.level}; component state may not be "
                    "complete enough to resume a rollout. Re-running from "
                    "lead time zero."
                )
            else:
                restart_step = ckpt.write_count - 1
                if restart_step >= nsteps:
                    logger.success("\nInference complete")
                    return io

        x = fetch_data(
            source=data,
            time=time,
            variable=prognostic_ic.coords["variable"].values,
            lead_time=prognostic_ic.coords["lead_time"].values,
            device=device,
        )
        logger.success(f"Fetched data from {data.__class__.__name__}")

        x = map_field(x, prognostic_ic)
        model = _rollout(prognostic, x, restart_step is None)

        logger.info("Inference starting!")
        initial_progress = 0 if restart_step is None else restart_step + 1
        with tqdm(
            total=nsteps + 1,
            initial=initial_progress,
            desc="Running inference",
            position=1,
            disable=(not verbose),
        ) as pbar:
            for local_step, x in enumerate(model):
                step = (
                    local_step
                    if restart_step is None
                    else restart_step + local_step + 1
                )

                x = cast(xr.DataArray, x)
                current_lead_time = x.coords["lead_time"].values[-1]
                x = diagnostic(map_field(x, diagnostic_ic))
                x = _with_lead_time(x, current_lead_time)
                x = map_field(x, output_coords)
                io.write(x)
                ckpt.write(lead_time=current_lead_time)
                pbar.update(1)
                if step == nsteps:
                    break

        ckpt.flush()

    io.flush()
    logger.success("\nInference complete")
    return io


def ensemble(
    time: list[str] | list[datetime] | list[np.datetime64],
    nsteps: int,
    nensemble: int,
    prognostic: PrognosticModel,
    data: DataSource,
    io: IOBackend,
    perturbation: Perturbation,
    batch_size: int | None = None,
    output_coords: CoordSystem = OrderedDict({}),
    device: torch.device | None = None,
    verbose: bool = True,
    checkpoint: Checkpoint | CheckpointSession | NullCheckpoint = NullCheckpoint(),
) -> IOBackend:
    """Built in 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 : Perturbation
        Method to perturb the initial condition to create an ensemble.
    batch_size: int, optional
        Number of ensemble members to run in a single batch,
        by default None.
    output_coords: CoordSystem, optional
        IO output coordinate system override, by default OrderedDict({})
    device : torch.device, optional
        Device to run inference on, by default None
    verbose : bool, optional
        Print inference progress, by default True
    checkpoint : Checkpoint, optional
        Checkpoint manager or checkpoint session used to record and resume workflow
        progress, by default no checkpoint

    Returns
    -------
    IOBackend
        Output IO object
    """
    logger.info("Running ensemble inference!")
    _require_unforced(prognostic, "ensemble")

    device = (
        device
        if device is not None
        else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    )
    logger.info(f"Inference device: {device}")
    prognostic = prognostic.to(device)

    prognostic_ic = cast(xr.DataArray, prognostic.input_coords())
    _require_analysis_time_input(prognostic_ic)
    time = to_time_array(time)
    x0 = fetch_data(
        source=data,
        time=time,
        variable=prognostic_ic.coords["variable"].values,
        lead_time=prognostic_ic.coords["lead_time"].values,
        device=device,
    )
    logger.success(f"Fetched data from {data.__class__.__name__}")

    x0 = map_field(x0, prognostic_ic)
    template = _io_template(
        prognostic.output_coords(prognostic_ic),
        nsteps,
        leading={"ensemble": np.arange(nensemble), "time": np.asarray(time)},
        output_coords=output_coords,
    )
    io.add_array(template)
    # Member selections pick which members of each batch are written
    stored_members = template.coords["ensemble"].values
    field_coords = OrderedDict(
        (k, v) for k, v in output_coords.items() if k != "ensemble"
    )

    if batch_size is None:
        batch_size = nensemble
    batch_size = min(nensemble, batch_size)
    with checkpoint as ckpt:
        completed_ensembles = []
        if ckpt.exists and not isinstance(ckpt, NullCheckpoint):
            completed_ensembles = [
                int(value) for value in ckpt.metadata.get("completed_ensembles", [])
            ]

        completed = set(completed_ensembles)
        start_batch_id = next(
            (index for index in range(nensemble) if index not in completed),
            nensemble,
        )
        number_of_batches = ceil((nensemble - start_batch_id) / batch_size)
        restart_first_batch = (
            ckpt.exists
            and ckpt.write_count > 0
            and start_batch_id < nensemble
            and ckpt.lead_time != template.coords["lead_time"].values[-1]
        )

        logger.info(f"Starting {nensemble} Member Ensemble Inference with \
            {number_of_batches} number of batches.")
        for batch_index, batch_id in enumerate(
            tqdm(
                range(start_batch_id, nensemble, batch_size),
                total=number_of_batches,
                desc="Total Ensemble Batches",
                position=2,
                disable=(not verbose),
            )
        ):
            mini_batch_size = min(batch_size, nensemble - batch_id)
            ensemble_coords = np.arange(batch_id, batch_id + mini_batch_size)
            ensemble_members = [int(value) for value in ensemble_coords]
            written_members = np.intersect1d(ensemble_coords, stored_members)
            restart_step = None
            if batch_index == 0 and restart_first_batch:
                if ckpt.catalog.level < 2:
                    logger.warning(
                        "ensemble received checkpoint level "
                        f"{ckpt.catalog.level}; component state may not be "
                        "complete enough to resume a rollout. Re-running from "
                        "lead time zero."
                    )
                    ckpt.write_count = 0
                else:
                    restart_step = ckpt.write_count - 1
                    if restart_step >= nsteps:
                        continue
            elif not isinstance(ckpt, NullCheckpoint):
                ckpt.write_count = 0

            x = x0.expand_dims(ensemble=ensemble_coords).copy(deep=True)
            x = perturbation(x)

            model = _rollout(prognostic, x, restart_step is None)
            initial_progress = 0 if restart_step is None else restart_step + 1
            with tqdm(
                total=nsteps + 1,
                initial=initial_progress,
                desc=f"Running batch {batch_id} inference",
                position=1,
                leave=False,
                disable=(not verbose),
            ) as pbar:
                for local_step, x in enumerate(model):
                    step = (
                        local_step
                        if restart_step is None
                        else restart_step + local_step + 1
                    )

                    x = cast(xr.DataArray, x)
                    current_lead_time = x.coords["lead_time"].values[-1]
                    x = map_field(x, field_coords)
                    if len(written_members) < mini_batch_size:
                        x = x.sel(ensemble=written_members)
                    if len(written_members):
                        io.write(x)
                    if step == nsteps:
                        completed.update(ensemble_members)
                        completed_ensembles = sorted(completed)
                    ckpt.write(
                        lead_time=current_lead_time,
                        completed_ensembles=completed_ensembles,
                    )
                    pbar.update(1)
                    if step == nsteps:
                        break

            ckpt.flush()

    io.flush()
    logger.success("\nInference complete")
    return io

Thus, we need the following:

import os

os.makedirs("outputs", exist_ok=True)
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.dx import PrecipitationAFNO
from earth2studio.models.px import FCN
from earth2studio.utils.time import to_time_array

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

package = PrecipitationAFNO.load_default_package()
diagnostic_model = PrecipitationAFNO.load_model(package)

# Create the data source
data = GFS()

# Create the IO handler, store in memory
io = ZarrBackend()
Console output65 lines
Downloading config.json: 0%|          | 0.00/22.0 [00:00<?, ?B/s]
Downloading config.json: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 22.0/22.0 [00:00<00:00, 144B/s]
Downloading config.json: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 22.0/22.0 [00:00<00:00, 143B/s]

Downloading fcn.mdlus: 0%|          | 0.00/287M [00:00<?, ?B/s]
Downloading fcn.mdlus: 3%|โ–Ž         | 10.0M/287M [00:01<00:29, 9.90MB/s]
Downloading fcn.mdlus: 7%|โ–‹         | 20.0M/287M [00:01<00:13, 20.8MB/s]
Downloading fcn.mdlus: 10%|โ–ˆ         | 30.0M/287M [00:01<00:10, 25.3MB/s]
Downloading fcn.mdlus: 14%|โ–ˆโ–        | 40.0M/287M [00:01<00:07, 33.7MB/s]
Downloading fcn.mdlus: 17%|โ–ˆโ–‹        | 50.0M/287M [00:01<00:05, 41.5MB/s]
Downloading fcn.mdlus: 21%|โ–ˆโ–ˆ        | 60.0M/287M [00:01<00:04, 47.8MB/s]
Downloading fcn.mdlus: 24%|โ–ˆโ–ˆโ–       | 70.0M/287M [00:02<00:04, 56.3MB/s]
Downloading fcn.mdlus: 28%|โ–ˆโ–ˆโ–Š       | 80.0M/287M [00:02<00:03, 64.0MB/s]
Downloading fcn.mdlus: 31%|โ–ˆโ–ˆโ–ˆโ–      | 90.0M/287M [00:02<00:02, 70.5MB/s]
Downloading fcn.mdlus: 35%|โ–ˆโ–ˆโ–ˆโ–      | 100M/287M [00:02<00:02, 78.3MB/s] 
Downloading fcn.mdlus: 42%|โ–ˆโ–ˆโ–ˆโ–ˆโ–     | 120M/287M [00:02<00:02, 87.2MB/s]
Downloading fcn.mdlus: 45%|โ–ˆโ–ˆโ–ˆโ–ˆโ–Œ     | 130M/287M [00:02<00:01, 84.2MB/s]
Downloading fcn.mdlus: 49%|โ–ˆโ–ˆโ–ˆโ–ˆโ–Š     | 140M/287M [00:02<00:01, 87.1MB/s]
Downloading fcn.mdlus: 52%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–    | 150M/287M [00:02<00:01, 89.8MB/s]
Downloading fcn.mdlus: 56%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Œ    | 160M/287M [00:03<00:01, 87.3MB/s]
Downloading fcn.mdlus: 59%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‰    | 170M/287M [00:03<00:01, 90.3MB/s]
Downloading fcn.mdlus: 66%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Œ   | 190M/287M [00:03<00:01, 96.1MB/s]
Downloading fcn.mdlus: 70%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‰   | 200M/287M [00:03<00:00, 95.5MB/s]
Downloading fcn.mdlus: 77%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‹  | 220M/287M [00:03<00:00, 90.4MB/s]
Downloading fcn.mdlus: 80%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ  | 230M/287M [00:03<00:00, 73.8MB/s]
Downloading fcn.mdlus: 84%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Ž | 240M/287M [00:04<00:00, 66.2MB/s]
Downloading fcn.mdlus: 87%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‹ | 250M/287M [00:04<00:00, 62.7MB/s]
Downloading fcn.mdlus: 91%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ | 260M/287M [00:04<00:00, 61.6MB/s]
Downloading fcn.mdlus: 94%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–| 270M/287M [00:04<00:00, 67.9MB/s]
Downloading fcn.mdlus: 97%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‹| 280M/287M [00:04<00:00, 73.4MB/s]
Downloading fcn.mdlus: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 287M/287M [00:04<00:00, 62.0MB/s]

Downloading global_means.npy: 0%|          | 0.00/336 [00:00<?, ?B/s]
Downloading global_means.npy: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 336/336 [00:00<00:00, 670B/s]
Downloading global_means.npy: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 336/336 [00:00<00:00, 666B/s]

Downloading global_stds.npy: 0%|          | 0.00/336 [00:00<?, ?B/s]
Downloading global_stds.npy: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 336/336 [00:00<00:00, 1.22kB/s]
Downloading global_stds.npy: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 336/336 [00:00<00:00, 1.21kB/s]

Downloading precipitation_afno.zip: 0%|          | 0.00/261M [00:00<?, ?B/s]
Downloading precipitation_afno.zip: 0%|          | 1.21M/261M [00:00<00:21, 12.7MB/s]
Downloading precipitation_afno.zip: 3%|โ–Ž         | 7.24M/261M [00:00<00:06, 42.3MB/s]
Downloading precipitation_afno.zip: 10%|โ–ˆ         | 26.8M/261M [00:00<00:02, 88.9MB/s]
Downloading precipitation_afno.zip: 15%|โ–ˆโ–        | 38.4M/261M [00:00<00:02, 99.6MB/s]
Downloading precipitation_afno.zip: 20%|โ–ˆโ–ˆ        | 53.4M/261M [00:00<00:01, 118MB/s] 
Downloading precipitation_afno.zip: 25%|โ–ˆโ–ˆโ–       | 64.6M/261M [00:00<00:02, 90.6MB/s]
Downloading precipitation_afno.zip: 30%|โ–ˆโ–ˆโ–ˆ       | 78.5M/261M [00:00<00:01, 105MB/s] 
Downloading precipitation_afno.zip: 34%|โ–ˆโ–ˆโ–ˆโ–      | 89.3M/261M [00:01<00:02, 86.8MB/s]
Downloading precipitation_afno.zip: 39%|โ–ˆโ–ˆโ–ˆโ–Š      | 101M/261M [00:01<00:01, 95.3MB/s] 
Downloading precipitation_afno.zip: 43%|โ–ˆโ–ˆโ–ˆโ–ˆโ–Ž     | 111M/261M [00:01<00:02, 65.6MB/s]
Downloading precipitation_afno.zip: 46%|โ–ˆโ–ˆโ–ˆโ–ˆโ–Œ     | 119M/261M [00:01<00:02, 67.7MB/s]
Downloading precipitation_afno.zip: 50%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ     | 132M/261M [00:01<00:01, 81.6MB/s]
Downloading precipitation_afno.zip: 54%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–    | 141M/261M [00:01<00:01, 72.6MB/s]
Downloading precipitation_afno.zip: 61%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ    | 158M/261M [00:01<00:01, 96.7MB/s]
Downloading precipitation_afno.zip: 65%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–   | 169M/261M [00:02<00:01, 66.6MB/s]
Downloading precipitation_afno.zip: 68%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Š   | 178M/261M [00:02<00:01, 72.2MB/s]
Downloading precipitation_afno.zip: 72%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–  | 188M/261M [00:02<00:01, 66.5MB/s]
Downloading precipitation_afno.zip: 75%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Œ  | 197M/261M [00:02<00:00, 71.5MB/s]
Downloading precipitation_afno.zip: 78%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Š  | 205M/261M [00:02<00:00, 74.8MB/s]
Downloading precipitation_afno.zip: 82%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ– | 215M/261M [00:02<00:00, 66.4MB/s]
Downloading precipitation_afno.zip: 88%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Š | 231M/261M [00:03<00:00, 89.5MB/s]
Downloading precipitation_afno.zip: 92%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–| 241M/261M [00:03<00:00, 73.1MB/s]
Downloading precipitation_afno.zip: 99%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Š| 258M/261M [00:03<00:00, 91.4MB/s]
Downloading precipitation_afno.zip: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 261M/261M [00:03<00:00, 81.0MB/s]

Fetch Data

You can easily fetch raw Xarray data from an initial condition data source with a simple call. By default, this caches the data locally on your machine, so you won't have to re-download it if you access it again or use it in an inference pipeline.

sample = data(
    to_time_array(["2024-01-01"]),
    prognostic_model.input_coords().coords["variable"].values,
)
print(sample)
Console output73 lines
Fetching GFS data:   0%|          | 0/26 [00:00<?, ?it/s]
Fetching GFS data:   4%|โ–         | 1/26 [00:00<00:04,  5.06it/s]
Fetching GFS data:  23%|โ–ˆโ–ˆโ–Ž       | 6/26 [00:00<00:02,  7.16it/s]
Fetching GFS data:  35%|โ–ˆโ–ˆโ–ˆโ–      | 9/26 [00:00<00:01, 10.32it/s]
Fetching GFS data:  42%|โ–ˆโ–ˆโ–ˆโ–ˆโ–     | 11/26 [00:01<00:01, 11.98it/s]
Fetching GFS data:  54%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–    | 14/26 [00:01<00:00, 15.22it/s]
Fetching GFS data:  85%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ– | 22/26 [00:01<00:00, 29.29it/s]
Fetching GFS data: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 26/26 [00:01<00:00, 19.93it/s]

Fetching GFS statistics: 0it [00:00, ?it/s]
Fetching GFS statistics: 0it [00:00, ?it/s]
<xarray.DataArray (time: 1, variable: 26, lat: 721, lon: 1440)> Size: 216MB
array([[[[-3.37807129e+00, -3.38807129e+00, -3.40807129e+00, ...,
          -3.33807129e+00, -3.34807129e+00, -3.36807129e+00],
         [-3.33807129e+00, -3.34807129e+00, -3.36807129e+00, ...,
          -3.28807129e+00, -3.30807129e+00, -3.31807129e+00],
         [-4.05807129e+00, -4.06807129e+00, -4.07807129e+00, ...,
          -3.99807129e+00, -4.01807129e+00, -4.03807129e+00],
         ...,
         [ 4.13192871e+00,  4.14192871e+00,  4.16192871e+00, ...,
           4.09192871e+00,  4.11192871e+00,  4.12192871e+00],
         [ 5.24192871e+00,  5.26192871e+00,  5.27192871e+00, ...,
           5.21192871e+00,  5.22192871e+00,  5.23192871e+00],
         [ 5.72192871e+00,  5.73192871e+00,  5.74192871e+00, ...,
           5.69192871e+00,  5.70192871e+00,  5.71192871e+00]],

        [[-3.13438721e+00, -3.11438721e+00, -3.10438721e+00, ...,
          -3.17438721e+00, -3.16438721e+00, -3.14438721e+00],
         [-3.23438721e+00, -3.21438721e+00, -3.20438721e+00, ...,
          -3.27438721e+00, -3.25438721e+00, -3.24438721e+00],
         [-3.72438721e+00, -3.70438721e+00, -3.69438721e+00, ...,
          -3.77438721e+00, -3.76438721e+00, -3.74438721e+00],
...
         [ 9.52740394e+04,  9.52732546e+04,  9.52728622e+04, ...,
           9.52760014e+04,  9.52752166e+04,  9.52748242e+04],
         [ 9.52579510e+04,  9.52571662e+04,  9.52567738e+04, ...,
           9.52587358e+04,  9.52583434e+04,  9.52579510e+04],
         [ 9.52442170e+04,  9.52442170e+04,  9.52442170e+04, ...,
           9.52442170e+04,  9.52442170e+04,  9.52442170e+04]],

        [[ 2.13206797e+02,  2.13206797e+02,  2.13206797e+02, ...,
           2.13206797e+02,  2.13206797e+02,  2.13206797e+02],
         [ 2.13416797e+02,  2.13416797e+02,  2.13406797e+02, ...,
           2.13416797e+02,  2.13416797e+02,  2.13416797e+02],
         [ 2.13756797e+02,  2.13756797e+02,  2.13746797e+02, ...,
           2.13766797e+02,  2.13766797e+02,  2.13766797e+02],
         ...,
         [ 2.13926797e+02,  2.13926797e+02,  2.13936797e+02, ...,
           2.13916797e+02,  2.13916797e+02,  2.13916797e+02],
         [ 2.13806797e+02,  2.13806797e+02,  2.13806797e+02, ...,
           2.13796797e+02,  2.13806797e+02,  2.13806797e+02],
         [ 2.13736797e+02,  2.13736797e+02,  2.13736797e+02, ...,
           2.13736797e+02,  2.13736797e+02,  2.13736797e+02]]]])
Coordinates:
  * time       (time) datetime64[ns] 8B 2024-01-01
  * variable   (variable) <U5 520B 'u10m' 'v10m' 't2m' ... 'v250' 'z250' 't250'
  * lat        (lat) float64 6kB 90.0 89.75 89.5 89.25 ... -89.5 -89.75 -90.0
  * lon        (lon) float64 12kB 0.0 0.25 0.5 0.75 ... 359.0 359.2 359.5 359.8
    lead_time  timedelta64[ns] 8B 00:00:00
Attributes: (12/17)
    type:                         LatLonGrid
    dims:                         ['lat', 'lon']
    shape:                        [721, 1440]
    topology:                     rectilinear
    crs:                          EPSG:4326
    crs_wkt:                      GEOGCRS["WGS 84",ENSEMBLE["World Geodetic S...
    ...                           ...
    prime_meridian_name:          Greenwich
    geographic_crs_name:          WGS 84
    horizontal_datum_name:        World Geodetic System 1984 ensemble
    grid_mapping_name:            latitude_longitude
    earth2studio_crs:             EPSG:4326
    earth2studio_grid_id:         latlon-0.25deg

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.

import earth2studio.run as run

nsteps = 8
io = run.diagnostic(
    ["2024-01-01"], nsteps, prognostic_model, diagnostic_model, data, io
)

print(io.root.tree())
Console output35 lines
2026-11-19 17:16:11.070 | INFO     | earth2studio.run:diagnostic:267 - Running diagnostic workflow!
2026-11-19 17:16:11.070 | INFO     | earth2studio.run:diagnostic:274 - Inference device: cuda

Fetching GFS data:   0%|          | 0/26 [00:00<?, ?it/s]
Fetching GFS data:   4%|โ–         | 1/26 [00:00<00:10,  2.47it/s]
Fetching GFS data:  15%|โ–ˆโ–Œ        | 4/26 [00:00<00:02,  9.18it/s]
Fetching GFS data:  73%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Ž  | 19/26 [00:00<00:00, 45.73it/s]
Fetching GFS data: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 26/26 [00:00<00:00, 40.26it/s]

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


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

Running inference:  11%|โ–ˆ         | 1/9 [00:00<00:03,  2.39it/s]

Running inference:  33%|โ–ˆโ–ˆโ–ˆโ–Ž      | 3/9 [00:00<00:01,  5.84it/s]

Running inference:  56%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Œ    | 5/9 [00:00<00:00,  7.95it/s]

Running inference:  78%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–Š  | 7/9 [00:00<00:00,  9.32it/s]

Running inference: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 9/9 [00:01<00:00, 10.24it/s]
Running inference: 100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 9/9 [00:01<00:00,  8.32it/s]
2026-11-19 17:16:13.141 | SUCCESS  | earth2studio.run:diagnostic:352 - 
Inference complete
/
โ”œโ”€โ”€ lat (720,) float64
โ”œโ”€โ”€ lead_time (9,) timedelta64[ns]
โ”œโ”€โ”€ lon (1440,) float64
โ”œโ”€โ”€ time (1,) datetime64[ns]
โ””โ”€โ”€ tp06 (1, 9, 720, 1440) float32

Post Processing

The last step is to plot the resulting predicted total precipitation. The power of diagnostic models is that they allow the prediction of any variable from a pre-trained prognostic model.

Note

The built in workflow will only save the direct outputs of the diagnostic. In this example only total precipitation is accessible for plotting. If you wish to save outputs of both the prognostic and diagnostic, we recommend writing a custom workflow.

from datetime import datetime

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

forecast = datetime(2024, 1, 1)
variable = "tp06"
step = 8  # lead time = 48 hrs

plt.close("all")
# Create a Orthographic projection of USA
projection = ccrs.Orthographic(-100, 40)

# Create a figure and axes with the specified projection
fig, ax = plt.subplots(subplot_kw={"projection": projection}, figsize=(10, 6))

# Plot the field using pcolormesh
levels = np.arange(0.0, 0.01, 0.001)
im = ax.contourf(
    io["lon"][:],
    io["lat"][:],
    io[variable][0, step],
    levels,
    transform=ccrs.PlateCarree(),
    vmax=0.01,
    vmin=0.00,
    cmap="terrain",
)

# Set title
ax.set_title(f"{forecast.strftime('%Y-%m-%d')} - Lead time: {6*step}hrs")

# Add coastlines and gridlines6
ax.set_extent([220, 340, 20, 70])  # [lat min, lat max, lon min, lon max]
ax.coastlines()
ax.gridlines()
plt.colorbar(
    im, ax=ax, ticks=levels, shrink=0.75, pad=0.04, label="Total precipitation (m)"
)

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

Output from Running Diagnostic Inference


Execution profile

Runtime telemetry

Profiled phases

Total runtime46.5 s
Setup33.8 s ยท 32 samples
Duration33.8 sTagged cells
CPU load9%Average ยท Peak 76%
Process memory2.4 GiBPeak resident set
Network received568.8 MiBHost-wide estimate
Network sent927.0 KiBHost-wide estimate
GPU utilization0%Peak 0%
GPU memory0.5 GiBof 79.6 GiB
GPU power82 WPeak draw
Inference2.4 s ยท 2 samples
Duration2.4 sTagged cells
CPU load8%Average ยท Peak 9%
Process memory2.7 GiBPeak resident set
Network received0 BHost-wide estimate
Network sent0 BHost-wide estimate
GPU utilization46%Peak 91%
GPU memory2.4 GiBof 79.6 GiB
GPU power186 WPeak draw
Plotting7.3 s ยท 6 samples
Duration7.3 sTagged cells
CPU load8%Average ยท Peak 9%
Process memory2.6 GiBPeak resident set
Network received5.8 KiBHost-wide estimate
Network sent4.2 KiBHost-wide estimate
GPU utilization0%Peak 0%
GPU memory2.5 GiBof 79.6 GiB
GPU power136 WPeak draw

Execution environment

CPUAMD EPYC 7313P 16-Core Processor
GPUNVIDIA H100 PCIe ยท 79.6 GiB
System RAM58.5 GiB
PlatformLinux 6.8.0-147-generic
Python3.13.13
GPU driver / CUDADriver 595.99.02 ยท CUDA support 13.2