High-level API
- Python · CPU
- Open in Colab
- Notebook on GitHub
GeoZL compresses a raster tile through an OpenZL graph chosen for that data. This notebook runs the four high-level calls on a Copernicus DEM tile. profile measures the candidate recipes, graph builds the one you pick, compress runs a tile through it, and decompress gives the bytes back.
%pip install -q -U geozl rasterioimport geozl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rasterio
import seaborn as sns
from rasterio.windows import Window
geozl.__version__'0.32.0'
GeoZL ships each decoder more than once. A plain C version, scalar, runs on any CPU. Vector versions handle 8 to 16 values per instruction and decode several times faster, with sse2 and avx2 on Intel and AMD and neon on ARM chips such as Apple silicon.
simd_info lists the versions this package was built with (built), the ones this CPU supports (cpu) and the one in use (active), which is the fastest in both lists. The output below comes from an Apple laptop, so it shows neon. Colab runs on Intel or AMD and usually shows avx2. Set GEOZL_SIMD=scalar before import geozl to force the plain version, for example to compare speeds.
geozl.simd_info(){'built': ['scalar', 'neon'], 'cpu': ['scalar', 'neon'], 'active': 'neon'}The tile
A 512×512 window of the Copernicus GLO-30 DEM over the French Alps near Albertville, read from the public copy on AWS. Elevation in whole metres fits in int16, and smooth terrain leaves small residuals once each pixel is predicted from its neighbours.
url = ("https://copernicus-dem-30m.s3.amazonaws.com/"
"Copernicus_DSM_COG_10_N45_00_E006_00_DEM/"
"Copernicus_DSM_COG_10_N45_00_E006_00_DEM.tif")
with rasterio.open(url) as src:
tile = np.round(src.read(1, window=Window(1000, 1000, 512, 512))).astype(np.int16)
raw = tile.nbytes
print(tile.shape, tile.dtype, f"{raw/1e6:.2f} MB")(512, 512) int16 0.52 MB
plt.imshow(tile, cmap="terrain")
plt.colorbar()<matplotlib.colorbar.Colorbar at 0x1154bfcb0>
What a graph is
Most codecs are one fixed algorithm. DEFLATE, zstd or a Blosc setting run the same steps on every tile, whatever the data looks like. GeoZL builds on OpenZL, where a compressor is a graph of small codecs chained together, and the recipe string names that chain. Since every tile can get its own chain, GeoZL tries many of them and keeps the one that fits the data best.
The predictors page shows what each predictor reads, the streams page covers the backends, and How PivCo works explains the coder inside lanes.
profile measures the candidates
profile compresses and decompresses the tile with every graph that applies and returns one row per graph, best ratio first. prior=None tries every predictor, and reps=5 keeps the fastest of five runs. The timing runs in C, so Python overhead stays out of the numbers. The Python reference lists the other arguments.
Each row has ratio (raw size over compressed size), encode_mbps, decode_mbps and shannon_pct.
shannon_pct compares the frame with a simple limit. Count how often each byte value appears in the tile, and Shannon's formula gives the smallest size a coder can reach when it codes each byte on its own from those counts alone. That size is the tile's order-0 entropy, and shannon_pct is that size over the frame size, in per cent (code).
- 100 means the graph matched that limit.
- Below 100 means it did worse than a perfect byte-by-byte coder.
- Above 100 means it beat the limit, which only works by using structure between samples, such as neighbouring pixels being alike. The best graphs here reach about 350, so their frames are three and a half times smaller than any byte-by-byte coder could make them.
rows = geozl.profile(tile, prior=None, reps=5)
print(rows)input shape (512, 512) [rows, columns] dtype int16 [2 bytes/sample] raw 0.52 MB profile 1 plane · row width 512 · all predictors · 5 reps · lossless graph ratio enc MB/s dec MB/s shan% wp_static>zigzag>entropy 4.53 134.0 2131.3 349 wp_static>zigzag>categorical 4.53 110.5 2122.6 349 wp_static>zigzag>sparse 4.53 110.5 2131.3 349 wp_static>zigzag>transpose>entropy 4.51 121.0 1074.4 347 planar>zigzag>entropy 4.50 622.7 2582.7 346 planar>zigzag>categorical 4.50 279.0 2508.6 346 planar>zigzag>sparse 4.50 302.7 2647.9 346 planar>zigzag>transpose>entropy 4.50 1142.2 2212.2 346 planar>zigzag>lanes 4.40 609.6 7489.8 339 wp_static>zigzag>lanes 4.36 105.8 3102.3 335 wp_static>zigzag>transpose>zstd 4.21 87.7 1839.6 324 planar>zigzag>transpose>zstd 4.14 224.9 1846.1 319 med>zigzag>transpose>zstd 3.87 231.6 1281.9 298 med>zigzag>entropy 3.84 563.1 1464.5 295 med>zigzag>categorical 3.84 295.0 1493.7 295 med>zigzag>sparse 3.84 306.1 1528.5 295 med>zigzag>transpose>entropy 3.84 1213.6 1351.3 295 wp_static>zigzag>field_lz 3.83 68.0 1927.5 294 wp_static>zigzag>pfor 3.74 127.2 6096.4 287 med>zigzag>lanes 3.72 566.2 1978.4 286 planar>zigzag>pfor 3.72 729.2 9039.5 286 average>zigzag>transpose>zstd 3.71 231.4 1129.9 286 planar>zigzag>field_lz 3.71 126.7 1383.3 285 med>zigzag>field_lz 3.58 125.1 956.7 275 average>zigzag>field_lz 3.58 123.9 1054.9 275 delta_w>zigzag>transpose>zstd 3.46 252.2 2072.3 266 wp_static>zigzag>zstd 3.45 71.3 1191.6 266 delta_n>zigzag>transpose>zstd 3.45 246.3 1920.5 265 delta_n>zigzag>field_lz 3.40 124.8 1765.3 262 planar>zigzag>zstd 3.39 139.5 1254.3 261 average>zigzag>transpose>entropy 3.33 798.0 771.0 256 delta_w>zigzag>field_lz 3.29 126.0 1807.9 253 med>zigzag>pfor 3.29 1048.6 2945.4 253 delta_1d>field_lz 3.29 130.5 1747.6 253 average>zigzag>entropy 3.28 1659.1 1183.5 252 average>zigzag>categorical 3.28 479.2 1183.5 252 average>zigzag>sparse 3.28 478.4 1197.0 252 med>zigzag>zstd 3.28 138.4 943.0 252 average>zigzag>zstd 3.25 136.6 807.8 250 delta_w>zigzag>transpose>entropy 3.24 810.3 1178.2 249 average>zigzag>lanes 3.22 385.8 1502.3 247 delta_w>zigzag>entropy 3.20 1569.7 2157.6 246 delta_w>zigzag>categorical 3.20 465.6 2114.1 246 delta_w>zigzag>sparse 3.20 433.7 2148.7 246 delta_1d>entropy 3.20 683.6 967.3 246 delta_1d>categorical 3.20 371.8 987.4 246 delta_1d>sparse 3.20 330.2 970.9 246 delta_n>zigzag>transpose>entropy 3.12 1245.3 1985.9 240 delta_w>zigzag>lanes 3.12 380.2 3799.2 240 delta_n>zigzag>zstd 3.10 136.7 1245.3 239 delta_n>zigzag>entropy 3.06 1593.6 2240.5 236 delta_n>zigzag>categorical 3.06 412.5 2279.5 236 delta_n>zigzag>sparse 3.06 437.3 2269.6 236 delta_w>zigzag>zstd 3.05 135.8 1222.1 235 delta_1d>zstd 3.03 140.0 1144.7 233 average>zigzag>pfor 3.02 905.5 1949.0 232 delta_n>zigzag>lanes 3.01 423.8 4297.4 232 delta_w>zigzag>pfor 2.93 859.5 10280.1 225 delta_1d>transpose>zstd 2.90 152.2 1379.7 223 delta_n>zigzag>pfor 2.79 1014.1 11915.6 215 delta_1d>transpose>entropy 2.70 838.9 1251.3 208 delta_1d>lanes 2.46 290.0 2978.9 189 id>field_lz 2.15 112.0 1489.5 165 id>transpose>zstd 2.06 293.7 6168.1 159 id>zstd 1.91 149.0 1152.3 147 id>transpose>entropy 1.59 996.7 1833.2 122 id>entropy 1.54 1795.5 2427.3 119 id>categorical 1.54 496.5 2438.5 119 id>sparse 1.54 460.3 2427.3 119 id>lanes 1.51 429.0 4405.8 116 id>pfor 1.50 1036.1 27594.2 115 delta_1d>pfor 1.45 510.0 3566.6 111
Compare the top rows with id>transpose>zstd, which predicts nothing and shuffles bytes before zstd, close to a Blosc setup. The plot shows the same rows as ratio against decode speed.
Compression ratio against decode speedcode
COLORS = {"planar": "#492AE8", "wp_static": "#128A6E", "med": "#E0532A",
"average": "#B7791F", "delta_w": "#D6409F", "delta_n": "#2B8CBE",
"delta_1d": "#7A7F87", "id": "#111111"}
def frontier(df):
"""Graphs that no other graph beats on both ratio and decode speed."""
keep, best = [], 0.0
for name, r in df.sort_values("ratio", ascending=False).iterrows():
if r["decode_mbps"] > best:
keep.append(name)
best = r["decode_mbps"]
return df.loc[keep].sort_values("decode_mbps")
def pareto(rows):
df = pd.DataFrame(rows)
df["predictor"] = df["graph"].str.split(">").str[0]
front = frontier(df)
fig, (ax, side) = plt.subplots(
1, 2, figsize=(11, 5.2), gridspec_kw={"width_ratios": [1.3, 1]})
ax.scatter(df["decode_mbps"], df["ratio"], s=20, color="#CDD2D9", zorder=1)
ax.step(front["decode_mbps"], front["ratio"], where="post",
color="#5C6370", lw=1.2, zorder=2)
for _, r in front.iterrows():
ax.scatter(r["decode_mbps"], r["ratio"], s=95,
color=COLORS[r["predictor"]], edgecolor="white", lw=1.5,
zorder=3)
# Graphs that tie on ratio and speed sit on one spot, so they share a label.
groups = []
for i, (_, r) in enumerate(front.iterrows(), 1):
last = groups[-1] if groups else None
if (last and abs(r["ratio"] - last["ratio"]) < 0.02
and r["decode_mbps"] < last["decode_mbps"] * 1.4):
last["last"] = i
else:
groups.append({"first": i, "last": i, "ratio": r["ratio"],
"decode_mbps": r["decode_mbps"]})
for k, g in enumerate(groups):
text = str(g["first"]) if g["first"] == g["last"] else f"{g['first']}-{g['last']}"
ax.annotate(text, (g["decode_mbps"], g["ratio"]),
xytext=(0, 10) if k % 2 == 0 else (0, -17),
textcoords="offset points", ha="center", fontsize=10,
weight="bold", color="#111111", zorder=4)
ax.set_xscale("log")
ax.set_xlabel("decode MB/s", fontsize=11)
ax.set_ylabel("compression ratio", fontsize=11)
ax.tick_params(labelsize=10)
ax.grid(color="#E6E8EC", lw=0.8)
ax.set_axisbelow(True)
for spine in ("top", "right"):
ax.spines[spine].set_visible(False)
ax.set_title(f"{len(df)} graphs, {len(front)} on the frontier",
loc="left", fontsize=11, color="#5C6370")
side.axis("off")
side.text(0, 0.97, "frontier, slowest to fastest", fontsize=10,
color="#5C6370", transform=side.transAxes)
for i, (_, r) in enumerate(front.iterrows(), 1):
y = 0.87 - 0.082 * (i - 1)
side.scatter([0.015], [y], s=55, color=COLORS[r["predictor"]],
transform=side.transAxes, clip_on=False)
side.text(0.05, y, f"{i:>2} {r['graph']}", fontsize=9.5,
family="monospace", va="center", transform=side.transAxes)
side.text(1.0, y, f"{r['ratio']:.2f}x {r['decode_mbps']:>6,.0f} MB/s",
fontsize=9.5, family="monospace", va="center", ha="right",
color="#5C6370", transform=side.transAxes)
fig.suptitle("Each dot is a graph. The line joins the ones that no other "
"graph beats on both ratio and decode speed.",
x=0.01, ha="left", fontsize=11)
fig.tight_layout()
plt.show()
pareto(rows)graph builds one recipe
graph builds one recipe and returns a handle, and compress runs a tile through it. The search happens in profile and the build in graph, so compress only compresses.
Pass the recipe exactly as the graph column spells it. It also has to fit the element width. transpose needs 2 to 8 bytes per sample and refuses a uint8 tile, categorical takes 1 or 2, and pfor takes 1, 2, 4 or 8.
best = rows[0]['graph'] # the top row of profile
g = geozl.graph(tile, best) # build that graph once
frame = geozl.compress(tile, graph=g) # compress with it
print(best, f"{raw/len(frame):.2f}x")wp_static>zigzag>entropy 4.53x
error trades exactness for size
Pass the same error to profile and graph to build a lossy graph. A number such as 2.5 bounds the absolute error with LINEAR, and a percentage such as "1%" bounds the relative error with LOG. SQRT and the other options take a full recipe string, described on the near-lossless page. The tile passed to graph fixes the value range, so compress refuses a later tile outside it.
| recipe | guarantee | for |
|---|---|---|
LINEAR:MAX_ERROR=V | |x-x̂| ≤ V | elevation, temperature |
LOG:MAX_ERROR=P% | |x-x̂| ≤ P/100 |x| | data spanning decades, precipitation |
SQRT:MAX_ERROR=kN | |x-x̂| ≤ k√(a+bx) | photon-counting sensors |
The next cell sweeps LINEAR and SQRT on this tile up to 20 m of worst-case error. LOG is left out, since its error grows with the value and these elevations all sit in one decade, between 300 and 2300 m.
Compression ratio against error, LINEAR and SQRTcode
CEILING = 20.0 # metres of worst case, the top of every sweep
src = tile.astype(np.float64)
top = float(src.max())
curve = geozl.lossy.fit_noise(tile) # sigma^2 = a + b*x, for SQRT
sigma = float(np.sqrt(curve.a + curve.b * top))
# Each family states its bound in its own unit, so the ceiling is converted into
# each one before the sweep. LINEAR delivers its bound exactly. SQRT states its
# bound at the largest sample and an integer raster rounds the reconstruction to
# a whole number, so the delivered worst case comes out near half, hence the 2.
# The filter after the loop is what holds the ceiling, this only aims the ladder.
HEAD = {"LINEAR": CEILING,
"SQRT": 2 * CEILING / sigma}
LADDER = np.geomspace(1 / 16, 1, 7)
FAMILIES = {
"LINEAR": [f"LINEAR:MAX_ERROR={HEAD['LINEAR'] * t:.4g}" for t in LADDER],
"SQRT": [curve.recipe(HEAD["SQRT"] * t) for t in LADDER],
}
COLORS = {"LINEAR": "#E0532A", "SQRT": "#128A6E"}
def budget_of(recipe):
"""The number the recipe asked for. Noise.recipe writes A and B at full
precision, so the count of sigmas comes out long and is rounded here."""
asked = recipe.split("MAX_ERROR=")[1].split(",")[0]
unit = asked[-1] if asked[-1] in "%N" else ""
return f"{float(asked.rstrip('%N')):.3g}{unit}"
lossless = len(geozl.compress(tile, graph=geozl.graph(tile, best)))
sweep = []
for family, recipes in FAMILIES.items():
for recipe in recipes:
# one graph per recipe, since every recipe is a different quantizer
g = geozl.graph(tile, best, error=recipe)
frame = geozl.compress(tile, graph=g)
back = geozl.decompress(frame).view(tile.dtype).reshape(tile.shape)
e = np.abs(back.astype(np.float64) - src)
sweep.append(dict(family=family, recipe=recipe, size=len(frame),
ratio=raw / len(frame), maxabs=float(e.max()),
rmse=float(np.sqrt((e ** 2).mean()))))
over = [r for r in sweep if r["maxabs"] > CEILING]
sweep = [r for r in sweep if r["maxabs"] <= CEILING]
if over:
print(f"{len(over)} recipes dropped, past the {CEILING:g} m ceiling")
sns.set_theme(style="whitegrid", font_scale=0.95)
fig, ax = plt.subplots(figsize=(9.5, 5.6))
ax.axhline(raw / lossless, color="0.55", ls="--", lw=1.2)
ax.annotate(f"lossless {raw / lossless:.2f}x",
(max(r["rmse"] for r in sweep), raw / lossless), xytext=(0, 7),
textcoords="offset points", ha="right", color="0.45", fontsize=9)
for family in FAMILIES:
pts = sorted((r for r in sweep if r["family"] == family),
key=lambda r: r["rmse"])
ax.plot([r["rmse"] for r in pts], [r["ratio"] for r in pts],
color=COLORS[family], lw=2, marker="o", ms=5, label=family,
zorder=3)
# the budget at each end, so the recipe can be read off the curve
for r, dy in ((pts[0], 10), (pts[-1], -16)):
ax.annotate(budget_of(r["recipe"]), (r["rmse"], r["ratio"]),
xytext=(0, dy), textcoords="offset points", ha="center",
fontsize=8, color=COLORS[family])
ax.set_xscale("log")
ax.set_xlabel("RMSE after the round trip (metres)")
ax.set_ylabel("compression ratio")
ax.set_title(f"two error curves on one raster, capped at {CEILING:g} m of "
f"worst case", loc="left", fontsize=12)
ax.legend(frameon=False, loc="upper left")
ax.grid(alpha=0.25)
fig.text(0.005, 0.955, "each line is one family swept over its own budget. "
"Same distortion on x, so the highest line wins.",
fontsize=9, color="0.4", ha="left")
fig.tight_layout(rect=(0, 0, 1, 0.94))
plt.show()
print(f"max {top:.0f} m, sigma at the top {sigma:.2f} m")
print(f"{'family':7} {'budget':9} {'rmse':>7} {'max':>6} {'ratio':>7}")
for r in sweep:
print(f"{r['family']:7} {budget_of(r['recipe']):9} {r['rmse']:7.2f} "
f"{r['maxabs']:6.0f} {r['ratio']:7.2f}")max 2274 m, sigma at the top 0.80 m family budget rmse max ratio LINEAR 1.25 0.70 1 6.04 LINEAR 1.98 0.82 1 7.17 LINEAR 3.15 1.78 3 9.73 LINEAR 5 2.92 5 10.92 LINEAR 7.94 4.34 7 11.42 LINEAR 12.6 7.23 12 11.86 LINEAR 20 11.63 20 13.06 SQRT 3.14N 0.73 1 6.13 SQRT 4.98N 1.02 2 7.67 SQRT 7.9N 1.58 3 9.39 SQRT 12.5N 2.48 5 10.59 SQRT 19.9N 3.92 8 11.32 SQRT 31.6N 6.22 12 11.79 SQRT 50.2N 9.80 20 12.75
decompress returns the bytes
GeoZL works one level below the array. A tile enters OpenZL as a numeric stream with one property, the bytes per element. An int16 and a uint16 are both 2-byte elements to the frame. It stores the exact bytes, but not the sign and not that they were 512×512 rather than a flat vector.
So decompress returns what the frame holds, a flat uint8 array, and you add the two facts it never had.
.view(dtype)reads the elements with the right type. Read asuint16instead ofint16, a −1000 becomes 64536..reshape(shape)puts the rows back.
GeoZL does not store dtype or shape in the frame. A dataset container keeps them and applies .view and .reshape after decoding.
# the sweep left a lossy frame behind, so build the lossless one again
frame = geozl.compress(tile, graph=geozl.graph(tile, best))
back = geozl.decompress(frame)
print(back.dtype, back.shape) # uint8, flat
out = back.view(tile.dtype).reshape(tile.shape)
print(out.dtype, out.shape, np.array_equal(out, tile))
outuint8 (524288,) int16 (512, 512) True
array([[1021, 1013, 1008, ..., 490, 498, 512],
[1005, 998, 992, ..., 498, 508, 520],
[ 986, 980, 972, ..., 501, 512, 525],
...,
[ 297, 298, 298, ..., 1018, 1016, 1019],
[ 298, 301, 306, ..., 1002, 996, 1000],
[ 310, 305, 305, ..., 1009, 1000, 992]],
shape=(512, 512), dtype=int16)The whole loop
Measure once, build once, then compress every tile with the same graph.
ERROR = 2.5
rows = geozl.profile(tile, prior=None, error=ERROR, reps=1) # the slow call, run once
best = rows[0]['graph'] # the winning recipe
g = geozl.graph(tile, best, error=ERROR) # the build, run once
frame = geozl.compress(tile, graph=g) # the fast call, run always
back = geozl.decompress(frame).view(tile.dtype).reshape(tile.shape)
err = np.abs(back.astype(np.int32) - tile.astype(np.int32)).max()
print(best, f"{raw/len(frame):.2f}x lossy")
print(f"{len(frame)/1e6:.2f} MB")
print(f"max error {err} bound {ERROR}")wp_static>zigzag>transpose>entropy 9.34x lossy 0.06 MB max error 2 bound 2.5
fig, ax = plt.subplots(1, 3, figsize=(10, 5))
ax[0].imshow(tile, cmap="terrain")
ax[0].set_title("original")
ax[1].imshow(back, cmap="terrain")
ax[1].set_title("reconstructed")
ax[2].imshow(tile - back, cmap="bwr", vmin=-5, vmax=5)
ax[2].set_title("error")
plt.tight_layout()
plt.show()