Skip to main content

RasterX Function Reference

Every RasterX function runs on every compute. GeoBrix picks the implementation level for the compute. See Surfaces & Levels. Each function section shows the surfaces it runs on, and an Implementation note names its backing library.

Complete reference for all RasterX functions with detailed descriptions, parameters, return values, and examples.

Built on rasterio

RasterX is, in large part, distributed rasterio + a best-of-breed raster stack. See Rasterio Distributed for the coverage matrix and honest gaps.

Overview​

RasterX is GeoBrix's raster data processing package. It provides comprehensive tools for working with raster datasets such as satellite imagery, elevation models, and other gridded spatial data. It is a refactor and improvement of Mosaic raster functions. It was extended through v0.5.0 with terrain analysis, spectral indices, vector-raster bridging, web-mercator tile output, and H3/quadbin/BNG grid aggregations. In v0.5.0 it also gained virtual tiles, a COG-preparation lane, and VRT mosaics for memory-safe processing of multi-gigabyte rasters. The Databricks product does not (yet) support anything built-in specifically for raster processing. RasterX therefore provides a gap-filling capability for raster operations on the Databricks platform.

Key Features​

  • GDAL-Powered: Leverages GDAL for robust raster format support
  • Distributed Processing: Built on Spark for scalable raster operations
  • Multiple Format Support: GeoTIFF, COG, NetCDF, and other GDAL-supported formats
  • Metadata Extraction: Comprehensive raster metadata access
  • Raster Operations: Clipping, resampling, transformations, map algebra
  • Band Operations: Multi-band raster support, single-band extraction
  • Terrain Analysis: Slope, aspect, hillshade, TRI, TPI, roughness, color-relief
  • Spectral Indices: EVI, SAVI, NDWI, NBR, NDVI, plus a generic dispatcher
  • Vector-Raster Bridge: Rasterize geometries, polygonize value regions
  • Tile Publishing: Web-mercator XYZ tile generation (PNG / JPEG / WebP)
  • Grid Aggregations: H3, CARTO quadbin v0, and BNG cell aggregations
  • Virtual Tiles: Bytes-free windowed reads — process multi-gigabyte rasters without materializing them into executor memory
  • COG Preparation & VRT Mosaics: file_gbx + cog_gbx prepare spec-valid Cloud-Optimized GeoTIFFs and portable VRT mosaics for cheap windowed reads
Coordinate reference systems

Many RasterX functions accept CRS parameters. Use srid / out_srid (integer EPSG or ESRI code) or crs / out_crs (CRS string — EPSG, ESRI, OGC, WKT, PROJ4) to declare or project CRS. Functions that consume a clip polygon or sample geometry accept clip_crs / crs as a source-CRS fallback. rst_srid returns the stored SRID integer; rst_crs returns the canonical CRS string and always returns a value. See Coordinate reference systems for the full model, the EPSG→ESRI resolution order, and the ESRI/OGC authority-preservation behavior.

Function Categories​

RasterX exposes 166 SQL functions (registered as gbx_rst_*; available in Python as rst_*), organized into the following categories:

The RasterX functions in their categories, each card listing its function names. Call them from SQL after register(spark), from the rasterx Python API, or from Unity Catalog SQL.The RasterX functions in their categories, each card listing its function names. Call them from SQL after register(spark), from the rasterx Python API, or from Unity Catalog SQL.

Each card links to a section below:

Tile payload​

Unless noted, a RasterX function returns a materialized tile whose raster field is a self-contained, in-memory raster (GTiff by default). It is safe to serialize between Spark stages and executors, persist to Delta, hand off to rasterio or GDAL, or write back out via the raster_gbx writer. The bytes are never an XML reference to a per-executor /vsimem/ tempfile or to a path that only exists on the producing node.

See Tile structure for the full tile-struct schema (the shared cellid / raster / path / window / … struct). See Virtual Tiles for the bytes-free variant and how tiles move between materialized and virtual.

gbx_rst_merge, gbx_rst_merge_agg, gbx_rst_frombands, gbx_rst_combineavg, gbx_rst_combineavg_agg, gbx_rst_derivedband and gbx_rst_derivedband_agg return GTiff bytes, so downstream stages on different executors see real raster bytes. Inspect a tile's payload format from tile.metadata.driver; for any of the functions above, it will read GTiff (not VRT). See Release Notes for the v0.3.0 correctness fix that introduced this invariant. See Tile structure for the full tile-struct schema.

Virtual-tile force-output params​

Virtual-tile force-output params — Python only

Tile-returning rst_* Python functions accept three optional keyword arguments. They control whether the produced tile carries raster bytes or a bytes-free virtual reference (a path + window instead of in-memory pixels):

ArgumentTypeMeaning
virtualize_dirstr (durable path)Write the produced tile to <dir>/[<prefix>_]<name>.tif and return a virtual tile (path + window, no bytes). The directory must be a durable, executor-readable location such as a Unity Catalog Volume path. Cannot be set together with materialize=True.
virtualize_prefixstrOptional filename prefix added before the provenance-based filename — use this to deconflict when two different function outputs share the same virtualize_dir.
materializeboolTrue — ensure the produced tile carries bytes. False — no-op. Default (unset) — auto: reference/passthrough ops (header reads, rst_clip, rst_setsrid, identity rst_transform) belong to the no-new-pixels class and incur no pixel computation; pixel-producing ops (slope, focal, mapalgebra, reproject, merge, combineavg, frombands, …) materialize.

Default (auto) behavior: reference/passthrough operations (rst_clip, rst_setsrid, identity rst_transform) produce no new pixels. They describe a region of, or an annotation on, existing backing data. They do not compute fresh values, so they are the low-cost class. Pixel-producing operations (slope, focal, mapalgebra, reproject, merge, combineavg, frombands, …) materialize and return bytes. For these, virtualize_dir is the only way to get a virtual tile back. It writes the computed result to a durable path and returns a virtual tile.

SQL has no such keywords. In SQL, GeoBrix sends a virtual tile to the Python implementation, because the JVM level reads materialized tiles only. See Virtual tiles and the JVM level.

Setup​

With the GeoBrix wheel already installed (Installation), run this once. Every example below assumes the setup. Python and SQL use the same rx alias and the same views. (See Surfaces & Levels for how GeoBrix picks an implementation.)

The examples on this page read from four temp views, each a raster loaded as a tile column. Point the four path placeholders at your own rasters:

PlaceholderSample fileReader — Temp viewBacks
GTIFF_SAMPLE_DIRsingle-band GeoTIFFgtiff_gbx — rastersDefault — most accessor, tile-ops, transform, and generator examples
GTIFF_MULTI_DIRmulti-band GeoTIFF (red/NIR/green)gtiff_gbx — multiband_rastersband-math and spectral-index examples, rst_numbands, rst_bandmetadata
DTM_DIRdigital elevation modelgtiff_gbx — dem_rastersterrain examples (rst_slope, rst_aspect, …)
NETCDF_DIRNetCDF with subdatasetsnetcdf_gbx — netcdf_rastersrst_subdatasets, rst_getsubdataset

Each format has a named *_gbx reader. The generic raster_gbx reader also reads any raster that GDAL supports.

The four *_DIR placeholders in the code below are wired to small sample rasters committed in the GeoBrix repo under src/test/resources/binary/. The _SAMPLE_PATHS[...] / *_path() helpers you'll see in the snippet resolve them. To run the examples yourself, stage those sample files, or your own rasters, in a Unity Catalog Volume directory. Then set each placeholder to its Volume path.

The setup below loads GTIFF_SAMPLE_DIR into rasters and then loads the other three the same way — swap the path and view name (and, for NetCDF, the reader). Every example on the page assumes these four views exist.

Setup
from databricks.labs.gbx import register

# One call registers every gbx_* SQL function and the Python DataSource readers
# (raster_gbx / gtiff_gbx / netcdf_gbx / cog_gbx).
register(spark)

GTIFF_SAMPLE_DIR = _SAMPLE_PATHS["gtiff"]
GTIFF_MULTI_DIR = _SAMPLE_PATHS["gtiff_multi"]
DTM_DIR = _SAMPLE_PATHS["dtm"]
NETCDF_DIR = _SAMPLE_PATHS["netcdf"]

def load_tiles(path, reader, view):
df = spark.read.format(reader).load(path)
df.createOrReplaceTempView(view)
return df

# Load the default single-band raster into the `rasters` view:
rasters = load_tiles(GTIFF_SAMPLE_DIR, "gtiff_gbx", "rasters")

# The other three load the same way — GeoTIFFs use "gtiff_gbx", NetCDF uses "netcdf_gbx":
load_tiles(GTIFF_MULTI_DIR, "gtiff_gbx", "multiband_rasters")
load_tiles(DTM_DIR, "gtiff_gbx", "dem_rasters")
load_tiles(NETCDF_DIR, "netcdf_gbx", "netcdf_rasters")
Example output
Four temp views created — `rasters` (single-band), `multiband_rasters`,
`dem_rasters`, and `netcdf_rasters` — each a DataFrame with a `tile` column.
Every example on this page reads from one of these views.

Prefer pure SQL? After register(spark), create the same four views directly so the SQL examples can use FROM rasters, FROM multiband_rasters, and so on:

SQL view setup
-- After registering GeoBrix (Python: gbx.register(spark)), create the views:
CREATE OR REPLACE TEMP VIEW rasters USING raster_gbx OPTIONS (path '{SAMPLE_RASTER_PATH}'); -- GTIFF_SAMPLE_DIR (single-band)

CREATE OR REPLACE TEMP VIEW multiband_rasters USING raster_gbx OPTIONS (path '{MULTIBAND_RASTER_PATH}'); -- GTIFF_MULTI_DIR

CREATE OR REPLACE TEMP VIEW dem_rasters USING raster_gbx OPTIONS (path '{DEM_RASTER_PATH}'); -- DTM_DIR

CREATE OR REPLACE TEMP VIEW netcdf_rasters USING netcdf_gbx OPTIONS (path '{NETCDF_RASTER_PATH}'); -- NETCDF_DIR
Example output
Views `rasters`, `multiband_rasters`, `dem_rasters`, and `netcdf_rasters` created.
Every example on this page reads from one of these views.

Implementation notes​

Each function below carries an :::note Implementation admonition. It names the library behind the function and any behavior worth knowing. For how gbx_rst_derivedband runs your Python code, see VRT Python pixel functions at the end of this page.

Scala tags

A Scala tag on a function means the GeoBrix JAR has a faster JVM form of it. On dedicated compute with the JAR, GeoBrix runs that form for you. You still call the SQL or Python function. See Surfaces & Levels and Functions the JAR speeds up.

Examples — Conventions​

Every function on this page shows one example, expressed on each surface it runs on. This section defines the shared setup so each function tab contains only its invocation — nothing more.

Canonical sample files​

Each function uses one of four canonical files, chosen by what the function demonstrates:

FileWhat it demonstratesUsed by
nyc_sentinel2_red.tifSingle-band GeoTIFF (Sentinel-2 red band, NYC area)Default — most accessor, tile-ops, transform, and generator functions
rgb_nir_small.tif3-band GeoTIFF with per-band metadata (red, NIR, green — 8×8 px)Band-math and spectral-index functions (rst_ndvi, rst_evi, …), rst_numbands, rst_bandmetadata
srtm_n40w073.tifDigital Elevation Model (SRTM, NYC area)Terrain functions (rst_slope, rst_aspect, rst_hillshade, …)
CMIP5 NetCDF (prAdjust_day_…nc)Multi-variable NetCDF with two subdatasetsrst_subdatasets, rst_getsubdataset only

The tile-column convention​

In every example on this page:

  • SQL: rasters is a temporary view whose tile column holds the canonical sample loaded via the reader. FROM rasters means "the sample as tiles."
  • Python: df is a DataFrame with a tile column loaded from the canonical file. df.select(...) means "apply this function to the sample tiles."

Each function's example therefore shows only the invocation — the load is the convention, not the code.

How to read the tabs​

TabSurface
SQLSession SQL, after register(spark)
Unity Catalog SQLA <catalog>.<schema>.gbx_* function, where the function exists in Unity Catalog
PythonThe rasterx Python API

A function shows only the tabs for the surfaces it runs on. The Scala tag has no tab: it links to Functions the JAR speeds up. The tabs show the same operation on the same file. Where the output differs in form, a short note explains why — for example:

  • Geometry-returning functions (rst_boundingbox, rst_georeference): SQL returns WKT; Python returns a binary column. The note reads ... (WKB binary).
  • Subdataset maps (rst_subdatasets): SQL returns map<string,string>; rendered as {SUBDATASET_1_NAME -> ..., SUBDATASET_1_DESC -> ...}. A note clarifies the key pattern.
  • Band-metadata maps (rst_bandmetadata): similarly noted where the rendering differs between surfaces.

Scalar values are identical across all tabs — same fixture, same function, same result.

Tile-returning functions (rst_clip, rst_resample, rst_transform, the aggregators, the constructors, …) return a v2 Tile. Their output is shown as a representative struct — {0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}} — rather than a literal byte dump. Tiles loaded via rst_fromcontent / rst_fromfile (as in Setup) are materialized: the raster field holds the encoded bytes and path is null. Virtual tiles — a populated path with lazily-read bytes — arise from the force-output parameters, not from the default load.

SQL naming and arguments: in the SQL tab, RasterX functions carry the gbx_ prefix (e.g. gbx_rst_boundingbox, gbx_rst_width); Python uses the bare rst_* name via rx. SQL binds arguments by position, so leave out only trailing optional arguments. See Language Bindings for more.

Per-function notes​

Functions that use a non-default fixture (multiband GeoTIFF, DEM, or NetCDF) carry a one-line note immediately before their code example flagging the file. Functions that produce a tile rather than consuming one (constructors: rst_fromfile, rst_fromcontent, rst_frombands, …) show a fuller load/build example with a note. The bare-invocation model does not apply when there is no input tile yet.

Accessor Functions​

Functions to read raster properties and metadata (29 total).

rst_avg​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_avg(tile)array<double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_avg(tile)array<double>
Pythonrasterx.functions.rst_avg(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio + NumPy. Per-band mean over valid (non-NoData) pixels.

Per-band average pixel values.

Returns NULL for a band with zero valid pixels (all NoData) at every level.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands: red, NIR, green); the canonical single-band sentinel2 tile is all-NoData for this function.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_avg(tile) AS band_averages FROM multiband_rasters;
Example output
+-----------------------------+
|band_averages |
+-----------------------------+
|[83.59375, 153.125, 114.3125]|
+-----------------------------+

rst_bandmetadata​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bandmetadata(tile, band)map<string,string>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bandmetadata(tile, band)map<string,string>
Pythonrasterx.functions.rst_bandmetadata(tile, band)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
bandINTINTThe 1-based band number.
Implementation

Powered by rasterio.

Band metadata map.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands with per-band GDAL metadata tags); plain single-band GeoTIFFs without tags return an empty map {}.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_bandmetadata(tile, 1) AS band_meta FROM multiband_rasters;
Example output
+----------------------------------------------+
|band_meta |
+----------------------------------------------+
|{name -> red, wavelength_nm -> 665, band_in...|
+----------------------------------------------+

rst_boundingbox​

SQLUnity Catalog SQLPythonScala
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_boundingbox(tile)BINARY
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_boundingbox(tile)BINARY
Pythonrasterx.functions.rst_boundingbox(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Bounding box geometry.

Since v0.2.0
SELECT path, gbx_rst_boundingbox(tile) as bbox FROM rasters;
Example output
+--------------------+-----------------+
|path |bbox |
+--------------------+-----------------+
|.../nyc_sentinel2...|POLYGON ((-74....|
+--------------------+-----------------+

rst_crs​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_crs(tile)STRING
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_crs(tile)STRING
Pythonrasterx.functions.rst_crs(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio + pyproj.

The CRS of the tile as a string: EPSG:4326, ESRI:54008 or, with no authority code, its WKT. Every raster with a CRS gets a value, including an authority-less one that rst_srid cannot name. A raster with no CRS gives NULL. See Coordinate Reference Systems.

Returns the authority string (AUTHORITY:CODE, e.g. EPSG:4326 or ESRI:54008) when the CRS has one, otherwise its WKT. rst_srid gives the integer authority code, and NULL when the CRS has none. rst_crs names every CRS a raster has, including an authority-less one defined by WKT or PROJ4.

CRS: SRID int vs CRS string
  • rst_srid returns the integer authority code, EPSG or ESRI (for example 4326, or 54008 for ESRI:54008). It returns NULL for a raster with no CRS, an authority-less WKT or PROJ4 CRS, or a code that is not a number (such as OGC:CRS84). Use it when you need the numeric SRID for the native ST bridge.
  • rst_crs returns the CRS string and never loses a non-EPSG CRS.
  • rst_setcrs / rst_transformcrs take a CRS string. An int-castable string is treated as an EPSG SRID ('4326' behaves like SRID 4326); otherwise the string is parsed as an authority code (EPSG:/ESRI:), WKT, or PROJ4. This is how ESRI codes, WKT, and PROJ4 definitions survive a round trip.
Since v0.5.0
SELECT gbx_rst_crs(tile) AS crs FROM rasters;
Example output
+----------+
|crs |
+----------+
|EPSG:32618|
+----------+

rst_format​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_format(tile)STRING
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_format(tile)STRING
Pythonrasterx.functions.rst_format(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

GDAL format name.

Since v0.2.0
SELECT gbx_rst_format(tile) AS format FROM rasters;
Example output
+------+
|format|
+------+
|GTiff |
+------+

rst_georeference​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_georeference(tile)map<string,double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_georeference(tile)map<string,double>
Pythonrasterx.functions.rst_georeference(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Georeference parameters as a map.

The result is a MapType with the following keys, corresponding to GDAL's 6-element geotransform:

KeyGeotransform indexMeaning
upperLeftXGT(0)X of the upper-left corner of the upper-left pixel
upperLeftYGT(3)Y of the upper-left corner of the upper-left pixel
scaleXGT(1)Pixel width (west–east resolution)
scaleYGT(5)Pixel height (north–south resolution; often negative for north-up)
skewXGT(2)Row rotation (typically 0)
skewYGT(4)Column rotation (typically 0)

See the GDAL geotransform tutorial and raster data model for details.

Since v0.2.0
SELECT gbx_rst_georeference(tile) AS georeference FROM rasters;
Example output
+-------------------------------------------------------------+
|georeference |
+-------------------------------------------------------------+
|{scaleX -> 10.0, scaleY -> -10.0, upperLeftX -> 2121950.0,...|
+-------------------------------------------------------------+

rst_getnodata​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_getnodata(tile)array<double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_getnodata(tile)array<double>
Pythonrasterx.functions.rst_getnodata(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio. Returns the dataset NoData value repeated once per band.

NoData values per band.

Since v0.2.0
SELECT gbx_rst_getnodata(tile) AS nodata FROM rasters;
Example output
+------+
|nodata|
+------+
|[0.0] |
+------+

rst_getsubdataset​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_getsubdataset(tile, subset_name)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_getsubdataset(tile, subset_name)TILE
Pythonrasterx.functions.rst_getsubdataset(tile, subset_name)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEA tile whose raster is a container with subdatasets, such as a NetCDF file.
subset_nameSTRINGSTRINGThe name of the subdataset (the last part of its GDAL name, such as 'prAdjust'). A name that matches none raises.
Implementation

Powered by rasterio. Subdataset availability depends on rasterio's bundled GDAL driver set.

Extract a subdataset of a container file. A tile that holds no subdataset of that name raises an error that names it.

Examples use the CMIP5 NetCDF fixture (prAdjust_day_HadGEM2-CC_*.nc) which has two subdatasets: time_bnds and prAdjust. Subdatasets require a multi-layer format such as NetCDF; plain GeoTIFFs return no subdatasets.

Since v0.2.0
-- netcdf_rasters view is from the CMIP5 NetCDF fixture (has time_bnds and prAdjust)
SELECT gbx_rst_getsubdataset(tile, 'prAdjust') AS subdataset FROM netcdf_rasters;
Example output
+-----------------------------------------------------------+
|subdataset |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(the extracted prAdjust subdataset as a tile — 720x360, 31 bands)

rst_height​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_height(tile)INT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_height(tile)INT
Pythonrasterx.functions.rst_height(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Height in pixels.

Since v0.2.0
SELECT gbx_rst_height(tile) AS height FROM rasters;
Example output
+------+
|height|
+------+
|161 |
+------+

rst_max​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_max(tile)array<double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_max(tile)array<double>
Pythonrasterx.functions.rst_max(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio + NumPy. Per-band maximum over valid (non-NoData) pixels.

Maximum pixel values per band.

Returns NULL for a band with zero valid pixels (all NoData) at every level.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands); the canonical single-band sentinel2 tile is all-NoData for this function.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_max(tile) AS band_max FROM multiband_rasters;
Example output
+---------------------+
|band_max |
+---------------------+
|[119.0, 197.0, 148.0]|
+---------------------+

rst_median​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_median(tile)array<double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_median(tile)array<double>
Pythonrasterx.functions.rst_median(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio + NumPy. Per-band median over valid (non-NoData) pixels.

Median pixel values per band.

Returns NULL for a band with zero valid pixels (all NoData) at every level.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands); the canonical single-band sentinel2 tile is all-NoData for this function.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_median(tile) AS band_median FROM multiband_rasters;
Example output
+--------------------+
|band_median |
+--------------------+
|[85.0, 157.5, 111.5]|
+--------------------+

rst_memsize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_memsize(tile)BIGINT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_memsize(tile)BIGINT
Pythonrasterx.functions.rst_memsize(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio. Returns the serialized raster size in bytes.

In-memory size in bytes.

Since v0.2.0
SELECT gbx_rst_memsize(tile) AS memsize FROM rasters;
Example output
+-------+
|memsize|
+-------+
|71749 |
+-------+

rst_metadata​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_metadata(tile)map<string,string>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_metadata(tile)map<string,string>
Pythonrasterx.functions.rst_metadata(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Metadata map.

Since v0.2.0
SELECT gbx_rst_metadata(tile) as metadata FROM rasters;
Example output
+--------------------------------------------------+
|metadata |
+--------------------------------------------------+
|{driver -> GTiff, crs -> EPSG:32618, count -> 1,..|
+--------------------------------------------------+

rst_min​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_min(tile)array<double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_min(tile)array<double>
Pythonrasterx.functions.rst_min(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio + NumPy. Per-band minimum over valid (non-NoData) pixels.

Minimum pixel values per band.

Returns NULL for a band with zero valid pixels (all NoData) at every level.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands); the canonical single-band sentinel2 tile is all-NoData for this function.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_min(tile) AS band_min FROM multiband_rasters;
Example output
+-------------------+
|band_min |
+-------------------+
|[50.0, 102.0, 82.0]|
+-------------------+

rst_numbands​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_numbands(tile)INT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_numbands(tile)INT
Pythonrasterx.functions.rst_numbands(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Number of bands.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands: red, NIR, green).

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_numbands(tile) AS num_bands FROM multiband_rasters;
Example output
+---------+
|num_bands|
+---------+
|3 |
+---------+

rst_pixelcount​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_pixelcount(tile)array<bigint>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_pixelcount(tile)array<bigint>
Pythonrasterx.functions.rst_pixelcount(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio + NumPy. Per-band count of valid (non-NoData) pixels.

Total pixel count.

Examples use the multiband fixture (rgb_nir_small.tif, 8×8, 3 bands, no NoData set), yielding 64 valid pixels per band. The canonical single-band sentinel2 tile has NoData=0 with all pixels equal zero, returning [0].

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_pixelcount(tile) AS pixel_count FROM multiband_rasters;
Example output
+------------+
|pixel_count |
+------------+
|[64, 64, 64]|
+------------+

rst_pixelheight​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_pixelheight(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_pixelheight(tile)DOUBLE
Pythonrasterx.functions.rst_pixelheight(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Pixel height in ground units.

Since v0.2.0
SELECT gbx_rst_pixelheight(tile) AS pixel_height FROM rasters;
Example output
+------------+
|pixel_height|
+------------+
|10.0 |
+------------+

rst_pixelwidth​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_pixelwidth(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_pixelwidth(tile)DOUBLE
Pythonrasterx.functions.rst_pixelwidth(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Pixel width in ground units.

Since v0.2.0
SELECT gbx_rst_pixelwidth(tile) AS pixel_width FROM rasters;
Example output
+-----------+
|pixel_width|
+-----------+
|10.0 |
+-----------+

rst_rotation​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_rotation(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_rotation(tile)DOUBLE
Pythonrasterx.functions.rst_rotation(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Rotation in radians.

Since v0.2.0
SELECT gbx_rst_rotation(tile) AS rotation FROM rasters;
Example output
+--------+
|rotation|
+--------+
|0.0 |
+--------+

rst_scalex​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_scalex(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_scalex(tile)DOUBLE
Pythonrasterx.functions.rst_scalex(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Scale (pixel size) in X/Y.

Since v0.2.0
SELECT gbx_rst_scalex(tile) AS scale_x FROM rasters;
Example output
+-------+
|scale_x|
+-------+
|10.0 |
+-------+

rst_scaley​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_scaley(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_scaley(tile)DOUBLE
Pythonrasterx.functions.rst_scaley(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Scale (pixel size) in X/Y.

Since v0.2.0
SELECT gbx_rst_scaley(tile) AS scale_y FROM rasters;
Example output
+-------+
|scale_y|
+-------+
|-10.0 |
+-------+

rst_skewx​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_skewx(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_skewx(tile)DOUBLE
Pythonrasterx.functions.rst_skewx(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Skew in X/Y.

Since v0.2.0
SELECT gbx_rst_skewx(tile) AS skew_x FROM rasters;
Example output
+------+
|skew_x|
+------+
|0.0 |
+------+

rst_skewy​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_skewy(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_skewy(tile)DOUBLE
Pythonrasterx.functions.rst_skewy(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Skew in X/Y.

Since v0.2.0
SELECT gbx_rst_skewy(tile) AS skew_y FROM rasters;
Example output
+------+
|skew_y|
+------+
|0.0 |
+------+

rst_srid​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_srid(tile)INT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_srid(tile)INT
Pythonrasterx.functions.rst_srid(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

The stored spatial reference ID integer (an EPSG or ESRI code), or NULL when the tile has none. Returns the code as stored; it is classified only when applied. See Coordinate Reference Systems for the SRID-vs-CRS-string model and the epsg→esri resolution rule.

Since v0.2.0
SELECT gbx_rst_srid(tile) AS srid FROM rasters;
Example output
+-----+
|srid |
+-----+
|32618|
+-----+

rst_subdatasets​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_subdatasets(tile)map<string,string>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_subdatasets(tile)map<string,string>
Pythonrasterx.functions.rst_subdatasets(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio. Empty for single-dataset rasters (e.g. a plain GeoTIFF).

List of subdataset names.

Examples use the CMIP5 NetCDF fixture (prAdjust_day_HadGEM2-CC_*.nc) which has two subdatasets: time_bnds and prAdjust. Subdatasets require a multi-layer format; plain GeoTIFFs return an empty map.

Since v0.2.0
-- netcdf_rasters view is from the CMIP5 NetCDF fixture (has time_bnds and prAdjust)
SELECT gbx_rst_subdatasets(tile) AS subdatasets FROM netcdf_rasters;
Example output
+------------------------------------------------------+
|subdatasets |
+------------------------------------------------------+
|{SUBDATASET_1_NAME -> ..., SUBDATASET_1_DESC -> [31...|
+------------------------------------------------------+
(map with SUBDATASET_1_NAME/DESC for time_bnds and SUBDATASET_2_NAME/DESC for prAdjust)

rst_stats_partial​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_stats_partial(tile)array<struct<band:int,count:double,sum:double,m2:double,min:double,max:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_stats_partial(tile)array<struct<band:int,count:double,sum:double,m2:double,min:double,max:double>>
Pythonrasterx.functions.rst_stats_partial(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to summarize.

Give the mergeable state of each band of a tile, in one pass over the pixels. Each row of the array holds count, sum, m2, min and max for one band. The average of a band is sum / count. The variance is m2 / count, and the standard deviation is its square root.

SELECT t.band, t.sum / t.count AS avg, t.max - t.min AS spread
FROM (SELECT gbx_rst_stats_partial(tile) AS stats FROM rasters) r
LATERAL VIEW inline(r.stats) t

Compute the array in a subquery, as above. Spark refuses a SQL function placed directly under inline or explode.

The state merges across tiles of one table. Sum count and sum, and take the least min and the greatest max. Combine m2 with the update on the Unity Catalog functions page, so the variance of a band that spans two tiles is exact. The average of the per-tile averages is not the average of the union, because the tiles hold different numbers of pixels. Tiles must not overlap. A pixel in two tiles counts twice. On Unity Catalog a virtual tile is refused, and so is a tile over the size limit.

Since v0.6.0
-- One row per band: count, sum, m2 (the sum of squared deviations), min and max.
-- The average is sum / count; the standard deviation is sqrt(m2 / count).
WITH s AS (SELECT gbx_rst_stats_partial(tile) AS stats FROM multiband_rasters)
SELECT band, count, sum / count AS avg, sqrt(m2 / count) AS stddev, min, max
FROM (SELECT inline(stats) FROM s);
Example output
+----+-----+--------+------------------+-----+-----+
|band|count|avg |stddev |min |max |
+----+-----+--------+------------------+-----+-----+
|1 |64.0 |83.59375|18.77641368679067 |50.0 |119.0|
|2 |64.0 |153.125 |28.971160228751625|102.0|197.0|
|3 |64.0 |114.3125|19.828069592121164|82.0 |148.0|
+----+-----+--------+------------------+-----+-----+
(one row per band; count, sum and m2 merge across tiles)

rst_summary​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_summary(tile)STRING
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_summary(tile)STRING
Pythonrasterx.functions.rst_summary(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Runs GDAL's raster info with statistics in the worker, on every compute.

Describe the tile as JSON, with GDAL's own report: the text of gdalinfo -json with statistics. The JSON holds the driver, size, coordinate system, geotransform and corner coordinates. Each band lists its type, NoData value, minimum, maximum, mean and stdDev. GDAL computes the statistics from the pixels, never from stored STATISTICS_* tags. The result is NULL for a NULL tile, an error tile, or a tile GDAL cannot read.

Breaking change in 0.6

The JSON is GDAL's, not the earlier GeoBrix shape. A query that reads its keys must change.

  • bands[].min and bands[].max are now bands[].minimum and bands[].maximum.
  • coordinateSystem.epsg and coordinateSystem.crs are now coordinateSystem.wkt. The EPSG code is stac."proj:epsg".
  • GDAL rounds minimum, maximum, mean and stdDev to three decimals. The band's metadata holds STATISTICS_* values with more digits.
  • A band with no valid pixel has no statistics. A tile held as bytes in another driver, such as PNG or netCDF, reports its own driver. A tile with no band held that way, such as a netCDF container, has an empty bands list. A virtual tile is read into a GeoTIFF of its window first, so it reports GTiff. A virtual tile of a container with no band gives NULL.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands) which has real pixel data.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT
get_json_object(summary, '$.driverShortName') AS driver,
get_json_object(summary, '$.bands[0].maximum') AS band1_max,
get_json_object(summary, '$.bands[0].mean') AS band1_mean
FROM (SELECT gbx_rst_summary(tile) AS summary FROM multiband_rasters);
Example output
+------+---------+----------+
|driver|band1_max|band1_mean|
+------+---------+----------+
|GTiff |119.0 |83.594 |
+------+---------+----------+

rst_type​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_type(tile)array<string>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_type(tile)array<string>
Pythonrasterx.functions.rst_type(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Data type per band.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands, UInt16).

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_type(tile) AS band_types FROM multiband_rasters;
Example output
+------------------------+
|band_types |
+------------------------+
|[UInt16, UInt16, UInt16]|
+------------------------+

rst_upperleftx​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_upperleftx(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_upperleftx(tile)DOUBLE
Pythonrasterx.functions.rst_upperleftx(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Upper-left corner coordinates.

Since v0.2.0
SELECT gbx_rst_upperleftx(tile) AS upper_left_x FROM rasters;
Example output
+------------+
|upper_left_x|
+------------+
|2121950.0 |
+------------+

rst_upperlefty​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_upperlefty(tile)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_upperlefty(tile)DOUBLE
Pythonrasterx.functions.rst_upperlefty(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Upper-left corner coordinates.

Since v0.2.0
SELECT gbx_rst_upperlefty(tile) AS upper_left_y FROM rasters;
Example output
+------------+
|upper_left_y|
+------------+
|-10790470.0 |
+------------+

rst_width​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_width(tile)INT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_width(tile)INT
Pythonrasterx.functions.rst_width(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Width in pixels.

Since v0.2.0
SELECT gbx_rst_width(tile) AS width FROM rasters;
Example output
+-----+
|width|
+-----+
|236 |
+-----+

Aggregator Functions​

Combine or merge rasters in group-by (7 total).

rst_bng_rasterize_agg​

SQLPythonScala
SurfaceCallReturns
SQL (session)gbx_rst_bng_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
Pythonrasterx.functions.rst_bng_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None)Column
ParameterSQL typeDefaultDescription
cellidSTRINGThe BNG cell id, for example 'TQ3080'.
valueDOUBLEThe value burned for the cell. A repeated cell burns its largest value; a NULL value in a typed column never wins against a number, and a cell of nothing but NULL burns NaN. An untyped NULL (the argument left out, or None in Python) is the presence mask and burns 1.0.
out_sridINTNot read: the output is always EPSG:27700.
pixel_sizeDOUBLEThe pixel size in metres.
xminDOUBLEThe west edge of the canvas in EPSG:27700 metres.
yminDOUBLEThe south edge of the canvas in EPSG:27700 metres.
xmaxDOUBLEThe east edge of the canvas in EPSG:27700 metres.
ymaxDOUBLEThe north edge of the canvas in EPSG:27700 metres.
widthINTThe canvas width in pixels.
heightINTThe canvas height in pixels.
modeSTRINGHow the canvas is derived when no extent is given, for example 'centroids'.
kring_padINTCells of padding around the derived canvas.
out_crsSTRINGNULLMust be NULL. Reproject the tile with gbx_rst_transformcrs instead.
Grouped-agg UDF

If a cell id repeats in a group with different values, the largest value is burned, whatever order the rows arrive in. A null value (or NaN) never wins against a number. A cell whose values are all null burns NaN, also when the whole value column is null. Only an omitted value (or an untyped NULL) is the presence mask and burns 1.0. A DECIMAL column reaches the aggregate without its type, so a column of DECIMAL nulls counts as omitted too: cast it to DOUBLE first. A NaN that is a real value, not a null, is ignored the same way at every level. Beside a number in one cell, the number is burned. A cell whose values are all NaN burns NaN.

Implementation

The implementation is backed by BNG cell math and rasterio. It parses BNG cell IDs (STRING) to EPSG:27700-native cell geometries and burns them into the output band. The output canvas is EPSG:27700 throughout, with no warp step. This aggregator takes cellid+value rows, not a raster tile.

NoData sentinel is -9999.0

Pixels not covered by any geometry in the group are set to -9999.0 (band-registered NoData). Filter or mask downstream via gbx_rst_getnodata or IS NULL on the extracted band value.

gbx_rst_bng_rasterize_agg returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), not a tile. A grouped aggregate cannot return the tile struct there. Wrap the SQL or Python result with gbx_rst_fromcontent to get a tile back:

SELECT
cell_id AS cellid,
gbx_rst_fromcontent(gbx_rst_bng_rasterize_agg(cellid, burn_value), 'GTiff') AS tile
FROM bng_cell_values
GROUP BY cell_id

The Python call rx.rst_bng_rasterize_agg(...) returns the same BINARY column. Pass it to rx.rst_fromcontent(col, "GTiff") for a tile.

Streaming aggregator that burns BNG cell geometry/value pairs (one row per cell) into a single rasterized tile per group. The output tile is always in EPSG:27700 (British National Grid). BNG cell IDs are STRING. The inverse of rst_bng_rastertogrid*: where those functions reduce raster pixels to per-cell statistics, this one synthesizes a raster from per-cell values.

Optional trailing out_crs parameter (refused when non-NULL, at every level)

Both levels accept an optional trailing out_crs (string CRS) argument so the signature matches. A non-NULL value is refused with a parameter error at either level. The output is always EPSG:27700: pass NULL for out_crs, and reproject the tile with rst_transformcrs when another CRS is wanted. out_srid is not read at either level (it exists for signature parity with the H3/quadbin aggregators).

Multi-row fixture: 3 BNG 1km STRING cell rows near central London (EPSG:27700) with burn values 1.0/2.0/3.0. All tabs use the same grouped-agg rasterize invocation.

Since v0.4.3
-- Rasterize BNG cells into one raster tile per region. cellid is a STRING
-- (e.g. 'TQ38SW'); the srid argument is a no-op (BNG always forces EPSG:27700,
-- pass 27700 for clarity). The extent auto-derives from the cell set (null
-- canvas args).
SELECT region_id,
gbx_rst_bng_rasterize_agg(
cellid, burn_value,
27700, cast(null as double),
cast(null as double), cast(null as double),
cast(null as double), cast(null as double),
cast(null as int), cast(null as int),
'centroids', cast(0 as int)
) AS tile
FROM bng_cell_values
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|tile |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(tile, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|tile |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+

rst_bng_rasterize_tvf​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_bng_rasterize_tvf(rows, xmin, ymin, xmax, ymax, width, height)rows
Pythonrasterx.functions.rst_bng_rasterize_tvf(df, xmin, ymin, xmax, ymax, width, height)DataFrame

Rows: key STRING, raster BINARY.

ParameterSQL typeDefaultDescription
rowsTABLEThe cells, as TABLE(SELECT key, cellid, value FROM ...) PARTITION BY (key): one canvas per key. cellid is the BNG cell id (for example 'TQ3080') and value the value burned for it. A repeated cell burns its largest value; a NULL value never wins against a number, and a cell of nothing but NULL burns NaN. A NULL cell id is skipped. A partition that holds more than one key raises. A NULL canvas value raises and names the value.
xminDOUBLEThe west edge of the canvas in EPSG:27700 metres.
yminDOUBLEThe south edge of the canvas in EPSG:27700 metres.
xmaxDOUBLEThe east edge of the canvas in EPSG:27700 metres.
ymaxDOUBLEThe north edge of the canvas in EPSG:27700 metres.
widthINTThe canvas width in pixels.
heightINTThe canvas height in pixels.

Use it instead of rst_bng_rasterize_agg for groups of many cells: SELECT * FROM gbx_rst_bng_rasterize_tvf(TABLE(SELECT key, cellid, value FROM cells) PARTITION BY (key), xmin, ymin, xmax, ymax, width, height). It reads each key's cells a row at a time and keeps only the largest value per cell. It needs less memory than the grouped aggregate and burns the same pixels. The canvas is explicit, and a key with no cell gives no row. It does not run on Serverless, whose table-function engine fails PARTITION BY once a task holds more than one row; use rst_bng_rasterize_agg there.

Since v0.6.0
-- One tile per key: the canvas is 3 x 2 pixels of 1 km. A repeated cell burns its largest value.
SELECT key, raster
FROM gbx_rst_bng_rasterize_tvf(
TABLE(SELECT key, cellid, value FROM (VALUES
('a', 'TQ3080', 1.0), ('a', 'TQ3080', 3.0), ('a', 'TQ3180', 2.0),
('b', 'TQ3081', 4.0)
) AS t(key, cellid, value)) PARTITION BY (key),
530000.0, 180000.0, 533000.0, 182000.0, 3, 2
);
Example output
+---+---------------+
|key|raster |
+---+---------------+
|a |[B@... (BINARY)|
|b |[B@... (BINARY)|
+---+---------------+
(one GeoTIFF per key, Float64, NoData -9999, EPSG:27700)

rst_bng_rasterize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
Pythonrasterx.functions.rst_bng_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
cellsarray<struct<cellid:string,value:double>>array<struct<cellid:string,value:double>>The group's cells as an array of structs (cellid, value), for example collect_list(struct(cellid, value)). The rules of the aggregate hold: a repeated cell burns its largest value, a NULL cell id is skipped.
out_sridINTINTNot read: the output is always EPSG:27700.
pixel_sizeDOUBLEDOUBLEThe pixel size in metres.
xminDOUBLEDOUBLEThe west edge of the canvas in EPSG:27700 metres.
yminDOUBLEDOUBLEThe south edge of the canvas in EPSG:27700 metres.
xmaxDOUBLEDOUBLEThe east edge of the canvas in EPSG:27700 metres.
ymaxDOUBLEDOUBLEThe north edge of the canvas in EPSG:27700 metres.
widthINTINTThe canvas width in pixels.
heightINTINTThe canvas height in pixels.
modeSTRINGSTRINGHow the canvas is derived when no extent is given, for example 'centroids'.
kring_padINTINTCells of padding around the derived canvas.
out_crsSTRINGSTRINGNULLMust be NULL. Reproject the tile with gbx_rst_transformcrs instead.

Rasterize an array of BNG cells into one tile, the scalar twin of rst_bng_rasterize_agg. Collect the group's cells first, for example gbx_rst_bng_rasterize(collect_list(struct(cellid, value)), ...). The answer is the same bytes as the aggregate gives. Use it for a group the aggregate's streaming shape cannot take, such as a Serverless finalize or a group from an earlier step. It also runs on Unity Catalog, where an array or canvas over 64 MiB is refused with a Fix: that names the aggregate.

Since v0.6.0
-- collect_list(struct(cellid, value)) gathers the cells into one array. Two values for
-- TQ3080 burn the larger (3.0). The canvas is 3 x 2 pixels of 1 km; out_srid is not read.
SELECT gbx_rst_bng_rasterize(
collect_list(struct(cellid, value)),
27700, 1000.0, 530000.0, 180000.0, 533000.0, 182000.0, 3, 2, 'centroids', 0
) AS content
FROM (VALUES
('TQ3080', 1.0), ('TQ3080', 3.0), ('TQ3180', 2.0), ('TQ3081', 4.0)
) AS t(cellid, value);
Example output
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:27700. Pixels, north row first:
[4.0, -9999, -9999]
[3.0, 2.0, -9999])

rst_combineavg_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_combineavg_agg(tile)BINARY
Pythonrasterx.functions.rst_combineavg_agg(tile)Column
ParameterSQL typeDefaultDescription
tileTILEThe tile of one member. An error tile or a tile that cannot be read is skipped.
Grouped-agg UDF
Implementation

Powered by rasterio + NumPy. Aggregate — groupBy(...).agg(rx.rst_combineavg_agg("tile")) returns the NoData-aware per-pixel mean as one tile per group; input tiles must share the same grid (shape/extent/CRS).

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Average tiles per group.

Multi-tile fixture: 3 per-band rows from rgb_nir_small.tif (same grid). All tabs use the same grouped-agg invocation on multiple tile rows.

Since v0.2.0
-- Group by region and average
SELECT
region,
gbx_rst_combineavg_agg(tile) as regional_average
FROM rasters
GROUP BY region;
Example output
# Heavyweight SQL — one tile struct per group:
+------+-----------------------------------------------------------+
|region|regional_average |
+------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(<agg>, 'GTiff') to rebuild a tile:
+------+----------------+
|region|regional_average|
+------+----------------+
|... |[B@... (BINARY) |
+------+----------------+

rst_derivedband_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_derivedband_agg(tile, python_func, func_name)BINARY
Pythonrasterx.functions.rst_derivedband_agg(tile, python_func, func_name)Column
ParameterSQL typeDefaultDescription
tileTILEOne input band per tile.
python_funcSTRINGThe source of a GDAL VRT pixel function. It runs in the process: pass only trusted code.
func_nameSTRINGThe name of the function in python_func.
Grouped-agg UDF
Implementation

Powered by rasterio and NumPy. Aggregate — groupBy(...).agg(rx.rst_derivedband_agg("tile", pyfunc, funcName)) stacks the group's tiles as bands and applies your pixel function, returning one tile per group. The function runs with exec in the query's Python process, with that process's permissions. Pass only code you trust, as a literal. Unity Catalog does not run it.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Apply Python UDF to tiles per group.

Multi-tile fixture: 3 per-band rows from rgb_nir_small.tif. All tabs use the same grouped-agg invocation; pixel function selects band 0 (identity).

Since v0.2.0
SELECT region, gbx_rst_derivedband_agg(tile, 'def f(a): return a', 'f') as result FROM rasters GROUP BY region;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+------+-----------------------------------------------------------+
|region|result |
+------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(result, 'GTiff') to rebuild a tile struct:
+------+---------------+
|region|result |
+------+---------------+
|... |[B@... (BINARY)|
+------+---------------+

rst_dtmfromgeoms_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_dtmfromgeoms_agg(point, breaklines, merge_tolerance, snap_tolerance, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [no_data], [out_crs])BINARY
Pythonrasterx.functions.rst_dtmfromgeoms_agg(point, breaklines, merge_tolerance, snap_tolerance, xmin, ymin, xmax, ymax, width_px, height_px, out_srid=None, no_data=None, out_crs=None)Column
ParameterSQL typeDefaultDescription
pointBINARY or STRINGA point with a Z coordinate: WKB, EWKB, WKT or EWKT. An empty one is skipped.
breaklinesARRAY<BINARY> or ARRAY<STRING>Breaklines, the same for the whole group. Accepted but not enforced.
merge_toleranceDOUBLEAccepted, not applied.
snap_toleranceDOUBLEAccepted, not applied.
xminDOUBLEThe west edge of the output.
yminDOUBLEThe south edge.
xmaxDOUBLEThe east edge.
ymaxDOUBLEThe north edge.
width_pxINTThe output width in pixels.
height_pxINTThe output height in pixels.
out_sridINTNULLThe EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS.
no_dataDOUBLE-9999.0The NoData value.
out_crsSTRINGNULLThe output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises.
Grouped-agg UDF
Implementation

Powered by rasterio + SciPy (scipy.spatial.Delaunay). Aggregate — builds one TIN DTM tile per group from the group's Z-valued points. It uses barycentric interpolation over an unconstrained Delaunay triangulation. breaklines, merge_tolerance, and snap_tolerance are accepted but not enforced. The Python function also takes an optional trailing out_crs (string CRS) that SQL does not. SQL takes the integer out_srid only.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming aggregator that accepts one Z-valued point WKB per row and produces a TIN/Delaunay DTM raster tile per group. Breaklines are supplied as a per-group constant array to enforce hard terrain edges.

Multi-row fixture: 4 Z-valued WKB POINT rows (elevation 100–250 m) over a [0,0,1,1] EPSG:4326 extent. All tabs use the same grouped-agg invocation.

Since v0.4.0
-- Stream survey points per region into one TIN DTM tile. Breaklines are a
-- per-group constant array; for 10 m cells over a 1000 m extent use 100 px.
SELECT region_id,
gbx_rst_dtmfromgeoms_agg(
point_wkb, breaklines_wkb_array,
0.0, 0.01,
bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax,
100, 100, 32633
) AS dtm
FROM survey_points
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|dtm |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(dtm, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|dtm |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+
Memory & scale — thin the points that feed a TIN

A Delaunay TIN must hold all of a group's points in memory to triangulate, so peak memory is proportional to the points per group. Unlike rst_binpoints_agg, a triangulation is inherently global and cannot be made grid-bounded the way bin_points_tiled bounds binning. At full LiDAR density a single tile's ground returns (hundreds of thousands to millions of points) can exhaust worker RAM.

A bare-earth TIN is near-identical from a representative subset, so thin the input points before the aggregate. Use df.sample(fraction=…) down to a bounded per-group count (e.g. ~150 k), or use smaller tiles. This is standard LiDAR TIN practice and keeps memory bounded regardless of source density. See the LiDAR reader and Performance.

rst_frombands_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_frombands_agg(tile, band_index)BINARY
Pythonrasterx.functions.rst_frombands_agg(tile, band_index)Column
ParameterSQL typeDefaultDescription
tileTILEA single-band tile. An error tile or a tile that cannot be read is skipped.
band_indexINTThe band the tile becomes, counted up from 1. A NULL index skips the row.
Grouped-agg UDF
Implementation

Powered by rasterio. Aggregate — groupBy(...).agg(rx.rst_frombands_agg("tile", "band_index")) stacks the group's tiles into one multi-band tile ordered by ascending band_index.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming aggregator that collects ordered per-band tiles (one row per band) into a single multi-band raster tile per group. Use it when bands arrive as separate rows rather than a pre-built array.

Multi-tile fixture: 3 per-band rows from rgb_nir_small.tif with band_index 1/2/3. All tabs stack via the same grouped-agg invocation.

Since v0.4.0
-- Collect per-band tiles in acquisition order into one multi-band raster per scene.
SELECT scene_id,
gbx_rst_frombands_agg(tile, band_index) AS multi_band
FROM band_tiles
GROUP BY scene_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+--------+-----------------------------------------------------------+
|scene_id|multi_band |
+--------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+--------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(multi_band, 'GTiff') to rebuild a tile struct:
+--------+---------------+
|scene_id|multi_band |
+--------+---------------+
|... |[B@... (BINARY)|
+--------+---------------+

rst_gridfrompoints_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_gridfrompoints_agg(point, value, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [power], [max_pts], [out_crs])BINARY
Pythonrasterx.functions.rst_gridfrompoints_agg(point, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid=None, power=None, max_pts=None, out_crs=None)Column
ParameterSQL typeDefaultDescription
pointBINARY or STRINGThe point: WKB, EWKB, WKT or EWKT. A row with a NULL value or an empty point is dropped.
valueDOUBLEThe point's value.
xminDOUBLEThe west edge of the output.
yminDOUBLEThe south edge.
xmaxDOUBLEThe east edge.
ymaxDOUBLEThe north edge.
width_pxINTThe output width in pixels.
height_pxINTThe output height in pixels.
out_sridINTNULLThe EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS.
powerDOUBLE2.0The inverse-distance exponent, above 0.
max_ptsINT12The number of nearest points used per pixel, above 0.
out_crsSTRINGNULLThe output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises.
Grouped-agg UDF
Implementation

Powered by rasterio + SciPy (cKDTree IDW). Aggregate — groupBy(...).agg(rx.rst_gridfrompoints_agg(...)) inverse-distance-interpolates the group's points into one Float64 grid tile (NoData −9999). The Python function also takes an optional trailing out_crs (string CRS) that SQL does not. SQL takes the integer out_srid only.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming IDW-interpolation aggregator that accepts one point geometry and one scalar value per row and produces a Float64 GeoTIFF tile per group. Use it when observations arrive one per row rather than as pre-built arrays.

Multi-row fixture: 4 WKB POINT rows with observations 10–40 over a [0,0,1,1] EPSG:4326 extent. All tabs use the same grouped-agg IDW invocation.

Since v0.4.0
-- Aggregate per-station observations into one IDW tile per region.
SELECT region_id,
gbx_rst_gridfrompoints_agg(
station_wkb, observation,
bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax,
256, 256, 32633
) AS idw
FROM observations
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|idw |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(idw, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|idw |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+

rst_h3_rasterize_agg​

SQLPythonScala
SurfaceCallReturns
SQL (session)gbx_rst_h3_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
Pythonrasterx.functions.rst_h3_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None)Column
ParameterSQL typeDefaultDescription
cellidBIGINTThe H3 cell id.
valueDOUBLEThe value burned for the cell. A repeated cell burns its largest value; a NULL value in a typed column never wins against a number, and a cell of nothing but NULL burns NaN. An untyped NULL (the argument left out, or None in Python) is the presence mask and burns 1.0.
out_sridINTThe EPSG code of the output CRS.
pixel_sizeDOUBLEThe pixel size in CRS units; NULL takes it from the cells' resolution.
xminDOUBLEThe west edge of the canvas; NULL derives the canvas from the cells.
yminDOUBLEThe south edge of the canvas.
xmaxDOUBLEThe east edge of the canvas.
ymaxDOUBLEThe north edge of the canvas.
widthINTThe canvas width in pixels.
heightINTThe canvas height in pixels.
modeSTRINGHow the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'.
kring_padINTRings of padding around the derived canvas.
out_crsSTRINGNULLThe output CRS as EPSG:<n>. Set out_srid or out_crs, not both: setting both raises.
Grouped-agg UDF

If a cell id repeats in a group with different values, the largest value is burned, whatever order the rows arrive in. A null value (or NaN) never wins against a number. A cell whose values are all null burns NaN, also when the whole value column is null. Only an omitted value (or an untyped NULL) is the presence mask and burns 1.0. A DECIMAL column reaches the aggregate without its type, so a column of DECIMAL nulls counts as omitted too: cast it to DOUBLE first.

Implementation

Powered by rasterio + h3. Aggregate — groupBy(...).agg(rx.rst_h3_rasterize_agg("cellid", "value", ...)) burns each H3 cell's centroid pixel (or spatial-envelope pixels with mode='spatial_envelope') into one raster tile per group. When value is omitted (or an untyped NULL), all burned pixels carry 1.0 (presence mask). A typed column of nulls burns NaN. The extent and pixel size come from the H3 resolution unless you supply explicit bounds. kring_pad (default 1) expands the canvas by that many rings to avoid clipping edge cells.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming aggregator that burns H3 cell centroid pixels (or spatial-envelope pixels) into one raster tile per group. This is the inverse of rst_h3_rastertogrid*: where those functions reduce raster pixels to per-cell statistics, rst_h3_rasterize_agg reconstructs a raster from per-cell values. Use rst_frombands_agg to stack per-threshold rasters (each produced by one rst_h3_rasterize_agg call) into a single multi-band output.

Python-only out_crs parameter

The aggregate accepts an optional trailing out_crs (string CRS) argument. Set out_srid or out_crs, not both: setting both raises. It reads any CRS string.

Worked example

The H3 Rasterize notebook walks this through end to end on a San Francisco Bay Area DEM. The steps are elevation isobands → H3 polyfill → a shared canvas from rst_h3_gridspec → per-band rst_h3_rasterize_agg → multi-band stack via rst_frombands_agg, visualized with the gbx.vizx helpers. The same pattern maps directly to a telco multi-threshold signal-coverage stack.

Multi-row fixture: 3 H3 resolution-9 cell rows with burn values 1.0/2.0/3.0. All tabs use the same grouped-agg rasterize invocation.

Since v0.4.0
-- Rasterize H3 cells into one raster tile per region. Each cell's value is
-- burned at the cell centroid pixel.
SELECT region_id,
gbx_rst_h3_rasterize_agg(
cellid, burn_value,
4326, cast(null as double),
cast(null as double), cast(null as double),
cast(null as double), cast(null as double),
cast(null as int), cast(null as int),
'centroids', cast(1 as int)
) AS tile
FROM h3_cell_values
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|tile |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(tile, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|tile |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+

rst_h3_rasterize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
Pythonrasterx.functions.rst_h3_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
cellsarray<struct<cellid:bigint,value:double>>array<struct<cellid:bigint,value:double>>The group's cells as an array of structs (cellid, value), for example collect_list(struct(cellid, value)). The rules of the aggregate hold: a repeated cell burns its largest value, a NULL cell id is skipped.
out_sridINTINTThe EPSG code of the output CRS.
pixel_sizeDOUBLEDOUBLEThe pixel size in CRS units; NULL takes it from the cells' resolution.
xminDOUBLEDOUBLEThe west edge of the canvas; NULL derives the canvas from the cells.
yminDOUBLEDOUBLEThe south edge of the canvas.
xmaxDOUBLEDOUBLEThe east edge of the canvas.
ymaxDOUBLEDOUBLEThe north edge of the canvas.
widthINTINTThe canvas width in pixels.
heightINTINTThe canvas height in pixels.
modeSTRINGSTRINGHow the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'.
kring_padINTINTRings of padding around the derived canvas.
out_crsSTRINGSTRINGNULLThe output CRS as EPSG:<n>. Set out_srid or out_crs, not both: setting both raises.

Rasterize an array of H3 cells into one tile, the scalar twin of rst_h3_rasterize_agg. Collect the group's cells first, for example gbx_rst_h3_rasterize(collect_list(struct(cellid, value)), ...). The answer is the same bytes as the aggregate gives. Use it for a group the aggregate's streaming shape cannot take, such as a Serverless finalize or a group from an earlier step. It also runs on Unity Catalog, where an array or canvas over 64 MiB is refused with a Fix: that names the aggregate.

Since v0.6.0
-- collect_list(struct(cellid, value)) gathers the cells into one array. The canvas is
-- 2 x 2 pixels of 0.01 degrees; each cell burns its value at the pixel of its centroid.
SELECT gbx_rst_h3_rasterize(
collect_list(struct(cellid, value)),
4326, 0.01, 0.005, 0.005, 0.025, 0.025, 2, 2, 'centroids', 0
) AS content
FROM (VALUES
(619056821909585919L, 1.0), (619056822407921663L, 2.0), (619056559519170559L, 3.0)
) AS t(cellid, value);
Example output
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:4326. Pixels, north row first:
[2.0, -9999]
[1.0, 3.0 ])

rst_merge_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_merge_agg(tile)BINARY
Pythonrasterx.functions.rst_merge_agg(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeDefaultDescription
tileTILEThe tiles of the group.
Grouped-agg UDF
Implementation

Powered by rasterio (rasterio.merge). Aggregate — groupBy(...).agg(rx.rst_merge_agg("tile")) merges the group's tiles into one mosaic tile (output spans the union extent). A tile in a different CRS is reprojected onto the pixel size and the pixel grid of a tile in the reference CRS. A mosaic built in memory and one streamed from disk (when it is too large for memory) then place the tiles on the same pixels. The reprojected tile can grow by up to a pixel on each side to stay on that grid. A tile reprojected from another CRS that declares no NoData (or has its own mask band) gets the footprint of the warp as its mask. The mosaic then has a mask band, and a pixel no tile reaches is invalid in it. A gap between tiles that are all in the reference CRS and declare no NoData is still filled with zeros. The aggregate streams under the worker cap. A result over the cap raises an error with a Fix: that names rasterx.helpers.mint_vrt or the cog_gbx writer in mosaic mode.

Where tiles overlap, the last tile in a fixed order wins. Tiles with bytes come first, sorted by their bytes. Virtual tiles follow, sorted by path and window. The result does not depend on the order the rows arrive. A virtual tile therefore wins over a tile with bytes.

A virtual tile is merged as a file: its path and window go into the mosaic, and no pixel is read into memory first. So a group of any size merges in the same memory. Tiles with bytes are held by the task, so the group must fit it.

On Serverless, pass virtual tiles (the readers' default).

gbx_rst_merge_agg returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), not a tile. A grouped aggregate cannot return the tile struct there. Wrap the SQL or Python result with gbx_rst_fromcontent to get a tile back:

SELECT
group_key AS cellid,
gbx_rst_fromcontent(gbx_rst_merge_agg(tile), 'GTiff') AS tile
FROM tiles
GROUP BY group_key

The Python call rx.rst_merge_agg(...) returns the same BINARY column. Pass it to rx.rst_fromcontent(col, "GTiff") for a tile.

Merge tiles per group. On Serverless a task holds the bytes of its whole group at once. A group of tiles with bytes that add up (decoded) to more than the task's memory cap is refused before the merge. The Fix: names merge_by_key, which reads the tiles as files. The Python call returns the group's error tile, and the SQL call raises. Virtual tiles are not counted: they are read as files.

Multi-tile fixture: 3 per-band rows from rgb_nir_small.tif. All tabs use the same grouped-agg mosaic invocation.

Since v0.2.0
SELECT
scene_id,
gbx_rst_merge_agg(tile) as merged_scene
FROM satellite_tiles
GROUP BY scene_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+--------+-----------------------------------------------------------+
|scene_id|merged_scene |
+--------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+--------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(merged_scene, 'GTiff') to rebuild a tile struct:
+--------+---------------+
|scene_id|merged_scene |
+--------+---------------+
|... |[B@... (BINARY)|
+--------+---------------+

rst_merge_tvf​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_merge_tvf(rows)rows
Pythonrasterx.functions.rst_merge_tvf(df)DataFrame

Rows: key STRING, raster BINARY.

ParameterSQL typeDefaultDescription
rowsTABLEThe tiles, as TABLE(SELECT key, tile FROM ...) PARTITION BY (key): one mosaic per key. An error tile, an empty tile and a tile that does not open are left out. The tile column is a tile, not BINARY: wrap bytes with gbx_rst_fromcontent. A partition that holds more than one key raises.

Use it instead of rst_merge_agg for large groups: SELECT * FROM gbx_rst_merge_tvf(TABLE(SELECT key, tile FROM tiles) PARTITION BY (key)). It merges each key's tiles into the same pixels as the aggregate. It reads them a row at a time, not as one batch of the whole group. A key with no readable tile gives no row. It does not run on Serverless, whose table-function engine fails PARTITION BY once a task holds more than one row; use rst_merge_agg there. A key whose mosaic is too large to build raises with a Fix that names the VRT-mosaic route (mint_vrt).

Since v0.6.0
-- Two 2 x 2 tiles side by side under one key merge into one 4 x 2 mosaic.
WITH tiles AS (
SELECT 'a' AS key,
gbx_rst_rasterize('POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))', 1.0, 0.0, 0.0, 2.0, 2.0, 2, 2, 4326) AS tile
UNION ALL
SELECT 'a',
gbx_rst_rasterize('POLYGON((2 0, 4 0, 4 2, 2 2, 2 0))', 2.0, 2.0, 0.0, 4.0, 2.0, 2, 2, 4326)
)
SELECT key, raster
FROM gbx_rst_merge_tvf(TABLE(SELECT key, tile FROM tiles) PARTITION BY (key));
Example output
+---+---------------+
|key|raster |
+---+---------------+
|a |[B@... (BINARY)|
+---+---------------+
(one GeoTIFF mosaic per key: a 4 x 2 raster, [1, 1, 2, 2] in each row)

rst_quadbin_rasterize_agg​

SQLPythonScala
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
Pythonrasterx.functions.rst_quadbin_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None)Column
ParameterSQL typeDefaultDescription
cellidBIGINTThe quadbin cell id.
valueDOUBLEThe value burned for the cell. A repeated cell burns its largest value; a NULL value in a typed column never wins against a number, and a cell of nothing but NULL burns NaN. An untyped NULL (the argument left out, or None in Python) is the presence mask and burns 1.0.
out_sridINTThe EPSG code of the output CRS.
pixel_sizeDOUBLEThe pixel size in CRS units; NULL takes it from the cells' resolution.
xminDOUBLEThe west edge of the canvas; NULL derives the canvas from the cells.
yminDOUBLEThe south edge of the canvas.
xmaxDOUBLEThe east edge of the canvas.
ymaxDOUBLEThe north edge of the canvas.
widthINTThe canvas width in pixels.
heightINTThe canvas height in pixels.
modeSTRINGHow the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'.
kring_padINTRings of padding around the derived canvas.
out_crsSTRINGNULLThe output CRS as EPSG:<n>. Set out_srid or out_crs, not both: setting both raises.
Grouped-agg UDF

If a cell id repeats in a group with different values, the largest value is burned, whatever order the rows arrive in. A null value (or NaN) never wins against a number. A cell whose values are all null burns NaN, also when the whole value column is null. Only an omitted value (or an untyped NULL) is the presence mask and burns 1.0. A DECIMAL column reaches the aggregate without its type, so a column of DECIMAL nulls counts as omitted too: cast it to DOUBLE first.

Implementation

The implementation is backed by quadbin cell math and rasterio. It burns each quadbin cell's geometry and value into the output band with rasterio.features.rasterize.

NoData sentinel is -9999.0

Pixels not covered by any geometry in the group are set to -9999.0 (band-registered NoData). Filter or mask downstream via gbx_rst_getnodata or IS NULL on the extracted band value.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming aggregator that burns quadbin cell geometry/value pairs (one row per cell) into a single rasterized tile per group. Quadbin cells are defined in EPSG:4326 lon/lat. Their geometry is reprojected to out_srid, so the output tile is in that CRS (pixel_size, the extent and width/height are given in it). The cell IDs carry their zoom level (0..26). The inverse of rst_quadbin_rastertogrid*: where those functions reduce raster pixels to per-cell statistics, this one synthesizes a raster from per-cell values.

Python-only out_crs parameter

The aggregate accepts an optional trailing out_crs (string CRS) argument. Set out_srid or out_crs, not both: setting both raises. It reads any CRS string.

Multi-row fixture: 3 quadbin zoom-12 cell rows near central London with burn values 1.0/2.0/3.0. All tabs use the same grouped-agg rasterize invocation.

Since v0.4.3
-- Rasterize quadbin cells into one raster tile per region. Each cell's value
-- is burned at the cell centroid pixel; the extent auto-derives from the cell
-- set (null canvas args). cellid is BIGINT.
SELECT region_id,
gbx_rst_quadbin_rasterize_agg(
cellid, burn_value,
4326, cast(null as double),
cast(null as double), cast(null as double),
cast(null as double), cast(null as double),
cast(null as int), cast(null as int),
'centroids', cast(0 as int)
) AS tile
FROM quadbin_cell_values
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|tile |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(tile, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|tile |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+

rst_quadbin_rasterize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, [out_crs])BINARY
Pythonrasterx.functions.rst_quadbin_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
cellsarray<struct<cellid:bigint,value:double>>array<struct<cellid:bigint,value:double>>The group's cells as an array of structs (cellid, value), for example collect_list(struct(cellid, value)). The rules of the aggregate hold: a repeated cell burns its largest value, a NULL cell id is skipped.
out_sridINTINTThe EPSG code of the output CRS.
pixel_sizeDOUBLEDOUBLEThe pixel size in CRS units; NULL takes it from the cells' resolution.
xminDOUBLEDOUBLEThe west edge of the canvas; NULL derives the canvas from the cells.
yminDOUBLEDOUBLEThe south edge of the canvas.
xmaxDOUBLEDOUBLEThe east edge of the canvas.
ymaxDOUBLEDOUBLEThe north edge of the canvas.
widthINTINTThe canvas width in pixels.
heightINTINTThe canvas height in pixels.
modeSTRINGSTRINGHow the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'.
kring_padINTINTRings of padding around the derived canvas.
out_crsSTRINGSTRINGNULLThe output CRS as EPSG:<n>. Set out_srid or out_crs, not both: setting both raises.

Rasterize an array of quadbin cells into one tile, the scalar twin of rst_quadbin_rasterize_agg. Collect the group's cells first, for example gbx_rst_quadbin_rasterize(collect_list(struct(cellid, value)), ...). The answer is the same bytes as the aggregate gives. Use it for a group the aggregate's streaming shape cannot take, such as a Serverless finalize or a group from an earlier step. It also runs on Unity Catalog, where an array or canvas over 64 MiB is refused with a Fix: that names the aggregate.

Since v0.6.0
-- Three zoom-12 cells over London. collect_list(struct(cellid, value)) gathers them into
-- one array. The canvas is 3 x 1 pixels of 0.2 degrees; each cell burns its value at the
-- pixel of its centroid.
SELECT gbx_rst_quadbin_rasterize(
collect_list(struct(cellid, value)),
4326, 0.2, -0.4, 51.3, 0.2, 51.5, 3, 1, 'centroids', 0
) AS content
FROM (
SELECT gbx_quadbin_pointascell(lon, lat, 12) AS cellid, value
FROM (VALUES
(-0.30, 51.40, 1.0), (-0.10, 51.40, 2.0), (0.10, 51.40, 3.0)
) AS p(lon, lat, value)
);
Example output
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:4326. Pixels: [1.0, 2.0, 3.0])

rst_custom_rasterize_agg​

SQLPythonScala
SurfaceCallReturns
SQL (session)gbx_rst_custom_rasterize_agg(cellid, value, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad)BINARY
Pythonrasterx.functions.rst_custom_rasterize_agg(cellid, value, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad)Column
ParameterSQL typeDefaultDescription
cellidBIGINTThe custom-grid cell id.
valueDOUBLEThe value burned for the cell. A repeated cell burns its largest value; a NULL value in a typed column never wins against a number, and a cell of nothing but NULL burns NaN. An untyped NULL (the argument left out, or None in Python) is the presence mask and burns 1.0.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, from gbx_custom_grid. The same for every row of the group.
out_sridINTThe EPSG code of the output CRS.
pixel_sizeDOUBLEThe pixel size in CRS units; NULL takes it from the cells' resolution.
xminDOUBLEThe west edge of the canvas; NULL derives the canvas from the cells.
yminDOUBLEThe south edge of the canvas.
xmaxDOUBLEThe east edge of the canvas.
ymaxDOUBLEThe north edge of the canvas.
widthINTThe canvas width in pixels.
heightINTThe canvas height in pixels.
modeSTRINGHow the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'.
kring_padINTRings of padding around the derived canvas.
Grouped-agg UDF

If a cell id repeats in a group with different values, the largest value is burned, whatever order the rows arrive in. A null value (or NaN) never wins against a number. A cell whose values are all null burns NaN, also when the whole value column is null. Only an omitted value (or an untyped NULL) is the presence mask and burns 1.0. A DECIMAL column reaches the aggregate without its type, so a column of DECIMAL nulls counts as omitted too: cast it to DOUBLE first.

Implementation

Powered by rasterio + custom-grid cell math. Aggregate — groupBy(...).agg(rx.rst_custom_rasterize_agg("cellid", "value", ...)) burns each custom-grid cell's centroid pixel (or spatial-envelope pixels with mode='spatial_envelope') into one raster tile per group. Cell IDs are BIGINT encoded by the custom-grid layout. When value is omitted (or an untyped NULL), all burned pixels carry 1.0 (presence mask); a typed column of nulls burns NaN. The extent auto-derives from the cell set when canvas parameters are null.

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming aggregator that burns custom-grid cell values into one raster tile per group. Cell IDs are BIGINT encoded by the gbx_custom_grid(...) layout. This is the inverse of rst_custom_rastertogrid*: where those functions reduce raster pixels to per-cell statistics, rst_custom_rasterize_agg reconstructs a raster from per-cell values. Pass the custom-grid struct (from gbx_custom_grid(...)) as the third argument; the canvas extent auto-derives from the cell set when all spatial parameters are null. The derived canvas follows the cell edges of the grid, from bound_x_min and bound_y_min, when out_srid is the grid's CRS.

Since v0.5.1
-- Rasterize custom-grid cells into one raster tile per region. cellid is BIGINT.
-- Pass the custom grid struct as the third argument; the extent auto-derives from
-- the cell set (null canvas args).
SELECT region_id,
gbx_rst_custom_rasterize_agg(
cellid, burn_value,
{_CUSTOM_GRID_LITERAL},
27700, cast(null as double),
cast(null as double), cast(null as double),
cast(null as double), cast(null as double),
cast(null as int), cast(null as int),
'centroids', cast(1 as int)
) AS tile
FROM custom_cell_values
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|tile |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY; wrap with
# gbx_rst_fromcontent(tile, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|tile |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+

rst_custom_rasterize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rasterize(cells, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad)BINARY
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rasterize(cells, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad)BINARY
Pythonrasterx.functions.rst_custom_rasterize(cells, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad)Column
ParameterSQL typeUC typeDefaultDescription
cellsarray<struct<cellid:bigint,value:double>>array<struct<cellid:bigint,value:double>>The group's cells as an array of structs (cellid, value), for example collect_list(struct(cellid, value)). The rules of the aggregate hold: a repeated cell burns its largest value, a NULL cell id is skipped.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, from gbx_custom_grid. The same for every row of the group.
out_sridINTINTThe EPSG code of the output CRS.
pixel_sizeDOUBLEDOUBLEThe pixel size in CRS units; NULL takes it from the cells' resolution.
xminDOUBLEDOUBLEThe west edge of the canvas; NULL derives the canvas from the cells.
yminDOUBLEDOUBLEThe south edge of the canvas.
xmaxDOUBLEDOUBLEThe east edge of the canvas.
ymaxDOUBLEDOUBLEThe north edge of the canvas.
widthINTINTThe canvas width in pixels.
heightINTINTThe canvas height in pixels.
modeSTRINGSTRINGHow the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'.
kring_padINTINTRings of padding around the derived canvas.

Rasterize an array of custom-grid cells into one tile, the scalar twin of rst_custom_rasterize_agg. Collect the group's cells first, for example gbx_rst_custom_rasterize(collect_list(struct(cellid, value)), ...). The answer is the same bytes as the aggregate gives. Use it for a group the aggregate's streaming shape cannot take, such as a Serverless finalize or a group from an earlier step. It also runs on Unity Catalog, where an array or canvas over 64 MiB is refused with a Fix: that names the aggregate.

Since v0.6.0
-- Three 2 km cells (resolution 1) of the grid. collect_list(struct(cellid, value)) gathers
-- them into one array. The canvas is 2 x 2 pixels of 2 km; each cell burns its value at
-- the pixel of its centroid.
SELECT gbx_rst_custom_rasterize(
collect_list(struct(cellid, value)),
{_CUSTOM_GRID_LITERAL},
27700, 2000.0, 529000.0, 179000.0, 533000.0, 183000.0, 2, 2, 'centroids', 0
) AS content
FROM (
SELECT gbx_custom_pointascell(wkt, {_CUSTOM_GRID_LITERAL}, 1) AS cellid, value
FROM (VALUES
('POINT(530000 180000)', 1.0), ('POINT(532000 180000)', 2.0), ('POINT(530000 182000)', 3.0)
) AS p(wkt, value)
);
Example output
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:27700. Pixels, north row first:
[3.0, -9999]
[1.0, 2.0 ])

rst_rasterize_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_rasterize_agg(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid)BINARY
Pythonrasterx.functions.rst_rasterize_agg(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid)Column
ParameterSQL typeDefaultDescription
geomBINARY or STRINGThe feature geometry: WKB, EWKB, WKT or EWKT. A NULL or unparseable one is skipped.
valueDOUBLEThe value burned where the geometry covers a pixel centre. A NULL value skips the row.
xminDOUBLEThe west edge of the output.
yminDOUBLEThe south edge.
xmaxDOUBLEThe east edge.
ymaxDOUBLEThe north edge.
width_pxINTThe output width in pixels.
height_pxINTThe output height in pixels.
out_sridINTThe EPSG code of the output CRS.
Grouped-agg UDF
Implementation

Powered by rasterio (rasterio.features). Aggregate — burns the group's (geom, value) rows into one tile over the given extent/size/SRID (last-wins on overlap).

The aggregate returns BINARY

In SQL and Python the aggregate returns the raster as BINARY (the GeoTIFF bytes), on every compute. Wrap it with gbx_rst_fromcontent(<aggregate>, 'GTiff') to get a tile back.

Streaming aggregator that burns geometry/value pairs (one row per feature) into a single rasterized tile per group. Use it when features arrive as individual rows, not as a pre-built collection.

Multi-row fixture: 3 polygon rows burned at values 1.0/2.0/3.0 over a [0,0,4,4] EPSG:4326 extent. All tabs use the same grouped-agg burn invocation.

Since v0.4.0
-- Aggregate per-feature burn values into one rasterized tile per region.
SELECT region_id,
gbx_rst_rasterize_agg(
geom_wkb, burn_value,
bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax,
256, 256, 4326
) AS tile
FROM features
GROUP BY region_id;
Example output
# Heavyweight SQL — one v2 tile struct per group:
+---------+-----------------------------------------------------------+
|region_id|tile |
+---------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+---------+-----------------------------------------------------------+

# Lightweight SQL — raster bytes as BINARY (see the note above); wrap with
# gbx_rst_fromcontent(tile, 'GTiff') to rebuild a tile struct:
+---------+---------------+
|region_id|tile |
+---------+---------------+
|... |[B@... (BINARY)|
+---------+---------------+

Constructor Functions​

Create or load rasters from path, binary content, or bands (4 total).

rst_dtmfromgeoms​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_dtmfromgeoms(points_array, breaklines_array, merge_tolerance, snap_tolerance, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [no_data], [out_crs])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_dtmfromgeoms(points_array, breaklines_array, merge_tolerance, snap_tolerance, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [no_data], [out_crs])TILE
Pythonrasterx.functions.rst_dtmfromgeoms(points_array, breaklines_array, merge_tolerance, snap_tolerance, xmin, ymin, xmax, ymax, width_px, height_px, out_srid=None, no_data=None, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
points_arrayARRAY<BINARY> or ARRAY<STRING>ARRAY<GEOMETRY>The points, each with a Z value: WKB, EWKB, WKT or EWKT, as an array.
breaklines_arrayARRAY<BINARY> or ARRAY<STRING>ARRAY<GEOMETRY>Break lines, as an array; NULL or empty for none. The Python level uses their vertices as extra points and does not enforce them as edges.
merge_toleranceDOUBLEDOUBLEAccepted for signature compatibility; not applied.
snap_toleranceDOUBLEDOUBLEAccepted for signature compatibility; not applied.
xminDOUBLEDOUBLEThe west edge of the output in the output CRS.
yminDOUBLEDOUBLEThe south edge of the output.
xmaxDOUBLEDOUBLEThe east edge of the output, above xmin.
ymaxDOUBLEDOUBLEThe north edge of the output, above ymin.
width_pxINTINTThe output width in pixels, above 0.
height_pxINTINTThe output height in pixels, above 0.
out_sridINTINTNULLThe EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS, or with the geometry's own when out_crs is NULL too.
no_dataDOUBLEDOUBLE-9999.0The value of a pixel outside the points' hull.
out_crsSTRINGSTRINGNULLThe output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises.
Implementation

Powered by rasterio + SciPy (scipy.spatial.Delaunay). Barycentric interpolation over an unconstrained Delaunay TIN; cells outside the convex hull are NoData. breaklines, merge_tolerance, and snap_tolerance are accepted for signature parity but not enforced.

Create a DTM raster tile via TIN/Delaunay interpolation from an array of Z-valued point WKB geometries. An optional array of breakline WKB geometries preserves sharp terrain transitions.

Python-only out_crs parameter

The Python function takes an optional trailing out_crs (string CRS) that SQL does not.

Output CRS via out_srid (int); input points assumed already in the output CRS. See Coordinate Reference Systems.

On Unity Catalog the points and break lines are an ARRAY<GEOMETRY(ANY)>, and the Z of each point is kept. See Points as geometries.

Since v0.4.0
-- TIN interpolation from arrays of Z-valued point WKB and breakline WKB.
-- Output is a 100 x 100 Float64 GTiff over the extent. For N-metre cells set
-- width_px = round((xmax-xmin)/N): here a 1000 m extent at 10 m cells -> 100 px.
SELECT gbx_rst_dtmfromgeoms(
points_wkb_array, breaklines_wkb_array,
0.0, 0.01,
0.0, 0.0, 1000.0, 1000.0,
100, 100, 32633
) AS dtm
FROM survey_points;
Example output
+-----------------------------------------------------------+
|dtm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_frombands​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_frombands(bands)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_frombands(bands)TILE
Pythonrasterx.functions.rst_frombands(bands, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
bandsARRAY<TILE>ARRAY<TILE>The single-band tiles, in an array: element 0 becomes band 1, element 1 band 2, and so on. The georeference, data type and NoData come from the first.
Implementation

Powered by rasterio. Stacks an ARRAY of single-band tiles into one multi-band tile in array order (element 0 → band 1), preserving georeference/CRS/dtype/NoData from the first.

Create a raster from an array of band tiles.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Constructor — stacks per-band tiles into a multi-band tile. Example splits the multiband fixture into per-band tiles via rst_band, then re-stacks them into a 3-band tile.

Since v0.2.0
SELECT
gbx_rst_frombands(array(band1, band2, band3)) as multi_band
FROM separated_bands;
Example output
+-----------------------------------------------------------+
|multi_band |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_fromcontent​

SQLUnity Catalog SQLPythonScala
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_fromcontent(content, driver)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_fromcontent(content, driver)TILE
Pythonrasterx.functions.rst_fromcontent(content, driver)Column
ParameterSQL typeUC typeDefaultDescription
contentBINARYBINARYThe raster file's bytes, for example the content column of the binaryFile reader.
driverSTRINGSTRINGThe GDAL driver short name the bytes are in, for example 'GTiff', in any case. It goes into the tile's driver metadata; a name that is no raster driver (no driver of that name, or a vector-only one such as 'GeoJSON') raises.
Implementation

Powered by rasterio. The driver defaults to GTiff when unspecified and outputs are re-encoded as GeoTIFF; readable input formats are limited to the GDAL build bundled with rasterio.

Create a raster from binary content.

Returns: Binary raster tile data

Constructor — builds a tile from binary content. Example uses Spark's binaryFile reader to load bytes, then rst_fromcontent to decode them — this is the canonical pattern and works on any compute, including Serverless.

Serverless memory — you own the bytes

rst_fromcontent materializes bytes that are already in a column. Those bytes are in executor memory before this call; GeoBrix does not guard their size. On Serverless the connect-aware cap is 64 MiB per tile — keep individual content values at or under that limit. For larger sources, use the virtual-tile raster readers (the default) and let the runtime page bytes lazily. See Serverless & Memory.

Since v0.2.0
-- Load from binary table
SELECT
path,
gbx_rst_fromcontent(content, 'GTiff') as tile
FROM binary_raster_table;
Example output
+----+-----------------------------------------------------------+
|path|tile |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+

rst_fromfile​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_fromfile(path, [driver], [geom], [clip_crs], [resolution])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_fromfile(path, [driver], [geom], [clip_crs], [resolution])TILE
Pythonrasterx.functions.rst_fromfile(path, driver=None, geom=None, clip_crs=None, resolution=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
pathSTRING or FILEFILEThe raster file: a path (local, /Volumes/..., /Workspace/...) or a FILE value. A remote URL is refused unless the driver's remote-read switch is on.
driverSTRINGSTRING'GTiff'The GDAL driver short name hint, in any case. It goes into the tile's driver metadata; a name that is no raster driver (no driver of that name, or a vector-only one such as 'GeoJSON') raises.
geomBINARY or STRING or GEOMETRYGEOMETRYNULLAn optional polygon to clip to, as WKB, EWKB, WKT or EWKT, or a GEOMETRY. Only the blocks the polygon covers are read.
clip_crsSTRINGSTRINGNULLThe CRS of a geom that carries no SRID: EPSG:<code>, ESRI:<code>, WKT or an integer code. The CRS of the raster when NULL. An EWKB or EWKT SRID wins.
resolutionDOUBLEDOUBLENULLAn optional target pixel size in the raster's CRS units. The coarsest overview that is still at least this fine is read. Full resolution when NULL.

Read a raster file into a tile. Pass a path, or a FILE value, as path. Add geom or resolution to read only part of the file.

In Python, rst_fromfile returns a virtual tile by default. It holds no bytes, points at path over the whole-file window and reads width, height and the CRS from the header. No pixel is read until a later function needs it, so it is the way to load large rasters lazily. Pass materialize=True to read the pixels now. There is no virtualize_dir or virtualize_prefix argument, because the source file is the durable store.

The SQL function gbx_rst_fromfile always reads the file's pixels and returns a tile that holds them, so every function accepts it. It is a Python function and needs the env wheel. It reads UC Volume /Volumes/... paths with the credential held by the Spark Python worker. A path that cannot be opened gives null.

Read a window: geom and resolution​

  • geom clips to a polygon. Pass a GEOMETRY, or WKB, EWKB, WKT or EWKT, in a session and on Unity Catalog alike, so one SQL text runs in both. A geom that misses the raster gives NULL.
  • An SRID in the geometry wins over clip_crs. A geom without an SRID takes clip_crs, or the raster's CRS when clip_crs is NULL.
  • resolution is a pixel size in the raster's CRS units. The function reads the coarsest overview that is still at least this fine. NULL reads full resolution.
  • Either argument reads only the COG blocks the window needs. The result is a materialized tile, in Python and in SQL.
  • With neither argument, the Python level returns a virtual tile and SQL returns a materialized tile.
  • A FILE value with its own offset reads only its slice of the object, in a session as on Unity Catalog.

On Unity Catalog​

The Unity Catalog function takes a FILE value as path. A path string is not accepted.

  • Pass a FILE or a FILE EXTERNAL column directly. Do not write CAST(<col> AS FILE): from a FILE EXTERNAL column it fails with CAST_TO_FILE_TYPE.FROM_FILE.
  • Pass a GEOMETRY(4326) column directly as geom. No cast is needed.
  • The function reads FILE byte ranges, so the file must be a tiled GeoTIFF or a COG. A FILE value with its own offset, a slice of an object, reads correctly.
  • The function has no error tile. A refused read raises an error with a Fix:.
RefusedFix
A window over 64 MiB decodedPass a coarser resolution or a smaller geom.
A striped GeoTIFFWrite the file as a COG with cog_gbx.
A file that is not a TIFFRun the function in a notebook or job session. Or read the bytes with read_files and call gbx_rst_fromcontent.
A header over 4 MiBWrite smaller COGs with cog_gbx, with a smaller raster per file.
A block table that names bytes outside the fileWrite the file again as a COG with cog_gbx.
A fetch over 256 MiBPass a coarser resolution or a smaller geom, or run the function in a notebook or job session.

Query FILE columns from Unity Catalog lists the steps from a Volume of files to a query.

Remote paths

A remote URL (http(s)://, /vsicurl/, ...) is data here. rst_fromfile refuses it at its first evaluation, with the location and a Fix:. Set GBX_ALLOW_REMOTE_PATHS=true in the driver's environment before register() and before the column is built to allow it (see Security § 7).

materialize=True errors over the Serverless cap

Reading a file larger than the connect-aware stream cap raises a ValueError. The cap is 64 MiB on Serverless and 256 MiB on classic compute (dedicated or standard access mode). This applies to materialize=True and to the SQL function gbx_rst_fromfile. The error is intentional, because reading an oversized tile would run the executor out of memory. The Python default (materialize unset, a virtual tile) is Serverless-safe: pixels are read lazily and size-gated at each later function. See Serverless & Memory.

Since v0.2.0
-- gbx_rst_fromfile is a Python UDF (no JVM form; requires the lightweight tier, e.g. the env6 wheel). The
-- SQL call is the same 2-argument form in both tiers — the tier you register
-- decides the result (whichever register() ran last wins):
-- Lightweight (rx.register / pyrx): returns a VIRTUAL tile (bytes-free,
-- path + whole-file window; lazy).
-- Heavyweight (rasterx register): returns a MATERIALIZED tile (raster
-- bytes present) — JVM/heavy callers
-- cannot use a virtual path-only tile.
SELECT
gbx_rst_fromfile('/Volumes/main/geobrix_samples/nyc/sentinel2.tif', 'GTiff') AS tile;

-- Either way, accessors read what they need — width/height come from the header
-- (no pixel read even for the virtual tile):
SELECT
path,
gbx_rst_width(gbx_rst_fromfile(path, 'GTiff')) as width,
gbx_rst_height(gbx_rst_fromfile(path, 'GTiff')) as height
FROM raster_paths;
Example output
# Both tiers return the SAME v2 tile struct (cellid, raster, path, window, ...);
# only the field values differ — virtual carries the path, materialized the bytes.

# Lightweight registration — a VIRTUAL v2 tile (raster null; path + window set):
+---------------------------------------------------------------+
|tile |
+---------------------------------------------------------------+
|{0, null, /Volumes/..., {0, 0, 10980, 10980}, ..., null, {...}}|
+---------------------------------------------------------------+

# Heavyweight registration — a MATERIALIZED v2 tile (raster bytes; path null):
+------------------------------------------------------------+
|tile |
+------------------------------------------------------------+
|{0, <raster bytes>, null, null, ..., {driver -> GTiff, ...}}|
+------------------------------------------------------------+

# width/height (either tier) read from the header:
+----+-----+------+
|path|width|height|
+----+-----+------+
|... |10980|10980 |
+----+-----+------+
Loading rasters at scale? Use the Raster Reader

rst_fromfile pulls columnar raster paths into a tile column inline. To ingest rasters as a normal Spark job — partitioned parallel reads, optional tiling (sizeInMB), FUSE-safe Volume staging — use the Raster Reader (raster_gbx / gtiff_gbx): spark.read.format("raster_gbx").load(path). It, too, emits virtual tiles by default.

Have the bytes already, or need a materialized tile? Use rst_fromcontent

If you already hold raster bytes in a column (e.g. from Spark's built-in binaryFile reader), build the tile with gbx_rst_fromcontent(content, driver). Note this is not a lazy equivalent of rst_fromfile: rst_fromcontent takes bytes you have already read, so it always produces a materialized tile. It also works on any compute, since the binaryFile reader runs in Spark, which holds the Volume credential:

df = (
spark.read.format("binaryFile")
.load("/Volumes/main/geobrix_samples/geobrix-examples/nyc/*.tif")
.selectExpr("path", "gbx_rst_fromcontent(content, 'GTiff') AS tile")
)

rst_gridfrompoints​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_gridfrompoints(points_array, values_array, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [power], [max_pts], [out_crs])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_gridfrompoints(points_array, values_array, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [power], [max_pts], [out_crs])TILE
Pythonrasterx.functions.rst_gridfrompoints(points_array, values_array, xmin, ymin, xmax, ymax, width_px, height_px, out_srid=None, power=None, max_pts=None, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
points_arrayARRAY<BINARY> or ARRAY<STRING>ARRAY<GEOMETRY>The points: WKB, EWKB, WKT or EWKT, as an array. An empty or NULL element is dropped with its value.
values_arrayARRAY<DOUBLE>ARRAY<DOUBLE>The value of each point, in the same order.
xminDOUBLEDOUBLEThe west edge of the output in the output CRS.
yminDOUBLEDOUBLEThe south edge of the output.
xmaxDOUBLEDOUBLEThe east edge of the output, above xmin.
ymaxDOUBLEDOUBLEThe north edge of the output, above ymin.
width_pxINTINTThe output width in pixels, above 0.
height_pxINTINTThe output height in pixels, above 0.
out_sridINTINTNULLThe EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS, or with the geometry's own when out_crs is NULL too.
powerDOUBLEDOUBLE2.0The inverse-distance exponent, above 0.
max_ptsINTINT12The number of nearest points used per pixel, above 0.
out_crsSTRINGSTRINGNULLThe output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises.

See interpolation & fill to choose among sampling, resampling, and gap-filling.

Implementation

Powered by rasterio + SciPy (cKDTree IDW). Inverse-distance interpolation (power, max_pts) to a single-band Float64 grid; NoData −9999. Matches GDAL's invdist defaults (power=2.0, max_pts=12).

IDW-interpolate an array of Z-valued point geometries to a Float64 GeoTIFF tile covering an explicit bounding box and pixel grid. Supply the points and their scalar values as arrays in a single row; use rst_gridfrompoints_agg when points arrive one per row.

Python-only out_crs parameter

The Python function takes an optional trailing out_crs (string CRS) that SQL does not. SQL takes the integer out_srid only.

Output CRS via out_srid (int); input points are assumed already in the output CRS. See Coordinate Reference Systems.

On Unity Catalog the points are an ARRAY<GEOMETRY(ANY)>. See Points as geometries.

Since v0.4.0
-- IDW (power=2, max_points=12) from arrays of point WKB and values.
-- Output is a 256 x 256 Float64 GTiff covering the requested extent.
SELECT gbx_rst_gridfrompoints(
points_wkb_array, values_array,
0.0, 0.0, 1000.0, 1000.0,
256, 256, 32633
) AS idw
FROM point_clouds;
Example output
+-----------------------------------------------------------+
|idw |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(IDW-interpolated tile over specified extent)

LiDAR / Point-Cloud DSM​

Four functions for building raster products from LiDAR point clouds. Available on every compute. Load point clouds with the lidar_gbx reader. For an end-to-end walkthrough — .laz → DSM/DTM binning → Canopy Height Model — see the Wireless Coverage example.

rst_binpoints​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_binpoints(x_array, y_array, z_array, xmin, ymin, xmax, ymax, width_px, height_px, srid, [statistic])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_binpoints(x_array, y_array, z_array, xmin, ymin, xmax, ymax, width_px, height_px, srid, [statistic])TILE
Pythonrasterx.functions.rst_binpoints(x_array, y_array, z_array, xmin, ymin, xmax, ymax, width_px, height_px, srid, statistic=None)Column
ParameterSQL typeUC typeDefaultDescription
x_arrayARRAY<DOUBLE>ARRAY<DOUBLE>The x coordinate of each point.
y_arrayARRAY<DOUBLE>ARRAY<DOUBLE>The y coordinate of each point, in the same order.
z_arrayARRAY<DOUBLE>ARRAY<DOUBLE>The value of each point, in the same order.
xminDOUBLEDOUBLEThe west edge of the output in the output CRS.
yminDOUBLEDOUBLEThe south edge of the output.
xmaxDOUBLEDOUBLEThe east edge of the output, above xmin.
ymaxDOUBLEDOUBLEThe north edge of the output, above ymin.
width_pxINTINTThe output width in pixels, above 0.
height_pxINTINTThe output height in pixels, above 0.
sridINTINTThe EPSG or ESRI code of the output CRS.
statisticSTRINGSTRING'max'How the points in a pixel combine: max, min, mean, median, count or percentile:<p> (for example percentile:90), in any case. Another word raises.

Bin a per-row ARRAY<DOUBLE> of (x, y, z) coordinate triples into a single-band Float32 raster tile. Each pixel carries the reduction of all points whose centroid falls within the pixel cell. Empty cells carry NoData (−9999). The bounding box uses a half-open interval on the upper x/y edges to prevent double-counting when DSM tiles are assembled from adjacent strips.

What it computes. This is the point-cloud→raster (DSM-building) step. Every input point is dropped into the grid cell its (x, y) falls in. The pixel value is the chosen reduction of the z-values that landed there. With the default "max" that is the tallest return per cell — a surface model (DSM), exactly the input rst_chm differences against a DEM. The "min"/"mean"/"median"/"count"/"percentile:<p>" modes reduce the same points into other surfaces.

Since v0.5.2
SELECT gbx_rst_binpoints(
array(550100.0, 550200.0, 550300.0),
array(180100.0, 180200.0, 180500.0),
array(42.5, 45.1, 38.7),
550000.0, 180000.0, 551000.0, 181000.0,
10, 10, 27700, 'max'
) AS dsm;
Example output
+-----------------------------------------------------------+
|dsm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band Float32 DSM tile: max-z per 100 m cell over the 1 km extent)

rst_binpoints_agg​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_binpoints_agg(x, y, z, xmin, ymin, xmax, ymax, width_px, height_px, srid, [statistic])BINARY
Pythonrasterx.functions.rst_binpoints_agg(x, y, z, xmin, ymin, xmax, ymax, width_px, height_px, srid, statistic=None)Column
ParameterSQL typeDefaultDescription
xDOUBLEThe point's x.
yDOUBLEThe point's y.
zDOUBLEThe point's value.
xminDOUBLEThe west edge of the output.
yminDOUBLEThe south edge.
xmaxDOUBLEThe east edge.
ymaxDOUBLEThe north edge.
width_pxINTThe output width in pixels.
height_pxINTThe output height in pixels.
sridINTThe EPSG code of the output CRS.
statisticSTRING'max''max', 'min', 'mean', 'median', 'count' or 'percentile:<p>'.
Grouped-agg UDF

Aggregator variant of rst_binpoints: stream one scalar (x, y, z) point per row into a DSM tile via groupBy(...).agg(rx.rst_binpoints_agg(...)). The xmin/ymin/xmax/ymax/width_px/height_px/srid/statistic arguments are per-group constants. The per-cell binning is identical to rst_binpoints. See What it computes there for the reduction semantics and statistic modes. It just streams one point per row instead of a per-row array.

The SQL aggregate returns BINARY (raster bytes). Wrap with gbx_rst_fromcontent(<agg>, 'GTiff') to rebuild a tile struct. The Python wrapper rx.rst_binpoints_agg(...) returns the full tile struct.

Since v0.5.2
SELECT tile_id,
gbx_rst_binpoints_agg(x, y, z, 550000.0, 180000.0, 551000.0, 181000.0, 10, 10, 27700, 'max') AS dsm
FROM (
VALUES (1, 550100.0, 180100.0, 42.5), (1, 550200.0, 180200.0, 45.1), (1, 550300.0, 180500.0, 38.7)
) AS t(tile_id, x, y, z)
GROUP BY tile_id;
Example output
+-------+--------------+
|tile_id|dsm |
+-------+--------------+
|1 |<raster bytes>|
+-------+--------------+
(BINARY raster bytes — wrap with gbx_rst_fromcontent(dsm, 'GTiff') to rebuild a tile struct)
Memory & scale — binning full-density LiDAR

Both rst_binpoints_agg (grouped — realizes a whole group's points in the worker) and rst_binpoints (scalar — realizes a row's point arrays) hold memory proportional to the points per group. That is fine at moderate density. A full-resolution tile (millions of returns — e.g. a 1 km tile of 1 m LiDAR) can exhaust worker RAM.

For large or full-density point clouds, use the bounded helper bin_points_tiled(df, x, y, z, by=[…], xmin=…, ymin=…, xmax=…, ymax=…, width, height, srid, stat). It runs a two-stage native aggregation — per-point pixel index → native groupBy(tile, cell) reduction → placement — so peak memory is the raster grid (W×H), independent of point count. It returns the same tile struct (drops straight into rst_chm), and its output is identical to groupBy(by).agg(rst_binpoints_agg(…)) for max/min/mean/count. median/percentile (which need every value in a cell) delegate to the buffered aggregator — decimate or use smaller tiles for those. Import it from databricks.labs.gbx.rasterx.helpers. Prefer bin_points_tiled over a collect_list(all points) → rst_binpoints pattern, which buffers the whole cloud. See Performance and the LiDAR reader.


rst_binpoints_partial​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_binpoints_partial(x, y, xmin, ymin, xmax, ymax, width_px, height_px)struct<col:int,row:int>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_binpoints_partial(x, y, xmin, ymin, xmax, ymax, width_px, height_px)struct<col:int,row:int>
Pythonrasterx.functions.rst_binpoints_partial(x, y, xmin, ymin, xmax, ymax, width_px, height_px)Column
ParameterSQL typeUC typeDefaultDescription
xDOUBLEDOUBLEThe point's x in the canvas CRS.
yDOUBLEDOUBLEThe point's y in the canvas CRS.
xminDOUBLEDOUBLEThe west edge of the canvas in its CRS.
yminDOUBLEDOUBLEThe south edge of the canvas.
xmaxDOUBLEDOUBLEThe east edge of the canvas, above xmin.
ymaxDOUBLEDOUBLEThe north edge of the canvas, above ymin.
width_pxINTINTThe canvas width in pixels, above 0.
height_pxINTINTThe canvas height in pixels, above 0.

Give the canvas pixel a point falls in, as a (col, row) key to group by. The column counts from the west and the row from the north. The rule is the one rst_binpoints uses: a point on the east or south edge is in no pixel. The function is a SQL expression, so a query runs it with no Python call. Use it with rst_binpoints_finalize to bin any number of points: the points never leave SQL, and only one value per occupied pixel reaches Python.

WITH b AS (
SELECT gbx_rst_binpoints_partial(x, y, 0D, 0D, 1024D, 1024D, 1024, 1024) AS px, z FROM points
),
c AS (
SELECT px.col AS col, px.row AS row, max(z) AS value -- min, avg, count, median, percentile(z, 0.9)
FROM b WHERE px IS NOT NULL AND z IS NOT NULL AND NOT isnan(z)
GROUP BY px.col, px.row
)
SELECT gbx_rst_binpoints_finalize(collect_list(struct(col, row, value)), 0D, 0D, 1024D, 1024D, 1024, 1024, 32633) AS tile
FROM c

The statement writes the tile that rst_binpoints_agg writes for the same points. Two differences hold when a z is NULL or NaN. The statement drops that point. The aggregate counts a NaN point in count, and gives NoData for mean and median when a pixel holds a NaN. Use count(*) for count, and cast the result to DOUBLE.

Since v0.6.0
-- A 10 x 10 canvas of 1 x 1 pixels. The column counts from the west and the row from the north.
-- A point on the east or south edge is in no pixel, so its key is NULL.
SELECT x, y, gbx_rst_binpoints_partial(x, y, 0D, 0D, 10D, 10D, 10, 10) AS px
FROM (VALUES
(1.5D, 8.5D), (0.5D, 0.5D), (0D, 10D), (10D, 5D)
) AS t(x, y);
Example output
+----+----+------+
|x |y |px |
+----+----+------+
|1.5 |8.5 |{1, 1}|
|0.5 |0.5 |{0, 9}|
|0.0 |10.0|{0, 0}|
|10.0|5.0 |NULL |
+----+----+------+
(px is STRUCT<col, row>)

rst_binpoints_finalize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_binpoints_finalize(cells, xmin, ymin, xmax, ymax, width_px, height_px, srid)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_binpoints_finalize(cells, xmin, ymin, xmax, ymax, width_px, height_px, srid)TILE
Pythonrasterx.functions.rst_binpoints_finalize(cells, xmin, ymin, xmax, ymax, width_px, height_px, srid)Column
ParameterSQL typeUC typeDefaultDescription
cellsarray<struct<col:int,row:int,value:double>>array<struct<col:int,row:int,value:double>>The reduced pixels as an array of structs (col, row, value), for example collect_list(struct(col, row, value)) over a GROUP BY of the gbx_rst_binpoints_partial keys. A NULL element or a NULL or NaN value leaves the pixel NoData; a pixel given twice keeps its largest value; a col or row outside the canvas raises.
xminDOUBLEDOUBLEThe west edge of the output in its CRS.
yminDOUBLEDOUBLEThe south edge of the output.
xmaxDOUBLEDOUBLEThe east edge of the output, above xmin.
ymaxDOUBLEDOUBLEThe north edge of the output, above ymin.
width_pxINTINTThe output width in pixels, above 0.
height_pxINTINTThe output height in pixels, above 0.
sridINTINTThe EPSG or ESRI code of the output CRS.

Write the reduced pixels of a points group into one single-band Float32 tile. Pass collect_list(struct(col, row, value)) over the pixels you grouped with rst_binpoints_partial. The input has one struct per occupied pixel, so its size follows the canvas and not the number of points. A pixel in no struct is NoData (-9999), and so is a pixel whose value is NULL or NaN. A col or row outside the canvas raises, because the keys came from another canvas. On Unity Catalog, a canvas that is too large for one function call is refused. The error names rst_binpoints_agg, which runs in a notebook or job session.

Since v0.6.0
-- Bin the points with rst_binpoints_partial, reduce each pixel with an ordinary GROUP BY
-- (here the maximum), then write the occupied pixels as one tile.
WITH b AS (
SELECT gbx_rst_binpoints_partial(x, y, 0D, 0D, 2D, 1D, 2, 1) AS px, z
FROM (VALUES (0.5D, 0.5D, 1D), (0.6D, 0.4D, 5D), (1.5D, 0.5D, 7D)) AS t(x, y, z)
),
c AS (
SELECT px.col AS col, px.row AS row, max(z) AS value
FROM b WHERE px IS NOT NULL
GROUP BY px.col, px.row
)
SELECT gbx_rst_binpoints_finalize(collect_list(struct(col, row, value)), 0D, 0D, 2D, 1D, 2, 1, 4326) AS tile
FROM c;
Example output
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(a 2 x 1 Float32 tile in EPSG:4326: [5.0, 7.0])

rst_isoband​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_isoband(tile, breaks)array<struct<geom_wkb:binary,band:int,lower:double,upper:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_isoband(tile, breaks)array<struct<geom_wkb:binary,band:int,lower:double,upper:double>>
Pythonrasterx.functions.rst_isoband(tile, breaks)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to classify.
breaksARRAY<DOUBLE>ARRAY<DOUBLE>The N+1 boundaries of N bands, strictly ascending. Band i holds the pixels from breaks[i] up to, not including, breaks[i+1].

Reclassify a raster band into value bins defined by a breaks array and return one polygon per contiguous patch of pixels in the same bin. Useful for producing height-band polygons from a CHM or DSM, or elevation isobands from a DEM.

Returns ARRAY<STRUCT<geom_wkb BINARY, band INT, lower DOUBLE, upper DOUBLE>> — one entry per contiguous region. geom_wkb is a WKB Polygon in the raster's own CRS. NoData pixels are excluded. Pixels below breaks[0] or >= breaks[-1] are dropped.

Each bin is half-open — [breaks[i], breaks[i+1]). It is closed on the lower bound and open on the upper. A value equal to a break belongs to the band that break opens. For example, with breaks = array(0, 50, 100, 150, 200), a value of 55.0 — and 50.0 itself — falls in the [50.0, 100.0) band (band index 1), while 100.0 moves up to the [100.0, 150.0) band and 200.0 (equal to breaks[-1]) is dropped.

Implemented with numpy.digitize + rasterio.features.shapes — no GDAL required.

Since v0.5.2
SELECT gbx_rst_isoband(tile, array(0.0, 50.0, 100.0, 150.0, 200.0)) AS patches
FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|patches |
+-----------------------------------------------------------+
|[{[BINARY], 0, 0.0, 50.0}, {[BINARY], 1, 50.0, 100.0}, ...]|
+-----------------------------------------------------------+
(array of per-patch structs: geom_wkb WKB polygon in raster CRS, band index, lower/upper break values)

rst_chm​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_chm(dsm_tile, dem_tile)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_chm(dsm_tile, dem_tile)TILE
Pythonrasterx.functions.rst_chm(dsm_tile, dem_tile)Column
ParameterSQL typeUC typeDefaultDescription
dsm_tileTILETILEThe Digital Surface Model tile.
dem_tileTILETILEThe Digital Elevation Model tile; it defines the output grid.

Compute a Canopy Height Model (CHM) from a Digital Surface Model (DSM) tile and a Digital Elevation Model (DEM) tile: CHM = clamp(align(DSM → DEM grid) − DEM, min=0).

What it computes. The DSM holds the height of the top surface in each cell (canopy, rooftops). The DEM holds bare-earth ground elevation. Subtracting one from the other leaves the height of whatever stands above the ground (canopy or object height) in the DEM's units. It is a per-cell subtraction, not an aggregation. Taking the max z per cell is how you build the DSM upstream (e.g. rst_binpoints over LiDAR returns). Then rst_chm differences that surface against the DEM.

The DSM is warped onto the DEM's grid (CRS, extent, width, height) via nearest-neighbour resampling before subtraction. Negative differences (where the DSM dips below the DEM due to noise) are clamped to 0. NoData in either input propagates to the output. Output is a Float32 GeoTIFF tile with NoData −9999.

Since v0.5.2
SELECT gbx_rst_chm(tile, tile) AS chm FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|chm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(Float32 CHM tile: clamp(DSM - DEM, min=0); NoData propagates from either input)

Generator Functions​

Produce multiple tiles or bands (7 total).

The generators are table functions: call them in the FROM clause with LATERAL, at every implementation level. The Python entry takes the input DataFrame first and returns it joined with the generated rows, for example rasterx.functions.rst_retile(df, "tile", 512, 512).

Compute the tile first

On Serverless, a SQL function cannot be an argument of a LATERAL call. This holds for functions such as gbx_rst_setsrid, gbx_rst_transform and gbx_rst_resample. Compute the tile in a subquery or CTE, then call the generator on that column, as the example does.

Retile a tile that another function made
from databricks.labs import gbx

gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
return spark.sql(
"""
WITH tagged AS (
SELECT gbx_rst_setsrid(tile, 32618) AS tile FROM rasters
)
SELECT t.* FROM tagged, LATERAL gbx_rst_retile(tile, 64, 64) t
"""
).take(3)
Example output
+------+--------------+-----+----------------------+
|cellid|raster |path |... |
+------+--------------+-----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+-----+----------------------+
(one row per sub-tile of the tile that gbx_rst_setsrid returned)

rst_bng_tessellate​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_tessellate(tile, resolution, [assignment], [coverage])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_tessellate(tile, resolution, [assignment], [coverage])rows
Pythonrasterx.functions.rst_bng_tessellate(df, tile, resolution, assignment=None, coverage=None)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps). Any other word raises.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, as all-NoData tiles; 'sparse' leaves them out. Any other word raises.
Streaming UDTF
Implementation

The implementation is backed by BNG cell math and rasterio. It auto-warps the input to EPSG:27700 with rasterio.warp, enumerates the overlapping BNG cells, and clips one tile per cell. BNG cell IDs are STRING at the row boundary.

Tessellate a raster to British National Grid (BNG) cells — one row per overlapping cell, each clipped to that cell's extent. The raster is automatically reprojected to EPSG:27700 (British National Grid) before tessellation, so any projected or geographic input is handled transparently. Resolution accepts integer indices ±1..±6 , where 1 = 100 km, 2 = 10 km, and 3 = 1 km. Index 4 = 100 m, 5 = 10 m, and 6 = 1 m. Negative indices address quadrant sub-cells. Resolution also accepts string keys from BNG.resolutionMap (e.g. "1km", "100m"). Cell IDs are STRING (e.g. "TQ28", "SU3412").

Natural fit for CV image-tiling workflows that require Ordnance Survey–scale cells aligned to the national grid. An example is tiling aerial or satellite imagery into 1 km BNG cells for object-detection model inference. See issue #49 for the background.

Assignment is "centroid" (default) or "covering"; coverage is "complete" (default) or "sparse".

SQL:

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per overlapping BNG
-- cell. 3rd arg is assignment ('covering' shown; default is 'centroid').
-- '1km' == integer resolution 3; a raster in any CRS is warped to EPSG:27700 first.
SELECT t.* FROM rasters, LATERAL gbx_rst_bng_tessellate(tile, '1km', 'covering') t;

-- Explicit assignment='centroid' (default) + coverage='complete' (default).
SELECT t.* FROM rasters, LATERAL gbx_rst_bng_tessellate(tile, '1km', 'centroid', 'complete') t;
Example output
+------+------+--------------+
|source|cellid|raster |
+------+------+--------------+
|... |TQ2979|<raster bytes>|
+------+------+--------------+
(SELECT t.* expands the v2-tile struct; cellid is the BNG grid-square STRING)

rst_h3_tessellate​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_tessellate(tile, resolution, [assignment], [coverage])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_tessellate(tile, resolution, [assignment], [coverage])rows
Pythonrasterx.functions.rst_h3_tessellate(df, tile, resolution, assignment=None, coverage=None)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps). Any other word raises.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, as all-NoData tiles; 'sparse' leaves them out. Any other word raises.
Streaming UDTF
Implementation

Powered by rasterio + h3. Clips the raster to each overlapping H3 cell at resolution, returning one row per cell via streaming UDTF.

Tessellate raster to H3 cells. assignment is "centroid" (default — pixel-centroid single-assignment) or "covering" (every overlapping cell, clipped); coverage is "complete" (default) or "sparse". See Grid raster tessellation for the full guide.

Covering mode uses a positive-area overlap rule. All three grids share it: rst_h3_tessellate, rst_quadbin_tessellate and rst_bng_tessellate. A cell is emitted iff its geometry has greater-than-zero area overlap with the raster. A cell that only touches the raster along a boundary edge or corner is excluded. That zero-overlap case is common on grid-aligned tiles. A within-extent cell whose pixels are all NoData is emitted — NoData renders in place, it does not punch a gap into the mosaic. This rule is identical at every level, so covering-mode cell sets match exactly.

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per overlapping H3
-- cell. 3rd arg is assignment ('covering' shown; default is 'centroid').
SELECT t.* FROM rasters, LATERAL gbx_rst_h3_tessellate(tile, 7, 'covering') t;

-- Explicit assignment='centroid' (default) + coverage='complete' (default).
SELECT t.* FROM rasters, LATERAL gbx_rst_h3_tessellate(tile, 7, 'centroid', 'complete') t;
Example output
+------+------------------+--------------+
|source|cellid |raster |
+------+------------------+--------------+
|... |599686042433355775|<raster bytes>|
+------+------------------+--------------+

rst_maketiles​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_maketiles(tile, size_in_mb)rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_maketiles(tile, size_in_mb)rows
Pythonrasterx.functions.rst_maketiles(df, tile, size_in_mb)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
size_in_mbINTINTThe most megabytes one tile may hold. The tile is cut into a 2^k by 2^k grid (1, 4, 16 ... at most 256 tiles) until each part fits; 0 or less does not cut. A fraction is cut to a whole number.
Streaming UDTF
Implementation

Powered by rasterio. Streams one tile row per subdivided region via streaming UDTF. It splits the tile into a power-of-4 grid, sized by its encoded bytes against size_in_mb. With size_in_mb > 0, every window is emitted, including windows whose pixels are all NoData, at every level.

Subdivide into smaller tiles by approximate size in MB.

SQL:

Since v0.2.0
-- Subdivide into MB-sized tiles. The second argument is a target size in MB,
-- not pixel dimensions; the tile grid is derived from the MB budget.
-- A table function, called with FROM ..., LATERAL; t.* expands the tile fields.
SELECT t.*
FROM rasters,
LATERAL gbx_rst_maketiles(tile, 4) t;
Example output
+------+--------------+----+----------------------+
|cellid|raster |path|... |
+------+--------------+----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+----+----------------------+
(one row per sub-tile; t.* expands the v2-Tile struct fields)

rst_quadbin_tessellate​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_tessellate(tile, resolution, [assignment], [coverage])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_tessellate(tile, resolution, [assignment], [coverage])rows
Pythonrasterx.functions.rst_quadbin_tessellate(df, tile, resolution, assignment=None, coverage=None)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps). Any other word raises.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, as all-NoData tiles; 'sparse' leaves them out. Any other word raises.
Streaming UDTF
Implementation

The implementation is backed by quadbin cell math and rasterio. It enumerates the quadbin cells that overlap the raster footprint and clips one tile per cell.

Tessellate a raster to CARTO quadbin v0 cells — one row per overlapping cell, each clipped to that cell's extent. A raster in another CRS is accepted. Its footprint is reprojected to EPSG:4326 to find the overlapping cells (see Grid raster tessellation for the antimeridian and pole limits). Resolution is the quadbin zoom level (0..26). Each output row carries the quadbin cell ID (BIGINT) and the clipped tile struct.

Assignment is "centroid" (default) or "covering"; coverage is "complete" (default) or "sparse".

SQL:

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per overlapping
-- quadbin cell, each chip clipped to its cell. 3rd arg is assignment
-- ('covering' shown; default is 'centroid'). Zoom 12 for a city-scale raster.
SELECT t.* FROM rasters, LATERAL gbx_rst_quadbin_tessellate(tile, 12, 'covering') t;

-- Explicit assignment='centroid' (default) + coverage='complete' (default).
SELECT t.* FROM rasters, LATERAL gbx_rst_quadbin_tessellate(tile, 12, 'centroid', 'complete') t;
Example output
+------+-------------------+--------------+
|source|cellid |raster |
+------+-------------------+--------------+
|... |5250127588525215743|<raster bytes>|
+------+-------------------+--------------+
(SELECT t.* expands the v2-tile struct; cellid is the quadbin index)

rst_custom_tessellate​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_tessellate(tile, grid, resolution, [assignment], [coverage])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_tessellate(tile, grid, resolution, [assignment], [coverage])rows
Pythonrasterx.functions.rst_custom_tessellate(df, tile, grid, resolution, assignment=None, coverage=None)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps). Any other word raises.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, as all-NoData tiles; 'sparse' leaves them out. Any other word raises.
Streaming UDTF
Implementation

The implementation is backed by custom-grid cell math and rasterio. It enumerates the overlapping custom-grid cells for the raster and clips one tile per cell, emitting Long-keyed chips (custom cell IDs as BIGINT). The raster is expected to be in the custom grid's native CRS — no automatic reprojection is performed; reproject upstream with rst_transform if needed.

Tessellate a raster to user-defined custom-grid cells — one row per overlapping cell, each clipped to that cell's extent. Pass a custom-grid struct (from gbx_custom_grid(...)) and a resolution integer that selects the cell size level. Cell IDs are BIGINT encoded by the custom-grid layout. For the covering-mode overlap rule (positive-area overlap, boundary touches excluded), see rst_h3_tessellate.

Assignment is "centroid" (default) or "covering"; coverage is "complete" (default) or "sparse".

SQL:

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: centroid assignment,
-- complete coverage (one chip per cell).
SELECT t.*
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_tessellate(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;

-- Explicit covering assignment (each pixel contributes to all overlapping cells).
SELECT t.*
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_tessellate(
tile,
{_CUSTOM_GRID_LITERAL},
1, 'covering', 'sparse'
) t;
Example output
+--------------+------------------------------------------------------+
|cellid |raster |
+--------------+------------------------------------------------------+
|<Long cell id>|{<Long>, <raster bytes>, null, {driver -> GTiff, ...}}|
+--------------+------------------------------------------------------+
(one v2 tile struct per cell; cellid is BIGINT encoding the custom cell)

rst_retile​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_retile(tile, tile_width, tile_height)rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_retile(tile, tile_width, tile_height)rows
Pythonrasterx.functions.rst_retile(df, tile, tile_width, tile_height)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
tile_widthINTINTThe sub-tile width in pixels.
tile_heightINTINTThe sub-tile height in pixels.
Streaming UDTF
Implementation

Powered by rasterio. Streams one tile row per retiled region via streaming UDTF. Every window is emitted, including windows whose pixels are all NoData, at every level. To drop them, filter with WHERE NOT gbx_rst_isempty(tile) or write with pruneEmpty.

Retile to uniform dimensions.

SQL:

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per sub-tile;
-- t.* expands the tile fields.
SELECT t.*
FROM rasters,
LATERAL gbx_rst_retile(tile, 256, 256) t;
Example output
+------+--------------+----+----------------------+
|cellid|raster |path|... |
+------+--------------+----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+----+----------------------+
(one row per sub-tile; t.* expands the v2-Tile struct fields)

rst_separatebands​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_separatebands(tile)rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_separatebands(tile)rows
Pythonrasterx.functions.rst_separatebands(df, tile)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
Streaming UDTF
Implementation

Powered by rasterio. Streams one band-tile row per band via streaming UDTF — O(1) worker memory regardless of band count.

Split multi-band into array of bands.

SQL:

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per band;
-- t.* expands the tile fields.
SELECT t.*
FROM multiband_rasters,
LATERAL gbx_rst_separatebands(tile) t;
Example output
+----+-----------------------------------------------------------+-----------------------------------------------------------+-----------------------------------------------------------+
|path|red_band |green_band |blue_band |
+----+-----------------------------------------------------------+-----------------------------------------------------------+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+-----------------------------------------------------------+-----------------------------------------------------------+

rst_tooverlappingtiles​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_tooverlappingtiles(tile, tile_width, tile_height, overlap)rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_tooverlappingtiles(tile, tile_width, tile_height, overlap)rows
Pythonrasterx.functions.rst_tooverlappingtiles(df, tile, tile_width, tile_height, overlap)DataFrame

Rows: cellid BIGINT, raster BINARY, path STRING, path_mode STRING, window struct<col_off:int,row_off:int,width:int,height:int>, clip_polygon BINARY, clip_crs STRING, crs STRING, metadata map<string,string>.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to split.
tile_widthINTINTThe width of each tile in pixels, above 0.
tile_heightINTINTThe height of each tile in pixels, above 0.
overlapINTINTThe overlap as a percentage of the tile size, from 0 to below 100. Each edge overlaps by the tile size times this, rounded up.
Streaming UDTF
Implementation

Powered by rasterio. Streams one tile row per overlapping region via streaming UDTF. Every window is emitted, including windows whose pixels are all NoData, at every level. To drop them, filter with WHERE NOT gbx_rst_isempty(tile) or write with pruneEmpty.

Create overlapping tiles.

SQL:

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per overlapping
-- tile; t.* expands the tile fields.
SELECT t.*
FROM rasters,
LATERAL gbx_rst_tooverlappingtiles(tile, 256, 256, 10) t;
Example output
+------+--------------+----+----------------------+
|cellid|raster |path|... |
+------+--------------+----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+----+----------------------+
(one row per overlapping tile; t.* expands the v2-Tile struct fields)

Grid Functions (H3)​

See Grid raster tessellation for the coverage / assignment / fill model shared by all grids.

Aggregate raster values to H3 grid cells, and utility functions for H3-based canvas setup (9 total).

The rst_<grid>_rastertogrid<stat> reducers of all four grids (H3, quadbin, BNG, custom grid) are table functions at every implementation level. They return one row per band and cell, with band (from 1), cellID and measure. Call them in the FROM clause with LATERAL, or through the Python API, which takes the input DataFrame first and returns it joined with the rows:

from databricks.labs.gbx.rasterx import functions as rx

rx.rst_h3_rastertogridavg(df, "tile", 5) # one row per band and H3 cell, beside the input columns

A NULL tile, an error tile and a tile that cannot be read give no rows. A resolution the grid does not define raises and names the value. A coverage or assignment word that names none does the same. Cell ids are BIGINT (H3, quadbin, custom grid) and never pass through a float; BNG ids are STRING.

h3_cell_bbox​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_h3_cell_bbox(cellid, [srid], [mode], [kring_pad], [out_crs])struct<xmin:double,ymin:double,xmax:double,ymax:double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_h3_cell_bbox(cellid, [srid], [mode], [kring_pad], [out_crs])struct<xmin:double,ymin:double,xmax:double,ymax:double>
Pythongridx.h3.functions.h3_cell_bbox(cellid, srid=None, mode=None, kring_pad=None, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
cellidBIGINTBIGINTThe H3 cell id.
sridINTINT4326The EPSG code of the output coordinates.
modeSTRINGSTRING'centroids''centroids' wraps the cell centres, 'spatial_envelope' the whole hexagons.
kring_padINTINT0How many rings of neighbours to include before taking the box; 0 is the cell alone.
out_crsSTRINGSTRINGNULLThe output coordinate system as EPSG:<n>, ESRI:<n> or WKT; when set it wins over srid. On Unity Catalog WKT is refused.
Implementation

Powered by h3. Returns a STRUCT<xmin DOUBLE, ymin DOUBLE, xmax DOUBLE, ymax DOUBLE> bounding box for the given H3 cell in the requested srid. In 'centroids' mode the box tightly wraps the centroid point; in 'spatial_envelope' mode it wraps the full hexagon outline. When kring_pad > 0 the k-ring of that radius is computed first and the bounding box covers all cells in the ring.

Scalar function — returns the bounding box STRUCT<xmin, ymin, xmax, ymax> for one H3 cell in the given CRS. Use this to drive the xmin/ymin/xmax/ymax and grid-size parameters of rst_h3_rasterize_agg when you need a consistent per-cell canvas. Use it also to clip and inspect cell extents in downstream queries.

Returns: STRUCT<xmin DOUBLE, ymin DOUBLE, xmax DOUBLE, ymax DOUBLE>

SQL:

Since v0.4.0
-- Bounding box (STRUCT<xmin, ymin, xmax, ymax>) for each H3 cell in EPSG:4326.
-- Uses 'centroids' mode with no k-ring padding (kring_pad=0).
SELECT
cellid,
gbx_h3_cell_bbox(cellid, 4326, 'centroids', 0) AS bbox
FROM (
VALUES
(617733151020810239),
(617733151085035519),
(617733151021334527)
) AS t(cellid);
Example output
+------------------+------------------------------+
|cellid |bbox |
+------------------+------------------------------+
|617733151020810239|{-74.02, 40.70, -74.01, 40.71}|
+------------------+------------------------------+
(STRUCT<xmin, ymin, xmax, ymax> per H3 cell, in EPSG:4326)

rst_h3_gridspec (Python / DataFrame helper)​

Python helper only

rst_h3_gridspec is not registered as a SQL function. It is a PySpark DataFrame helper in databricks.labs.gbx.rasterx.helpers.

In SQL, compose the equivalent shared canvas using the registered scalar gbx_h3_cell_bbox(cellid, srid, mode, kring_pad) with native Spark min/max aggregates and the same floor/ceil snap arithmetic:

SELECT min(cell_bbox.xmin), min(cell_bbox.ymin),
max(cell_bbox.xmax), max(cell_bbox.ymax)
FROM (SELECT gbx_h3_cell_bbox(cellid, 4326, 'centroids', 1) AS cell_bbox FROM cells)

rst_h3_gridspec computes the shared, snapped canvas (extent + pixel size) that a group of H3 cells should use. Per-threshold rasters then align on a common grid. You can stack them via rst_frombands_agg or mosaic them via rst_merge_agg.

Signature:

from databricks.labs.gbx.rasterx.helpers import rst_h3_gridspec

rst_h3_gridspec(df, cell_col="cellid", *group_cols,
srid=4326, pixel_size=None,
mode="centroids", kring_pad=1)

Typical multi-threshold workflow:

  1. Call rst_h3_gridspec(df, cell_col="cellid", srid=4326, mode='centroids', kring_pad=1) once on the distinct cell set. It returns the grouped DataFrame with a grid struct column — one row per group containing the shared canvas.
  2. For each threshold band, run rst_h3_rasterize_agg with those fixed bounds — all output tiles share the same origin and pixel grid.
  3. Stack aligned bands with rst_frombands_agg (ordered by band_index), or mosaic per-cell tiles with rst_merge_agg.

Parameters:

  • df — input Spark DataFrame containing H3 cell IDs
  • cell_col — column name holding H3 cell IDs (integer or string); default "cellid"
  • *group_cols — additional grouping columns (e.g. a transmitter ID, year, month); one grid spec row is produced per group
  • srid — EPSG code for the output CRS; 4326 for WGS 84 (default)
  • pixel_size — ground resolution in CRS units; None = auto-derived from the H3 resolution via an edge-length heuristic (default)
  • mode — 'centroids' (default) or 'spatial_envelope'
  • kring_pad — k-ring expansion applied per cell before computing its bounding box (default 1)

Returns: the grouped DataFrame with a grid column of type:

STRUCT<xmin DOUBLE, ymin DOUBLE, xmax DOUBLE, ymax DOUBLE,
pixel_size DOUBLE, width INT, height INT, srid INT>

rst_h3_rastertogrid_partial​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogrid_partial(tile, resolution, [coverage], [assignment])array<struct<band:int,cellid:bigint,count:double,sum:double,m2:double,min:double,max:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogrid_partial(tile, resolution, [coverage], [assignment])array<struct<band:int,cellid:bigint,count:double,sum:double,m2:double,min:double,max:double>>
Pythonrasterx.functions.rst_h3_rastertogrid_partial(tile, resolution, coverage=None, assignment=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.

Give the state of every H3 cell a tile covers, in one pass over the pixels. Each row of the array holds count, sum, m2, min and max for one band and one cell. The average of a cell is sum / count. The variance is m2 / count, and the standard deviation is its square root. The seven table functions rst_h3_rastertogridavg, count, max, min, stddev, sum and variance read these fields, so one pass serves every statistic. The median does not split. It keeps its own table function.

SELECT t.band, t.cellid, t.sum / t.count AS avg, t.max - t.min AS spread
FROM rasters r LATERAL VIEW inline(gbx_rst_h3_rastertogrid_partial(r.tile, 7)) t

The state merges across tiles of one table. Sum count and sum, and take the least min and the greatest max. Combine m2 with the update on the Unity Catalog functions page, so the variance of a cell that spans two tiles is exact. Tiles must not overlap. A pixel in two tiles counts twice. On Unity Catalog a virtual tile is refused, and so is a result over the size limit.

Since v0.6.0
-- A 40 x 40 tile of value 1.0 over a lon/lat box of London. One row per band and H3 cell
-- with count, sum, m2, min and max; the average of a cell is sum / count.
WITH r AS (
SELECT gbx_rst_rasterize(
'POLYGON((-0.20 51.40, -0.10 51.40, -0.10 51.50, -0.20 51.50, -0.20 51.40))',
1.0, -0.20, 51.40, -0.10, 51.50, 40, 40, 4326
) AS tile
)
SELECT band, cellid, count, sum / count AS avg
FROM (SELECT inline(gbx_rst_h3_rastertogrid_partial(tile, 6)) FROM r);
Example output
+----+------------------+-----+---+
|band|cellid |count|avg|
+----+------------------+-----+---+
|1 |603927292439166975|61.0 |1.0|
|1 |603927296197263359|607.0|1.0|
|1 |603927296331481087|326.0|1.0|
|... | | | |
+----+------------------+-----+---+
(one row per band and H3 cell, 8 in all)

rst_h3_rastertogridavg​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridavg(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridavg(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridavg(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Mean pixel value per H3 cell.

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridavg(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridavg(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|123.45 |
|1 |599686043374559743|98.12 |
|2 |599686042433355775|210.67 |
+----+------------------+-------+
(one row per band×cell. The lightweight LATERAL form yields these [band, cellID,
measure] rows directly; the heavyweight scalar form returns a nested ARRAY that
posexplode + inline flatten to the same rows.)

rst_h3_rastertogridcount​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridcount(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridcount(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridcount(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Pixel count (Double) per H3 cell.

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridcount(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridcount(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|256.0 |
|1 |599686043374559743|240.0 |
|2 |599686042433355775|256.0 |
+----+------------------+-------+
(pixel count per band×cell; measure is DOUBLE)

rst_h3_rastertogridmax​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridmax(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridmax(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridmax(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Max value per H3 cell.

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmax(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmax(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|255.0 |
|1 |599686043374559743|254.0 |
|2 |599686042433355775|240.0 |
+----+------------------+-------+
(max value per band×cell)

rst_h3_rastertogridmedian​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridmedian(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridmedian(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridmedian(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Median value per H3 cell.

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmedian(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmedian(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|120.5 |
|1 |599686043374559743|122.0 |
|2 |599686042433355775|115.0 |
+----+------------------+-------+
(median value per band×cell)

rst_h3_rastertogridmin​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridmin(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridmin(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridmin(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Min value per H3 cell.

Since v0.2.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmin(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmin(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|0.0 |
|1 |599686043374559743|10.0 |
|2 |599686042433355775|5.0 |
+----+------------------+-------+
(min value per band×cell)

rst_h3_rastertogridstddev​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridstddev(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridstddev(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridstddev(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population standard deviation of pixel values per H3 cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridstddev(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridstddev(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|35.29 |
|1 |599686043374559743|37.27 |
|2 |599686042433355775|34.01 |
+----+------------------+-------+
(standard deviation per band×cell)

rst_h3_rastertogridsum​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridsum(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridsum(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridsum(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Sum of pixel values per H3 cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridsum(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridsum(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|31563.0|
|1 |599686043374559743|29488.0|
|2 |599686042433355775|28672.0|
+----+------------------+-------+
(sum of pixel values per band×cell)

rst_h3_rastertogridvariance​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_h3_rastertogridvariance(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_h3_rastertogridvariance(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_h3_rastertogridvariance(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe H3 resolution, a whole number from 0 to 15.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population variance of pixel values per H3 cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridvariance(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridvariance(tile, 4, 'complete', 'covering') t;
Example output
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|1245.5 |
|1 |599686043374559743|1389.2 |
|2 |599686042433355775|1156.0 |
+----+------------------+-------+
(variance per band×cell)

Grid Functions (quadbin)​

See Grid raster tessellation for the coverage / assignment / fill model shared by all grids.

Aggregate raster values to CARTO quadbin v0 grid cells (8 reducers). Each reducer is a table function with one row per band and cell (band, cellID BIGINT, measure DOUBLE). Resolution is the quadbin zoom (0..20). See also rst_quadbin_tessellate (Generator Functions) and rst_quadbin_rasterize_agg (Aggregator Functions) for the remaining quadbin raster-grid surface.

rst_quadbin_rastertogrid_partial​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogrid_partial(tile, resolution, [coverage], [assignment])array<struct<band:int,cellid:bigint,count:double,sum:double,m2:double,min:double,max:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogrid_partial(tile, resolution, [coverage], [assignment])array<struct<band:int,cellid:bigint,count:double,sum:double,m2:double,min:double,max:double>>
Pythonrasterx.functions.rst_quadbin_rastertogrid_partial(tile, resolution, coverage=None, assignment=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.

Give the state of every quadbin cell a tile covers, in one pass over the pixels. Each row of the array holds count, sum, m2, min and max for one band and one cell. The average of a cell is sum / count. The variance is m2 / count, and the standard deviation is its square root. The table functions rst_quadbin_rastertogridavg, count, max, min, stddev, sum and variance give the same values. On Unity Catalog each of them computes only its own statistic, so use the partial for several statistics in one pass. The median does not split. It keeps its own table function.

Merge the state across tiles of one table as rst_h3_rastertogrid_partial does. Tiles must not overlap. On Unity Catalog a virtual tile is refused, and so is a result over the size limit.

Since v0.6.0
-- A 40 x 40 tile of value 1.0 over a lon/lat box of London. One row per band and quadbin
-- cell with count, sum, m2, min and max; the average of a cell is sum / count.
WITH r AS (
SELECT gbx_rst_rasterize(
'POLYGON((-0.20 51.40, -0.10 51.40, -0.10 51.50, -0.20 51.50, -0.20 51.40))',
1.0, -0.20, 51.40, -0.10, 51.50, 40, 40, 4326
) AS tile
)
SELECT band, cellid, count, sum / count AS avg
FROM (SELECT inline(gbx_rst_quadbin_rastertogrid_partial(tile, 12)) FROM r);
Example output
+----+-------------------+-----+---+
|band|cellid |count|avg|
+----+-------------------+-----+---+
|1 |5243165738268622847|180.0|1.0|
|1 |5243165738805493759|220.0|1.0|
|1 |5243165739073929215|540.0|1.0|
|1 |5243165739610800127|660.0|1.0|
+----+-------------------+-----+---+
(one row per band and quadbin cell)

rst_quadbin_rastertogridavg​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridavg(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridavg(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridavg(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Mean pixel value per quadbin cell.

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridavg(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridavg(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |123.45 |
|1 |12346 |124.20 |
|2 |12345 |210.67 |
+----+------+-------+
(one row per band×Quadbin cell)

rst_quadbin_rastertogridcount​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridcount(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridcount(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridcount(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Pixel count (Double) per quadbin cell.

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridcount(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridcount(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |256.0 |
|1 |12346 |240.0 |
|2 |12345 |256.0 |
+----+------+-------+
(pixel count per band×Quadbin cell; measure is DOUBLE)

rst_quadbin_rastertogridmax​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridmax(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridmax(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridmax(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Max pixel value per quadbin cell.

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmax(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmax(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |255.0 |
|1 |12346 |254.0 |
|2 |12345 |240.0 |
+----+------+-------+
(max value per band×Quadbin cell)

rst_quadbin_rastertogridmedian​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridmedian(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridmedian(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridmedian(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Median pixel value per quadbin cell.

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmedian(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmedian(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |120.5 |
|1 |12346 |122.0 |
|2 |12345 |115.0 |
+----+------+-------+
(median value per band×Quadbin cell)

rst_quadbin_rastertogridmin​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridmin(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridmin(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridmin(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Min pixel value per quadbin cell.

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmin(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmin(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |0.0 |
|1 |12346 |10.0 |
|2 |12345 |5.0 |
+----+------+-------+
(min value per band×Quadbin cell)

rst_quadbin_rastertogridstddev​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridstddev(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridstddev(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridstddev(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population standard deviation of pixel values per quadbin cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridstddev(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridstddev(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |35.29 |
|1 |12346 |37.27 |
|2 |12345 |34.01 |
+----+------+-------+
(standard deviation per band×Quadbin cell)

rst_quadbin_rastertogridsum​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridsum(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridsum(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridsum(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Sum of pixel values per quadbin cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridsum(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridsum(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |31563.0|
|1 |12346 |29488.0|
|2 |12345 |28672.0|
+----+------+-------+
(sum of pixel values per band×Quadbin cell)

rst_quadbin_rastertogridvariance​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_quadbin_rastertogridvariance(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_quadbin_rastertogridvariance(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_quadbin_rastertogridvariance(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINTINTThe quadbin zoom level, a whole number from 0 to 20.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population variance of pixel values per quadbin cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridvariance(tile, 4) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridvariance(tile, 4, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |1245.5 |
|1 |12346 |1389.2 |
|2 |12345 |1156.0 |
+----+------+-------+
(variance per band×Quadbin cell)

Grid Functions (BNG)​

See Grid raster tessellation for the coverage / assignment / fill model shared by all grids.

Aggregate raster values to British National Grid (BNG) cells (8 total). BNG functions automatically reproject the input raster to EPSG:27700 before sampling — no rst_transform needed upstream. Resolution accepts integer indices ±1..±6 , where 1 = 100 km, 2 = 10 km, and 3 = 1 km. Index 4 = 100 m, 5 = 10 m, and 6 = 1 m. Negative indices address quadrant sub-cells. Resolution also accepts string keys (e.g. "1km", "100m"). Cell IDs are STRING.

NoData and NULL

With the default complete coverage, a cell that overlaps the raster but holds only NoData pixels is returned with a NULL measure (0 for a count; never NaN). The H3 and quadbin reducers behave the same. NULL is safe to filter (WHERE measure IS NULL) and is excluded by SQL aggregates like MAX/MIN/AVG.

rst_bng_rastertogrid_partial​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogrid_partial(tile, resolution, [coverage], [assignment])array<struct<band:int,cellid:string,count:double,sum:double,m2:double,min:double,max:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogrid_partial(tile, resolution, [coverage], [assignment])array<struct<band:int,cellid:string,count:double,sum:double,m2:double,min:double,max:double>>
Pythonrasterx.functions.rst_bng_rastertogrid_partial(tile, resolution, coverage=None, assignment=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.

Give the state of every BNG cell a tile covers, in one pass over the pixels. Each row of the array holds count, sum, m2, min and max for one band and one cell. The average of a cell is sum / count. The variance is m2 / count, and the standard deviation is its square root. The table functions rst_bng_rastertogridavg, count, max, min, stddev, sum and variance give the same values. On Unity Catalog each of them computes only its own statistic, so use the partial for several statistics in one pass. The median does not split. It keeps its own table function.

Merge the state across tiles of one table as rst_h3_rastertogrid_partial does. Tiles must not overlap. On Unity Catalog a virtual tile is refused, and so is a result over the size limit.

Since v0.6.0
-- A 40 x 40 tile of value 1.0 over a 4 km square of London (EPSG:27700). One row per band and
-- 1 km cell with count, sum, m2, min and max; the average of a cell is sum / count.
WITH r AS (
SELECT gbx_rst_rasterize(
'POLYGON((529000 179000, 533000 179000, 533000 183000, 529000 183000, 529000 179000))',
1.0, 529000.0, 179000.0, 533000.0, 183000.0, 40, 40, 27700
) AS tile
)
SELECT band, cellid, count, sum / count AS avg
FROM (SELECT inline(gbx_rst_bng_rastertogrid_partial(tile, 3)) FROM r);
Example output
+----+------+-----+---+
|band|cellid|count|avg|
+----+------+-----+---+
|1 |TQ2979|100.0|1.0|
|1 |TQ2980|100.0|1.0|
|1 |TQ2981|100.0|1.0|
|... | | | |
+----+------+-----+---+
(one row per band and 1 km BNG cell, 16 in all; cellid is a STRING)

rst_bng_rastertogridavg​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridavg(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridavg(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridavg(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Mean pixel value per BNG cell. The raster is reprojected to EPSG:27700 internally before sampling.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridavg(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridavg(tile, 3, 'complete', 'covering') t;
Example output
+----+------+------------------+
|band|cellID|measure |
+----+------+------------------+
|1 |OW5574|77.22222222222223 |
|1 |OW5575|80.66666666666667 |
|2 |OW5574|144.33333333333334|
+----+------+------------------+
(one row per band × BNG cell; cellID is a STRING grid-square label)

rst_bng_rastertogridcount​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridcount(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridcount(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridcount(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Valid (non-NoData) pixel count per BNG cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridcount(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridcount(tile, 3, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|9.0 |
|1 |OW5575|21.0 |
|2 |OW5574|9.0 |
+----+------+-------+
(pixel count per band × BNG cell; measure is DOUBLE)

rst_bng_rastertogridmax​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridmax(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridmax(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridmax(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Maximum pixel value per BNG cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmax(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmax(tile, 3, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|106.0 |
|1 |OW5575|118.0 |
|1 |OW5674|107.0 |
+----+------+-------+
(max value per band × BNG cell)

rst_bng_rastertogridmedian​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridmedian(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridmedian(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridmedian(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Median pixel value per BNG cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmedian(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmedian(tile, 3, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|88.0 |
|1 |OW5575|80.0 |
|1 |OW5674|81.0 |
+----+------+-------+
(median value per band × BNG cell)

rst_bng_rastertogridmin​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridmin(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridmin(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridmin(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Minimum pixel value per BNG cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmin(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmin(tile, 3, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|0.0 |
|1 |OW5575|54.0 |
|1 |OW5674|65.0 |
+----+------+-------+
(min value per band × BNG cell)

rst_bng_rastertogridstddev​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridstddev(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridstddev(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridstddev(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population standard deviation (sqrt of the population variance) of pixel values per BNG cell — a single-pixel cell yields 0.0.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridstddev(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridstddev(tile, 3, 'complete', 'covering') t;
Example output
+----+------+------------------+
|band|cellID|measure |
+----+------+------------------+
|1 |OW5574|31.043975181373415|
|1 |OW5575|21.543606571950388|
|1 |OW5674|14.023789311975086|
+----+------+------------------+
(population standard deviation per band × BNG cell)

rst_bng_rastertogridsum​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridsum(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridsum(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridsum(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Sum of pixel values per BNG cell.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridsum(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridsum(tile, 3, 'complete', 'covering') t;
Example output
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|695.0 |
|1 |OW5575|1694.0 |
|1 |OW5674|774.0 |
+----+------+-------+
(sum of pixel values per band × BNG cell)

rst_bng_rastertogridvariance​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_bng_rastertogridvariance(tile, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_bng_rastertogridvariance(tile, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_bng_rastertogridvariance(df, tile, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID STRING, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
resolutionINT or STRINGSTRINGBNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population variance (÷ n, two-pass) of pixel values per BNG cell — a single-pixel cell yields 0.0.

Since v0.4.3
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridvariance(tile, 3) t;

SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridvariance(tile, 3, 'complete', 'covering') t;
Example output
+----+------+------------------+
|band|cellID|measure |
+----+------+------------------+
|1 |OW5574|963.7283950617285 |
|1 |OW5575|464.126984126984 |
|1 |OW5674|196.66666666666666|
+----+------+------------------+
(population variance per band × BNG cell)

Grid Functions (Custom Grid)​

See Grid raster tessellation for the coverage / assignment / fill model shared by all grids.

Aggregate raster values to user-defined custom-grid cells (8 total). Custom grids are defined via gbx_custom_grid(origin_x, origin_y, min_x, min_y, max_x, max_y, root_cell_size_x, root_cell_size_y, crs_srid) — a regular planar grid with an explicit origin, bounds, and cell size. Cell IDs are BIGINT encoded by the custom-grid layout, and the resolution parameter selects the subdivision level. The raster is expected to be in the grid's native CRS — no automatic reprojection is performed; use rst_transform upstream if needed.

NoData and NULL

With the default complete coverage, a cell that overlaps the raster but holds only NoData pixels is returned with a NULL measure (0 for a count; never NaN). The H3, quadbin, and BNG reducers behave the same. NULL is safe to filter (WHERE measure IS NULL) and is excluded by SQL aggregates like MAX/MIN/AVG.

rst_custom_rastertogrid_partial​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogrid_partial(tile, grid, resolution, [coverage], [assignment])array<struct<band:int,cellid:bigint,count:double,sum:double,m2:double,min:double,max:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogrid_partial(tile, grid, resolution, [coverage], [assignment])array<struct<band:int,cellid:bigint,count:double,sum:double,m2:double,min:double,max:double>>
Pythonrasterx.functions.rst_custom_rastertogrid_partial(tile, grid, resolution, coverage=None, assignment=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.

Give the state of every custom-grid cell a tile covers, in one pass over the pixels. Each row of the array holds count, sum, m2, min and max for one band and one cell. The average of a cell is sum / count. The variance is m2 / count, and the standard deviation is its square root. The table functions rst_custom_rastertogridavg, count, max, min, stddev, sum and variance give the same values. On Unity Catalog each of them computes only its own statistic, so use the partial for several statistics in one pass. The median does not split. It keeps its own table function.

Merge the state across tiles of one table as rst_h3_rastertogrid_partial does. Tiles must not overlap. On Unity Catalog a virtual tile is refused, and so is a result over the size limit.

Since v0.6.0
-- A 40 x 40 tile of value 1.0 over a 4 km square of London (EPSG:27700), binned to the
-- 2 km cells (resolution 1) of the grid. The average of a cell is sum / count.
WITH r AS (
SELECT gbx_rst_rasterize(
'POLYGON((529000 179000, 533000 179000, 533000 183000, 529000 183000, 529000 179000))',
1.0, 529000.0, 179000.0, 533000.0, 183000.0, 40, 40, 27700
) AS tile
)
SELECT band, cellid, count, sum / count AS avg
FROM (SELECT inline(gbx_rst_custom_rastertogrid_partial(tile, {_CUSTOM_GRID_LITERAL}, 1)) FROM r);
Example output
+----+-----------------+-----+---+
|band|cellid |count|avg|
+----+-----------------+-----+---+
|1 |72057594037927936|400.0|1.0|
|1 |72057594037927937|400.0|1.0|
|1 |72057594037927938|400.0|1.0|
|1 |72057594037927939|400.0|1.0|
+----+-----------------+-----+---+
(one row per band and 2 km custom-grid cell)

rst_custom_rastertogridavg​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridavg(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridavg(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridavg(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Mean pixel value per custom-grid cell.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridavg(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;

SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridavg(
tile,
{_CUSTOM_GRID_LITERAL},
1, 'complete', 'covering'
) t;
Example output
+----+--------------+-----------------+
|band|cellID |measure |
+----+--------------+-----------------+
|1 |<Long cell id>|<avg pixel value>|
+----+--------------+-----------------+
(one row per band × custom-grid cell; cellID is a BIGINT)

rst_custom_rastertogridcount​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridcount(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridcount(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridcount(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Valid (non-NoData) pixel count per custom-grid cell (measure is DOUBLE).

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridcount(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<count>|
+----+--------------+-------+
(pixel count per band × custom-grid cell; measure is DOUBLE)

rst_custom_rastertogridmax​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridmax(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridmax(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridmax(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Maximum pixel value per custom-grid cell.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridmax(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<max> |
+----+--------------+-------+
(max pixel value per band × custom-grid cell)

rst_custom_rastertogridmedian​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridmedian(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridmedian(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridmedian(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Median pixel value per custom-grid cell.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridmedian(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+--------+
|band|cellID |measure |
+----+--------------+--------+
|1 |<Long cell id>|<median>|
+----+--------------+--------+
(median pixel value per band × custom-grid cell)

rst_custom_rastertogridmin​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridmin(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridmin(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridmin(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Minimum pixel value per custom-grid cell.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridmin(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<min> |
+----+--------------+-------+
(min pixel value per band × custom-grid cell)

rst_custom_rastertogridstddev​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridstddev(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridstddev(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridstddev(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population standard deviation (sqrt of the population variance) of pixel values per custom-grid cell — a single-pixel cell yields 0.0.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridstddev(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+--------+
|band|cellID |measure |
+----+--------------+--------+
|1 |<Long cell id>|<stddev>|
+----+--------------+--------+
(population standard deviation of pixel values per band × custom-grid cell)

rst_custom_rastertogridsum​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridsum(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridsum(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridsum(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Sum of pixel values per custom-grid cell.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridsum(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<sum> |
+----+--------------+-------+
(sum of pixel values per band × custom-grid cell)

rst_custom_rastertogridvariance​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_custom_rastertogridvariance(tile, grid, resolution, [coverage], [assignment])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_custom_rastertogridvariance(tile, grid, resolution, [coverage], [assignment])rows
Pythonrasterx.functions.rst_custom_rastertogridvariance(df, tile, grid, resolution, coverage=None, assignment=None)DataFrame

Rows: band INT, cellID BIGINT, measure DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to aggregate.
gridstruct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>struct<bound_x_min:bigint,bound_x_max:bigint,bound_y_min:bigint,bound_y_max:bigint,cell_splits:int,root_cell_size_x:int,root_cell_size_y:int,srid:int>The grid, as built by gbx_custom_grid.
resolutionINTINTThe grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits.
coverageSTRINGSTRING'complete''complete' also gives the cells that overlap the raster but hold no valid pixel, with a NULL measure (0 for a count); 'sparse' gives only the cells that hold a valid pixel. Any other word raises.
assignmentSTRINGSTRING'centroid'How a pixel joins a cell: 'centroid' (the cell holds the pixel's centre) or 'covering' (every cell the pixel overlaps, in proportion to the overlapping area). Any other word raises.
Streaming UDTF

Population variance (÷ n, two-pass) of pixel values per custom-grid cell — a single-pixel cell yields 0.0.

Since v0.5.1
-- A table function, called with FROM ..., LATERAL: one row per band and cell,
-- with the columns [band, cellID, measure].
SELECT t.band, t.cellID, t.measure
FROM (SELECT gbx_rst_fromfile('{_CUSTOM_RASTER_PATH}') AS tile) AS r,
LATERAL gbx_rst_custom_rastertogridvariance(
tile,
{_CUSTOM_GRID_LITERAL},
1
) t;
Example output
+----+--------------+----------+
|band|cellID |measure |
+----+--------------+----------+
|1 |<Long cell id>|<variance>|
+----+--------------+----------+
(population variance of pixel values per band × custom-grid cell)

Operations​

Transform and analyze rasters (20 total).

rst_align_to​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_align_to(tile, reference_tile)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_align_to(tile, reference_tile)TILE
Pythonrasterx.functions.rst_align_to(tile, reference_tile, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to warp.
reference_tileTILETILEThe tile whose grid (CRS, extent, width, height) the result takes.
Implementation

Powered by rasterio (rasterio.warp). Warps tile onto the reference tile's grid — matching its CRS, extent, and pixel dimensions — using nearest-neighbour resampling. Satisfies the alignment precondition required by the rst_combine* family.

Warp a tile to match the grid of a reference tile exactly — same CRS, extent, width, height, and geotransform — using nearest-neighbour resampling (-r near). This is the explicit fix for the alignment precondition of the cross-raster combine family (rst_combine*): align each tile to a common reference, then combine.

Since v0.5.1
SELECT gbx_rst_align_to(tile, reference_tile) AS aligned FROM paired_rasters;
Example output
+-----------------------------------------------------------+
|aligned |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile warped to reference grid; output has reference tile's CRS, extent, width, height)

rst_asformat​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_asformat(tile, new_format)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_asformat(tile, new_format)TILE
Pythonrasterx.functions.rst_asformat(tile, new_format, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to re-encode.
new_formatSTRINGSTRINGA GDAL driver short name that can write a raster, in any case: 'GTiff', 'PNG', 'COG'. A name that names none raises.
Implementation

Powered by rasterio. Output formats are limited to rasterio's bundled-GDAL writable driver set; the tile is re-encoded in the requested format. 'COG' produces a Cloud Optimized GeoTIFF (512-pixel blocks, size-adaptive ZSTD compression, and overviews when the tile is larger than 512 pixels), the same layout as rst_cog_convert.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Convert to another format. A driver that is unknown, or cannot write a raster, raises an error that names it. An error tile in comes out as it is.

Since v0.2.0
-- Convert NetCDF to GeoTIFF
SELECT
path,
gbx_rst_asformat(tile, 'GTiff') as geotiff_tile
FROM netcdf_rasters;

-- Convert to PNG
SELECT
path,
gbx_rst_asformat(tile, 'PNG') as png_tile
FROM visualization_tiles;
Example output
+----+-----------------------------------------------------------+
|path|geotiff_tile |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+

rst_clip​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_clip(tile, geom, cutline_all_touched, [clip_crs])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_clip(tile, geom, cutline_all_touched, [clip_crs])TILE
Pythonrasterx.functions.rst_clip(tile, geom, cutline_all_touched, clip_crs=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to clip.
geomBINARY or STRINGGEOMETRYThe cutline: a polygon as WKB, EWKB, WKT or EWKT.
cutline_all_touchedBOOLEANBOOLEANtrue keeps every pixel the cutline touches; false keeps the pixels whose centre it holds. A cutline smaller than a pixel keeps the pixel it touches either way.
clip_crsSTRINGSTRINGNULLThe CRS of a cutline that carries no SRID: EPSG:<code>, ESRI:<code>, WKT or an integer code. The CRS of the tile when NULL. An EWKB or EWKT SRID wins.
Cutline CRS

A cutline with an EWKB or EWKT SRID is reprojected to the tile's CRS. A plain WKB or WKT cutline takes clip_crs, else the tile's CRS. The result is NULL when the cutline misses the tile.

Changed in 0.6.0

The pixels a clip leaves out are NoData, never valid zeros. They take the tile's own NoData, else the fallback of its type, which the output declares. A tile with an alpha band gets alpha 0 there. A cutline smaller than one pixel keeps the pixel it touches.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Clip by geometry. The clip argument must be WKT (string), EWKT (SRID-prefixed string), WKB (binary), or EWKB (SRID-embedded binary); do not use st_geomfromtext() or other DBR native geometry. Optional clip_crs (string, source role) declares the CRS of a plain WKB/WKT cutline — an EWKB/EWKT embedded SRID wins, absent → assumed already in the raster CRS. See Coordinate Reference Systems.

CRS handling:

  • EWKT (SRID=4326;POLYGON(...)) or EWKB (SRID encoded in the byte header). The SRID is read. If it differs from the raster's CRS, the cutline is reprojected before clipping. Use this form whenever the geometry and raster may be in different CRSs.
  • Plain WKT / WKB (no SRID) — the geometry is assumed to already be in the raster's CRS. If that assumption is wrong (for example, lon/lat polygons against a UTM raster), the cutline will land outside the raster. You'll get an empty or blank output. Either switch to EWKT/EWKB, or reproject the geometry to the raster's CRS first.

Example clip geometry: a WKT polygon in the raster's native CRS (EPSG:32618, no SRID prefix). To clip with a WGS84 geometry use EWKT: SRID=4326;POLYGON(...) — the embedded SRID triggers auto-reprojection to the raster's CRS.

Since v0.2.0
-- Clip with WKT geometry
SELECT
path,
gbx_rst_clip(
tile,
'POLYGON((-122 37, -122 38, -121 38, -121 37, -122 37))',
true
) as clipped
FROM rasters;
Example output
+----+-----------------------------------------------------------+
|path|clipped |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+

rst_percentile_stretch​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_percentile_stretch(tile, lo_pct, hi_pct)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_percentile_stretch(tile, lo_pct, hi_pct)TILE
Pythonrasterx.functions.rst_percentile_stretch(tile, lo_pct, hi_pct, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to stretch.
lo_pctDOUBLEDOUBLEThe lower percentile, in [0, 100] and below hi_pct: the value at it becomes 0.
hi_pctDOUBLEDOUBLEThe upper percentile, in [0, 100]: the value at it becomes 255.
Implementation

Powered by rasterio + NumPy. Computes per-band percentiles over valid pixels, clips to that range, and linearly rescales to [0,255]. Each band is stretched independently.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Per-band percentile contrast stretch to uint8. For each band, lo_pct and hi_pct (percentiles in 0–100) define the stretch range. Pixels at the lower percentile map to 0, those at the upper percentile map to 255, and the rest are linearly rescaled. NoData pixels remain 0 in the output. Typical values are lo_pct=2.0, hi_pct=98.0, which trim outliers and use the full uint8 range. The output is a uint8 GTiff with the same bands, extent, and CRS as the input.

Since v0.5.2
SELECT gbx_rst_percentile_stretch(tile, 2.0, 98.0) AS stretched
FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|stretched |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(multiband uint8: each band stretched independently to [0,255])

rst_combineavg​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combineavg(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combineavg(tiles)TILE
Pythonrasterx.functions.rst_combineavg(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns the NoData-aware per-pixel mean; input tiles must share the same grid (shape/extent/CRS). cellid is preserved when all inputs share one, else −1.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Per-pixel mean across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the mean of that location's valid (non-NoData) values across the stack. A pixel that is NoData in every input stays NoData. Use for temporal/ensemble composites such as cloud-reduced mean reflectance.

Average multiple tiles (e.g. temporal composite).

Since v0.2.0
SELECT gbx_rst_combineavg(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_combinecount​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combinecount(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combinecount(tiles)TILE
Pythonrasterx.functions.rst_combinecount(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns a tile where each pixel is the count of valid (non-NoData) inputs across the stack. Input tiles must share the same grid (shape/extent/CRS). All-NoData pixels yield NoData in the output (never 0 for an all-NoData pixel). Align tiles with gbx_rst_align_to before combining.

Per-pixel count of valid (non-NoData) inputs across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the number of inputs whose value at that location is valid. A location that is NoData in every input yields NoData (never 0). Use alongside the other rst_combine* reducers to build multi-statistic temporal or ensemble composites.

Count of valid pixels per location.

Since v0.5.1
SELECT gbx_rst_combinecount(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_combinemax​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combinemax(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combinemax(tiles)TILE
Pythonrasterx.functions.rst_combinemax(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns the NoData-aware per-pixel maximum; input tiles must share the same grid (shape/extent/CRS). All-NoData pixels yield NoData in the output. Align tiles with gbx_rst_align_to before combining.

Per-pixel maximum across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the largest of that location's valid (non-NoData) values across the stack. A pixel that is NoData in every input stays NoData. Use to build cloud-free maximum-NDVI composites or storm-peak accumulations.

Maximum pixel value per location.

Since v0.5.1
SELECT gbx_rst_combinemax(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_combinemedian​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combinemedian(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combinemedian(tiles)TILE
Pythonrasterx.functions.rst_combinemedian(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns the NoData-aware per-pixel median; input tiles must share the same grid (shape/extent/CRS). Even-count median uses the mean of the two middle values (numpy np.ma.median convention). All-NoData pixels yield NoData in the output. Align tiles with gbx_rst_align_to before combining.

Per-pixel median across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the median of that location's valid (non-NoData) values across the stack. Even counts average the two middle values. A pixel that is NoData in every input stays NoData. Robust to outliers — useful for seasonal median composites from time-series imagery.

Median pixel value per location.

Since v0.5.1
SELECT gbx_rst_combinemedian(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_combinemin​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combinemin(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combinemin(tiles)TILE
Pythonrasterx.functions.rst_combinemin(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns the NoData-aware per-pixel minimum; input tiles must share the same grid (shape/extent/CRS). All-NoData pixels yield NoData in the output. Align tiles with gbx_rst_align_to before combining.

Per-pixel minimum across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the smallest of that location's valid (non-NoData) values across the stack. A pixel that is NoData in every input stays NoData. Use to extract the lowest-cloud-probability pixel from a time stack or to track cumulative minimum temperatures.

Minimum pixel value per location.

Since v0.5.1
SELECT gbx_rst_combinemin(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_combinestddev​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combinestddev(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combinestddev(tiles)TILE
Pythonrasterx.functions.rst_combinestddev(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns the NoData-aware per-pixel population standard deviation (ddof=0) across the stack; input tiles must share the same grid (shape/extent/CRS). All-NoData pixels yield NoData in the output. Align tiles with gbx_rst_align_to before combining.

Per-pixel population standard deviation across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the population standard deviation (ddof=0) of that location's valid (non-NoData) values across the stack. A pixel that is NoData in every input stays NoData. Quantifies variability in a time-series or multi-scene ensemble — high values indicate heterogeneous pixels.

Population standard deviation of pixel values per location.

Since v0.5.1
SELECT gbx_rst_combinestddev(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_combinesum​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_combinesum(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_combinesum(tiles)TILE
Pythonrasterx.functions.rst_combinesum(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first).
Implementation

Powered by rasterio + NumPy. Takes an ARRAY<tile> and returns the NoData-aware per-pixel sum across the stack; input tiles must share the same grid (shape/extent/CRS). All-NoData pixels yield NoData in the output. Align tiles with gbx_rst_align_to before combining.

Per-pixel sum across an ARRAY of aligned tiles. On invocation the tiles are read as a pixel-aligned stack. They must share grid, extent, and CRS, so align them with rst_align_to first. Each output pixel is the sum of that location's valid (non-NoData) values across the stack. A pixel that is NoData in every input stays NoData. Use to accumulate total precipitation from a daily time-series or to sum spectral flux across dates.

Sum of pixel values per location.

Since v0.5.1
SELECT gbx_rst_combinesum(array(tile)) AS combined FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_convolve​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_convolve(tile, kernel)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_convolve(tile, kernel)TILE
Pythonrasterx.functions.rst_convolve(tile, kernel, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to convolve.
kernelARRAY<ARRAY<DOUBLE>>ARRAY<ARRAY<DOUBLE>>A 2-D array of weights with an odd number of rows and columns, applied unflipped (correlation).

See interpolation & fill to choose among sampling, resampling, and gap-filling.

Implementation

Powered by SciPy (scipy.ndimage). Every level give a Float64 result and apply the kernel unflipped, with the edges zero-padded. A NoData or masked neighbour adds 0, and the result is never NoData.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Apply a convolution kernel. A kernel that is not a rectangular array with an odd number of rows and columns raises an error that names its shape.

Example kernel: 3×3 identity ([[0,0,0],[0,1,0],[0,0,0]]), which passes pixels through unchanged.

Since v0.2.0
-- Apply 3x3 kernel (e.g. blur); kernel format is driver-specific
SELECT path, gbx_rst_convolve(tile, kernel) as filtered FROM rasters_with_kernels;
Example output
+----+-----------------------------------------------------------+
|path|filtered |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+

rst_derivedband​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_derivedband(tile, python_func, func_name)TILE
Pythonrasterx.functions.rst_derivedband(tile, python_func, func_name, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeDefaultDescription
tileTILEThe tile whose bands are the pixel function's input.
python_funcSTRINGPython source that defines the pixel function, with GDAL's VRT pixel-function signature func(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs): in_ar is the list of band arrays and out_ar the output array the function fills in place.
func_nameSTRINGThe name of the function in python_func. A source that does not parse, or that defines no such name, raises.
Implementation

Powered by rasterio and NumPy. GeoBrix runs your Python source with exec in the query's Python process. It does not use GDAL's VRT pixel-function API.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Apply a Python pixel function to derive a band. The function runs in the session's Python (exec), with the permissions of that process, as any Python you run does. Only code you trust belongs in python_func. Write it as a literal in your query. Do not pass a column of code from a table that others can write. GeoBrix adds no sandbox, and Unity Catalog does not run this function (see Security). A source that does not parse, or that defines no function of the name func_name, raises an error that names it.

Since v0.2.0
SELECT gbx_rst_derivedband(tile, 'def double(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):\\n out_ar[:] = in_ar[0] * 2\\n', 'double') AS result FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|result |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_filter​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_filter(tile, kernel_size, operation)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_filter(tile, kernel_size, operation)TILE
Pythonrasterx.functions.rst_filter(tile, kernel_size, operation, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to filter.
kernel_sizeINTINTThe side of the square window, a positive odd integer.
operationSTRINGSTRING'min', 'max', 'mean' or 'median', in any case. Another word raises.

See interpolation & fill to choose among sampling, resampling, and gap-filling.

Implementation

Powered by SciPy (scipy.ndimage). Every level take 'min', 'max', 'mean' and 'median' (any case); 'avg' and 'mode' are not accepted. The median of an even number of valid pixels, at an edge or beside NoData, is the mean of the two middle values.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Spatial filter over a square window. A window width that is not a positive odd number raises an error that names it. So does an operation that is not one of the four.

Since v0.2.0
-- Median filter (3x3 window)
SELECT
path,
gbx_rst_filter(tile, 3, 'median') as denoised
FROM noisy_rasters;

-- Average smoothing (5x5 window)
SELECT
path,
gbx_rst_filter(tile, 5, 'avg') as smoothed
FROM rasters;
Example output
+----+-----------------------------------------------------------+
|path|denoised |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+

rst_initnodata​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_initnodata(tile)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_initnodata(tile)TILE
Pythonrasterx.functions.rst_initnodata(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to give a NoData value.
Implementation

Powered by rasterio. A source without NoData gets the data type's fallback value (for example 65535 for UInt16). A NoData value the source already declares is kept.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Initialize NoData values.

Since v0.2.0
SELECT gbx_rst_initnodata(tile) as tile FROM rasters;
Example output
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile with NoData initialized)

rst_isempty​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_isempty(tile)BOOLEAN
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_isempty(tile)BOOLEAN
Pythonrasterx.functions.rst_isempty(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Check if raster is empty.

Returns true when the raster has no size or every band is entirely NoData.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands with real pixel data); the canonical single-band sentinel2 tile has NoData=0 with all pixels equal zero, returning true.

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_isempty(tile) AS is_empty FROM multiband_rasters;
Example output
+--------+
|is_empty|
+--------+
|false |
+--------+

rst_mapalgebra​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_mapalgebra(tiles, expression)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_mapalgebra(tiles, expression)TILE
Pythonrasterx.functions.rst_mapalgebra(tiles, expression, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The input tiles. Band 1 of each tile binds to A, B, C and so on, in array order.
expressionSTRINGSTRINGThe expression: a JSON envelope with a calc key, or a bare expression such as '(A - B) / (A + B)'.
Implementation

Runs GDAL's own raster calc with its muparser grammar, in the worker. Bands map to A, B, C, …; the output is single-band Float32 with NoData -9999. A pixel is NoData where any input pixel is NoData.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Map algebra expression (e.g. A - B).

How the inputs bind. tiles is an ARRAY<tile>. By default, band 1 of each tile, in array order, binds to the variables A, B, C, … (A = first tile, B = second, …). The result is a single-band Float32 tile on the first input's georeference.

Expression format. The expression takes either of two forms:

  • JSON envelope (recommended): a JSON object with a calc expression, such as '{"calc": "A * 2"}'.
  • Bare expression string: the calc expression on its own — "A * 2".

Selecting a specific band or raster per variable (A_index / A_band). You do not need to decompose a multiband raster to do band math. The JSON envelope's per-variable keys — A_index / A_band (and B_, C_, …) — map each variable to a chosen raster (0-based, into the tiles array) and a chosen 1-based band, mirroring gdal_calc. For example, NDVI from bands 4 (NIR) and 3 (Red) of a single raster:

{"calc": "(A - B) / (A + B)", "A_index": 0, "B_index": 0, "A_band": 4, "B_band": 3}

Both A and B read raster 0 (the one tile in the array), with A = band 4 and B = band 3 — the direct equivalent of gdal_calc -A in.tif --A_band=4 -B in.tif --B_band=3 --calc="(A - B) / (A + B)". A variable with no *_index/*_band keeps the default (its ordinal raster, band 1). An index or band out of range raises.

The envelope does not take extra_options (raw gdal_calc flags) or dialect. Either key raises an error that names it. A key other than calc and the *_index and *_band keys raises too.

Expression grammar

Every expression uses GDAL's muparser grammar, in a session and on Unity Catalog, for example (A - B) / (A + B), A > 0 ? A : 0 and max(A, B). NumPy spellings such as numpy.where are not accepted. An expression GDAL cannot evaluate raises. See the GDAL raster calculator reference.

Since v0.2.0
SELECT gbx_rst_mapalgebra(
array(tile),
'{"calc": "(A - B) / (A + B)", "A_index": 0, "B_index": 0, "A_band": 2, "B_band": 1}'
) AS ndvi
FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|ndvi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_merge​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_merge(tiles)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_merge(tiles)TILE
Pythonrasterx.functions.rst_merge(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tilesARRAY<TILE>ARRAY<TILE>The tiles to mosaic, in an array. Tiles in another CRS are reprojected onto the grid of a tile in the reference CRS.
Implementation

Powered by rasterio (rasterio.merge). Takes an ARRAY<tile> (in one row) and mosaics them into a single tile spanning the union extent. Where tiles overlap, the winner does not depend on the array order: the tile whose bytes sort last wins. Tiles in a different CRS are reprojected onto the pixel size and grid of a tile in the reference CRS and mosaicked with it. A tile reprojected from another CRS that declares no NoData (or has its own mask band) gets the footprint of the warp as its mask. The mosaic then has a mask band, and a pixel no tile reaches is invalid in it. A gap between tiles that are all in the reference CRS and declare no NoData is still filled with zeros.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Merge tiles into mosaic.

Since v0.2.0
SELECT gbx_rst_merge(array(tile)) AS merged FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|merged |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_ndvi​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_ndvi(tile, red_idx, nir_idx)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_ndvi(tile, red_idx, nir_idx)TILE
Pythonrasterx.functions.rst_ndvi(tile, red_idx, nir_idx, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe multi-band tile.
red_idxINTINTThe 1-based band of red.
nir_idxINTINTThe 1-based band of near infrared.
NoData

A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

NDVI from band indices.

Since v0.2.0
SELECT gbx_rst_ndvi(tile, 1, 2) AS ndvi FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|ndvi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NDVI raster: (NIR-Red)/(NIR+Red))

rst_rastertoworldcoord​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_rastertoworldcoord(tile, x, y)struct<x:double,y:double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_rastertoworldcoord(tile, x, y)struct<x:double,y:double>
Pythonrasterx.functions.rst_rastertoworldcoord(tile, x, y)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
xINTINTThe pixel column, counted from 0.
yINTINTThe pixel row, counted from 0.
Implementation

Powered by rasterio.

Pixel to world coordinates as a struct with .x and .y fields.

Since v0.2.0
SELECT
gbx_rst_rastertoworldcoord(tile, 100, 80) as world_coord,
gbx_rst_rastertoworldcoord(tile, 100, 80).x as easting,
gbx_rst_rastertoworldcoord(tile, 100, 80).y as northing
FROM rasters;
Example output
+---------------+-------+--------+
|world_coord |easting|northing|
+---------------+-------+--------+
|{500980.0, ...}|500980 |4599220 |
+---------------+-------+--------+

rst_rastertoworldcoordx​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_rastertoworldcoordx(tile, x, y)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_rastertoworldcoordx(tile, x, y)DOUBLE
Pythonrasterx.functions.rst_rastertoworldcoordx(tile, x, y)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
xINTINTThe pixel column, counted from 0.
yINTINTThe pixel row, counted from 0.
Implementation

Powered by rasterio.

World X / Y coordinate of a pixel.

Since v0.2.0
SELECT
gbx_rst_rastertoworldcoordx(tile, 100, 80) as easting
FROM rasters;
Example output
+-------+
|easting|
+-------+
|500980 |
+-------+

rst_rastertoworldcoordy​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_rastertoworldcoordy(tile, x, y)DOUBLE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_rastertoworldcoordy(tile, x, y)DOUBLE
Pythonrasterx.functions.rst_rastertoworldcoordy(tile, x, y)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
xINTINTThe pixel column, counted from 0.
yINTINTThe pixel row, counted from 0.
Implementation

Powered by rasterio.

World X / Y coordinate of a pixel.

Since v0.2.0
SELECT
gbx_rst_rastertoworldcoordy(tile, 100, 80) as northing
FROM rasters;
Example output
+--------+
|northing|
+--------+
|4599220 |
+--------+

rst_resample​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_resample(tile, factor, [algorithm])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_resample(tile, factor, [algorithm])TILE
Pythonrasterx.functions.rst_resample(tile, factor, algorithm=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to resample.
factorDOUBLEDOUBLEThe multiplicative factor, above 0: above 1 upsamples, below 1 downsamples.
algorithmSTRINGSTRING'bilinear'The resampling algorithm: near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3 (any case; nearest is accepted as near). A word that names none raises.

See interpolation & fill to choose among sampling, resampling, and gap-filling.

Implementation

Runs GDAL's own raster reproject algorithm in the worker, on every compute.

Resample a raster tile by a multiplicative factor, scaling pixel dimensions up or down relative to the source. A factor of 0 or less, or an unknown algorithm, raises an error that names the value. A virtual tile is read at the target size, so a file with overviews serves a shrink from them. An overview carries the resampling algorithm it was built with. A shrink served from it therefore differs in its pixels from the same call on a materialized tile. To apply your algorithm to every pixel, materialize the tile first. A result too large for the compute's memory gives an error tile with a Fix:.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Esri Resample / changing cell size

The rst_resample* family is GeoBrix's equivalent of the ArcGIS Resample tool — producing a new raster at a different cell size with a chosen resampling method. The algorithm is one of near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3, in any case. Pick the variant by how you specify the target:

  • rst_resample — by a multiplicative factor (e.g. 2.0 doubles the grid).
  • rst_resample_to_res — by target ground resolution in CRS units (e.g. metres per pixel).
  • rst_resample_to_size — by target pixel dimensions (width × height).

Unlike rst_sample — which reads a value at a point and is nearest-pixel only — resampling rewrites the whole grid. So to sample with bilinear or cubic interpolation, resample first with the desired algorithm, then call rst_sample.

See Raster Sampling for the full workflow guide.

SQL:

Since v0.4.0
-- Upsample 2x with bilinear interpolation. Output dims = source dims * 2.
SELECT gbx_rst_resample(tile, 2.0, 'bilinear') AS upsampled FROM rasters;
Example output
+-----------------------------------------------------------+
|upsampled |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_resample_to_res​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_resample_to_res(tile, x_res, y_res, [algorithm])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_resample_to_res(tile, x_res, y_res, [algorithm])TILE
Pythonrasterx.functions.rst_resample_to_res(tile, x_res, y_res, algorithm=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to resample.
x_resDOUBLEDOUBLEThe size of a pixel along x in the units of the tile's CRS, above 0.
y_resDOUBLEDOUBLEThe size of a pixel along y in the units of the tile's CRS, above 0.
algorithmSTRINGSTRING'bilinear'The resampling algorithm: near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3 (any case; nearest is accepted as near). A word that names none raises.
Implementation

Runs GDAL's own raster reproject algorithm in the worker, on every compute.

Resample a raster tile to an explicit ground resolution in CRS units. The pixels have exactly that size. When the resolution does not divide the extent, the extent grows or shrinks by less than one pixel. A resolution of 0 or less raises an error that names it.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Part of the rst_resample* family — see the Esri Resample note for how it relates to the ArcGIS Resample tool and rst_sample.

SQL:

Since v0.4.0
-- Downsample to a 100 m grid (metric CRS). 'average' weights cells by area.
SELECT gbx_rst_resample_to_res(tile, 100.0, 100.0, 'average') AS coarse
FROM rasters;
Example output
+-----------------------------------------------------------+
|coarse |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_resample_to_size​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_resample_to_size(tile, width_px, height_px, [algorithm])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_resample_to_size(tile, width_px, height_px, [algorithm])TILE
Pythonrasterx.functions.rst_resample_to_size(tile, width_px, height_px, algorithm=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to resample.
width_pxINTINTThe width of the result in pixels, above 0.
height_pxINTINTThe height of the result in pixels, above 0.
algorithmSTRINGSTRING'bilinear'The resampling algorithm: near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3 (any case; nearest is accepted as near). A word that names none raises.
Implementation

Runs GDAL's own raster reproject algorithm in the worker, on every compute.

Resample a raster tile to an explicit pixel grid size. A size of 0 or less raises an error that names it. A size that is not a whole number raises too.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Part of the rst_resample* family — see the Esri Resample note for how it relates to the ArcGIS Resample tool and rst_sample.

SQL:

Since v0.4.0
-- Force a 512 x 512 tile, near-neighbour for categorical rasters.
SELECT gbx_rst_resample_to_size(tile, 512, 512, 'near') AS sized FROM rasters;
Example output
+-----------------------------------------------------------+
|sized |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_transform​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_transform(tile, srid)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_transform(tile, srid)TILE
Pythonrasterx.functions.rst_transform(tile, srid, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to reproject.
sridINTINTThe EPSG (or ESRI) code of the target CRS, a positive integer.
Implementation

Runs GDAL's own raster reproject algorithm in the worker, on every compute.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Reproject to a target SRID: a positive EPSG or ESRI code. Pixels take the nearest source value. A tile already in that CRS comes back as it is. A code that names no CRS gives an error tile with the reason. A tile with no CRS also gives an error tile; set its CRS first with rst_setcrs. Use rst_transformcrs for a target given as a CRS string. See Coordinate Reference Systems. A tile with no NoData value gets a mask band over the pixels outside the footprint; they are never a valid 0.

Since v0.2.0
-- Reproject to WGS84
SELECT
path,
gbx_rst_transform(tile, 4326) as wgs84_tile,
gbx_rst_srid(gbx_rst_transform(tile, 4326)) as new_srid
FROM rasters;

-- Reproject and clip
SELECT
path,
gbx_rst_clip(gbx_rst_transform(tile, 4326), boundary, true) as result
FROM rasters;
Example output
+----+-----------------------------------------------------------+--------+
|path|wgs84_tile |new_srid|
+----+-----------------------------------------------------------+--------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|4326 |
+----+-----------------------------------------------------------+--------+

rst_transformcrs​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_transformcrs(tile, target_crs)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_transformcrs(tile, target_crs)TILE
Pythonrasterx.functions.rst_transformcrs(tile, target_crs)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to reproject.
target_crsSTRINGSTRINGThe target CRS: an authority code such as 'EPSG:3857' or 'ESRI:54008', WKT, PROJJSON or PROJ4. An integer string is an EPSG code.
Implementation

Runs GDAL's own raster reproject algorithm in the worker, on every compute.

Reproject to a target CRS given as a string (EPSG:x / ESRI:x / WKT / PROJ4; an int-castable string is treated as a SRID). Pixels take the nearest source value. See Coordinate Reference Systems. A tile with no NoData value gets a mask band over the pixels outside the footprint; they are never a valid 0.

Distinct from rst_transform (integer EPSG only): rst_transformcrs accepts any CRS string — an authority code (EPSG:3857, ESRI:54008), WKT, or PROJ4 — so you can reproject to a non-EPSG target. An int-castable string ('3857') is treated as an EPSG SRID. See the CRS: SRID int vs CRS string note above.

Since v0.5.0
-- Reproject to Web Mercator using a CRS string.
-- Unlike rst_transform (int EPSG only), rst_transformcrs also accepts
-- ESRI codes, WKT, or PROJ4 targets. An int-castable string ('3857')
-- is treated as an EPSG SRID.
SELECT
path,
gbx_rst_transformcrs(tile, 'EPSG:3857') as webmercator_tile,
gbx_rst_crs(gbx_rst_transformcrs(tile, 'EPSG:3857')) as new_crs
FROM rasters;
Example output
+----+-----------------------------------------------------------+---------+
|path|webmercator_tile |new_crs |
+----+-----------------------------------------------------------+---------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|EPSG:3857|
+----+-----------------------------------------------------------+---------+

rst_tryopen​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_tryopen(tile)BOOLEAN
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_tryopen(tile)BOOLEAN
Pythonrasterx.functions.rst_tryopen(tile)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
Implementation

Powered by rasterio.

Validate raster can be opened.

Examples use the multiband fixture (rgb_nir_small.tif, committed to the repo, always openable).

Since v0.2.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_tryopen(tile) AS try_open FROM multiband_rasters;
Example output
+--------+
|try_open|
+--------+
|true |
+--------+

rst_updatetype​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_updatetype(tile, new_type)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_updatetype(tile, new_type)TILE
Pythonrasterx.functions.rst_updatetype(tile, new_type, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to cast.
new_typeSTRINGSTRINGA GDAL data type name, in any case: Byte, Int8, UInt16, Int16, UInt32, Int32, Float32 or Float64. Another word raises.
Implementation

Powered by rasterio. Output is re-encoded as GeoTIFF; a NoData value that is not representable in the target type is dropped.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Convert raster data type.

Since v0.2.0
SELECT gbx_rst_updatetype(tile, 'Float32') as float_tile FROM rasters;
Example output
+-----------------------------------------------------------+
|float_tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_worldtorastercoord​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_worldtorastercoord(tile, x, y)struct<x:int,y:int>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_worldtorastercoord(tile, x, y)struct<x:int,y:int>
Pythonrasterx.functions.rst_worldtorastercoord(tile, x, y)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
xDOUBLEDOUBLEThe x coordinate in the raster CRS.
yDOUBLEDOUBLEThe y coordinate in the raster CRS.
Implementation

Powered by rasterio.

World to pixel coordinates as a struct with .x and .y fields.

Since v0.2.0
-- Find pixel coordinates for a specific location (center of raster)
SELECT
gbx_rst_worldtorastercoord(tile, 2122955.0, -10791275.0) as pixel_coord,
gbx_rst_worldtorastercoord(tile, 2122955.0, -10791275.0).x as pixel_col,
gbx_rst_worldtorastercoord(tile, 2122955.0, -10791275.0).y as pixel_row
FROM rasters;
Example output
+-----------+---------+---------+
|pixel_coord|pixel_col|pixel_row|
+-----------+---------+---------+
|{5490, ...}|5490 |5490 |
+-----------+---------+---------+

rst_worldtorastercoordx​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_worldtorastercoordx(tile, x, y)INT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_worldtorastercoordx(tile, x, y)INT
Pythonrasterx.functions.rst_worldtorastercoordx(tile, x, y)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
xDOUBLEDOUBLEThe x coordinate in the raster CRS.
yDOUBLEDOUBLEThe y coordinate in the raster CRS.
Implementation

Powered by rasterio.

Pixel column / row for a world coordinate.

Since v0.2.0
SELECT
gbx_rst_worldtorastercoordx(tile, 2122955.0, -10791275.0) as pixel_col
FROM rasters;
Example output
+---------+
|pixel_col|
+---------+
|5490 |
+---------+

rst_worldtorastercoordy​

SQLUnity Catalog SQLPythonScala
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_worldtorastercoordy(tile, x, y)INT
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_worldtorastercoordy(tile, x, y)INT
Pythonrasterx.functions.rst_worldtorastercoordy(tile, x, y)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
xDOUBLEDOUBLEThe x coordinate in the raster CRS.
yDOUBLEDOUBLEThe y coordinate in the raster CRS.
Implementation

Powered by rasterio.

Pixel column / row for a world coordinate.

Since v0.2.0
SELECT
gbx_rst_worldtorastercoordy(tile, 2122955.0, -10791275.0) as pixel_row
FROM rasters;
Example output
+---------+
|pixel_row|
+---------+
|5490 |
+---------+

rst_tilexyz​

SQLUnity Catalog SQLPythonScala
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_tilexyz(tile, z, x, y, [format], [size], [resampling], [rescale])BINARY
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_tilexyz(tile, z, x, y, [format], [size], [resampling], [rescale])BINARY
Pythonrasterx.functions.rst_tilexyz(tile, z, x, y, format=None, size=None, resampling=None, rescale=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to render.
zINTINTThe zoom level of the web tile, from 0.
xINTINTThe tile column, from 0 to 2^z - 1.
yINTINTThe tile row (north-down slippy-map order), from 0 to 2^z - 1.
formatSTRINGSTRING'PNG''PNG', 'JPEG' or 'WEBP', in any case. Any other word raises.
sizeINTINT256The side of the output tile in pixels, in (0, 4096]. Any other value raises.
resamplingSTRINGSTRING'bilinear'The GDAL warp resampling: near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3. Any other word raises.
rescaleSTRINGSTRING'auto'The 8-bit contrast: 'auto' rescales a tile that is not 8-bit by its band minimum and maximum and passes an 8-bit one through, 'none' keeps the full range of the data type, and 'min,max' rescales between two numbers. Any other text raises.
Implementation

Powered by rio-tiler + morecantile. Out-of-extent tiles return a transparent PNG (never null); available output formats depend on rasterio's bundled GDAL build.

Render a single web-mercator XYZ tile from a raster as encoded image bytes (e.g. PNG, JPEG, WebP) at the given tile coordinates and pixel size.

A bad argument raises an error that names the value. Bad arguments are a format other than PNG, JPEG or WEBP, a size outside (0, 4096], a resampling word that names none, or a rescale that is not auto, none or min,max. It raises also when the tile is NULL or cannot be read, because the argument is checked first; a NULL z, x or y gives NULL.

Display RGB(A) output (every level)

The output is a display web-map tile, not the source's raw bands. PNG and WebP are RGBA (4-band); JPEG is RGB (3-band, no alpha). The alpha channel is a binary transparency mask derived from the source's valid-data footprint. A NoData pixel renders transparent, whether it lies outside the raster or in an internal hole. Every level agrees on which pixels are transparent. Band mapping follows the Python level:

  • A single-band source becomes greyscale RGB (R=G=B).
  • A two-band source uses band 1 as greyscale RGB and band 2 as the alpha channel.
  • Three bands map to R, G, B, and an existing fourth band is treated as alpha.
  • Sources with five or more bands use the first three bands as RGB.

Non-8-bit sources are contrast-rescaled to 8-bit per the rescale argument (default "auto"; see the rescale note above). WebP alpha requires GDAL WebP-alpha support in the runtime; where absent, WebP falls back to RGB.

Since v0.4.0
-- Render tile (z=10, x=512, y=512) as 256x256 PNG bytes.
-- rescale='auto' (default) rescales non-8-bit imagery by whole-dataset min/max
-- for display contrast; 'none' keeps the raw full-dtype-range mapping; a
-- 'min,max' string sets explicit bounds.
SELECT
path,
gbx_rst_tilexyz(tile, 10, 512, 512, 'PNG', 256, 'bilinear', 'auto') as tile_png
FROM rasters;
Example output
+----+--------+
|path|tile_png|
+----+--------+
|... |[BINARY]|
+----+--------+

rst_to_webmercator​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_to_webmercator(tile, [resampling])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_to_webmercator(tile, [resampling])TILE
Pythonrasterx.functions.rst_to_webmercator(tile, resampling=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to reproject.
resamplingSTRINGSTRING'bilinear'The resampling algorithm: near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3 (any case; nearest is accepted as near). A word that names none raises.
Implementation

Runs GDAL's own raster reproject algorithm in the worker, on every compute.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Reproject a raster to EPSG:3857 (Web Mercator) using bilinear resampling by default. The returned tile carries srid = 3857. A resampling word that names none raises an error that names it. A tile with no CRS gives an error tile. A tile with no NoData value gets a mask band over the pixels outside the footprint; they are never a valid 0.

Since v0.4.0
-- Reproject to web mercator before slippy-map tiling (default bilinear resampling).
SELECT
path,
gbx_rst_to_webmercator(tile) as web_tile,
gbx_rst_srid(gbx_rst_to_webmercator(tile)) as new_srid
FROM rasters;
Example output
+----+-----------------------------------------------------------+--------+
|path|web_tile |new_srid|
+----+-----------------------------------------------------------+--------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|3857 |
+----+-----------------------------------------------------------+--------+

rst_xyzpyramid​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_xyzpyramid(tile, min_z, max_z, [format], [size], [resampling], [rescale])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_xyzpyramid(tile, min_z, max_z, [format], [size], [resampling], [rescale])rows
Pythonrasterx.functions.rst_xyzpyramid(df, tile, min_z, max_z, format=None, size=None, resampling=None, rescale=None)DataFrame

Rows: z INT, x INT, y INT, bytes BINARY.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to render.
min_zINTINTThe first zoom level, from 0.
max_zINTINTThe last zoom level, at least min_z and at most 20.
formatSTRINGSTRING'PNG''PNG', 'JPEG' or 'WEBP', in any case. Any other word raises.
sizeINTINT256The side of each output tile in pixels, in (0, 4096]. Any other value raises.
resamplingSTRINGSTRING'bilinear'The GDAL warp resampling, as for gbx_rst_tilexyz. Any other word raises.
rescaleSTRINGSTRING'auto'The 8-bit contrast, as for gbx_rst_tilexyz.
Streaming UDTF
Implementation

Powered by rio-tiler + morecantile. Streams one XYZ tile row per intersecting tile via streaming UDTF. Bounded by max_z <= 20 and at most 1,000,000 candidate tiles.

Generator: explode a raster into one row per intersecting (z, x, y) tile across a zoom range, producing PNG bytes per tile. Call it as a table function, FROM t, LATERAL gbx_rst_xyzpyramid(...); the output columns are z, x, y, and bytes. Each tile is rendered by rst_tilexyz, so the per-tile PNG is display RGBA with the same band mapping and binary NoData alpha described above.

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one (z, x, y, bytes) row per tile
-- across zoom levels 4..6 (PNG, 256px).
-- Optional trailing rescale arg (default 'auto') controls 8-bit display contrast:
-- gbx_rst_xyzpyramid(tile, 4, 6, 'PNG', 256, 'bilinear', 'auto')
SELECT path, t.z, t.x, t.y, t.bytes AS png_bytes
FROM rasters, LATERAL gbx_rst_xyzpyramid(tile, 4, 6) t;
Example output
+----+-+-+-+---------+
|path|z|x|y|png_bytes|
+----+-+-+-+---------+
|... |4|5|6|[BINARY] |
+----+-+-+-+---------+

Vector↔raster bridge​

Move data between the raster (tile) and vector (geom) worlds.

rst_polygonize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_polygonize(tile, [band], [connectedness])rows
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_polygonize(tile, [band], [connectedness])rows
Pythonrasterx.functions.rst_polygonize(df, tile, band=None, connectedness=None)DataFrame

Rows: geom_wkb BINARY, value DOUBLE.

ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to polygonize.
bandINTINT1The band to read, from 1.
connectednessINTINT44 joins pixels that share an edge; 8 also joins pixels that touch at a corner.
Streaming UDTF
Implementation

Runs GDAL's raster polygonize in the worker. Each row is one region: geom_wkb is a WKB polygon in the tile's CRS, and value is the pixel value.

gbx_rst_polygonize is a table function: call it with LATERAL. It gives one row per region. GDAL writes the regions to a temporary file on the worker's local disk, and the function reads them back one row at a time. Memory grows by about 30 bytes for each region, however large the polygons are. A tile of one million regions adds about 30 MB. The file is removed when the query ends. A tile with very many regions needs local disk for them. Pixels are grouped by their exact value. A float band is not rounded to whole numbers, and value is the pixel value itself. A NoData pixel gives no polygon. Nor does a pixel the tile's own mask band hides, or one that is transparent in its alpha band. A NaN or infinite pixel is NoData too, even when the tile declares no NoData value. A NULL, error or unreadable tile gives no rows. A band outside the tile raises and names the band. A connectedness other than 4 or 8 raises and names the value. A NULL band or connectedness takes its default. A virtual tile whose file is missing is retried, and then raises. The call takes the tile as a column argument, not as TABLE(...) PARTITION BY. The Serverless limit on PARTITION BY table functions does not apply to it.

SELECT t.geom_wkb, t.value FROM <table>, LATERAL gbx_rst_polygonize(tile, band, connectedness) t

SQL:

Since v0.4.0
-- A table function, called with FROM ..., LATERAL: one row per contiguous-value
-- region as (geom_wkb, value). Args are band and connectedness (4 or 8).
SELECT t.geom_wkb, t.value FROM rasters, LATERAL gbx_rst_polygonize(tile, 1, 4) t;

-- Round-trip: rasterize a polygon, then polygonize the result. The burn value
-- comes back as the `value` of the one region.
SELECT t.geom_wkb, t.value
FROM (
SELECT gbx_rst_rasterize(
unhex('010300000001000000050000000000000000000000000000000000000000000000000024400000000000000000000000000000244000000000000024400000000000000000000000000000244000000000000000000000000000000000'),
42.0, 0.0, 0.0, 10.0, 10.0, 100, 100, 4326
) AS tile
) r,
LATERAL gbx_rst_polygonize(tile) t;
Example output
+--------+-----+
|geom_wkb|value|
+--------+-----+
|... |365.0|
+--------+-----+
(one row per contiguous-value region; the rasterize round-trip returns one row with value 42.0)

rst_rasterize​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_rasterize(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [out_crs])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_rasterize(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [out_crs])TILE
Pythonrasterx.functions.rst_rasterize(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid=None, out_crs=None)Column
ParameterSQL typeUC typeDefaultDescription
geomBINARY or STRINGGEOMETRYThe geometry: WKB, EWKB, WKT or EWKT. A geometry with an SRID is reprojected into the output CRS first.
valueDOUBLEDOUBLEThe value burned into the pixels the geometry covers.
xminDOUBLEDOUBLEThe west edge of the output in the output CRS.
yminDOUBLEDOUBLEThe south edge of the output.
xmaxDOUBLEDOUBLEThe east edge of the output, above xmin.
ymaxDOUBLEDOUBLEThe north edge of the output, above ymin.
width_pxINTINTThe output width in pixels, above 0.
height_pxINTINTThe output height in pixels, above 0.
out_sridINTINTNULLThe EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS, or with the geometry's own when out_crs is NULL too.
out_crsSTRINGSTRINGNULLThe output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises.
Implementation

Powered by rasterio (rasterio.features).

Python-only out_crs parameter

The Python function takes an optional trailing out_crs (string CRS) that SQL does not. Neither → the geometry's carried source CRS.

Burn a polygon (WKB) into a fresh GeoTIFF tile at the given extent and pixel dimensions. Pixels inside the polygon carry burnValue; pixels outside are NoData. The output CRS is out_srid (integer EPSG code); the geometry is reprojected from its source CRS into the output CRS before burning. When out_srid is omitted the geometry's carried source CRS is used. See Coordinate Reference Systems.

SQL:

Since v0.4.0
-- WKB hex below is POLYGON((0 0, 10 0, 10 10, 0 10, 0 0)). The output `tile`
-- is a GTiff-backed raster at the given extent and resolution; pixels inside
-- the polygon carry the burn value (42.0), pixels outside are NoData.
SELECT gbx_rst_rasterize(
unhex('010300000001000000050000000000000000000000000000000000000000000000000024400000000000000000000000000000244000000000000024400000000000000000000000000000244000000000000000000000000000000000'),
42.0, 0.0, 0.0, 10.0, 10.0, 100, 100, 4326
) AS tile;
Example output
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(rasterized tile: pixels inside the polygon carry the burn value; outside = NoData)

Terrain Analysis​

Digital elevation model (DEM) derivatives. Each function takes a single-band DEM tile and returns a derived tile of the same footprint. They run GDAL's own raster algorithm in the worker, with Horn's method where the algorithm has a choice. See the Helios notebooks for a worked example: gbx_rst_slope, gbx_rst_aspect, and gbx_rst_hillshade are applied to 3DEP DEMs in NB03 to produce terrain layers and a per-H3-cell solar score.

rst_aspect​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_aspect(tile, [trigonometric], [zero_for_flat])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_aspect(tile, [trigonometric], [zero_for_flat])TILE
Pythonrasterx.functions.rst_aspect(tile, trigonometric=None, zero_for_flat=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
trigonometricBOOLEANBOOLEANfalsetrue gives counter-clockwise degrees from east; false gives compass degrees clockwise from north.
zero_for_flatBOOLEANBOOLEANfalsetrue gives 0 for flat cells; false leaves them NoData. The border and the cells next to NoData stay NoData.
Edges and NoData

A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Compass direction of steepest descent in degrees (0=N, 90=E, 180=S, 270=W). Flat areas are NoData unless zero_for_flat is true. Set trigonometric to true for the mathematical convention (0=E, counter-clockwise).

With zero_for_flat, GDAL would drop the NoData value and write 0 at the border. GeoBrix puts the NoData back there and in the cells next to NoData, so only flat cells are 0.

Since v0.4.0
-- Aspect in compass degrees (0=N, 90=E, 180=S, 270=W). Flat areas get -9999
-- unless zero_for_flat=true.
SELECT gbx_rst_aspect(tile, false, false) AS aspect FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|aspect |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(aspect in compass degrees: 0=N, 90=E, 180=S, 270=W)

rst_color_relief​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_color_relief(tile, color_table)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_color_relief(tile, color_table)TILE
Pythonrasterx.functions.rst_color_relief(tile, color_table, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
color_tableSTRINGSTRINGThe color table as text, in the gdaldem color-file format: one value R G B [A] line per entry, a color name such as red in place of R G B, nv for NoData, and N% for a share of the value range. Pass the text, not a file path.
Color table and NoData

The function runs GDAL's own raster color-map algorithm in the worker. The color table is text, not a path. Read a table file first and pass its text. The text is checked line by line: a line that is not a color entry raises, naming the line. A NoData pixel takes the nv color. Without an nv line it is transparent in an RGBA result and black in an RGB one. Values outside the entries take the nearest entry's color. The result is an RGB or RGBA Byte tile, RGBA when any entry has an alpha column.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Apply a gdaldem color table, given as text, to produce an RGB(A) visualization tile. Each line is value R G B [A], or value name with a color name such as red. A line nv R G B [A] colors NoData. A value such as 50% is a share of the range of the valid pixels. Entries need not be sorted, and # comments and commas are accepted.

Since v0.4.0
-- Map elevation values to RGB colors with a color table given as text (\\n is a new line).
SELECT gbx_rst_color_relief(tile, '0 34 139 34\\n100 144 238 144\\n200 255 255 0\\n311 255 255 255\\nnv 0 0 0') AS rgb
FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|rgb |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(3-band RGB tile mapped through the color table)

rst_hillshade​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_hillshade(tile, [azimuth], [altitude], [z_factor], [xscale], [yscale])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_hillshade(tile, [azimuth], [altitude], [z_factor], [xscale], [yscale])TILE
Pythonrasterx.functions.rst_hillshade(tile, azimuth=None, altitude=None, z_factor=None, xscale=None, yscale=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
azimuthDOUBLEDOUBLE315.0Sun azimuth in degrees clockwise from north.
altitudeDOUBLEDOUBLE45.0Sun elevation above the horizon in degrees.
z_factorDOUBLEDOUBLE1.0Vertical exaggeration applied to the gradients.
xscaleDOUBLEDOUBLENULLVertical units per horizontal unit along x; set it with yscale. When both are NULL, the scale comes from the raster CRS.
yscaleDOUBLEDOUBLENULLVertical units per horizontal unit along y; set it with xscale.
Edges and NoData

A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Shaded relief as an 8-bit image with values from 1 to 255; 0 is NoData. Common values are a north-west sun at azimuth 315.0, altitude 45.0 and z_factor 1.0. Pass both xscale and yscale, or neither.

Since v0.4.0
-- 8-bit (0..255) hillshade: NW sun, 45-deg altitude, default z-factor.
SELECT gbx_rst_hillshade(tile, 315.0, 45.0, 1.0) AS hillshade FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|hillshade |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(8-bit hillshade: 0..255, NW azimuth 45-degree altitude)

rst_roughness​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_roughness(tile)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_roughness(tile)TILE
Pythonrasterx.functions.rst_roughness(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
Edges and NoData

A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

The largest minus the smallest value in the 3×3 window around each pixel.

Since v0.4.0
-- Roughness: max absolute neighbour difference in a 3x3 window.
SELECT gbx_rst_roughness(tile) AS roughness FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|roughness |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(roughness: max absolute difference in 3x3 window)

rst_slope​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_slope(tile, [unit], [xscale], [yscale])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_slope(tile, [unit], [xscale], [yscale])TILE
Pythonrasterx.functions.rst_slope(tile, unit=None, xscale=None, yscale=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
unitSTRINGSTRING'degrees''degrees' or 'percent'.
xscaleDOUBLEDOUBLENULLVertical units per horizontal unit along x; set it with yscale. When both are NULL, the scale comes from the raster CRS.
yscaleDOUBLEDOUBLENULLVertical units per horizontal unit along y; set it with xscale.
Implementation

Runs GDAL's own raster slope algorithm with Horn's method, on every compute. Edge pixels are NoData.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Compute slope per pixel. unit is 'degrees' or 'percent'; xscale and yscale are the elevation/horizontal unit ratio per axis (supply both or neither; when omitted, GDAL 3.11+ auto-derives from the raster CRS). For isotropic scaling pass the same value to both (e.g. 1.0, 1.0 for a projected CRS in metres).

Since v0.4.0
-- Slope in degrees per pixel (auto-scale from CRS). Use unit='percent' for rise/run.
-- Pass xscale and yscale together to override the horizontal scale per axis.
SELECT gbx_rst_slope(tile, 'degrees', 1.0, 1.0) AS slope FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|slope |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(slope in degrees; auto-scaled from raster CRS units)

rst_tpi​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_tpi(tile)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_tpi(tile)TILE
Pythonrasterx.functions.rst_tpi(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
Edges and NoData

A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Topographic Position Index — pixel value minus the mean of its 8 neighbours. Positive values are ridges, negative values are valleys.

Since v0.4.0
-- TPI: difference from neighbour-mean; +ve = ridge, -ve = valley.
SELECT gbx_rst_tpi(tile) AS tpi FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|tpi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(TPI: positive=ridge, negative=valley)

rst_tri​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_tri(tile)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_tri(tile)TILE
Pythonrasterx.functions.rst_tri(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe single-band DEM tile.
Edges and NoData

A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Terrain Ruggedness Index (Riley): the square root of the summed squared differences between a pixel and its 8 neighbours. Useful for landscape-ecology habitat scoring.

Since v0.4.0
-- TRI: mean absolute neighbour difference; useful for landscape ecology.
SELECT gbx_rst_tri(tile) AS tri FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|tri |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(TRI: mean absolute neighbour difference)

Spectral Indices​

Multi-band satellite math. Band arguments are 1-based GDAL band indices; the output is always a single-band Float32 GeoTIFF tile. gbx_rst_ndvi is documented under Operations.

rst_evi​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_evi(tile, red_idx, nir_idx, blue_idx, [l], [c1], [c2], [g])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_evi(tile, red_idx, nir_idx, blue_idx, [l], [c1], [c2], [g])TILE
Pythonrasterx.functions.rst_evi(tile, red_idx, nir_idx, blue_idx, l=None, c1=None, c2=None, g=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe multi-band tile.
red_idxINTINTThe 1-based band of red.
nir_idxINTINTThe 1-based band of near infrared.
blue_idxINTINTThe 1-based band of blue.
lDOUBLEDOUBLE1.0The canopy background adjustment.
c1DOUBLEDOUBLE6.0The aerosol coefficient for red.
c2DOUBLEDOUBLE7.5The aerosol coefficient for blue.
gDOUBLEDOUBLE2.5The gain factor.
NoData

A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Enhanced Vegetation Index. Formula: G * (NIR - Red) / (NIR + C1*Red - C2*Blue + L) with MODIS canonical coefficients G=2.5, L=1.0, C1=6.0, C2=7.5.

Since v0.4.0
SELECT gbx_rst_evi(tile, 1, 2, 3) AS evi FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|evi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band EVI raster: G*(NIR-Red)/(NIR+C1*Red-C2*Blue+L))

rst_index​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_index(tile, formula_name, band_map)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_index(tile, formula_name, band_map)TILE
Pythonrasterx.functions.rst_index(tile, formula_name, band_map, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe multi-band tile.
formula_nameSTRINGSTRINGThe index: ndvi, gndvi, msavi, ndvi_re, ndmi or ndsi (any case).
band_mapMAP<STRING,INT>MAP<STRING,INT>The 1-based band of each name the index needs, such as map('red', 1, 'nir', 2).
NoData

A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Generic dispatcher that picks a built-in formula by name and wires bands via a MAP<STRING, INT> (e.g. map('red', 1, 'nir', 2)). Built-in names: ndvi, gndvi, msavi, ndvi_re, ndmi, ndsi. A pixel where the msavi square root has no real value is NoData too.

Since v0.4.0
SELECT gbx_rst_index(tile, 'ndvi', map('red', 1, 'nir', 2)) AS ndvi FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|ndvi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band index raster computed from named formula)

rst_land_cover​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_land_cover(tile, [method], [n_clusters], [smooth])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_land_cover(tile, [method], [n_clusters], [smooth])TILE
Pythonrasterx.functions.rst_land_cover(tile, method=None, n_clusters=None, smooth=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEA tile of 3 or more bands: red, green, blue (and optionally near-infrared).
methodSTRINGSTRING'hybrid''spectral' (thresholds on excess green and brightness), 'kmeans' or 'hybrid' (a k-means partition labelled by the same thresholds), in any case. Another word raises.
n_clustersINTINT6The k-means cluster count ('kmeans' and 'hybrid'), 1 or more.
smoothINTINT3The de-speckle window in pixels: isolated specks of a class are dropped; 0 turns it off.
Implementation

Powered by rasterio + NumPy + SciPy. Classifies a multi-band RGB(+NIR) tile into land-cover class ids using spectral thresholds, k-means clustering, or a hybrid approach. Registered as gbx_rst_land_cover in SQL.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Classify an RGB(+NIR) tile into land-cover class ids. The 'spectral' method uses fixed excess-green and brightness thresholds. The 'kmeans' method partitions the pixels with a scipy k-means over RGB, excess green and brightness, then labels each cluster by the same thresholds. The default 'hybrid' is the same partition as 'kmeans' today, kept as its own word so a later release can diverge it. smooth runs a binary-opening pass that drops isolated salt-and-pepper specks of each class back to NoData.

Requires a 3+ band tile (RGB, optionally +NIR — a 4th band is read but not yet consumed by any classifier). A tile with fewer bands is an error tile. Each output pixel is an index into the class list ["vegetation", "bare", "impervious", "dark"] by default. Map id to name by indexing that list with the value. NoData / unclassified pixels are -1, which is also the output tile's NoData value.

Tracing class regions to polygons, with a metric min-area filter

Because the output is an ordinary single-band tile, trace its class regions to polygons the same way as any other rst_* result. Use the registered gbx_rst_polygonize(tile, band, connectedness) table function. rst_polygonize has no min_area parameter, so filter out small regions after polygonizing. Filter in metric square meters via core.crs.area_m2(geom, crs). For a geographic CRS (e.g. EPSG:4326), it takes the geodesic area on the CRS's own ellipsoid. A raw geom.area in square degrees would silently drop every region against a metric threshold.

Since v0.5.2
SELECT gbx_rst_land_cover(tile, 'spectral', 6, 0) AS lc
FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|lc |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band Int32: each pixel is a land-cover class id index)
Classify land cover, then trace class regions to polygons
from databricks.labs import gbx
import numpy as np
import shapely.wkb
from pyspark.sql import functions as f
from rasterio.io import MemoryFile
from rasterio.transform import from_origin
from databricks.labs.gbx.core.crs import area_m2
from databricks.labs.gbx.rasterx import functions as rx_api
# The class scheme: a class id is an index into this list.
classes = ["vegetation", "bare", "impervious", "dark"]

# Build a 32 x 32, 3-band (RGB) uint8 raster with two regions: left half
# green (-> vegetation), right half bright/gray (-> bare).
h, w = 32, 32
a = np.zeros((3, h, w), np.uint8)
a[0, :, : w // 2] = 30 # left half: green
a[1, :, : w // 2] = 200
a[2, :, : w // 2] = 40
a[0, :, w // 2 :] = 210 # right half: bright/gray
a[1, :, w // 2 :] = 205
a[2, :, w // 2 :] = 200
profile = dict(
driver="GTiff",
width=w,
height=h,
count=3,
dtype="uint8",
crs="EPSG:4326",
transform=from_origin(0, h, 1, 1),
)
with MemoryFile() as mf:
with mf.open(**profile) as ds:
ds.write(a)
raster_bytes = mf.read()

df = spark.createDataFrame([(raster_bytes,)], ["raster"])
tile_df = df.select(rx_api.rst_fromcontent("raster", f.lit("GTiff")).alias("tile"))
lc_df = tile_df.select(
rx_api.rst_land_cover("tile", method="spectral", smooth=0).alias("lc")
)

# rst_land_cover is also registered as gbx_rst_land_cover in SQL; the
# resulting class-mask tile further composes with the registered streaming
# UDTF gbx_rst_polygonize, invoked via SQL LATERAL.
gbx.register(spark)
lc_df.createOrReplaceTempView("_pyrx_land_cover_demo")
rows = spark.sql(
"SELECT t.geom_wkb AS g, t.value AS v FROM _pyrx_land_cover_demo, "
"LATERAL gbx_rst_polygonize(lc, 1, 4) t"
).collect()

# value -> class name via the class scheme.
class_names = {int(r["v"]): classes[int(r["v"])] for r in rows}

# min_area is not an rst_polygonize / rst_land_cover parameter -- apply it
# as a post-polygonize filter, in metric square meters, via
# core.crs.area_m2 (geodesic here, since this tile's CRS is geographic
# EPSG:4326).
min_area = 0.0 # demo threshold
kept = [
r
for r in rows
if area_m2(shapely.wkb.loads(bytes(r["g"])), "EPSG:4326") >= min_area
]
Example output
Two contiguous regions traced from the class-mask tile, e.g.:
[Row(g=<wkb bytes>, v=0), Row(g=<wkb bytes>, v=1)]
class_names -> {0: "vegetation", 1: "bare"} (id -> classes[id])

rst_nbr​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_nbr(tile, nir_idx, swir_idx)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_nbr(tile, nir_idx, swir_idx)TILE
Pythonrasterx.functions.rst_nbr(tile, nir_idx, swir_idx, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe multi-band tile.
nir_idxINTINTThe 1-based band of near infrared.
swir_idxINTINTThe 1-based band of shortwave infrared.
NoData

A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Normalized Burn Ratio. Formula: (NIR - SWIR) / (NIR + SWIR). The pre-/post-fire difference (dNBR) is the canonical burn-severity index.

Since v0.4.0
SELECT gbx_rst_nbr(tile, 2, 3) AS nbr FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|nbr |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NBR raster: (NIR-SWIR)/(NIR+SWIR))

rst_ndwi​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_ndwi(tile, green_idx, nir_idx)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_ndwi(tile, green_idx, nir_idx)TILE
Pythonrasterx.functions.rst_ndwi(tile, green_idx, nir_idx, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe multi-band tile.
green_idxINTINTThe 1-based band of green.
nir_idxINTINTThe 1-based band of near infrared.
NoData

A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Normalized Difference Water Index (McFeeters 1996). Formula: (Green - NIR) / (Green + NIR). Positive values typically indicate open water.

Since v0.4.0
SELECT gbx_rst_ndwi(tile, 3, 2) AS ndwi FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|ndwi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NDWI raster: (Green-NIR)/(Green+NIR))

rst_savi​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_savi(tile, red_idx, nir_idx, [l])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_savi(tile, red_idx, nir_idx, [l])TILE
Pythonrasterx.functions.rst_savi(tile, red_idx, nir_idx, l=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe multi-band tile.
red_idxINTINTThe 1-based band of red.
nir_idxINTINTThe 1-based band of near infrared.
lDOUBLEDOUBLE0.5The soil-brightness correction; 0 reduces SAVI to NDVI.
NoData

A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.

Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Soil-Adjusted Vegetation Index. Formula: (NIR - Red) / (NIR + Red + L) * (1 + L). L = 0.5 (the canonical default) is a balanced soil/vegetation tradeoff; L = 0 reduces SAVI to NDVI.

Since v0.4.0
SELECT gbx_rst_savi(tile, 1, 2, 0.5) AS savi FROM multiband_rasters;
Example output
+-----------------------------------------------------------+
|savi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band SAVI raster: (NIR-Red)/(NIR+Red+L)*(1+L))

Pixel ops + extraction​

Per-pixel transformations and band-level extraction.

rst_band​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_band(tile, band_index)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_band(tile, band_index)TILE
Pythonrasterx.functions.rst_band(tile, band_index, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to take a band from.
band_indexINTINTThe 1-based band to extract, in [1 .. numbands].
Implementation

Powered by rasterio.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Extract a single band from a multi-band raster as a new single-band tile (gdal.Translate -b N). 1-based band index.

Example uses the multiband fixture (rgb_nir_small.tif, 3 bands) to demonstrate extraction; result has num_bands = 1.

Since v0.4.0
-- Pull band 1 (1-based) as a fresh single-band tile.
SELECT gbx_rst_band(tile, 1) AS b1 FROM rasters;
Example output
+-----------------------------------------------------------+
|b1 |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_buildoverviews​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_buildoverviews(tile, levels, [resampling])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_buildoverviews(tile, levels, [resampling])TILE
Pythonrasterx.functions.rst_buildoverviews(tile, levels, resampling=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to add overviews to.
levelsARRAY<INT>ARRAY<INT>The decimation factors, such as array(2, 4, 8): each at least 2.
resamplingSTRINGSTRING'average'The overview resampling: nearest, average, gauss, cubic, cubicspline, lanczos, bilinear or mode. Any other word raises.
Implementation

Powered by rasterio. Builds internal GeoTIFF overviews.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Add pyramid overview levels to a tile via ds.BuildOverviews. levels is an ARRAY<INT> (e.g. array(2, 4, 8, 16)); resampling is one of nearest, average, gauss, cubic, cubicspline, lanczos, bilinear, mode.

On Unity Catalog the function takes a tile of up to 64 MiB decoded and writes it to /tmp while GDAL builds the pyramid. A virtual tile is refused with a Fix, a tile that cannot be read gives NULL, and an error tile comes out as itself. A result of more than 64 MiB plus a third is refused with a Fix that names the session function.

Since v0.4.0
-- Add 2x / 4x overviews to the tile via the 'average' resampling.
SELECT gbx_rst_buildoverviews(tile, array(2, 4), 'average') AS withovr
FROM rasters;
Example output
+-----------------------------------------------------------+
|withovr |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_fillnodata​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_fillnodata(tile, [max_search_dist], [smoothing_iter])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_fillnodata(tile, [max_search_dist], [smoothing_iter])TILE
Pythonrasterx.functions.rst_fillnodata(tile, max_search_dist=None, smoothing_iter=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to fill.
max_search_distDOUBLEDOUBLE100.0How far, in pixels, to search for valid pixels to interpolate from. A whole number.
smoothing_iterINTINT0The number of 3x3 smoothing passes over the filled pixels. A whole number.

See interpolation & fill to choose among sampling, resampling, and gap-filling.

Implementation

Runs GDAL's raster fill-nodata for each band, in the worker, on every compute.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Fill NoData pixels with GDAL's inverse-distance interpolation from the valid pixels within max_search_dist pixels. Each band is filled by its own mask. A pixel with no valid pixel in range stays NoData: the function adds no value beyond GDAL's interpolation. smoothing_iter adds 3×3 smoothing passes over the filled pixels. Both numbers must be whole, from 0 to 2147483647. A fraction or a negative number raises and names the value. A tile that declares no NoData value and has no mask band comes back as it is. A tile whose validity is its own mask band keeps it. The filled pixels become valid, and the pixels the search did not reach stay masked. An alpha band (the last band of an RGBA or gray-alpha tile) is the tile's mask, not a band of values. Its transparent pixels are filled from the opaque ones, and each becomes opaque where every band was reached. A transparent pixel the search did not reach stays transparent.

Since v0.4.0
-- Fill NoData holes searching up to 100 pixels in each direction.
SELECT gbx_rst_fillnodata(tile, 100.0, 0) AS filled FROM rasters;
Example output
+-----------------------------------------------------------+
|filled |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_histogram​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_histogram(tile, [n_buckets], [min_val], [max_val], [include_nodata])map<string,array<bigint>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_histogram(tile, [n_buckets], [min_val], [max_val], [include_nodata])map<string,array<bigint>>
Pythonrasterx.functions.rst_histogram(tile, n_buckets=None, min_val=None, max_val=None, include_nodata=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
n_bucketsINTINT256The number of equal-width buckets across the range.
min_valDOUBLEDOUBLENULLThe lower bound of the range; the band's smallest valid value when NULL.
max_valDOUBLEDOUBLENULLThe upper bound of the range; the band's largest valid value when NULL.
include_nodataBOOLEANBOOLEANfalseWhether NoData pixels are binned too; the default leaves them out.
Implementation

Powered by rasterio + NumPy. Per-band bucket counts via numpy.histogram; map keys are band_<i> (1-based).

Compute a histogram for each band. Returns MAP<STRING, ARRAY<LONG>> keyed by "band_<n>" with bucket counts. When min_val or max_val is NULL, the range comes from the band's valid pixels.

Examples use the multiband fixture (rgb_nir_small.tif, 3 bands) so the histogram has entries for each band.

Since v0.4.0
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_histogram(tile) AS histogram FROM multiband_rasters;
Example output
+-------------------------------------------------+
|histogram |
+-------------------------------------------------+
|{band_1 -> [1, 0, 0, ...], band_2 -> [1, 0, 1,...|
+-------------------------------------------------+

rst_sample​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_sample(tile, geom, [crs])array<double>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_sample(tile, geom, [crs])array<double>
Pythonrasterx.functions.rst_sample(tile, geom, crs=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe raster tile.
geomBINARY or STRINGGEOMETRYA POINT as WKB, EWKB, WKT or EWKT.
crsSTRINGSTRINGNULLThe CRS of a point with no SRID: EPSG:<code>, ESRI:<code>, WKT or an integer code. The raster CRS when NULL.

See interpolation & fill to choose among sampling, resampling, and gap-filling.

Implementation

Powered by rasterio. Point geometries only; the point is assumed to be in the raster's CRS.

Sample the raster at the geometry's location(s). For a POINT, returns ARRAY<DOUBLE> of one value per band at the nearest pixel. The point moves from its source CRS to the raster CRS. An EWKB or EWKT SRID wins, then the optional crs argument. With neither, the point is taken to be in the raster CRS. See Coordinate Reference Systems.

Esri RS_VALUE / raster sampling

rst_sample is GeoBrix's equivalent of the ArcGIS Sample tool's RS_VALUE — reading a raster's cell value at a point. It returns ARRAY<DOUBLE> (one value per band, in band order), or null where the point falls outside the raster (the NoData/out-of-extent case). Sampling is nearest-pixel; for bilinear or cubic, run rst_resample first, then sample.

  • Multiple rasters (Esri's RS_VALUE1, RS_VALUE2, …): call rst_sample once per raster and alias each result column.
  • A points table against a raster tile set (the Sample-tool workflow at scale): join the points to the tiles that contain them. Use st_intersects, or a raster grid tessellation such as rst_h3_tessellate for an index join. Then call rst_sample(tile, point) per row.

See Raster Sampling for the full workflow guide.

Since v0.4.0
-- Sample the DEM at a point in its native CRS (EPSG:32618). Tagging the point
-- with an SRID (EWKT `SRID=32618;...`) lets gbx_rst_sample land it correctly.
SELECT gbx_rst_sample(tile, 'SRID=32618;POINT(500320 4500320)') AS values FROM dem_rasters;
Example output
+-------+
|values |
+-------+
|[302.0]|
+-------+
(array of sampled values, one per band)

rst_setcrs​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_setcrs(tile, crs)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_setcrs(tile, crs)TILE
Pythonrasterx.functions.rst_setcrs(tile, crs)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to relabel.
crsSTRINGSTRINGThe CRS to stamp: an authority code such as 'EPSG:3857' or 'ESRI:54008', WKT, PROJ4, PROJJSON, or an integer string (an EPSG code). A value that is no CRS raises.
Implementation

Powered by rasterio + pyproj. Stamps the CRS without reprojecting.

Stamp a CRS onto a raster that lacks a spatial reference, or has a wrong one, from a CRS string (EPSG:x / ESRI:x / WKT / PROJ4). An int-castable string is treated as a SRID. Does NOT reproject — only rewrites the CRS metadata. Use rst_transformcrs when you need an actual reprojection. See Coordinate Reference Systems.

Distinct from rst_setsrid (integer EPSG only): rst_setcrs accepts any CRS string — an authority code (EPSG:3857, ESRI:54008), WKT, or PROJ4 — so a non-EPSG CRS can be applied. An int-castable string ('4326') behaves like rst_setsrid(tile, 4326). See the CRS: SRID int vs CRS string note above.

Since v0.5.0
-- Relabel the tile's CRS to Web Mercator without warping pixels.
-- Accepts authority strings (EPSG:/ESRI:), WKT, or PROJ4; an int-castable
-- string ('4326') behaves like rst_setsrid(tile, 4326).
-- Use rst_transformcrs if you actually need a reprojection.
SELECT gbx_rst_setcrs(tile, 'EPSG:3857') AS tagged FROM rasters;
Example output
+-----------------------------------------------------------+
|tagged |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_setsrid​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_setsrid(tile, srid)TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_setsrid(tile, srid)TILE
Pythonrasterx.functions.rst_setsrid(tile, srid, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to relabel.
sridINTINTThe code to stamp, an EPSG or ESRI code; 0 clears the CRS. A negative number, or a positive code that is neither, raises.
Implementation

Powered by rasterio. Stamps the CRS without reprojecting.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Stamp a SRID (>= 0; an EPSG or ESRI code) onto a raster that lacks (or has a wrong) spatial reference; 0 clears the CRS. Does NOT reproject — only rewrites the CRS metadata. A negative SRID is rejected, and a positive code that is neither EPSG nor ESRI raises when stamped. Use rst_transform when you need an actual reprojection, or rst_setcrs to stamp from a CRS string. See Coordinate Reference Systems.

Since v0.4.0
-- Tag the tile as EPSG:4326 without warping pixels.
-- Use rst_transform if you actually need a reprojection.
SELECT gbx_rst_setsrid(tile, 4326) AS tagged FROM rasters;
Example output
+-----------------------------------------------------------+
|tagged |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_threshold​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_threshold(tile, [op], [value])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_threshold(tile, [op], [value])TILE
Pythonrasterx.functions.rst_threshold(tile, op=None, value=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to threshold.
opSTRINGSTRING'>'The comparison: >, <, >=, <=, == or !=.
valueDOUBLEDOUBLE0.0The value to compare each pixel with.
Python-only keywords

The Python function accepts three optional keyword arguments that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a bytes-free virtual reference. See Virtual-tile force-output params.

Keep the pixels for which pixel op value holds, with their original values, and set the others to NoData. op is one of >, >=, <, <=, ==, !=. The result keeps the source type and band count. A source without NoData gets the data type's fallback value, such as 65535 for UInt16.

Since v0.4.0
-- Keep the pixels above 100 m, set the others to NoData.
SELECT gbx_rst_threshold(tile, '>', 100.0) AS mask FROM rasters;
Example output
+-----------------------------------------------------------+
|mask |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

Analysis​

Higher-level analytical transforms wrapping single GDAL primitives — COG layout publishing, proximity surfaces, contour extraction, and viewshed analysis. See the Helios notebooks for a worked example of gbx_rst_cog_convert converting 3DEP DEMs to COGs and cataloging them in a STAC Delta table (NB03).

rst_gdal​

SQLPython
SurfaceCallReturns
SQL (session)gbx_rst_gdal(tile, command)TILE
Pythonrasterx.functions.rst_gdal(tile, command, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeDefaultDescription
tileTILEThe tile to process.
commandSTRINGWhat follows gdal raster on the command line: one step or steps joined by !, such as 'slope --unit=percent' or 'reproject --output-crs=EPSG:3857 ! slope'. Every step and argument must be on the allowlist; a file, URL or option outside it raises.
Implementation

Runs GDAL's raster pipeline in the worker on every compute. GeoBrix adds the read and write steps itself.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Run a GDAL raster command on a tile. command is what follows gdal raster on the command line. It is one step or several steps joined by !. The result is a GeoTIFF tile with what the last step writes.

SELECT gbx_rst_gdal(tile, 'slope --unit=percent') FROM dem_rasters;
SELECT gbx_rst_gdal(tile, 'reproject --output-crs=EPSG:3857 ! slope ! hillshade --zfactor=2') FROM dem_rasters;

Steps. These steps run: aspect, clip, fill-nodata, hillshade, neighbors, nodata-to-alpha, proximity, reclassify, reproject, resize, roughness, scale, select, set-type, sieve, slope, tpi, tri, unscale and viewshed. Any other step raises. This includes read, write, calc and every vector step.

Arguments. Write each argument as --name=value, with = and no space. Short flags and unlisted arguments raise. A value is a number, a word, a list of numbers, a mapping or a polygon. It is never a file, a URL, an @file or a /vsi name. A CRS value such as --output-crs=3857 goes through the same CRS resolver as gbx_rst_transformcrs. clip --geometry takes a WKT polygon.

What the command cannot do. You cannot name an input or an output. The input is the tile you pass, and the output is the tile you get. You cannot set a file format, a creation option or a --config option. For map algebra, use gbx_rst_mapalgebra: GDAL's calc step does not run inside a pipeline.

Results. The function returns what GDAL writes. After a reproject step, a source with no declared NoData keeps its footprint as a mask, as gbx_rst_transformcrs does: the area outside it is masked, never zero. A step that GDAL cannot run on the tile gives an error tile with GDAL's reason. This includes reproject on a tile with no CRS. A command that breaks the rules above, or leaves out a required argument, raises. A virtual tile that is a whole file is read by its path, block by block. The decoded size of every step is checked against the compute's cap before GDAL runs. A step whose output size cannot be bounded gives an error tile that asks for --size.

Since v0.6.0
-- One step: slope in percent. Then a pipeline: reproject, slope, hillshade.
SELECT gbx_rst_gdal(tile, 'slope --unit=percent') AS slope_pct,
gbx_rst_gdal(tile, 'reproject --output-crs=EPSG:3857 ! slope ! hillshade --zfactor=2') AS shade
FROM dem_rasters;
Example output
+-----------------------------------------------------------+-----------------------------------------------------------+
|slope_pct |shade |
+-----------------------------------------------------------+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+-----------------------------------------------------------+
(the result is a GeoTIFF tile; a step or argument outside the allowlist raises)

rst_cog_convert​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_cog_convert(tile, [compression], [blocksize], [overview_resampling])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_cog_convert(tile, [compression], [blocksize], [overview_resampling])TILE
Pythonrasterx.functions.rst_cog_convert(tile, compression=None, blocksize=None, overview_resampling=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to convert.
compressionSTRINGSTRING'AUTO''AUTO' (a size-adaptive ZSTD with the predictor for the data type) or a codec: ZSTD, DEFLATE, LZW, LERC, JPEG, WEBP or NONE. Any other word raises.
blocksizeINTINT512The internal block size in pixels, square: a multiple of 16. Any other value raises.
overview_resamplingSTRINGSTRING'AVERAGE'The resampling of the overview pyramid, such as AVERAGE.
Implementation

Re-encodes the tile as a Cloud Optimized GeoTIFF (it passes GDAL's COG validator). compression defaults to "auto" — a size-adaptive ZSTD level with a dtype-matched predictor (the GeoBrix materialize baseline; see Materialized Compression) — or an explicit codec name (zstd, deflate, lzw, lerc, jpeg, webp, none). The tile's metadata.driver is GTiff (a COG is a valid GeoTIFF).

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Re-layout a raster tile as a Cloud Optimized GeoTIFF via gdal.Translate -of COG. It uses a ZSTD + dtype-predictor baseline. compression accepts an explicit codec (ZSTD, DEFLATE, LZW, NONE, LERC, JPEG, WEBP) and AUTO, its default. AUTO is a size-adaptive ZSTD level with the dtype predictor. blocksize is the internal tile size in pixels (square), any multiple of 16 down to 16. overviewResampling is the algorithm for the auto-generated overview pyramid. Output is a GTiff-on-disk variant suitable for HTTP range serving. See Materialized Compression for the codec/level details and when to override.

On Unity Catalog the function takes a tile of up to 64 MiB decoded and writes it to /tmp while GDAL builds the layout. A virtual tile is refused with a Fix, a tile that cannot be read gives NULL, and an error tile comes out as itself. A result of more than 64 MiB plus a third is refused with a Fix that names the session function.

Since v0.4.0
-- Convert to COG with ZSTD compression, 512-pixel blocks, AVERAGE overviews.
-- The lightweight tier also accepts 'AUTO' (size-adaptive ZSTD + dtype
-- predictor, the default); pass 'DEFLATE' for a portable hand-off file.
-- See the Materialized Compression page.
SELECT gbx_rst_cog_convert(tile, 'ZSTD', 512, 'AVERAGE') AS cog
FROM rasters;
Example output
+-----------------------------------------------------------+
|cog |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+

rst_contour​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_contour(tile, levels, [interval], [base], [attr_field])array<struct<geom_wkb:binary,value:double>>
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_contour(tile, levels, [interval], [base], [attr_field])array<struct<geom_wkb:binary,value:double>>
Pythonrasterx.functions.rst_contour(tile, levels, interval=None, base=None, attr_field=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to trace.
levelsARRAY<DOUBLE>ARRAY<DOUBLE>The values to trace; NULL or empty to use interval and base.
intervalDOUBLEDOUBLE0.0The spacing of the lines, used when levels is empty; above 0.
baseDOUBLEDOUBLE0.0The value one line is drawn at, used with interval.
attr_fieldSTRINGSTRING'elev'Accepted for compatibility; the value is always the struct field value.
Implementation

Runs GDAL's raster contour in the worker. Returns ARRAY<struct(geom_wkb, value)> of contour LineStrings in the raster CRS. The lines sit at each fixed level, or at base + k*interval across the data range when levels is empty. A NoData pixel is never traced. That includes a pixel equal to -9999 in a tile that declares no NoData value.

Pass a non-empty levels ARRAY<DOUBLE> for fixed contour values. Or pass array() and set interval (above 0) for equal-step contours at base + n*interval. Levels may come in any order. Repeated and NULL elements are dropped, and levels wins over interval when both are given. Each entry is one contour line in the source raster's CRS. A line runs to the tile's edge, half a pixel past the outermost pixel centres. An empty array means no line crosses. NULL means a NULL, error or unreadable tile, or a call GDAL cannot run. A call over the compute's memory budget is NULL too.

Since v0.4.0
-- Equal-interval contours every 50 m. Pass array() of fixed levels to override.
SELECT gbx_rst_contour(tile, array(), 50.0, 0.0, 'elev') AS contours
FROM dem_rasters;
Example output
+-----------------------------------------------------------------------------------------------------------------+
|contours |
+-----------------------------------------------------------------------------------------------------------------+
|[{[BINARY], 50.0}, {[BINARY], 100.0}, {[BINARY], 150.0}, {[BINARY], 200.0}, {[BINARY], 250.0}, {[BINARY], 300.0}]|
+-----------------------------------------------------------------------------------------------------------------+
(array of contour features: LineString geometry + elevation)

rst_proximity​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_proximity(tile, [target_values], [dist_units], [max_distance])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_proximity(tile, [target_values], [dist_units], [max_distance])TILE
Pythonrasterx.functions.rst_proximity(tile, target_values=None, dist_units=None, max_distance=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe tile to measure: its first band.
target_valuesSTRINGSTRINGNULLThe source pixel values as a comma-separated list, such as '1,2'. NULL makes every pixel that is not 0 a source.
dist_unitsSTRINGSTRING'GEO''GEO' measures in the units of the tile's CRS; 'PIXEL' counts pixels. NULL is 'GEO'.
max_distanceDOUBLEDOUBLENULLThe largest distance to compute, above 0: farther pixels are NoData. NULL for no limit.
Implementation

Powered by SciPy (scipy.ndimage.distance_transform_edt). Distance to the nearest source pixel (target_values, or any non-zero pixel by default), in GEO (CRS units) or PIXEL units; pixels beyond max_distance → NoData −1.0. Single-band Float32.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Compute a Float32 raster where each pixel holds the exact Euclidean distance to the nearest source pixel. target_values is a comma-separated list of source-pixel values (e.g. "1,2,3"); null means every pixel that is not 0 is a source. dist_units is "GEO" (CRS ground units, default; NULL is "GEO") or "PIXEL"; any other word raises an error. max_distance caps the output; pixels beyond it get the NoData sentinel -1.0.

Since v0.4.0
-- Distance in pixels to any non-NoData pixel; cap distances at 100 pixels.
SELECT gbx_rst_proximity(tile, '', 'PIXEL', cast(100.0 as double)) AS dist
FROM rasters;
Example output
+-----------------------------------------------------------+
|dist |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(distance in pixels to nearest non-NoData pixel, capped at 100)

rst_viewshed​

SQLUnity Catalog SQLPython
Also available as a Unity Catalog function for SQL warehouses. See Unity Catalog functions.
SurfaceCallReturns
SQL (session)gbx_rst_viewshed(tile, observer_geom, [observer_height], [target_height], [max_distance], [crs])TILE
SQL (Unity Catalog)<catalog>.<schema>.gbx_rst_viewshed(tile, observer_geom, [observer_height], [target_height], [max_distance], [crs])TILE
Pythonrasterx.functions.rst_viewshed(tile, observer_geom, observer_height=None, target_height=None, max_distance=None, crs=None, virtualize_dir=None, virtualize_prefix=None, materialize=None)Column
ParameterSQL typeUC typeDefaultDescription
tileTILETILEThe DEM tile.
observer_geomBINARY or STRINGGEOMETRYThe observer: a POINT as WKB, EWKB, WKT or EWKT, in the DEM's CRS (an SRID in EWKB or EWKT wins over crs). Any other geometry raises.
observer_heightDOUBLEDOUBLE0.0The observer's height above the DEM, 0 or more. NULL is 0.
target_heightDOUBLEDOUBLE1.6The height of the target above the DEM at each cell, 0 or more.
max_distanceDOUBLEDOUBLENULLThe largest distance to analyse in the DEM's CRS units, above 0. NULL for no limit: the whole DEM. A limit gives the window around the observer.
crsSTRINGSTRINGNULLThe CRS of the observer when it has no SRID (EPSG:n, ESRI:n or WKT). NULL means the DEM's CRS.
Implementation

Runs GDAL's raster viewshed in the worker, in its edge line-of-sight mode with a curvature coefficient of 0.85714. Returns a Byte tile (255 visible, 0 invisible) from a DEM tile and a POINT observer.

Changed in 0.6.0

With a max_distance, the result is the window around the observer, aligned to the DEM's pixel grid. In v0.5.2, DEMs above the small-DEM limit (about 366 × 366 pixels by default) stretched that window over the whole DEM.

Python-only keywords

The Python function takes three optional keywords that SQL does not: virtualize_dir, virtualize_prefix and materialize. They choose whether the tile carries raster bytes or a virtual reference. See force-output params.

Compute a binary viewshed Byte raster (255 = visible, 0 = invisible or out of range) from a DEM tile and an observer POINT. The observer is a WKB, EWKB, WKT or EWKT POINT. The call moves it from its own CRS into the DEM's CRS. An embedded SRID wins, then the optional crs argument, then the DEM's own CRS. Any other geometry raises. A NULL observer_height is 0, and a NULL target_height gives NULL. Heights are above the DEM at each pixel. A max_distance limits the search radius; NULL means no limit. For an observer outside the DEM, GDAL assumes nothing blocks the view to the DEM and takes the observer's height from elevation 0. A max_distance that leaves no part of the DEM gives an error tile. GDAL reads a virtual tile that is a whole file from the file, block by block. A large DEM then needs no more memory than GDAL's block cache. A tile with bytes, or a window of a file, is read whole under the compute's read cap. See Coordinate Reference Systems.

Since v0.4.0
-- Visibility from observer at (-73.5 40.5), eye 100 m, target 1.6 m, cap 5000 m.
SELECT gbx_rst_viewshed(tile, 'POINT(-73.5 40.5)', 100.0, 1.6, 5000.0) AS vs
FROM dem_rasters;
Example output
+-----------------------------------------------------------+
|vs |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(binary viewshed: 255=visible, 0=not visible)

rst_viewshed_towers (Python / DataFrame helper)​

Python helper only

rst_viewshed_towers is not registered as a SQL function. It is a PySpark DataFrame pipeline function in databricks.labs.gbx.rasterx.helpers. It runs on Serverless and needs no JAR.

Changed in 0.6.0

visible_px and total_px now come from the window around each tower (the radius_m square, clipped to the DSM), as rst_viewshed returns it. In v0.5.2 a stretched mask inflated them on DEMs above the same limit. A tower that stands in a grid cell with no DSM tile has no row. One outside the DSM used to get a row with no visible pixels.

rst_viewshed_towers runs a per-tower raster viewshed over a tiled DSM and returns one scalar row per tower. For each tower it selects the in-radius DSM tiles via the tile_range windowing helper. The helper uses an EPSG:3857 grid origin + tile size that the tx/ty indices in dsm_tiles_df reference. It then mints one bytes-free VRT over those tiles, runs a single rst_viewshed (materialized once, in-memory), and derives coverage counts from a histogram. One call per tower mints the VRT and reads it, so the VRT never passes between tasks or UDFs. No raster bytes cross a shuffle, so there is no FUSE read-back and no whole-AOI merge. Powers the Wireless Coverage series Part 3b viewshed analysis.

Signature:

from databricks.labs.gbx.rasterx.helpers import rst_viewshed_towers

result_df = rst_viewshed_towers(
towers_df, dsm_tiles_df, radius_m, observer_height,
x0=x0, y0=y0, tile_m=tile_m,
target_height=1.6, to_crs=None, vrt_dir=None,
tower_id_col="tower_cellid", x_col="x", y_col="y",
num_partitions=None,
)

Parameters:

  • towers_df — DataFrame of tower sites; must carry tower_id_col plus the projected observer coordinate columns x_col/y_col (EPSG:3857 metres, matching the DSM grid). When observer_height is a column name, that column must also be present.
  • dsm_tiles_df — bytes-free DSM tile manifest; must have columns path (absolute COG path), tx and ty (integer grid indices). Collected once on the driver.
  • radius_m — viewshed analysis radius in projected metres (> 0); also caps the DSM window and the rst_viewshed max-distance.
  • observer_height — observer/mast height above the DSM surface — a scalar applied to every tower, or a column name for per-tower heights.
  • x0, y0 — EPSG:3857 tile-grid origin that the tx/ty indices in dsm_tiles_df reference.
  • tile_m — tile size in metres (> 0).
  • target_height — receiver height above the DSM at each tested cell; defaults to 1.6.
  • to_crs — optional EPSG code to reproject the viewshed into (rst_transform, materialized once); when set, the result gains visible_px_reproj and total_px_reproj.
  • vrt_dir — optional durable, worker-readable directory (e.g. a UC Volume path) for the per-tower VRTs. When omitted, each VRT is minted in a local temp folder by the call that reads it, and removed after.
  • tower_id_col / x_col / y_col — tower identity and coordinate column names; defaults "tower_cellid" / "x" / "y".
  • num_partitions — fan-out for the per-tower stage (repartition by tower_id_col); defaults to the distinct tower count (~one tower per task).

Returns: DataFrame with one row per tower that has in-radius DSM coverage: tower_id_col, observer_x, observer_y, visible_px (long), total_px (long), frac (double, visible/total), and — when to_crs is set — visible_px_reproj and total_px_reproj.

An unreadable DSM tile fails the query. A reprojection to to_crs that fails also fails the query. The error names the tower and gives the reason the read or the step gave.

databricks.labs.gbx.rasterx.helpers.tile_range computes the index window covering a circle of radius_m around a projected coordinate. rst_viewshed_towers uses it to select the tiles each tower needs before minting the per-tower VRT.


VRT Python pixel functions​

GDAL can run Python code that a VRT file carries in a <PixelFunctionCode> element. GeoBrix keeps that off: GDAL_VRT_ENABLE_PYTHON is NO in the process. A VRT from a table or a Volume does not run its Python code. See Security.

gbx_rst_derivedband and gbx_rst_derivedband_agg do not use that GDAL API. They run the Python source you pass with exec, in the query's Python process. You set nothing on the cluster.

When you read a Python-pixel VRT yourself​

Suppose you call the GDAL Python bindings (from osgeo import gdal) directly, outside the RasterX functions. A VRT that declares a <PixelFunctionLanguage>Python</...> band then reads as empty unless you enable the option. Enable it only for a VRT you wrote, and only around your own read:

from osgeo import gdal

gdal.SetConfigOption("GDAL_VRT_ENABLE_PYTHON", "YES")
try:
ds = gdal.Open("/path/to/your/vrt-with-pixel-function.vrt")
arr = ds.GetRasterBand(1).ReadAsArray()
ds = None
finally:
gdal.SetConfigOption("GDAL_VRT_ENABLE_PYTHON", "NO")

GDAL also accepts GDAL_VRT_ENABLE_PYTHON=TRUSTED_MODULES with a GDAL_VRT_PYTHON_TRUSTED_MODULES allowlist. It limits the pixel-function code to the module prefixes you name. Use it if the <PixelFunctionCode> may come from a less-trusted source.


Escape hatches​

When a raster operation isn't in the rst_* surface, drop down to rasterio/NumPy per tile (Python level). These are Python-only helpers on databricks.labs.gbx.rasterx.helpers — not SQL functions, and not registered as gbx_rst_*.

tile_to_numpy​

from databricks.labs.gbx.rasterx.helpers import tile_to_numpy

arr = tile_to_numpy(tile_or_bytes) # -> np.ndarray, shape (bands, rows, cols)

Read a tile's raster into a NumPy array (all bands). Accepts either a tile struct (a Row/dict with a raster field) or raw bytes. Useful when you've collected a tile to the driver, or inside your own UDF.

rst_apply​

from pyspark.sql.types import DoubleType
from databricks.labs.gbx.rasterx.helpers import rst_apply

df.select(
rst_apply("tile", lambda ds: float(ds.read(1).mean()), returnType=DoubleType()).alias("band1_mean")
)

Apply your own function to each tile's open rasterio dataset, returning one scalar per row. fn receives a rasterio DatasetReader; the return value must match returnType (default DoubleType(); any Spark DataType). A null/empty tile yields null. This is the "GeoBrix doesn't have function X — run my own rasterio per tile" path; it returns a scalar (raster→raster transforms are the domain of rst_mapalgebra / rst_derivedband).

For rendering tiles and building maps from results, see the Visualization (gbx.vizx) page.


Next Steps​