Python
- Package
geozlon PyPI, with wheels for Linux x86-64 and macOS arm64.
pip install geozl
The top-level calls, geozl.lossy.fit_noise and Noise need only NumPy. geozl.lossless, the geozl.lossy nodes and register_decoders also need the openzl package. On other platforms a source install builds the native library first.
geozl
Everything below is in geozl.__all__. Arrays go in as NumPy arrays or anything np.ascontiguousarray accepts, in native byte order, at 1, 2, 4 or 8 bytes per sample.
profile
geozl.profile(tile, *, prior='planar', width=None, planes=None, error=None,
reps=5, nodata=None, verify=False) -> ProfileResults
Compresses and decompresses tile with every candidate recipe and returns one row per recipe, sorted by compression ratio. Timing runs in C and keeps the fastest of reps round trips.
| prior | A predictor name, "planar", "med", "delta_w", "delta_n", "average", "wp_static" or "delta_1d", profiles that predictor and the id path. None profiles every predictor and "none" only id. |
|---|---|
| width | Row length in samples, a whole number from 1 to 4294967295. Defaults to the last axis and is required for a 1d array. |
| planes | Stacked images predicted independently, a whole number from 1 to 4294967295. Defaults to the first axis of an array with three or more dimensions, otherwise 1. |
| error | The error budget, see error budgets. None is lossless. |
| reps | Round trips timed per recipe, a whole number from 1 to 2147483647. |
| nodata | A sentinel value to mask, as in graph. NaNs are masked without it on a float tile. |
| verify | A boolean, to verify checksums while timing decode. The frames always carry them. |
Returns a ProfileResults. Each row is a dict with graph, bytes, ratio, encode_mbps, decode_mbps and shannon_pct, the frame size against the order 0 byte entropy of the tile. A recipe that fails on the tile is left out.
Raises TypeError when reps, width or planes is not a whole number, nodata is not a number or verify is not a boolean. Raises ValueError for reps below 1, an unknown prior, a bad error budget, geometry or sentinel, and a dtype that is not native byte order or not 1, 2, 4 or 8 bytes. Raises GeoZLError with the first reason when every recipe fails.
graph
geozl.graph(raster, method, *, width=None, planes=None, error=None,
nodata=None) -> Graph
Builds a reusable compression graph for one recipe. The graph owns one compression context, so threads that share a graph take turns on it. Build one per thread to compress in parallel. Fork only while no thread is compressing with it, since the child inherits the lock as it was.
| raster | A representative tile. It fixes the dtype and, for a lossy budget, the domain later tiles must stay inside. Build it from data spanning the product. |
|---|---|
| method | A recipe as profile spells it, <predictor>>zigzag><terminal>, delta_1d><terminal> or id><terminal>. The predictors are delta_w, delta_n, planar, med, average and wp_static. The terminals are entropy, field_lz, zstd, categorical, transpose>entropy, transpose>zstd, pfor, lanes and sparse. |
| width, planes | As in profile. Row predictors reset at each plane. Pass width=Y*X, planes=1 to predict across bands. |
| error | See error budgets. |
| nodata | A sentinel to mask, one number read at the raster dtype. NaN marks every NaN of a float raster. Without it a float raster that holds NaNs gets a NaN mask. |
Returns a Graph.
Raises TypeError when width or planes is not a whole number or nodata is not a number. Raises ValueError for an empty method or one holding a NUL character, a bad budget, geometry or dtype, a lossy budget on a dtype the quantizers lack, such as complex, a sentinel outside the dtype, NaN as the sentinel of an integer raster and a sentinel on float16. Raises GeoZLError when the C library refuses the recipe, such as an unknown method, a terminal that does not take the sample width, or a bound finer than the dtype resolves. Each of these three is also a ValueError.
import numpy as np
import geozl
y, x = np.mgrid[0:256, 0:256]
tile = (1000 + 3 * x + 2 * y).astype(np.uint16)
g = geozl.graph(tile, "planar>zigzag>pfor", error=2)
g.error # 'LINEAR:MAX_ERROR=2'
compress
geozl.compress(tile, graph, *, coeffs=None) -> bytes
Compresses one tile with a prepared graph and returns the frame. The dtype must equal the graph's. The shape is not checked against the graph, but a row predictor refuses a tile longer than one row that is not whole rows of its width.
| graph | A Graph from geozl.graph, by position or by name. |
|---|---|
| coeffs | Integer vectors stored in the frame header, read back with coeffs. At most 255 non-empty vectors of int32 values within 10,000 packed bytes. GeoZL gives them no meaning. |
Raises TypeError when graph is not a Graph or a coefficient is not an integer. Raises ValueError for a dtype mismatch or coefficients past the limits. Raises GeoZLError when compression fails. A lossy tile the graph's grid cannot hold to its bound is one such refusal, and it is also a ValueError.
That check refuses a negative sample where the raster had none, a floating-point sample whose magnitude exceeds the raster's largest magnitude under LINEAR, and a finite value outside the raster's range under SQRT. Integer LINEAR and every LOG grid span the whole dtype, so only the sign is checked there. NaN and infinity are not checked, apart from LOG refusing -inf on a graph built without negatives.
decompress
geozl.decompress(frame, *, verify=True, max_output_size=None) -> ndarray
Decodes a frame into a flat, 8-byte aligned uint8 array. The frame stores no dtype or shape, so restore them with .view(dtype).reshape(shape).
| verify | A boolean, to check the frame checksums. Set False to skip them. |
|---|---|
| max_output_size | Refuse a frame that declares more output bytes than this. OpenZL may still allocate intermediate streams while decoding. |
Raises TypeError when verify is not a boolean. Raises ValueError when max_output_size is negative, not finite or below the declared size. Raises GeoZLError for an unreadable or corrupt frame, and for one that decodes to fewer bytes than it declares.
coeffs
geozl.coeffs(frame) -> tuple[tuple[int, ...], ...] | None
Returns the coefficient vectors stored by compress, or None when the frame has none. Only the frame header is read.
Raises GeoZLError for an unreadable frame or one older than OpenZL format 22.
frame = geozl.compress(tile, graph=g, coeffs=[[1, 2, 3], [4]])
geozl.coeffs(frame) # ((1, 2, 3), (4,))
Error budgets
The error argument of profile and graph takes a number, a percentage or a full recipe. Near-lossless explains the three quantizers.
| None, 0 | Lossless. So is any recipe whose bound is zero. |
|---|---|
| 2.5 | LINEAR:MAX_ERROR=2.5, an absolute bound |x − x̂| ≤ 2.5. |
| "1%" | LOG:MAX_ERROR=1%, a relative bound |x − x̂| ≤ 0.01 |x|. Between 0% and 100%. |
| recipe | LINEAR:MAX_ERROR=V, LOG:MAX_ERROR=P% or SQRT:MAX_ERROR=kN, with |x − x̂| ≤ k √(a + b x). SQRT fits a and b from the raster unless the recipe carries both A= and B=, as Noise.recipe writes them. |
A boolean, a negative or non-finite number and any other string raise ValueError.
Graph
The type geozl.graph returns. It is exported for isinstance checks and annotations, and calling it raises TypeError.
Its attributes are method, width, planes, dtype, itemsize, error, the normalized recipe or None, and nodata. Its repr shows the method, the dtype, the row width, the planes and the recipe.
A graph holds native state. Pickling or copying one raises TypeError, so a process pool builds one graph per worker from the same raster and recipe.
geozl.graph(tile, "planar>zigzag>pfor")
# <geozl.Graph planar>zigzag>pfor, uint16, row width 256, 1 plane, lossless>
ProfileResults
The type geozl.profile returns. It is exported for isinstance checks and annotations, and calling it raises TypeError.
It is a list of profile rows that also keeps the input and settings as the attributes shape, dtype, raw_bytes, width, planes, prior, reps and error. print(rows) shows them above the table.
GeoZLError
geozl.GeoZLError(message, code=None)
Raised when the C library refuses a recipe, a tile or a frame. It derives from RuntimeError, so except RuntimeError still catches it.
code is the ZL error code as an int. It is None when the refusal has no code, as for a frame that decodes to fewer bytes than it declares.
A refusal with code 21, an invalid parameter, or 30, an invalid graph, is an invalid request, and its class also derives from ValueError. An unknown method or a lossy tile outside the grid is then caught as a bad argument is. A corrupt frame is not.
try:
geozl.graph(tile, "planar>nothing")
except ValueError as exc:
exc.code # 21
simd_info
geozl.simd_info() -> SimdInfo
Returns a dict with the SIMD paths compiled in (built), those the CPU supports (cpu) and the one in use (active). The names are scalar, sse2, avx2 and neon. Set GEOZL_SIMD to one of them before import to cap the active path.
register_decoders
geozl.register_decoders(dctx) -> None
Registers the decoders of the low-level codec classes in an openzl.ext.DCtx, the six predictors, planar_zigzag, med_zigzag, planar_zigzag_pfor, deinterleave, nodata, pfor and the three quantizers. lanes and planar_zigzag_lanes exist only in C and are not registered, so decode frames that use them with geozl.decompress. Raises ModuleNotFoundError when the openzl package is missing.
__version__
The installed version string, or "0+unknown" when the package metadata is missing.
geozl.lossless
The lossless codecs as openzl.ext nodes, for graphs the recipe grid does not cover. The module needs the openzl package. Where OpenZL publishes no wheel, geozl.lossless is absent from geozl, geozl.lossy keeps only fit_noise and Noise, and the calls above still work.
geozl.lossless.DeltaW(width)
geozl.lossless.DeltaN(width, planes=1)
geozl.lossless.Planar(width, planes=1)
geozl.lossless.PlanarZigzag(width, planes=1)
geozl.lossless.PlanarZigzagPfor(width, planes=1)
geozl.lossless.Med(width, planes=1)
geozl.lossless.MedZigzag(width, planes=1)
geozl.lossless.Average(width, planes=1)
geozl.lossless.WpStatic(width, planes=1)
geozl.lossless.Deinterleave()
geozl.lossless.Nodata(width, value=None, dtype=None, radius=None)
geozl.lossless.Pfor()
Each instance is called as node(compressor, successor) and returns an openzl.ext.GraphID, so a graph is built from the tail. Nodata takes (compressor, values_successor, mask_successor), and Deinterleave sends both lanes to its one successor. PlanarZigzagPfor and Pfor emit a serial stream. DeltaW reads only to the left, so it takes no plane count.
Each codec has a decoder class of the same name plus Decoder, such as PlanarDecoder, all registered by register_decoders. The codec pages describe what each one computes.
| Nodata | Splits holes into a validity mask and fills them. Pass value and dtype together for a sentinel, or neither to mask NaNs. radius is the largest error of later stages, 0 for a lossless graph. |
|---|---|
| WpStatic | Fits four weights and a shift per stream, shared by all planes. |
geozl.lossless.component_dtype(dtype)
geozl.lossless.nodata_bits(value, dtype) -> int
component_dtype returns the real dtype of a complex dtype, float32 for complex64. nodata_bits returns a sentinel's bit pattern as an unsigned integer, the form Nodata stores.
geozl.lossless.pfor_bound(nb_elts, elt_width)
geozl.lossless.pfor_encode(values)
geozl.lossless.pfor_decode(packed, nb_elts, dtype)
geozl.lossless.planar_zigzag_pfor_bound(nb_elts, elt_width, width, planes=1)
geozl.lossless.planar_zigzag_pfor_encode(values, width, planes=1)
geozl.lossless.planar_zigzag_pfor_decode(packed, nb_elts, dtype, width,
planes=1)
Encode and decode the raw payload of Pfor and PlanarZigzagPfor, the bytes inside the frame without the OpenZL frame around them. The GPU decoder expands this payload, so these help test another reader against it.
The bound functions return the worst case payload size, or 0 for a refused geometry. The encode functions raise ValueError for a refused geometry and the decode functions for a corrupt stream.
import numpy as np
import openzl.ext as zl
import geozl
y, x = np.mgrid[0:256, 0:256]
tile = (1000 + 3 * x + 2 * y).astype(np.uint16)
c = zl.Compressor()
c.select_starting_graph(
geozl.lossless.Planar(256)(c, zl.nodes.Zigzag()(c, zl.graphs.Entropy()(c))))
cctx = zl.CCtx()
cctx.ref_compressor(c)
cctx.set_parameter(zl.CParam.FormatVersion, zl.MAX_FORMAT_VERSION)
frame = cctx.compress([zl.Input(zl.Type.Numeric, tile.reshape(-1))])
dctx = zl.DCtx()
geozl.register_decoders(dctx)
back = dctx.decompress(frame)[0].content.as_nparray().view(np.uint16)
assert np.array_equal(back.reshape(tile.shape), tile)
geozl.lossy
geozl.lossy.QuantLinear(recipe, dtype)
geozl.lossy.QuantLog(recipe, dtype)
geozl.lossy.QuantSqrt(recipe, dtype)
The three quantizers as nodes, called like the lossless ones. recipe is a full recipe string such as "LINEAR:MAX_ERROR=0.5". The grid is resolved from each stream they encode, so there is no shared domain or cross-tile check as in geozl.graph. A QuantSqrt recipe must carry A= and B=, since a node cannot fit them.
The compression context must disable the content checksum with cctx.set_parameter(zl.CParam.ContentChecksum, 2), and without it cctx.compress raises RuntimeError. The constructors raise ValueError for a recipe they cannot parse, a QuantSqrt recipe without A= and B=, or a dtype without a kernel. The decoders are QuantLinearDecoder, QuantLogDecoder and QuantSqrtDecoder.
geozl.lossy.fit_noise(data) -> Noise
geozl.lossy.Noise(a, b, blocks, bins, range, colin, resid)
geozl.lossy.Noise.recipe(max_error) -> str
fit_noise fits variance = a + b x to a 2d raster, an (N, H, W) stack or a sequence of 2d rasters of one dtype, and returns a frozen Noise. The other fields are fit diagnostics. Noise.recipe(k) returns the SQRT recipe for a bound of k sigmas with the fitted curve, so one grid serves every tile. Both need only the kernels, not the openzl package.
fit_noise raises ValueError for the wrong dimensions, mixed dtypes or a side under 10 samples, and GeoZLError when the data supports no fit, such as a constant raster. recipe raises ValueError for a boolean or for a bound that is not a positive finite number.
rng = np.random.default_rng(0)
counts = rng.poisson(100, (256, 256)).astype(np.uint16)
noise = geozl.lossy.fit_noise(counts)
g = geozl.graph(counts, "planar>zigzag>pfor", error=noise.recipe(2))