GeoZL

Compress and decompress

  • One tile through GeoZL in Python, R and Julia, from a recipe to a checked round trip.

These examples compress one tile, pick a recipe for it, mask missing samples, bound the error, stack bands and limit the size of untrusted frames. Each example comes in Python, R and Julia. The three packages write the same frames, so a tile compressed in one language decodes in the others.

Installation

pip install geozl
install.packages("geozl", repos = "https://asterisk-labs.r-universe.dev")
using Pkg
Pkg.Registry.add(url = "https://github.com/asterisk-labs/AsteriskRegistry")
Pkg.add("GeoZL")
import numpy as np
import geozl
library(geozl)
using GeoZL

Shapes. These examples use (Y, X) and (B, Y, X) in Python, and (X, Y) and (X, Y, B) in R and Julia. The samples are laid out in the same order, so they give the same frame. Arrays from raster packages may need rearranging first; see R and Julia.

One tile

The tile is a synthetic 256 by 256 int16 elevation model, a gentle slope with a little noise. A graph fixes the recipe, the dtype and the row width, so build it once and reuse it for every tile of the same kind.

y, x = np.mgrid[0:256, 0:256]
tile = (1200 + 2 * x + 3 * y + (7919 * x + 104729 * y) ** 2 % 13).astype(np.int16)

g = geozl.graph(tile, "planar>zigzag>zstd")
frame = geozl.compress(tile, graph=g)
back = geozl.decompress(frame).view(tile.dtype).reshape(tile.shape)

assert np.array_equal(back, tile)
print(len(frame))                           # 204
tile <- outer(0:255, 0:255, function(x, y) {
  1200 + 2 * x + 3 * y + (7919 * x + 104729 * y)^2 %% 13
})

g <- geozl_graph(tile, "planar>zigzag>zstd", dtype = "int16")
frame <- geozl_compress(tile, g)
back <- geozl_decompress(frame, "int16", dim = dim(tile))

stopifnot(identical(back, tile))
length(frame)                               # 204
tile = [Int16(1200 + 2x + 3y + (7919x + 104729y)^2 % 13) for x in 0:255, y in 0:255]

g = GeoZL.graph(tile, "planar>zigzag>zstd")
frame = GeoZL.compress(tile, g)
back = GeoZL.decompress(Int16, frame, size(tile))

@assert back == tile
length(frame)                               # 204

The frame stores neither the dtype nor the shape. Keep both next to it, in a catalog, a file header or a database row, and pass them back to decompress. This R tile is stored as doubles, so dtype names the sample type to encode. Python and Julia take it from the array.

The tile is smooth on purpose, so 128 KiB shrinks to 204 bytes. Real elevation data usually has a much lower compression ratio.

Choosing a recipe

A recipe names the codecs in the order data flows through them. Most read predictor>zigzag>terminal. The predictor turns samples into small residuals, zigzag folds signed residuals into small unsigned numbers, and the terminal stores them. id>terminal skips the prediction. graph lists every predictor and terminal.

Profile tries the recipes on a sample tile and ranks them by ratio. The default prior tries planar and the id path. Pass another predictor, or none to try them all.

rows = geozl.profile(tile, reps=1)
print(rows)                                 # settings, then one line per recipe
best = rows[0]["graph"]                     # 'planar>zigzag>transpose>zstd'

every = geozl.profile(tile, prior=None, reps=1)
rows <- geozl_profile(tile, dtype = "int16", reps = 1)
print(rows)                                 # settings, then one line per recipe
best <- rows$graph[[1]]                     # "planar>zigzag>transpose>zstd"

every <- geozl_profile(tile, prior = NULL, dtype = "int16", reps = 1)
rows = GeoZL.profile(tile; reps = 1)
display(rows)                               # settings, then one line per recipe
best = rows[1].graph                        # "planar>zigzag>transpose>zstd"

every = GeoZL.profile(tile; prior = nothing, reps = 1)

Each row gives the recipe, the compressed bytes, the ratio, the encode and decode speed in MB/s, and the ratio as a share of the Shannon bound. Ratio is the same on every machine. Speed is not, so profile on the machine that will decode. reps sets how many round trips each recipe gets, and the fastest one counts.

Profile once per product, not per tile. Tiles of one product usually agree on a recipe, and a graph is cheap to reuse but not free to build.

NoData

A hole filled with a sentinel such as −32768 is a cliff to a predictor, and the residuals around it cost bits. nodata adds the nodata codec in front. It moves the holes to a mask and fills them from their neighbours, so the predictor sees a smooth surface.

hole = tile.copy()
hole[100:140, 50:90] = -32768

g = geozl.graph(hole, "planar>zigzag>zstd", nodata=-32768)
frame = geozl.compress(hole, graph=g)
back = geozl.decompress(frame).view(np.int16).reshape(hole.shape)

assert np.array_equal(back, hole)
missing = back == -32768
hole <- tile
hole[51:90, 101:140] <- NA

g <- geozl_graph(hole, "planar>zigzag>zstd", nodata = -32768, dtype = "int16")
frame <- geozl_compress(hole, g)
back <- geozl_decompress(frame, "int16", dim = dim(hole), nodata = -32768)

stopifnot(identical(back, hole))
missing <- is.na(back)
hole = Array{Union{Missing,Int16}}(tile)
hole[51:90, 101:140] .= missing

g = GeoZL.graph(hole, "planar>zigzag>zstd"; nodata = -32768)
frame = GeoZL.compress(hole, g)
back = GeoZL.decompress(Int16, frame, size(hole); nodata = -32768)

@assert isequal(back, hole)
missing_mask = ismissing.(back)

The sentinel comes back exactly. Python returns it as a number. R turns it into NA and Julia into missing when decompress gets the same nodata. A float raster with NaN holes gets the mask without asking.

Bounded error

Lossless is the default. error adds a quantizer right after the nodata step and keeps finite, unmasked samples within the bound you give. A number is an absolute bound, a percentage is a bound relative to each value, and a full recipe picks the quantizer by name. Near-lossless explains the three.

g = geozl.graph(tile, "planar>zigzag>zstd", error=2)
frame = geozl.compress(tile, graph=g)
back = geozl.decompress(frame).view(np.int16).reshape(tile.shape)

print(g.error)                              # LINEAR:MAX_ERROR=2
assert np.abs(back.astype(int) - tile).max() <= 2

relative = geozl.graph(tile, "planar>zigzag>zstd", error="1%")
same = geozl.graph(tile, "planar>zigzag>zstd", error="LINEAR:MAX_ERROR=2")
g <- geozl_graph(tile, "planar>zigzag>zstd", error = 2, dtype = "int16")
frame <- geozl_compress(tile, g)
back <- geozl_decompress(frame, "int16", dim = dim(tile))

g$error                                     # "LINEAR:MAX_ERROR=2"
stopifnot(max(abs(back - tile)) <= 2)

relative <- geozl_graph(tile, "planar>zigzag>zstd", error = "1%", dtype = "int16")
same <- geozl_graph(tile, "planar>zigzag>zstd", error = "LINEAR:MAX_ERROR=2",
                    dtype = "int16")
g = GeoZL.graph(tile, "planar>zigzag>zstd"; error = 2)
frame = GeoZL.compress(tile, g)
back = GeoZL.decompress(Int16, frame, size(tile))

g.error                                     # "LINEAR:MAX_ERROR=2"
@assert maximum(abs.(Int.(back) .- tile)) <= 2

relative = GeoZL.graph(tile, "planar>zigzag>zstd"; error = "1%")
same = GeoZL.graph(tile, "planar>zigzag>zstd"; error = "LINEAR:MAX_ERROR=2")

The tile you build a lossy graph from also fixes the range later tiles must stay inside, and compress refuses a tile outside it. Build the graph from data that spans the whole product.

Several bands

A stack of bands is one frame. Each band is a plane, and row predictors start again at the top of every plane. The plane count defaults to the band axis.

stack = np.stack([tile, tile + 40, tile + 90])        # (B, Y, X)

per_band = geozl.graph(stack, "planar>zigzag>zstd")
across = geozl.graph(stack, "planar>zigzag>zstd", width=256 * 256, planes=1)

print(len(geozl.compress(stack, graph=per_band)))     # 235
print(len(geozl.compress(stack, graph=across)))       # 197
stack <- array(c(tile, tile + 40, tile + 90), dim = c(256, 256, 3))   # (X, Y, B)

per_band <- geozl_graph(stack, "planar>zigzag>zstd", dtype = "int16")
across <- geozl_graph(stack, "planar>zigzag>zstd", width = 256 * 256, planes = 1,
                      dtype = "int16")

length(geozl_compress(stack, per_band))               # 235
length(geozl_compress(stack, across))                 # 197
stack = cat(tile, tile .+ Int16(40), tile .+ Int16(90); dims = 3)   # (X, Y, B)

per_band = GeoZL.graph(stack, "planar>zigzag>zstd")
across = GeoZL.graph(stack, "planar>zigzag>zstd"; width = 256 * 256, planes = 1)

length(GeoZL.compress(stack, per_band))               # 235
length(GeoZL.compress(stack, across))                 # 197

With width set to a whole band and one plane, the row above a pixel is the same pixel in the band before. That wins here because the bands differ by a constant. When bands do not look alike, keep the default. Profile takes width and planes too, so compare both there.

Coefficients in the frame

A frame can carry a few integer vectors in its header, such as a scale and an offset, or the index of the tile. GeoZL stores them and gives them no meaning. Reading them back touches only the header.

g = geozl.graph(tile, "planar>zigzag>zstd")
frame = geozl.compress(tile, graph=g, coeffs=[[10, -3], [7]])

geozl.coeffs(frame)                         # ((10, -3), (7,))
g <- geozl_graph(tile, "planar>zigzag>zstd", dtype = "int16")
frame <- geozl_compress(tile, g, coeffs = list(c(10L, -3L), 7L))

geozl_coeffs(frame)                         # list(c(10L, -3L), 7L)
g = GeoZL.graph(tile, "planar>zigzag>zstd")
frame = GeoZL.compress(tile, g; coeffs = ([10, -3], [7]))

@assert GeoZL.coeffs(frame) == [Int32[10, -3], Int32[7]]

Untrusted frames

Checksums are verified by default. A frame also declares how many bytes it decodes to, and that number comes from whoever wrote it. Pass max_output_size for frames from outside your process, so a hostile frame cannot ask for a huge buffer.

back = geozl.decompress(frame, max_output_size=tile.nbytes)

try:
    geozl.decompress(bytes(range(64)))
except geozl.GeoZLError as error:
    print(error)                            # geozl.decompress: unreadable frame (ZL error code 10)
back <- geozl_decompress(frame, "int16", dim = dim(tile),
                         max_output_size = 2 * length(tile))

e <- tryCatch(geozl_decompress(as.raw(0:63)), geozl_error = identity)
e$code                                      # 10
back = GeoZL.decompress(Int16, frame, size(tile); max_output_size = sizeof(tile))

try
    GeoZL.decompress(UInt8.(0:63))
catch error
    error isa GeoZLError || rethrow()
    println(error.code)                     # 10
end

A frame the library cannot read raises geozl.GeoZLError in Python, signals a geozl_error condition in R and throws GeoZLError in Julia. Each carries the ZL error code. A frame that declares more than max_output_size is refused before decoding, as a ValueError in Python, a plain error in R and an ArgumentError in Julia.

GPU-friendly recipes

Four recipes have a GPU decoder: id>pfor, planar>zigzag>pfor, id>lanes and planar>zigzag>lanes. Their blocks or byte lanes can be decoded in parallel. GPU routing also requires one chunk and samples of 1 or 2 bytes; GPU decoding lists the remaining limits.

pfor = geozl.compress(tile, graph=geozl.graph(tile, "planar>zigzag>pfor"))
lanes = geozl.compress(tile, graph=geozl.graph(tile, "planar>zigzag>lanes"))

print(len(pfor), len(lanes))                # 41811 11621
pfor <- geozl_compress(tile, geozl_graph(tile, "planar>zigzag>pfor", dtype = "int16"))
lanes <- geozl_compress(tile, geozl_graph(tile, "planar>zigzag>lanes", dtype = "int16"))

c(length(pfor), length(lanes))              # 41811 11621
pfor = GeoZL.compress(tile, GeoZL.graph(tile, "planar>zigzag>pfor"))
lanes = GeoZL.compress(tile, GeoZL.graph(tile, "planar>zigzag>lanes"))

length(pfor), length(lanes)                 # (41811, 11621)

All three packages write these frames and decode them on the CPU. The GPU decoder is a C API in geozl/gpu.h, and a library that wants tensors on a GPU binds it, as Rumi does. GPU decoding lists the exact recipes, and PFOR and PivCo explain the two coders.