GeoZL in Zarr
- Python · CPU
- Open in Colab
- Notebook on GitHub
Zarr stores an array as a grid of chunks and runs every chunk through the codecs its metadata lists. This notebook adds GeoZL to those codecs, writes a Sentinel-2 cube over Lake Annecy with xarray, reads part of it back, and compares size and read speed with zstd and Blosc.
GeoZL is written once as a numcodecs codec, which serves Zarr 2 as it is and Zarr 3 through a short wrapper. The high-level notebook covers recipes and profile in more depth.
%pip install -q -U geozl "zarr==3.4.2" xarray dask rasterioimport json
import os
import shutil
import threading
import time
from dataclasses import dataclass
from pathlib import Path
import geozl
import matplotlib.pyplot as plt
import numcodecs
import numpy as np
import pandas as pd
import rasterio
import xarray as xr
import zarr
from numcodecs.abc import Codec
from numcodecs.compat import ndarray_copy
from rasterio.windows import Window
from zarr.abc.codec import ArrayBytesCodec
from zarr.codecs import BloscCodec
from zarr.registry import register_codec
from zarr.storage import MemoryStore
print("geozl", geozl.__version__, "· zarr", zarr.__version__,
"· numcodecs", numcodecs.__version__, "· xarray", xr.__version__)geozl 0.32.0 · zarr 3.4.2 · numcodecs 0.17.1 · xarray 2026.9.0
The cube
Four 10 m bands, blue, green, red and near infrared, from a clear Sentinel-2 L2A scene of 8 August 2025, read from the public copy on AWS. The window is 2048×2048 pixels, 20 km on a side, with Lake Annecy and the town at its north end, in uint16 reflectance. The coordinates are the UTM metres of each pixel centre.
base = ("https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/"
"31/T/GL/2025/8/S2A_31TGL_20250808_0_L2A/")
BANDS = ["B02", "B03", "B04", "B08"]
window = Window(3300, 800, 2048, 2048)
bands = []
for band in BANDS:
with rasterio.open(base + band + ".tif") as src:
bands.append(src.read(1, window=window))
transform, crs = src.window_transform(window), src.crs
x = transform.c + (np.arange(window.width) + 0.5) * transform.a
y = transform.f + (np.arange(window.height) + 0.5) * transform.e
cube = xr.DataArray(
np.stack(bands),
coords={"band": BANDS, "y": y, "x": x},
dims=("band", "y", "x"),
name="reflectance",
attrs={"crs": crs.to_string()},
)
print(cube.shape, cube.dtype, f"{cube.nbytes / 1e6:.1f} MB")(4, 2048, 2048) uint16 33.6 MB
def rgb(da):
"""Red, green and blue as an image, stretched for display."""
return np.clip(da.sel(band=["B04", "B03", "B02"]).transpose("y", "x", "band") / 2500, 0, 1)
plt.figure(figsize=(6, 6))
plt.imshow(rgb(cube))
plt.axis("off")
plt.show()Where a codec sits
A Zarr 3 array lists its codecs in zarr.json, and each chunk goes through them in order. There are three kinds. Array to array codecs change the samples and keep an array, such as a transpose. Exactly one array to bytes codec turns the chunk into bytes, and by default that is bytes, a plain memory copy. Bytes to bytes codecs then compress those bytes, zstd by default. The Zarr 3 spec defines the chain.
GeoZL predicts each sample from its neighbours, so it needs the chunk as a raster, with its dtype and its rows. A bytes to bytes codec never sees those, so GeoZL takes the array to bytes step and replaces both bytes and zstd.
numcodecs
numcodecs is the codec library Zarr grew up with. A codec there is a class with encode, decode and a JSON configuration whose id names it, and the registry finds a class by that id. A Zarr 2 array uses only numcodecs codecs, listed in .zarray as filters and one compressor. Zarr 3 reaches the same codecs under numcodecs. names, such as numcodecs.delta.
That makes numcodecs the place to write GeoZL once. encode gets a chunk and returns one GeoZL frame. decode returns the frame's bytes, as geozl.decompress does, and Zarr 2 applies the dtype and shape itself after every compressor.
Zarr 3 does not do that for an array to bytes codec, so a short serializer wraps the numcodecs codec and adds the dtype and shape on the way back. It is registered under the name geozl, and the custom codec guide covers the rest of the interface.
_local = threading.local()
class GeoZL(Codec):
"""GeoZL as a numcodecs codec. decode returns bytes, as geozl.decompress does."""
codec_id = "geozl"
def __init__(self, method="planar>zigzag>lanes"):
self.method = method
def encode(self, buf):
chunk = np.ascontiguousarray(buf)
chunk = chunk.reshape(-1, chunk.shape[-1]) # rows of samples
graphs = _local.__dict__.setdefault("graphs", {})
key = (self.method, chunk.dtype.str, chunk.shape)
if key not in graphs: # one graph per thread and chunk shape
graphs[key] = geozl.graph(chunk, self.method)
return geozl.compress(chunk, graph=graphs[key])
def decode(self, buf, out=None):
return ndarray_copy(geozl.decompress(buf), out)
numcodecs.register_codec(GeoZL)
@dataclass(frozen=True)
class GeoZLSerializer(ArrayBytesCodec):
"""The numcodecs codec as a Zarr 3 array to bytes step."""
method: str = "planar>zigzag>lanes"
is_fixed_size = False
@classmethod
def from_dict(cls, data):
return cls(**data.get("configuration", {}))
def to_dict(self):
return {"name": "geozl", "configuration": {"method": self.method}}
def compute_encoded_size(self, input_byte_length, chunk_spec):
raise NotImplementedError # not known before compressing
def _encode_sync(self, chunk, spec):
frame = GeoZL(self.method).encode(chunk.as_ndarray_like())
return spec.prototype.buffer.from_bytes(frame)
def _decode_sync(self, data, spec):
raw = GeoZL(self.method).decode(data.as_numpy_array())
chunk = raw.view(spec.dtype.to_native_dtype()).reshape(spec.shape)
return spec.prototype.nd_buffer.from_ndarray_like(chunk)
async def _encode_single(self, chunk, spec):
return self._encode_sync(chunk, spec)
async def _decode_single(self, data, spec):
return self._decode_sync(data, spec)
register_codec("geozl", GeoZLSerializer)The recipe
The codec takes one recipe, stored in the array's metadata. profile measures the candidates on one red-band chunk. The best ratio decodes slowly. planar>zigzag>lanes and planar>zigzag>pfor keep nearly all of it and decode several times faster, and the GPU decoder reads both, so the same chunks could later go straight to a GPU. The notebook uses lanes, since PFOR gives up more ratio on smoother rasters, such as a DEM.
rows = geozl.profile(np.ascontiguousarray(cube.values[2, 512:1024, 512:1024]), reps=3)
table = pd.DataFrame(rows).set_index("graph")[["ratio", "decode_mbps"]]
table.loc[[table.index[0], "planar>zigzag>lanes", "planar>zigzag>pfor"]].round(2)| ratio | decode_mbps | |
|---|---|---|
| graph | ||
| planar>zigzag>transpose>entropy | 1.79 | 1304.20 |
| planar>zigzag>lanes | 1.74 | 6808.93 |
| planar>zigzag>pfor | 1.70 | 7943.77 |
Write
Three Zarr 3 stores with the same 512×512 chunks, one band per chunk. One uses Zarr's default, bytes then zstd. One uses Blosc with zstd and byte shuffle, a common choice for imagery. One uses GeoZL. xarray writes the coordinates and attributes next to the array, and encoding sets the codecs of reflectance only.
CHUNKS = (1, 512, 512)
STORES = {
"zstd": {},
"blosc": {"compressors": BloscCodec(cname="zstd", clevel=5, shuffle="shuffle")},
"geozl": {"serializer": GeoZLSerializer(), "compressors": None},
}
for name, codecs in STORES.items():
path = Path(f"annecy_{name}.zarr")
shutil.rmtree(path, ignore_errors=True)
cube.to_dataset().to_zarr(
path,
zarr_format=3,
consolidated=False,
encoding={"reflectance": {"chunks": CHUNKS, **codecs}},
)
def stored(path):
chunks = Path(path, "reflectance", "c")
return sum(f.stat().st_size for f in chunks.rglob("*") if f.is_file())
size = {name: stored(f"annecy_{name}.zarr") for name in STORES}
for name, n in size.items():
print(f"{name:6} {n / 1e6:6.2f} MB ratio {cube.nbytes / n:.2f}")zstd 24.10 MB ratio 1.39 blosc 20.59 MB ratio 1.63 geozl 19.36 MB ratio 1.73
The codec and its recipe are all GeoZL adds to zarr.json.
meta = json.loads(Path("annecy_geozl.zarr/reflectance/zarr.json").read_text())
print(json.dumps(meta["codecs"], indent=2))[
{
"name": "geozl",
"configuration": {
"method": "planar>zigzag>lanes"
}
}
]The same numcodecs codec writes a Zarr 2 store with no wrapper, as its compressor. .zarray records it by id, the way Zarr 2 records every codec.
shutil.rmtree("annecy_v2.zarr", ignore_errors=True)
cube.to_dataset().to_zarr(
"annecy_v2.zarr",
zarr_format=2,
consolidated=False,
encoding={"reflectance": {"chunks": CHUNKS, "compressors": GeoZL()}},
)
meta = json.loads(Path("annecy_v2.zarr/reflectance/.zarray").read_text())
print(meta["compressor"]){'id': 'geozl', 'method': 'planar>zigzag>lanes'}Read
Opening a store is one line, as with any Zarr store. The codec must be registered in the session, which the codec cell did, and in a fresh session Zarr refuses the store and names the codec it is missing.
xarray opens the store lazily with dask, one dask chunk per Zarr chunk, so a selection only decodes the chunks it touches. The window below covers the north end of the lake and the town.
ds = xr.open_zarr("annecy_geozl.zarr", consolidated=False)
part = ds.reflectance.isel(y=slice(100, 900), x=slice(500, 1300))
print(f"{part.data.npartitions} of {ds.reflectance.data.npartitions} chunks decoded")24 of 64 chunks decoded
The window, true colour and NDVIcode
red, nir = part.sel(band="B04").astype("float32"), part.sel(band="B08").astype("float32")
ndvi = (nir - red) / (nir + red).clip(min=1)
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4.8))
left.imshow(rgb(part))
left.set_title("true colour", loc="left")
im = right.imshow(ndvi, cmap="RdYlGn", vmin=-0.5, vmax=1)
right.set_title("NDVI", loc="left")
fig.colorbar(im, ax=right, fraction=0.046)
for ax in (left, right):
ax.axis("off")
plt.tight_layout()
plt.show()Every store gives back exactly the samples that went in, the Zarr 2 one included.
for name in [*STORES, "v2"]:
back = xr.open_zarr(f"annecy_{name}.zarr", consolidated=False).reflectance.values
print(f"{name:6} identical: {np.array_equal(back, cube.values)}")zstd identical: True
blosc identical: True geozl identical: True v2 identical: True
Read speed
The clock should see decoding, not the disk. Each array is copied into a MemoryStore first, and the timed call reads the whole array with plain Zarr, best of seven. Speed is raw megabytes delivered per second.
The reads use Zarr's FusedCodecPipeline, which takes a thread count in codec_pipeline.max_workers. Each store is read once on one thread and once on every core. Zarr's Blosc codec turns off Blosc's own threads, so one thread means one thread for all three.
THREADS = os.cpu_count()
FUSED = "zarr.core.codec_pipeline.FusedCodecPipeline"
def to_memory(name):
src = zarr.open_array(f"annecy_{name}.zarr/reflectance", mode="r")
dst = zarr.create_array(MemoryStore(), shape=src.shape, chunks=src.chunks,
dtype=src.dtype, **STORES[name])
dst[:] = src[:]
return dst.store
def best_read(store, workers, reps=7):
with zarr.config.set({"codec_pipeline.path": FUSED, "codec_pipeline.max_workers": workers}):
z = zarr.open_array(store, mode="r")
z[:]
best = float("inf")
for _ in range(reps):
t = time.perf_counter()
z[:]
best = min(best, time.perf_counter() - t)
return best
rows = []
for name in STORES:
store = to_memory(name)
for workers in (1, THREADS):
s = best_read(store, workers)
rows.append({"codec": name, "threads": workers, "ratio": cube.nbytes / size[name],
"read MB/s": cube.nbytes / s / 1e6})
speed = pd.DataFrame(rows).round(2)
speed| codec | threads | ratio | read MB/s | |
|---|---|---|---|---|
| 0 | zstd | 1 | 1.39 | 1166.97 |
| 1 | zstd | 10 | 1.39 | 6897.40 |
| 2 | blosc | 1 | 1.63 | 1360.64 |
| 3 | blosc | 10 | 1.63 | 7506.30 |
| 4 | geozl | 1 | 1.73 | 3162.37 |
| 5 | geozl | 10 | 1.73 | 10397.76 |
Stored size and read speedcode
COLORS = {"zstd": "#8A8F98", "blosc": "#E0532A", "geozl": "#492AE8"}
names = list(STORES)
panels = [
("Stored size (MB)", [size[n] / 1e6 for n in names]),
("Read, 1 thread (MB/s)",
[speed.query("codec == @n and threads == 1")["read MB/s"].item() for n in names]),
(f"Read, {THREADS} threads (MB/s)",
[speed.query("codec == @n and threads == @THREADS")["read MB/s"].item() for n in names]),
]
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
for ax, (title, values) in zip(axes, panels, strict=True):
bars = ax.bar(names, values, color=[COLORS[n] for n in names], width=0.55)
ax.bar_label(bars, fmt="%.0f" if max(values) > 100 else "%.1f", padding=3, color="#3d3d3a")
ax.set_title(title, loc="left", fontsize=11)
ax.spines[["top", "right", "left"]].set_visible(False)
ax.tick_params(axis="y", length=0, labelleft=False)
ax.set_ylim(0, max(values) * 1.18)
plt.tight_layout()
plt.show()Speeds depend on the machine and its SIMD path, so compare rows from one run only. A free Colab runtime has two cores.
What this example leaves out
- Lossy recipes.
geozl.graphtakes the lossy range from the raster it is built on. A codec builds its graph per chunk, so the range would have to live in the codec configuration. The near-lossless page explains the range. - Installing the codec. Here the codec is defined in the notebook. A package would declare it under the
zarr.codecsandnumcodecs.codecsentry points, so that installing it is enough for Zarr to open the store. - Other readers. A Zarr reader in another language needs its own GeoZL codec. GeoZL also has C, R, Julia and JavaScript bindings to build one on.