Skip to content

States — geocatalog.states

Query and load model states (analyses, forecasts, ensemble members) from a catalog built with build_state_catalog. The how-to is Model states.

Loading (extras: [xarray-raster])

geocatalog.states.load_states(catalog, slice_, *, data_vars=None, group_by=None, storage_options=None)

Load forecast states as an (init_time, member, lead_time, y, x) cube.

Every row overlapping slice_ is one run and member. Each file is clipped to the slice (bounds and valid-time interval), its valid times are relabelled as leads, τ = v - r, and the files are stacked by run time and member. Two runs valid at the same time stay two states, unlike load_xarray, which keeps one valid time. A member or lead missing from a run comes back as NaN, not as a shorter cube, and valid_time = init_time + lead_time is a 2-D coordinate. Members are in natural order: by number when every label is an integer ("2" before "10"), else as text (r1i1p1f1). A run whose file overlaps the slice without a time step inside it has no state there and is left out.

Parameters:

Name Type Description Default
catalog GeoCatalog

A state catalog (build_state_catalog), on either backend; filter it first with the typed queries (forecasts, ensemble_at, …).

required
slice_ GeoSlice

The region and valid-time interval to load. Bounds may be in another CRS; they are reprojected to the catalog's.

required
data_vars Sequence[str] | None

Data variables to keep. None keeps them all.

None
group_by str | None

A row column ("producer") to split the rows by. None returns one cube and requires one grid; a column returns an xarray.DataTree with one leaf per value, each leaf a cube on its own grid.

None
storage_options dict[str, Any] | None

obstore options for remote files (geocloud.fs).

None

Returns:

Type Description
Dataset | DataTree

An xarray.Dataset with dims ``(init_time, member, lead_time,

Dataset | DataTree

y, x)` (the files' own spatial names), or anxarray.DataTree`

Dataset | DataTree

of them when group_by is given. A deterministic run (null

Dataset | DataTree

member) is the member "".

Raises:

Type Description
ImportError

If the [xarray-raster] extra is missing.

TypeError

If the catalog is not of kind "xarray".

ValueError

If the catalog has no state columns, no row matches, the slice holds none of the matching files' time steps, a row has no run time, a run and member appears twice, or the rows are on different grids without group_by.

Example

from geocatalog.states import forecasts, load_states cube = load_states(forecasts(catalog), aoi) cube["xch4"].dims, cube["xch4"].shape (('init_time', 'member', 'lead_time', 'lat', 'lon'), (3, 4, 2, 4, 5))

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/states.py
def load_states(
    catalog: GeoCatalog,
    slice_: GeoSlice,
    *,
    data_vars: Sequence[str] | None = None,
    group_by: str | None = None,
    storage_options: dict[str, Any] | None = None,
) -> xr.Dataset | xr.DataTree:
    """Load forecast states as an ``(init_time, member, lead_time, y, x)`` cube.

    Every row overlapping ``slice_`` is one run and member. Each file is
    clipped to the slice (bounds and valid-time interval), its valid
    times are relabelled as leads, ``τ = v - r``, and the files are
    stacked by run time and member. Two runs valid at the same time stay
    two states, unlike `load_xarray`, which keeps one valid time. A
    member or lead missing from a run comes back as NaN, not as a shorter
    cube, and ``valid_time = init_time + lead_time`` is a 2-D coordinate.
    Members are in natural order: by number when every label is an
    integer (``"2"`` before ``"10"``), else as text (``r1i1p1f1``). A run
    whose file overlaps the slice without a time step inside it has no
    state there and is left out.

    Args:
        catalog: A state catalog (`build_state_catalog`), on either
            backend; filter it first with the typed queries
            (`forecasts`, `ensemble_at`, …).
        slice_: The region and valid-time interval to load. Bounds may be
            in another CRS; they are reprojected to the catalog's.
        data_vars: Data variables to keep. ``None`` keeps them all.
        group_by: A row column (``"producer"``) to split the rows by.
            ``None`` returns one cube and requires one grid; a column
            returns an `xarray.DataTree` with one leaf per value, each
            leaf a cube on its own grid.
        storage_options: obstore options for remote files (`geocloud.fs`).

    Returns:
        An `xarray.Dataset` with dims ``(init_time, member, lead_time,
        y, x)`` (the files' own spatial names), or an `xarray.DataTree`
        of them when ``group_by`` is given. A deterministic run (null
        member) is the member ``""``.

    Raises:
        ImportError: If the ``[xarray-raster]`` extra is missing.
        TypeError: If the catalog is not of kind ``"xarray"``.
        ValueError: If the catalog has no state columns, no row matches,
            the slice holds none of the matching files' time steps, a row
            has no run time, a run and member appears twice, or the rows
            are on different grids without ``group_by``.

    Example:
        >>> from geocatalog.states import forecasts, load_states
        >>> cube = load_states(forecasts(catalog), aoi)
        >>> cube["xch4"].dims, cube["xch4"].shape
        (('init_time', 'member', 'lead_time', 'lat', 'lon'), (3, 4, 2, 4, 5))
    """
    if xr is None:
        raise missing_extra("`load_states`", "xarray-raster")
    if catalog.kind != "xarray":
        raise TypeError(
            f"load_states requires an xarray-kind catalog; got {catalog.kind!r}"
        )
    require_state_columns(catalog, "load_states")
    filtered = catalog.query(slice_)
    rows = list(filtered.iter_rows())
    if not rows:
        raise ValueError("load_states: no catalog rows match the slice")
    bounds = _reproject_bounds(slice_.bounds, slice_.crs, filtered.crs)
    interval = (slice_.interval.left, slice_.interval.right)

    def read(row: CatalogRow) -> xr.Dataset:
        return _read_clipped(
            row.filepath,
            bounds=bounds,
            interval=interval,
            time_var=str(row.extras.get("time_var") or "time"),
            data_vars=data_vars,
            storage_options=storage_options,
        )

    # Catalog order is arbitrary (a SQL relation has none): sort first.
    rows.sort(key=lambda r: r.filepath)
    if group_by is None:
        return _stack(rows, read)
    if group_by not in rows[0].extras:
        raise ValueError(f"load_states: group_by column {group_by!r} not in catalog")
    groups: dict[str, list[CatalogRow]] = {}
    for row in rows:
        value = state_text(row.extras.get(group_by))
        if value is None or "/" in value:
            raise ValueError(
                f"load_states: {row.filepath} has {group_by}={value!r}; a group "
                "needs a non-null name without '/'."
            )
        groups.setdefault(value, []).append(row)
    return xr.DataTree.from_dict(
        {f"/{name}": _stack(group, read) for name, group in sorted(groups.items())}
    )

Typed queries

geocatalog.states.forecasts(catalog)

The forecast rows of a state catalog (kind == "forecast").

Parameters:

Name Type Description Default
catalog GeoCatalog

A catalog with the reserved state columns, on either backend.

required

Returns:

Type Description
GeoCatalog

A catalog of the same backend with the forecast rows.

Example

fc = forecasts(catalog) load_states(fc, aoi).sizes # (init_time, member, lead_time, y, x)

Source code in packages/geotoolz-catalog/src/geocatalog/_src/states.py
def forecasts(catalog: GeoCatalog) -> GeoCatalog:
    """The forecast rows of a state catalog (``kind == "forecast"``).

    Args:
        catalog: A catalog with the reserved state columns, on either
            backend.

    Returns:
        A catalog of the same backend with the forecast rows.

    Example:
        >>> fc = forecasts(catalog)
        >>> load_states(fc, aoi).sizes   # (init_time, member, lead_time, y, x)
    """
    return _filter(catalog, [("kind", "==", "forecast")], "forecasts")

geocatalog.states.ensemble_at(catalog, *, run_time)

Every member of one forecast run.

Parameters:

Name Type Description Default
catalog GeoCatalog

A state catalog.

required
run_time Timestamp

The run's initialisation time, a pd.Timestamp (a string raises TypeError). Matched exactly.

required

Returns:

Type Description
GeoCatalog

A catalog of the forecast rows with that run_time, one per

GeoCatalog

member file.

Raises:

Type Description
TypeError

If run_time is not datetime-like.

Example

members = ensemble_at(catalog, run_time=pd.Timestamp("2026-01-01"))

Source code in packages/geotoolz-catalog/src/geocatalog/_src/states.py
def ensemble_at(catalog: GeoCatalog, *, run_time: pd.Timestamp) -> GeoCatalog:
    """Every member of one forecast run.

    Args:
        catalog: A state catalog.
        run_time: The run's initialisation time, a `pd.Timestamp` (a
            string raises `TypeError`). Matched exactly.

    Returns:
        A catalog of the forecast rows with that ``run_time``, one per
        member file.

    Raises:
        TypeError: If ``run_time`` is not datetime-like.

    Example:
        >>> members = ensemble_at(catalog, run_time=pd.Timestamp("2026-01-01"))
    """
    ts = _timestamp(run_time, "run_time")
    return _filter(
        catalog,
        [("kind", "==", "forecast"), ("run_time", "==", ts)],
        "ensemble_at",
    )

geocatalog.states.forecast_chain(catalog, *, run_time, member)

One member of one forecast run: the files of a single trajectory.

Parameters:

Name Type Description Default
catalog GeoCatalog

A state catalog.

required
run_time Timestamp

The run's initialisation time, a pd.Timestamp.

required
member str

The member label, as text ("0", "r1i1p1f1").

required

Returns:

Type Description
GeoCatalog

A catalog of the forecast rows of that run and member.

Raises:

Type Description
TypeError

If run_time is not datetime-like or member is not a string (the column is text, so 0 would match nothing).

Example

chain = forecast_chain(catalog, run_time=pd.Timestamp("2026-01-02"), ... member="0")

Source code in packages/geotoolz-catalog/src/geocatalog/_src/states.py
def forecast_chain(
    catalog: GeoCatalog, *, run_time: pd.Timestamp, member: str
) -> GeoCatalog:
    """One member of one forecast run: the files of a single trajectory.

    Args:
        catalog: A state catalog.
        run_time: The run's initialisation time, a `pd.Timestamp`.
        member: The member label, as text (``"0"``, ``"r1i1p1f1"``).

    Returns:
        A catalog of the forecast rows of that run and member.

    Raises:
        TypeError: If ``run_time`` is not datetime-like or ``member`` is
            not a string (the column is text, so ``0`` would match
            nothing).

    Example:
        >>> chain = forecast_chain(catalog, run_time=pd.Timestamp("2026-01-02"),
        ...                        member="0")
    """
    ts = _timestamp(run_time, "run_time")
    label = _member(member)
    return _filter(
        catalog,
        [("kind", "==", "forecast"), ("run_time", "==", ts), ("member", "==", label)],
        "forecast_chain",
    )

geocatalog.states.lead_window(catalog, start, end)

Forecast rows whose leads overlap [start, end].

A row covers valid times [v_min, v_max], so its leads are [v_min - run_time, v_max - run_time]; lead time is derived, not stored.

Parameters:

Name Type Description Default
catalog GeoCatalog

A state catalog.

required
start Timedelta

First lead of the window, a pd.Timedelta.

required
end Timedelta

Last lead of the window (inclusive).

required

Returns:

Type Description
GeoCatalog

A catalog of the forecast rows with at least one lead in the

GeoCatalog

window.

Raises:

Type Description
TypeError

If a bound is not timedelta-like.

ValueError

If start > end.

Example

day_two = lead_window(catalog, pd.Timedelta("2D"), pd.Timedelta("2D"))

Source code in packages/geotoolz-catalog/src/geocatalog/_src/states.py
def lead_window(
    catalog: GeoCatalog, start: pd.Timedelta, end: pd.Timedelta
) -> GeoCatalog:
    """Forecast rows whose leads overlap ``[start, end]``.

    A row covers valid times ``[v_min, v_max]``, so its leads are
    ``[v_min - run_time, v_max - run_time]``; lead time is derived, not
    stored.

    Args:
        catalog: A state catalog.
        start: First lead of the window, a `pd.Timedelta`.
        end: Last lead of the window (inclusive).

    Returns:
        A catalog of the forecast rows with at least one lead in the
        window.

    Raises:
        TypeError: If a bound is not timedelta-like.
        ValueError: If ``start > end``.

    Example:
        >>> day_two = lead_window(catalog, pd.Timedelta("2D"), pd.Timedelta("2D"))
    """
    lo, hi = _timedelta(start, "start"), _timedelta(end, "end")
    if lo > hi:
        raise ValueError(f"lead_window: start {lo} is after end {hi}")
    return _filter(
        catalog,
        [("kind", "==", "forecast"), ("lead_end", ">=", lo), ("lead_start", "<=", hi)],
        "lead_window",
    )

geocatalog.states.at_time(catalog, time)

States of every kind valid at time: rows whose interval contains it.

Parameters:

Name Type Description Default
catalog GeoCatalog

A state catalog.

required
time Timestamp

The valid time, a pd.Timestamp.

required

Returns:

Type Description
GeoCatalog

A catalog of the rows whose valid-time interval contains time

GeoCatalog

(analyses, and every run and member that reaches it).

Example

jan3 = at_time(catalog, pd.Timestamp("2026-01-03"))

Source code in packages/geotoolz-catalog/src/geocatalog/_src/states.py
def at_time(catalog: GeoCatalog, time: pd.Timestamp) -> GeoCatalog:
    """States of every kind valid at ``time``: rows whose interval contains it.

    Args:
        catalog: A state catalog.
        time: The valid time, a `pd.Timestamp`.

    Returns:
        A catalog of the rows whose valid-time interval contains ``time``
        (analyses, and every run and member that reaches it).

    Example:
        >>> jan3 = at_time(catalog, pd.Timestamp("2026-01-03"))
    """
    ts = _timestamp(time, "time")
    return _filter(
        catalog,
        [("start_time", "<=", ts), ("end_time", ">=", ts)],
        "at_time",
    )

geocatalog.states.latest_analysis(catalog, *, before)

The analysis with the latest valid time at or before before.

Filters on the reserved kind column, not on a zero lead: a lead-0 forecast row is valid at its run time too. Analyses valid at the same time are ordered by run time, then by file path (the last wins), so every backend returns the same row.

Parameters:

Name Type Description Default
catalog GeoCatalog

A state catalog.

required
before Timestamp

The cut-off valid time, a pd.Timestamp (inclusive).

required

Returns:

Type Description
CatalogRow | None

The CatalogRow of that analysis, or None when there is none.

Example

row = latest_analysis(catalog, before=pd.Timestamp("2026-01-03 06:00")) row.filepath 'ana_20260103.nc'

Source code in packages/geotoolz-catalog/src/geocatalog/_src/states.py
def latest_analysis(catalog: GeoCatalog, *, before: pd.Timestamp) -> CatalogRow | None:
    """The analysis with the latest valid time at or before ``before``.

    Filters on the reserved ``kind`` column, not on a zero lead: a lead-0
    forecast row is valid at its run time too. Analyses valid at the same
    time are ordered by run time, then by file path (the last wins), so
    every backend returns the same row.

    Args:
        catalog: A state catalog.
        before: The cut-off valid time, a `pd.Timestamp` (inclusive).

    Returns:
        The `CatalogRow` of that analysis, or ``None`` when there is none.

    Example:
        >>> row = latest_analysis(catalog, before=pd.Timestamp("2026-01-03 06:00"))
        >>> row.filepath
        'ana_20260103.nc'
    """
    ts = _timestamp(before, "before")
    rows = _filter(
        catalog,
        [("kind", "==", "analysis"), ("end_time", "<=", ts)],
        "latest_analysis",
    )
    best: CatalogRow | None = None
    for row in rows.iter_rows():
        if best is None or _recency(row) > _recency(best):
            best = row
    return best

Columns and name maps

geocatalog.states.STATE_COLUMNS = ('kind', 'run_time', 'member', 'producer', 'parents') module-attribute

Row columns reserved, with fixed types, for model states (schema v1).

kind (string, a StateKind), run_time (datetime64[us], naive UTC: the run's initialisation time), member (string: a CF realization number written as text, or a CMIP variant label such as r1i1p1f1), producer (string) and parents (list<string>: the URIs the state was computed from). A state catalog is one with a run_time column (is_state_frame), and it carries all five; in any other catalog the names are ordinary extras. Lead time is not stored: it is the row's valid time minus run_time. They stay ordinary row columns (and CatalogRow.extras keys), unlike RESERVED_COLUMNS, which every artifact carries.

geocatalog.states.StateFields dataclass

The model-state fields of one catalog row (CatalogRow.state).

Attributes:

Name Type Description
kind str | None

"analysis", "forecast" or "reanalysis", or None when the file did not say.

run_time Timestamp | None

The run's initialisation time (naive UTC), or None.

member str | None

The ensemble member as text ("0", "r1i1p1f1"), or None for a deterministic run.

producer str | None

What made the state (a pipeline hash, a model id), or None.

parents tuple[str, ...]

URIs of the states this one was computed from; empty when none are recorded.

Example

row = next(catalog.iter_rows()) row.state.run_time, row.state.member (Timestamp('2026-01-02 00:00:00'), '0')

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
@dataclasses.dataclass(frozen=True)
class StateFields:
    """The model-state fields of one catalog row (`CatalogRow.state`).

    Attributes:
        kind: ``"analysis"``, ``"forecast"`` or ``"reanalysis"``, or
            ``None`` when the file did not say.
        run_time: The run's initialisation time (naive UTC), or ``None``.
        member: The ensemble member as text (``"0"``, ``"r1i1p1f1"``), or
            ``None`` for a deterministic run.
        producer: What made the state (a pipeline hash, a model id), or
            ``None``.
        parents: URIs of the states this one was computed from; empty
            when none are recorded.

    Example:
        >>> row = next(catalog.iter_rows())
        >>> row.state.run_time, row.state.member
        (Timestamp('2026-01-02 00:00:00'), '0')
    """

    kind: str | None
    run_time: pd.Timestamp | None
    member: str | None
    producer: str | None
    parents: tuple[str, ...] = ()

geocatalog.states.CF_NAMES = MappingProxyType({'valid_time': 'time', 'run_time': 'forecast_reference_time', 'member': 'realization', 'kind': 'kind', 'producer': 'producer', 'parents': 'parents'}) module-attribute

Where CF files keep each state field.

The run time is the forecast_reference_time coordinate or attribute, the member the realization one, and the valid time the time axis. kind, producer and parents have no CF name: they are global attributes of those names, written by the script that saves the states.

geocatalog.states.CFGRIB_NAMES = MappingProxyType({'valid_time': 'valid_time', 'run_time': 'time', 'member': 'number', 'kind': 'kind', 'producer': 'producer', 'parents': 'parents'}) module-attribute

Where cfgrib-decoded GRIB keeps each state field.

cfgrib names the run time time (a scalar coordinate), the lead step, the member number and the valid time valid_time (a coordinate along step).