Skip to content

Writing stores

Write HEALPix pyramids to Zarr stores on local disk or S3, and choose storage options and chunk sizes for them (grid_doctor.io).

Writing a pyramid

save_pyramid(pyramid, path, s3_options=None, *, mode='a', region='auto', zarr_format=2, encoding=None, write_coords='auto', structure='flat')

Write a HEALPix pyramid to Zarr stores on S3 or local disk.

Each level is stored below "<path>/level_<level>.zarr".

Parameters:

Name Type Description Default
pyramid dict[int, Dataset]

Mapping of HEALPix level to dataset.

required
path str

Target prefix. An "s3://bucket/pyramid" URL writes to S3; any other value is treated as a local directory path.

required
s3_options S3Options | None

Options forwarded to :class:s3fs.S3FileSystem. Only used for S3 targets; ignored (and optional) for local paths.

None
mode Literal['a', 'w', 'r+']

Zarr write mode.

'a'
region Literal['auto'] | Region

Region writes for partial updates.

'auto'
zarr_format Literal[2, 3]

Zarr format version.

2
encoding PyramidEncoding | None

Per-level encoding dictionaries.

None
write_coords bool | Literal['auto']

Whether to materialise the cell/latitude/longitude coordinate arrays in the store. HEALPix coordinates are a pure function of the cell index, and above roughly level 10 the arrays dwarf regional payloads (hundreds of GB at level 16, and they are never fill values, so chunk elision cannot help). "auto" (default) writes coordinates for levels up to :data:WRITE_COORDS_MAX_LEVEL and omits them above; True / False force either behaviour for all levels. Coordinate- less stores keep the crs grid mapping, are marked as having implicit coordinates (see HealpixMetadata), and are meant to be accessed through the region selectors (select_bbox, select_cells), which reconstruct coordinates for exactly the cells they return.

'auto'
structure Literal['flat', 'multiscales']

separate stores ('flat'), or combine them into a datatree ('multiscales').

'flat'
Source code in grid_doctor/io/_save.py
def save_pyramid(
    pyramid: dict[int, xr.Dataset],
    path: str,
    s3_options: S3Options | None = None,
    *,
    mode: Literal["a", "w", "r+"] = "a",
    region: Literal["auto"] | Region = "auto",
    zarr_format: Literal[2, 3] = 2,
    encoding: PyramidEncoding | None = None,
    write_coords: bool | Literal["auto"] = "auto",
    structure: Literal["flat", "multiscales"] = "flat",
) -> None:
    """Write a HEALPix pyramid to Zarr stores on S3 or local disk.

    Each level is stored below ``"<path>/level_<level>.zarr"``.

    Parameters
    ----------
    pyramid:
        Mapping of HEALPix level to dataset.
    path:
        Target prefix.  An ``"s3://bucket/pyramid"`` URL writes to S3; any
        other value is treated as a local directory path.
    s3_options:
        Options forwarded to :class:`s3fs.S3FileSystem`.  Only used for S3
        targets; ignored (and optional) for local paths.
    mode:
        Zarr write mode.
    region:
        Region writes for partial updates.
    zarr_format:
        Zarr format version.
    encoding:
        Per-level encoding dictionaries.
    write_coords:
        Whether to materialise the ``cell``/``latitude``/``longitude``
        coordinate arrays in the store.  HEALPix coordinates are a pure
        function of the cell index, and above roughly level 10 the
        arrays dwarf regional payloads (hundreds of GB at level 16, and
        they are never fill values, so chunk elision cannot help).
        ``"auto"`` (default) writes coordinates for levels up to
        :data:`WRITE_COORDS_MAX_LEVEL` and omits them above; ``True`` /
        ``False`` force either behaviour for all levels.  Coordinate-
        less stores keep the ``crs`` grid mapping, are marked as having
        implicit coordinates (see
        [`HealpixMetadata`][grid_doctor.metadata.HealpixMetadata]), and are
        meant to be accessed through the region selectors
        ([`select_bbox`][grid_doctor.select_bbox],
        [`select_cells`][grid_doctor.select_cells]), which reconstruct
        coordinates for exactly the cells they return.
    structure: Specify whether to write the datasets in the pyramid to
        separate stores ('flat'), or combine them into a datatree
        ('multiscales').
    """
    fs = get_filesystem(path, s3_options)

    if structure == "multiscales":
        _save_multiscale(
            pyramid,
            path,
            fs,
            mode,
            region,
            zarr_format,
            encoding,
            write_coords,
        )
        return
    # Stores are initialised per level; the data of all levels is written
    # in one pass (see grid_doctor.io._zarr for why).
    deferred: list[DeferredWrite] = []
    encoding = encoding or {}
    for level, dataset in pyramid.items():
        dataset = maybe_drop_coordinates(dataset, level, write_coords, WRITE_COORDS_MAX_LEVEL)
        store_name = f"level_{level}"
        root_path = f"{path}/{store_name}.zarr"
        store = get_store(root_path, fs)
        logger.info("Writing HEALPix to %s", store)
        zarr_options = get_zarr_options(mode, zarr_format, encoding.get(level, None))

        if region == "auto":
            dataset.to_zarr(store, **zarr_options)  # type: ignore[call-overload]
            written, write_region = dataset, None
        else:
            # Fill in the region of data.
            written = prepare_region_dataset(dataset, region)
            written.to_zarr(  # type: ignore[call-overload]
                store,
                region=region,
                **zarr_options,
            )
            write_region = region
        deferred.extend(
            deferred_writes(
                written,
                store,
                encoding=zarr_options.get("encoding"),
                region=write_region,
                zarr_format=zarr_format,
            )
        )
    store_all(deferred)

To split the write across many jobs (one array-job element per time range, say), see Parallel writes.

S3 options

get_s3_options(endpoint_url, secrets_file, **kwargs)

Build an S3 options dictionary from an endpoint and credentials file.

Parameters:

Name Type Description Default
endpoint_url str

S3-compatible endpoint URL.

required
secrets_file str | Path

JSON file containing accessKey and secretKey.

required
**kwargs str

Additional options merged into the returned dictionary.

{}

Returns:

Type Description
dict[str, str]

Options for s3fs.S3FileSystem.

Source code in grid_doctor/io/_options.py
def get_s3_options(
    endpoint_url: str,
    secrets_file: str | Path,
    **kwargs: str,
) -> dict[str, str]:
    """Build an S3 options dictionary from an endpoint and credentials file.

    Parameters
    ----------
    endpoint_url:
        S3-compatible endpoint URL.
    secrets_file:
        JSON file containing `accessKey` and `secretKey`.
    **kwargs:
        Additional options merged into the returned dictionary.

    Returns
    -------
    dict[str, str]
        Options for `s3fs.S3FileSystem`.
    """
    secrets: dict[str, str] = json.loads(Path(secrets_file).read_text())
    return {
        "endpoint_url": endpoint_url,
        "secret": secrets["secretKey"],
        "key": secrets["accessKey"],
        **kwargs,
    }

Chunking

Chunk sizes balance the number of objects in a store against the amount of data read for a small selection.

chunk_for_target_store_size(*, level, dtype='float32', target_stored_mib=16.0, compression_ratio=2.0, access='map', ntime=None, max_time_chunk=None, max_cell_chunk=None)

Compute (time, cell) chunks for a HEALPix dataset.

Parameters:

Name Type Description Default
level int

HEALPix order / level.

required
dtype DTypeLike

Variable dtype.

'float32'
target_stored_mib float

Desired approximate compressed chunk size on disk.

16.0
compression_ratio float

Estimated ratio: uncompressed_bytes / compressed_bytes

2.0
access Literal['time_series', 'map']

"map" or "time_series".

'map'
ntime int | None

Total time size. Needed for time_series mode unless max_time_chunk is given.

None
max_time_chunk int | None

Optional cap for time chunk.

None
max_cell_chunk int | None

Optional cap for cell chunk.

None

Returns:

Type Description
dict[str, int]

Chunk sizes, e.g. {"time": 5, "cell": 786432}.

Source code in grid_doctor/io/_options.py
def chunk_for_target_store_size(
    *,
    level: int,
    dtype: npt.DTypeLike = "float32",
    target_stored_mib: float = 16.0,
    compression_ratio: float = 2.0,
    access: Literal["time_series", "map"] = "map",
    ntime: int | None = None,
    max_time_chunk: int | None = None,
    max_cell_chunk: int | None = None,
) -> dict[str, int]:
    """
    Compute (time, cell) chunks for a HEALPix dataset.

    Parameters
    ----------
    level
        HEALPix order / level.
    dtype
        Variable dtype.
    target_stored_mib
        Desired approximate compressed chunk size on disk.
    compression_ratio
        Estimated ratio:
            uncompressed_bytes / compressed_bytes
    access
        "map" or "time_series".
    ntime
        Total time size. Needed for time_series mode unless max_time_chunk is given.
    max_time_chunk
        Optional cap for time chunk.
    max_cell_chunk
        Optional cap for cell chunk.

    Returns
    -------
    dict[str, int]
        Chunk sizes, e.g. {"time": 5, "cell": 786432}.
    """
    nside = 2**level
    ncell = 12 * nside * nside
    itemsize = np.dtype(dtype).itemsize

    target_stored_bytes = int(target_stored_mib * 1024 * 1024)
    target_uncompressed_bytes = int(target_stored_bytes * compression_ratio)

    if access == "map":
        cell_chunk = ncell if max_cell_chunk is None else min(ncell, max_cell_chunk)
        time_chunk = max(1, target_uncompressed_bytes // (itemsize * cell_chunk))
        return {"time": int(time_chunk), "cell": int(cell_chunk)}

    if access == "time_series":
        if max_time_chunk is not None:
            time_chunk = max_time_chunk
        elif ntime is not None:
            time_chunk = ntime
        else:
            raise ValueError("For access='time_series', provide either ntime or max_time_chunk.")

        if ntime is not None:
            time_chunk = min(time_chunk, ntime)

        cell_chunk = max(1, target_uncompressed_bytes // (itemsize * time_chunk))
        cell_chunk = min(cell_chunk, ncell)

        if max_cell_chunk is not None:
            cell_chunk = min(cell_chunk, max_cell_chunk)

        return {"time": int(time_chunk), "cell": int(cell_chunk)}

    raise ValueError(f"Unsupported access mode: {access!r}")