Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Overview

Within this notebook, we will cover:

  1. How to load a Kerchunk pre-generated reference file into Xarray as if it were a Zarr store.

Prerequisites

ConceptsImportanceNotes
Kerchunk BasicsRequiredCore
Xarray TutorialRequiredCore
  • Time to learn: 45 minutes


Opening Reference Dataset with Fsspec and Xarray

One way of using our reference dataset is opening it with Xarray. To do this, we will create an fsspec filesystem and pass it to Xarray.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[1], line 13
      9     remote_options={"anon": True},
     10     skip_instance_cache=True,
     11 )
     12 m = fs.get_mapper("")
---> 13 ds = xr.open_dataset(m, engine="zarr", backend_kwargs={"consolidated": False})

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/xarray/backends/api.py:619, in open_dataset(filename_or_obj, engine, chunks, cache, decode_cf, mask_and_scale, decode_times, decode_timedelta, use_cftime, concat_characters, decode_coords, drop_variables, create_default_indexes, inline_array, chunked_array_type, from_array_kwargs, backend_kwargs, **kwargs)
    607 decoders = _resolve_decoders_kwargs(
    608     decode_cf,
    609     open_backend_dataset_parameters=backend.open_dataset_parameters,
   (...)    615     decode_coords=decode_coords,
    616 )
    618 overwrite_encoded_chunks = kwargs.pop("overwrite_encoded_chunks", None)
--> 619 backend_ds = backend.open_dataset(
    620     filename_or_obj,
    621     drop_variables=drop_variables,
    622     **decoders,
    623     **kwargs,
    624 )
    625 ds = _dataset_from_backend_dataset(
    626     backend_ds,
    627     filename_or_obj,
   (...)    638     **kwargs,
    639 )
    640 return ds

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/xarray/backends/zarr.py:1747, in ZarrBackendEntrypoint.open_dataset(self, filename_or_obj, mask_and_scale, decode_times, concat_characters, decode_coords, drop_variables, use_cftime, decode_timedelta, group, mode, consolidated, storage_options, zarr_format, store, engine, use_zarr_fill_value_as_mask, cache_members)
   1745 filename_or_obj = _normalize_path(filename_or_obj)
   1746 if not store:
-> 1747     store = ZarrStore.open_group(
   1748         filename_or_obj,
   1749         group=group,
   1750         mode=mode,
   1751         consolidated=consolidated,
   1752         consolidate_on_close=False,
   1753         storage_options=storage_options,
   1754         use_zarr_fill_value_as_mask=None,
   1755         zarr_format=zarr_format,
   1756         cache_members=cache_members,
   1757     )
   1759 store_entrypoint = StoreBackendEntrypoint()
   1760 with close_on_error(store):

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/xarray/backends/zarr.py:797, in ZarrStore.open_group(cls, store, mode, group, consolidated, consolidate_on_close, storage_options, append_dim, write_region, safe_chunks, align_chunks, zarr_format, use_zarr_fill_value_as_mask, write_empty, cache_members)
    774 @classmethod
    775 def open_group(
    776     cls,
   (...)    790     cache_members: bool = True,
    791 ):
    792     (
    793         zarr_group,
    794         consolidate_on_close,
    795         close_store_on_close,
    796         use_zarr_fill_value_as_mask,
--> 797     ) = _get_open_params(
    798         store=store,
    799         mode=mode,
    800         group=group,
    801         consolidated=consolidated,
    802         consolidate_on_close=consolidate_on_close,
    803         storage_options=storage_options,
    804         use_zarr_fill_value_as_mask=use_zarr_fill_value_as_mask,
    805         zarr_format=zarr_format,
    806     )
    808     return cls(
    809         zarr_group,
    810         mode,
   (...)    819         cache_members=cache_members,
    820     )

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/xarray/backends/zarr.py:1951, in _get_open_params(store, mode, group, consolidated, consolidate_on_close, storage_options, use_zarr_fill_value_as_mask, zarr_format)
   1947 else:
   1948     # we have determined that we don't want to use consolidated metadata
   1949     # so we set that to False to avoid trying to read it
   1950     open_kwargs["use_consolidated"] = False
-> 1951     zarr_group = zarr.open_group(store, **open_kwargs)
   1953 close_store_on_close = zarr_group.store is not store
   1955 # we use this to determine how to handle fill_value

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/api/synchronous.py:567, in open_group(store, mode, cache_attrs, synchronizer, path, chunk_store, storage_options, zarr_format, meta_array, attributes, use_consolidated)
    496 def open_group(
    497     store: StoreLike | None = None,
    498     *,
   (...)    508     use_consolidated: bool | str | None = None,
    509 ) -> Group:
    510     """Open a group using file-mode-like semantics.
    511 
    512     Parameters
   (...)    564         The new group.
    565     """
    566     return Group(
--> 567         sync(
    568             async_api.open_group(
    569                 store=store,
    570                 mode=mode,
    571                 cache_attrs=cache_attrs,
    572                 synchronizer=synchronizer,
    573                 path=path,
    574                 chunk_store=chunk_store,
    575                 storage_options=storage_options,
    576                 zarr_format=zarr_format,
    577                 meta_array=meta_array,
    578                 attributes=attributes,
    579                 use_consolidated=use_consolidated,
    580             )
    581         )
    582     )

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/core/sync.py:155, in sync(coro, loop, timeout)
    152 return_result = next(iter(finished)).result()
    154 if isinstance(return_result, BaseException):
--> 155     raise return_result
    156 else:
    157     return return_result

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/core/sync.py:116, in _runner(coro)
    111 """
    112 Await a coroutine and return the result of running it. If awaiting the coroutine raises an
    113 exception, the exception will be returned.
    114 """
    115 try:
--> 116     return await coro
    117 except Exception as ex:  # noqa: BLE001 -- the caller re-raises the returned exception
    118     return ex

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/api/asynchronous.py:894, in open_group(store, mode, cache_attrs, synchronizer, path, chunk_store, storage_options, zarr_format, meta_array, attributes, use_consolidated)
    828 """Open a group using file-mode-like semantics.
    829 
    830 Parameters
   (...)    882     The new group.
    883 """
    885 _warn_unimplemented_kwargs(
    886     {
    887         "cache_attrs": cache_attrs,
   (...)    891     }
    892 )
--> 894 store_path = await make_store_path(store, mode=mode, storage_options=storage_options, path=path)
    895 if attributes is None:
    896     attributes = {}

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/storage/_common.py:481, in make_store_path(store_like, path, mode, storage_options)
    476     raise ValueError(
    477         "'path' was provided but is not used for FSMap store_like objects. Specify the path when creating the FSMap instance instead."
    478     )
    480 else:
--> 481     store = await make_store(store_like, mode=mode, storage_options=storage_options)
    482     return await StorePath.open(store, path=path_normalized, mode=mode)

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/storage/_common.py:413, in make_store(store_like, mode, storage_options)
    408         return FsspecStore.from_url(
    409             store_like, storage_options=storage_options, read_only=_read_only
    410         )
    412 elif _has_fsspec and isinstance(store_like, FSMap):
--> 413     return FsspecStore.from_mapper(store_like, read_only=_read_only)
    415 else:
    416     raise TypeError(f"Unsupported type for store_like: '{type(store_like).__name__}'")

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/storage/_fsspec.py:210, in FsspecStore.from_mapper(cls, fs_map, read_only, allowed_exceptions)
    186 @classmethod
    187 def from_mapper(
    188     cls,
   (...)    191     allowed_exceptions: tuple[type[Exception], ...] = ALLOWED_EXCEPTIONS,
    192 ) -> FsspecStore:
    193     """
    194     Create an FsspecStore from an FSMap object.
    195 
   (...)    208     FsspecStore
    209     """
--> 210     fs = _make_async(fs_map.fs)
    211     return cls(
    212         fs=fs,
    213         path=fs_map.root,
    214         read_only=read_only,
    215         allowed_exceptions=allowed_exceptions,
    216     )

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/zarr/storage/_fsspec.py:57, in _make_async(fs)
     52     return fs
     53 if fs.async_impl:
     54     # Convert sync instance of an async fs to an async instance. Reuse the original
     55     # constructor arguments rather than round-tripping through JSON, since storage
     56     # options may hold objects that are not JSON-serializable (e.g. credentials).
---> 57     return type(fs)(*fs.storage_args, **{**fs.storage_options, "asynchronous": True})
     59 if fsspec_version < parse_version("2024.12.0"):
     60     raise ImportError(
     61         f"The filesystem '{fs}' is synchronous, and the required "
     62         "AsyncFileSystemWrapper is not available. Upgrade fsspec to version "
     63         "2024.12.0 or later to enable this functionality."
     64     )

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/fsspec/spec.py:128, in _Cached.__call__(cls, *args, **kwargs)
    125         if inst is not None:
    126             return inst
--> 128 obj = super().__call__(*args, **kwargs, **strip_tokenize_options)
    129 # Setting _fs_token here causes some static linters to complain.
    130 obj._fs_token_ = token

File ~/micromamba/envs/kerchunk-cookbook/lib/python3.14/site-packages/fsspec/implementations/reference.py:785, in ReferenceFileSystem.__init__(self, fo, target, ref_storage_args, target_protocol, target_options, remote_protocol, remote_options, fs, template_overrides, simple_templates, max_gap, max_block, cache_size, **kwargs)
    783     self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
    784 elif self.asynchronous ^ f.asynchronous:
--> 785     raise ValueError(
    786         "Reference-FS's target filesystem must have same value "
    787         "of asynchronous"
    788     )

ValueError: Reference-FS's target filesystem must have same value of asynchronous

Opening Reference Dataset with Xarray and the Kerchunk Engine

As of writing, the latest version of Kerchunk supports opening an reference dataset with Xarray without specifically creating an fsspec filesystem. This is the same behavior as the example above, just a few less lines of code.