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.
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_gbxprepare spec-valid Cloud-Optimized GeoTIFFs and portable VRT mosaics for cheap windowed reads
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:

Each card links to a section below:
- Accessors: size, georeference, CRS, bands and statistics.
- Constructors: tiles from files, bytes, bands, points or shapes.
- Aggregators: merge, combine and rasterize tiles in
GROUP BY. - Generators: split a tile into tiles, bands or grid cells.
- Grid cells: raster values to H3, quadbin, British National Grid or custom grid cells.
- LiDAR and point clouds: bin points into surface and canopy-height models.
- Terrain analysis: slope, aspect, hillshade and relief from a DEM.
- Spectral indices: vegetation, water, burn and land-cover indices.
- Operations: clip, resample, reproject, combine, map algebra, coordinates and XYZ tiles.
- Vector and raster: geometries to tiles and tiles to polygons.
- Pixel ops and extraction: bands, NoData fill, thresholds, samples, histograms and overviews.
- Analysis: contours, proximity, viewshed, COG output and GDAL commands.
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
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):
| Argument | Type | Meaning |
|---|---|---|
virtualize_dir | str (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_prefix | str | Optional filename prefix added before the provenance-based filename — use this to deconflict when two different function outputs share the same virtualize_dir. |
materialize | bool | True — 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:
| Placeholder | Sample file | Reader — Temp view | Backs |
|---|---|---|---|
GTIFF_SAMPLE_DIR | single-band GeoTIFF | gtiff_gbx — rasters | Default — most accessor, tile-ops, transform, and generator examples |
GTIFF_MULTI_DIR | multi-band GeoTIFF (red/NIR/green) | gtiff_gbx — multiband_rasters | band-math and spectral-index examples, rst_numbands, rst_bandmetadata |
DTM_DIR | digital elevation model | gtiff_gbx — dem_rasters | terrain examples (rst_slope, rst_aspect, …) |
NETCDF_DIR | NetCDF with subdatasets | netcdf_gbx — netcdf_rasters | rst_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.
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")
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:
-- 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
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.
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:
| File | What it demonstrates | Used by |
|---|---|---|
nyc_sentinel2_red.tif | Single-band GeoTIFF (Sentinel-2 red band, NYC area) | Default — most accessor, tile-ops, transform, and generator functions |
rgb_nir_small.tif | 3-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.tif | Digital Elevation Model (SRTM, NYC area) | Terrain functions (rst_slope, rst_aspect, rst_hillshade, …) |
CMIP5 NetCDF (prAdjust_day_…nc) | Multi-variable NetCDF with two subdatasets | rst_subdatasets, rst_getsubdataset only |
The tile-column convention
In every example on this page:
- SQL:
rastersis a temporary view whosetilecolumn holds the canonical sample loaded via the reader.FROM rastersmeans "the sample as tiles." - Python:
dfis a DataFrame with atilecolumn 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
| Tab | Surface |
|---|---|
| SQL | Session SQL, after register(spark) |
| Unity Catalog SQL | A <catalog>.<schema>.gbx_* function, where the function exists in Unity Catalog |
| Python | The 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 returnsmap<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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_avg(tile) | array<double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_avg(tile) | array<double> |
| Python | rasterx.functions.rst_avg(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
- SQL
- Python
-- 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;
+-----------------------------+
|band_averages |
+-----------------------------+
|[83.59375, 153.125, 114.3125]|
+-----------------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_avg("tile").alias("band_averages")).first()
+------------------------------------+
|band_averages |
+------------------------------------+
|[83.59375, 153.125, 114.3125] |
+------------------------------------+
rst_bandmetadata
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_bandmetadata(tile, band) | map<string,string> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_bandmetadata(tile, band) | map<string,string> |
| Python | rasterx.functions.rst_bandmetadata(tile, band) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
band | INT | INT | The 1-based band number. |
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 {}.
- SQL
- Python
-- 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;
+----------------------------------------------+
|band_meta |
+----------------------------------------------+
|{name -> red, wavelength_nm -> 665, band_in...|
+----------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
result = df.select(rx.rst_bandmetadata("tile", f.lit(1)).alias("band_meta")).first()
+----------------------------------------------+
|band_meta |
+----------------------------------------------+
|{name -> red, wavelength_nm -> 665, band_in...|
+----------------------------------------------+
rst_boundingbox
SQLUnity Catalog SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_boundingbox(tile) | BINARY |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_boundingbox(tile) | BINARY |
| Python | rasterx.functions.rst_boundingbox(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Bounding box geometry.
Since v0.2.0- SQL
- Python
SELECT path, gbx_rst_boundingbox(tile) as bbox FROM rasters;
+--------------------+-----------------+
|path |bbox |
+--------------------+-----------------+
|.../nyc_sentinel2...|POLYGON ((-74....|
+--------------------+-----------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_boundingbox("tile").alias("bbox")).first()
+----+
|bbox|
+----+
|[...|
+----+
(WKB binary — bounding POLYGON of the raster extent in EPSG:32618)
rst_crs
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_crs(tile) | STRING |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_crs(tile) | STRING |
| Python | rasterx.functions.rst_crs(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
rst_sridreturns the integer authority code, EPSG or ESRI (for example4326, or54008forESRI:54008). It returnsNULLfor a raster with no CRS, an authority-less WKT or PROJ4 CRS, or a code that is not a number (such asOGC:CRS84). Use it when you need the numeric SRID for the native ST bridge.rst_crsreturns the CRS string and never loses a non-EPSG CRS.rst_setcrs/rst_transformcrstake a CRS string. An int-castable string is treated as an EPSG SRID ('4326'behaves like SRID4326); 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.
- SQL
- Python
SELECT gbx_rst_crs(tile) AS crs FROM rasters;
+----------+
|crs |
+----------+
|EPSG:32618|
+----------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_crs("tile").alias("crs")).first()
+----------+
|crs |
+----------+
|EPSG:32618|
+----------+
rst_format
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_format(tile) | STRING |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_format(tile) | STRING |
| Python | rasterx.functions.rst_format(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
GDAL format name.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_format(tile) AS format FROM rasters;
+------+
|format|
+------+
|GTiff |
+------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_format("tile").alias("format")).first()
+------+
|format|
+------+
|GTiff |
+------+
rst_georeference
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_georeference(tile) | map<string,double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_georeference(tile) | map<string,double> |
| Python | rasterx.functions.rst_georeference(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Georeference parameters as a map.
The result is a MapType with the following keys, corresponding to GDAL's 6-element geotransform:
| Key | Geotransform index | Meaning |
|---|---|---|
upperLeftX | GT(0) | X of the upper-left corner of the upper-left pixel |
upperLeftY | GT(3) | Y of the upper-left corner of the upper-left pixel |
scaleX | GT(1) | Pixel width (west–east resolution) |
scaleY | GT(5) | Pixel height (north–south resolution; often negative for north-up) |
skewX | GT(2) | Row rotation (typically 0) |
skewY | GT(4) | Column rotation (typically 0) |
See the GDAL geotransform tutorial and raster data model for details.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_georeference(tile) AS georeference FROM rasters;
+-------------------------------------------------------------+
|georeference |
+-------------------------------------------------------------+
|{scaleX -> 10.0, scaleY -> -10.0, upperLeftX -> 2121950.0,...|
+-------------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_georeference("tile").alias("georeference")).first()
+--------------------------------------------------------------+
|georeference |
+--------------------------------------------------------------+
|{scaleX -> 10.0, scaleY -> -10.0, upperLeftX -> 2121950.0,... |
+--------------------------------------------------------------+
rst_getnodata
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_getnodata(tile) | array<double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_getnodata(tile) | array<double> |
| Python | rasterx.functions.rst_getnodata(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio. Returns the dataset NoData value repeated once per band.
NoData values per band.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_getnodata(tile) AS nodata FROM rasters;
+------+
|nodata|
+------+
|[0.0] |
+------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_getnodata("tile").alias("nodata")).first()
+--------+
|nodata |
+--------+
|[0.0] |
+--------+
rst_getsubdataset
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_getsubdataset(tile, subset_name) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_getsubdataset(tile, subset_name) | TILE |
| Python | rasterx.functions.rst_getsubdataset(tile, subset_name) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | A tile whose raster is a container with subdatasets, such as a NetCDF file. | |
subset_name | STRING | STRING | The name of the subdataset (the last part of its GDAL name, such as 'prAdjust'). A name that matches none raises. |
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|subdataset |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(the extracted prAdjust subdataset as a tile — 720x360, 31 bands)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("netcdf_rasters")
result = df.select(
rx.rst_getsubdataset("tile", f.lit("prAdjust")).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(light tier returns a materialized v2 Tile; extracted prAdjust subdataset — 720 pixels wide, 31 bands, 360 rows)
rst_height
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_height(tile) | INT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_height(tile) | INT |
| Python | rasterx.functions.rst_height(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Height in pixels.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_height(tile) AS height FROM rasters;
+------+
|height|
+------+
|161 |
+------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_height("tile").alias("height")).first()
+------+
|height|
+------+
|161 |
+------+
rst_max
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_max(tile) | array<double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_max(tile) | array<double> |
| Python | rasterx.functions.rst_max(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
- SQL
- Python
-- 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;
+---------------------+
|band_max |
+---------------------+
|[119.0, 197.0, 148.0]|
+---------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_max("tile").alias("band_max")).first()
+---------------------+
|band_max |
+---------------------+
|[119.0, 197.0, 148.0]|
+---------------------+
rst_median
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_median(tile) | array<double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_median(tile) | array<double> |
| Python | rasterx.functions.rst_median(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
- SQL
- Python
-- 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;
+--------------------+
|band_median |
+--------------------+
|[85.0, 157.5, 111.5]|
+--------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_median("tile").alias("band_median")).first()
+---------------------+
|band_median |
+---------------------+
|[85.0, 157.5, 111.5] |
+---------------------+
rst_memsize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_memsize(tile) | BIGINT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_memsize(tile) | BIGINT |
| Python | rasterx.functions.rst_memsize(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio. Returns the serialized raster size in bytes.
In-memory size in bytes.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_memsize(tile) AS memsize FROM rasters;
+-------+
|memsize|
+-------+
|71749 |
+-------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_memsize("tile").alias("memsize")).first()
+-------+
|memsize|
+-------+
|71749 |
+-------+
rst_metadata
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_metadata(tile) | map<string,string> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_metadata(tile) | map<string,string> |
| Python | rasterx.functions.rst_metadata(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Metadata map.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_metadata(tile) as metadata FROM rasters;
+--------------------------------------------------+
|metadata |
+--------------------------------------------------+
|{driver -> GTiff, crs -> EPSG:32618, count -> 1,..|
+--------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_metadata("tile").alias("metadata")).first()
+--------------------------------------------------+
|metadata |
+--------------------------------------------------+
|{driver -> GTiff, crs -> EPSG:32618, count -> 1,..|
+--------------------------------------------------+
rst_min
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_min(tile) | array<double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_min(tile) | array<double> |
| Python | rasterx.functions.rst_min(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
- SQL
- Python
-- 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;
+-------------------+
|band_min |
+-------------------+
|[50.0, 102.0, 82.0]|
+-------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_min("tile").alias("band_min")).first()
+-------------------+
|band_min |
+-------------------+
|[50.0, 102.0, 82.0]|
+-------------------+
rst_numbands
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_numbands(tile) | INT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_numbands(tile) | INT |
| Python | rasterx.functions.rst_numbands(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Number of bands.
Examples use the multiband fixture (rgb_nir_small.tif, 3 bands: red, NIR, green).
- SQL
- Python
-- 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;
+---------+
|num_bands|
+---------+
|3 |
+---------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_numbands("tile").alias("num_bands")).first()
+---------+
|num_bands|
+---------+
|3 |
+---------+
rst_pixelcount
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_pixelcount(tile) | array<bigint> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_pixelcount(tile) | array<bigint> |
| Python | rasterx.functions.rst_pixelcount(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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].
- SQL
- Python
-- 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;
+------------+
|pixel_count |
+------------+
|[64, 64, 64]|
+------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_pixelcount("tile").alias("pixel_count")).first()
+------------+
|pixel_count |
+------------+
|[64, 64, 64]|
+------------+
rst_pixelheight
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_pixelheight(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_pixelheight(tile) | DOUBLE |
| Python | rasterx.functions.rst_pixelheight(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Pixel height in ground units.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_pixelheight(tile) AS pixel_height FROM rasters;
+------------+
|pixel_height|
+------------+
|10.0 |
+------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_pixelheight("tile").alias("pixel_height")).first()
+------------+
|pixel_height|
+------------+
|10.0 |
+------------+
rst_pixelwidth
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_pixelwidth(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_pixelwidth(tile) | DOUBLE |
| Python | rasterx.functions.rst_pixelwidth(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Pixel width in ground units.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_pixelwidth(tile) AS pixel_width FROM rasters;
+-----------+
|pixel_width|
+-----------+
|10.0 |
+-----------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_pixelwidth("tile").alias("pixel_width")).first()
+-----------+
|pixel_width|
+-----------+
|10.0 |
+-----------+
rst_rotation
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_rotation(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_rotation(tile) | DOUBLE |
| Python | rasterx.functions.rst_rotation(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Rotation in radians.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_rotation(tile) AS rotation FROM rasters;
+--------+
|rotation|
+--------+
|0.0 |
+--------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_rotation("tile").alias("rotation")).first()
+--------+
|rotation|
+--------+
|0.0 |
+--------+
rst_scalex
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_scalex(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_scalex(tile) | DOUBLE |
| Python | rasterx.functions.rst_scalex(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Scale (pixel size) in X/Y.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_scalex(tile) AS scale_x FROM rasters;
+-------+
|scale_x|
+-------+
|10.0 |
+-------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_scalex("tile").alias("scale_x")).first()
+-------+
|scale_x|
+-------+
|10.0 |
+-------+
rst_scaley
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_scaley(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_scaley(tile) | DOUBLE |
| Python | rasterx.functions.rst_scaley(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Scale (pixel size) in X/Y.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_scaley(tile) AS scale_y FROM rasters;
+-------+
|scale_y|
+-------+
|-10.0 |
+-------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_scaley("tile").alias("scale_y")).first()
+-------+
|scale_y|
+-------+
|-10.0 |
+-------+
rst_skewx
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_skewx(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_skewx(tile) | DOUBLE |
| Python | rasterx.functions.rst_skewx(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Skew in X/Y.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_skewx(tile) AS skew_x FROM rasters;
+------+
|skew_x|
+------+
|0.0 |
+------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_skewx("tile").alias("skew_x")).first()
+------+
|skew_x|
+------+
|0.0 |
+------+
rst_skewy
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_skewy(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_skewy(tile) | DOUBLE |
| Python | rasterx.functions.rst_skewy(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Skew in X/Y.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_skewy(tile) AS skew_y FROM rasters;
+------+
|skew_y|
+------+
|0.0 |
+------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_skewy("tile").alias("skew_y")).first()
+------+
|skew_y|
+------+
|0.0 |
+------+
rst_srid
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_srid(tile) | INT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_srid(tile) | INT |
| Python | rasterx.functions.rst_srid(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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- SQL
- Python
SELECT gbx_rst_srid(tile) AS srid FROM rasters;
+-----+
|srid |
+-----+
|32618|
+-----+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_srid("tile").alias("srid")).first()
+-----+
|srid |
+-----+
|32618|
+-----+
rst_subdatasets
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_subdatasets(tile) | map<string,string> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_subdatasets(tile) | map<string,string> |
| Python | rasterx.functions.rst_subdatasets(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
- SQL
- Python
-- netcdf_rasters view is from the CMIP5 NetCDF fixture (has time_bnds and prAdjust)
SELECT gbx_rst_subdatasets(tile) AS subdatasets FROM netcdf_rasters;
+------------------------------------------------------+
|subdatasets |
+------------------------------------------------------+
|{SUBDATASET_1_NAME -> ..., SUBDATASET_1_DESC -> [31...|
+------------------------------------------------------+
(map with SUBDATASET_1_NAME/DESC for time_bnds and SUBDATASET_2_NAME/DESC for prAdjust)
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("netcdf_rasters")
result = df.select(rx.rst_subdatasets("tile").alias("subdatasets")).first()
+------------------------------------------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_stats_partial(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The 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.
- SQL
- Python
-- 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);
+----+-----+--------+------------------+-----+-----+
|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)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
states = df.select(rx.rst_stats_partial("tile").alias("stats")).select(
f.inline("stats")
)
return states.select(
"band",
"count",
(f.col("sum") / f.col("count")).alias("avg"),
f.sqrt(f.col("m2") / f.col("count")).alias("stddev"),
"min",
"max",
).collect()
+----+-----+--------+------------------+-----+-----+
|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|
+----+-----+--------+------------------+-----+-----+
rst_summary
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_summary(tile) | STRING |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_summary(tile) | STRING |
| Python | rasterx.functions.rst_summary(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
The JSON is GDAL's, not the earlier GeoBrix shape. A query that reads its keys must change.
bands[].minandbands[].maxare nowbands[].minimumandbands[].maximum.coordinateSystem.epsgandcoordinateSystem.crsare nowcoordinateSystem.wkt. The EPSG code isstac."proj:epsg".- GDAL rounds
minimum,maximum,meanandstdDevto three decimals. The band'smetadataholdsSTATISTICS_*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
bandslist. A virtual tile is read into a GeoTIFF of its window first, so it reportsGTiff. 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.
- SQL
- Python
-- 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);
+------+---------+----------+
|driver|band1_max|band1_mean|
+------+---------+----------+
|GTiff |119.0 |83.594 |
+------+---------+----------+
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
summary = df.select(rx.rst_summary("tile").alias("summary"))
result = summary.select(
f.get_json_object("summary", "$.driverShortName").alias("driver"),
f.get_json_object("summary", "$.bands[0].maximum").alias("band1_max"),
f.get_json_object("summary", "$.bands[0].mean").alias("band1_mean"),
).first()
+------+---------+----------+
|driver|band1_max|band1_mean|
+------+---------+----------+
|GTiff |119.0 |83.594 |
+------+---------+----------+
rst_type
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_type(tile) | array<string> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_type(tile) | array<string> |
| Python | rasterx.functions.rst_type(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Data type per band.
Examples use the multiband fixture (rgb_nir_small.tif, 3 bands, UInt16).
- SQL
- Python
-- 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;
+------------------------+
|band_types |
+------------------------+
|[UInt16, UInt16, UInt16]|
+------------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_type("tile").alias("band_types")).first()
+-----------------------------+
|band_types |
+-----------------------------+
|[UInt16, UInt16, UInt16] |
+-----------------------------+
rst_upperleftx
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_upperleftx(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_upperleftx(tile) | DOUBLE |
| Python | rasterx.functions.rst_upperleftx(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Upper-left corner coordinates.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_upperleftx(tile) AS upper_left_x FROM rasters;
+------------+
|upper_left_x|
+------------+
|2121950.0 |
+------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_upperleftx("tile").alias("upper_left_x")).first()
+------------+
|upper_left_x|
+------------+
|2121950.0 |
+------------+
rst_upperlefty
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_upperlefty(tile) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_upperlefty(tile) | DOUBLE |
| Python | rasterx.functions.rst_upperlefty(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Upper-left corner coordinates.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_upperlefty(tile) AS upper_left_y FROM rasters;
+------------+
|upper_left_y|
+------------+
|-10790470.0 |
+------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_upperlefty("tile").alias("upper_left_y")).first()
+---------------+
|upper_left_y |
+---------------+
|-10790470.0 |
+---------------+
rst_width
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_width(tile) | INT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_width(tile) | INT |
| Python | rasterx.functions.rst_width(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Width in pixels.
Since v0.2.0- SQL
- Python
SELECT gbx_rst_width(tile) AS width FROM rasters;
+-----+
|width|
+-----+
|236 |
+-----+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_width("tile").alias("width")).first()
+-----+
|width|
+-----+
|236 |
+-----+
Aggregator Functions
Combine or merge rasters in group-by (7 total).
rst_bng_rasterize_agg
SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
cellid | STRING | The BNG cell id, for example 'TQ3080'. | |
value | DOUBLE | The 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_srid | INT | Not read: the output is always EPSG:27700. | |
pixel_size | DOUBLE | The pixel size in metres. | |
xmin | DOUBLE | The west edge of the canvas in EPSG:27700 metres. | |
ymin | DOUBLE | The south edge of the canvas in EPSG:27700 metres. | |
xmax | DOUBLE | The east edge of the canvas in EPSG:27700 metres. | |
ymax | DOUBLE | The north edge of the canvas in EPSG:27700 metres. | |
width | INT | The canvas width in pixels. | |
height | INT | The canvas height in pixels. | |
mode | STRING | How the canvas is derived when no extent is given, for example 'centroids'. | |
kring_pad | INT | Cells of padding around the derived canvas. | |
out_crs | STRING | NULL | Must be NULL. Reproject the tile with gbx_rst_transformcrs instead. |
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.
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.
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 BINARYIn 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.
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- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from pyspark.sql import functions as f
from databricks.labs.gbx.manager import register as gbx_register
from databricks.labs.gbx.rasterx import functions as rx
gbx_register(spark, only=["gbx_bng_eastnorthasbng"])
spark.sql("""
CREATE OR REPLACE TEMP VIEW _bng_cells AS
SELECT region,
gbx_bng_eastnorthasbng(e, n, 3) AS cellid,
val AS value
FROM (VALUES
('R1', cast(530000.0 as double), cast(180000.0 as double), cast(1.0 as double)),
('R1', cast(531000.0 as double), cast(181000.0 as double), cast(2.0 as double)),
('R1', cast(529000.0 as double), cast(179000.0 as double), cast(3.0 as double))
) AS t(region, e, n, val)
""")
df = spark.table("_bng_cells")
# A 3 km x 3 km canvas of 1 km pixels over the three cells. out_srid is not
# read (the output is always EPSG:27700); mode applies only when no extent is
# given. The aggregate returns GeoTIFF bytes; rst_fromcontent makes the tile.
burned = df.groupBy("region").agg(
rx.rst_bng_rasterize_agg(
"cellid",
"value",
27700,
1000.0,
529000.0,
179000.0,
532000.0,
182000.0,
3,
3,
"centroids",
0,
).alias("content")
)
result = burned.select(
"region", rx.rst_fromcontent("content", f.lit("GTiff")).alias("tile")
).first()
spark.catalog.dropTempView("_bng_cells")
+------+-----------------------------------------------------------+
|region|tile |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_bng_rasterize_tvf
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_bng_rasterize_tvf(rows, xmin, ymin, xmax, ymax, width, height) | rows |
| Python | rasterx.functions.rst_bng_rasterize_tvf(df, xmin, ymin, xmax, ymax, width, height) | DataFrame |
Rows: key STRING, raster BINARY.
| Parameter | SQL type | Default | Description |
|---|---|---|---|
rows | TABLE | The 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. | |
xmin | DOUBLE | The west edge of the canvas in EPSG:27700 metres. | |
ymin | DOUBLE | The south edge of the canvas in EPSG:27700 metres. | |
xmax | DOUBLE | The east edge of the canvas in EPSG:27700 metres. | |
ymax | DOUBLE | The north edge of the canvas in EPSG:27700 metres. | |
width | INT | The canvas width in pixels. | |
height | INT | The 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.
- SQL
- Python
-- 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
);
+---+---------------+
|key|raster |
+---+---------------+
|a |[B@... (BINARY)|
|b |[B@... (BINARY)|
+---+---------------+
(one GeoTIFF per key, Float64, NoData -9999, EPSG:27700)
from databricks.labs.gbx.rasterx import functions as rx
df = spark.createDataFrame(
[
("a", "TQ3080", 1.0),
("a", "TQ3080", 3.0),
("a", "TQ3180", 2.0),
("b", "TQ3081", 4.0),
],
"key STRING, cellid STRING, value DOUBLE",
)
return rx.rst_bng_rasterize_tvf(
df, 530000.0, 180000.0, 533000.0, 182000.0, 3, 2
).collect()
+---+---------------+
|key|raster |
+---+---------------+
|a |<GeoTIFF bytes>|
|b |<GeoTIFF bytes>|
+---+---------------+
(one GeoTIFF per key, Float64, NoData -9999, EPSG:27700)
rst_bng_rasterize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
cells | array<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_srid | INT | INT | Not read: the output is always EPSG:27700. | |
pixel_size | DOUBLE | DOUBLE | The pixel size in metres. | |
xmin | DOUBLE | DOUBLE | The west edge of the canvas in EPSG:27700 metres. | |
ymin | DOUBLE | DOUBLE | The south edge of the canvas in EPSG:27700 metres. | |
xmax | DOUBLE | DOUBLE | The east edge of the canvas in EPSG:27700 metres. | |
ymax | DOUBLE | DOUBLE | The north edge of the canvas in EPSG:27700 metres. | |
width | INT | INT | The canvas width in pixels. | |
height | INT | INT | The canvas height in pixels. | |
mode | STRING | STRING | How the canvas is derived when no extent is given, for example 'centroids'. | |
kring_pad | INT | INT | Cells of padding around the derived canvas. | |
out_crs | STRING | STRING | NULL | Must 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.
- SQL
- Python
-- 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);
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:27700. Pixels, north row first:
[4.0, -9999, -9999]
[3.0, 2.0, -9999])
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
df = spark.createDataFrame(
[("TQ3080", 1.0), ("TQ3080", 3.0), ("TQ3180", 2.0), ("TQ3081", 4.0)],
"cellid STRING, value DOUBLE",
)
result = df.agg(
rx.rst_bng_rasterize(
f.collect_list(f.struct("cellid", "value")),
27700, 1000.0, 530000.0, 180000.0, 533000.0, 182000.0, 3, 2, "centroids", 0,
).alias("content")
).first()
+---------------+
|content |
+---------------+
|<GeoTIFF bytes>|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:27700. Pixels, north row first:
[4.0, -9999, -9999]
[3.0, 2.0, -9999])
rst_combineavg_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combineavg_agg(tile) | BINARY |
| Python | rasterx.functions.rst_combineavg_agg(tile) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
tile | TILE | The tile of one member. An error tile or a tile that cannot be read is skipped. |
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).
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.
- SQL
- Python
-- Group by region and average
SELECT
region,
gbx_rst_combineavg_agg(tile) as regional_average
FROM rasters
GROUP BY region;
# 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) |
+------+----------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
df = _get_multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rasterx_api.rst_combineavg_agg("tile").alias("avg_tile"))
.first()
)
+------+-----------------------------------------------------------+
|region|avg_tile |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_derivedband_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_derivedband_agg(tile, python_func, func_name) | BINARY |
| Python | rasterx.functions.rst_derivedband_agg(tile, python_func, func_name) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
tile | TILE | One input band per tile. | |
python_func | STRING | The source of a GDAL VRT pixel function. It runs in the process: pass only trusted code. | |
func_name | STRING | The name of the function in python_func. |
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.
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).
- SQL
- Python
SELECT region, gbx_rst_derivedband_agg(tile, 'def f(a): return a', 'f') as result FROM rasters GROUP BY region;
# 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)|
+------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
pyfunc = (
"def fn(in_ar, out_ar, xoff, yoff, xsize, ysize, "
"raster_xsize, raster_ysize, buf_radius, gt, **kwargs):\n"
" out_ar[:] = in_ar[0]\n"
)
df = _get_multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rasterx_api.rst_derivedband_agg("tile", pyfunc, "fn").alias("derived"))
.first()
)
+------+-----------------------------------------------------------+
|region|derived |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_dtmfromgeoms_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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 |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
point | BINARY or STRING | A point with a Z coordinate: WKB, EWKB, WKT or EWKT. An empty one is skipped. | |
breaklines | ARRAY<BINARY> or ARRAY<STRING> | Breaklines, the same for the whole group. Accepted but not enforced. | |
merge_tolerance | DOUBLE | Accepted, not applied. | |
snap_tolerance | DOUBLE | Accepted, not applied. | |
xmin | DOUBLE | The west edge of the output. | |
ymin | DOUBLE | The south edge. | |
xmax | DOUBLE | The east edge. | |
ymax | DOUBLE | The north edge. | |
width_px | INT | The output width in pixels. | |
height_px | INT | The output height in pixels. | |
out_srid | INT | NULL | The EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS. |
no_data | DOUBLE | -9999.0 | The NoData value. |
out_crs | STRING | NULL | The output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises. |
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.
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.
- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
from pyspark.sql import functions as f
from pyspark.sql.types import (
BinaryType,
StringType,
StructField,
StructType,
)
def _wkb_point_z(x, y, z):
"""Build a WKB POINT Z (ISO wkbType 1001) as bytes."""
import struct
return struct.pack("<bIddd", 1, 1001, x, y, z)
rows = [
(_wkb_point_z(0.1, 0.1, 100.0), "R1"),
(_wkb_point_z(0.9, 0.1, 200.0), "R1"),
(_wkb_point_z(0.1, 0.9, 150.0), "R1"),
(_wkb_point_z(0.9, 0.9, 250.0), "R1"),
]
schema = StructType(
[
StructField("pt", BinaryType()),
StructField("region", StringType()),
]
)
df = spark.createDataFrame(rows, schema)
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_dtmfromgeoms_agg(
"pt",
f.lit(None).cast("array<binary>"),
f.lit(0.0),
f.lit(0.0),
f.lit(0.0),
f.lit(0.0),
f.lit(1.0),
f.lit(1.0),
f.lit(8),
f.lit(8),
f.lit(4326),
).alias("dtm")
)
.first()
)
+------+-----------------------------------------------------------+
|region|dtm |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_frombands_agg(tile, band_index) | BINARY |
| Python | rasterx.functions.rst_frombands_agg(tile, band_index) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
tile | TILE | A single-band tile. An error tile or a tile that cannot be read is skipped. | |
band_index | INT | The band the tile becomes, counted up from 1. A NULL index skips the row. |
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.
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.
- SQL
- Python
-- 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;
# 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)|
+--------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
df = _get_multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rasterx_api.rst_frombands_agg("tile", "band_index").alias("stacked"))
.first()
)
+------+-----------------------------------------------------------+
|region|stacked |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_gridfrompoints_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_gridfrompoints_agg(point, value, xmin, ymin, xmax, ymax, width_px, height_px, [out_srid], [power], [max_pts], [out_crs]) | BINARY |
| Python | rasterx.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 |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
point | BINARY or STRING | The point: WKB, EWKB, WKT or EWKT. A row with a NULL value or an empty point is dropped. | |
value | DOUBLE | The point's value. | |
xmin | DOUBLE | The west edge of the output. | |
ymin | DOUBLE | The south edge. | |
xmax | DOUBLE | The east edge. | |
ymax | DOUBLE | The north edge. | |
width_px | INT | The output width in pixels. | |
height_px | INT | The output height in pixels. | |
out_srid | INT | NULL | The EPSG or ESRI code of the output CRS. NULL leaves the output without a CRS. |
power | DOUBLE | 2.0 | The inverse-distance exponent, above 0. |
max_pts | INT | 12 | The number of nearest points used per pixel, above 0. |
out_crs | STRING | NULL | The output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises. |
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.
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.
- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
from pyspark.sql import functions as f
from pyspark.sql.types import (
BinaryType,
DoubleType,
StringType,
StructField,
StructType,
)
def _wkb_point(x, y):
"""Build a WKB POINT from (x, y) as bytes."""
import struct
return struct.pack("<bIdd", 1, 1, x, y)
rows = [
(_wkb_point(0.1, 0.1), 10.0, "R1"),
(_wkb_point(0.9, 0.1), 20.0, "R1"),
(_wkb_point(0.1, 0.9), 30.0, "R1"),
(_wkb_point(0.9, 0.9), 40.0, "R1"),
]
schema = StructType(
[
StructField("pt", BinaryType()),
StructField("val", DoubleType()),
StructField("region", StringType()),
]
)
df = spark.createDataFrame(rows, schema)
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_gridfrompoints_agg(
"pt",
"val",
f.lit(0.0),
f.lit(0.0),
f.lit(1.0),
f.lit(1.0),
f.lit(8),
f.lit(8),
f.lit(4326),
).alias("idw")
)
.first()
)
+------+-----------------------------------------------------------+
|region|idw |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_h3_rasterize_agg
SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
cellid | BIGINT | The H3 cell id. | |
value | DOUBLE | The 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_srid | INT | The EPSG code of the output CRS. | |
pixel_size | DOUBLE | The pixel size in CRS units; NULL takes it from the cells' resolution. | |
xmin | DOUBLE | The west edge of the canvas; NULL derives the canvas from the cells. | |
ymin | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | The east edge of the canvas. | |
ymax | DOUBLE | The north edge of the canvas. | |
width | INT | The canvas width in pixels. | |
height | INT | The canvas height in pixels. | |
mode | STRING | How the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'. | |
kring_pad | INT | Rings of padding around the derived canvas. | |
out_crs | STRING | NULL | The output CRS as EPSG:<n>. Set out_srid or out_crs, not both: setting both raises. |
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.
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.
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.
out_crs parameterThe 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.
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- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
import h3
from pyspark.sql import functions as f
res = 9
cell_strs = [
h3.latlng_to_cell(0.01, 0.01, res),
h3.latlng_to_cell(0.02, 0.01, res),
h3.latlng_to_cell(0.01, 0.02, res),
]
cells = [h3.str_to_int(c) for c in cell_strs]
rows = [
(int(cells[0]), 1.0, "R1"),
(int(cells[1]), 2.0, "R1"),
(int(cells[2]), 3.0, "R1"),
]
from pyspark.sql.types import (
DoubleType,
LongType,
StringType,
StructField,
StructType,
)
schema = StructType(
[
StructField("cellid", LongType()),
StructField("value", DoubleType()),
StructField("region", StringType()),
]
)
df = spark.createDataFrame(rows, schema)
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_h3_rasterize_agg(
"cellid",
"value",
f.lit(4326),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
"centroids",
f.lit(1),
).alias("tile")
)
.first()
)
+------+-----------------------------------------------------------+
|region|tile |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_h3_rasterize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
cells | array<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_srid | INT | INT | The EPSG code of the output CRS. | |
pixel_size | DOUBLE | DOUBLE | The pixel size in CRS units; NULL takes it from the cells' resolution. | |
xmin | DOUBLE | DOUBLE | The west edge of the canvas; NULL derives the canvas from the cells. | |
ymin | DOUBLE | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | DOUBLE | The east edge of the canvas. | |
ymax | DOUBLE | DOUBLE | The north edge of the canvas. | |
width | INT | INT | The canvas width in pixels. | |
height | INT | INT | The canvas height in pixels. | |
mode | STRING | STRING | How the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'. | |
kring_pad | INT | INT | Rings of padding around the derived canvas. | |
out_crs | STRING | STRING | NULL | The 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.
- SQL
- Python
-- 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);
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:4326. Pixels, north row first:
[2.0, -9999]
[1.0, 3.0 ])
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
df = spark.createDataFrame(
[
(619056821909585919, 1.0),
(619056822407921663, 2.0),
(619056559519170559, 3.0),
],
"cellid BIGINT, value DOUBLE",
)
result = df.agg(
rx.rst_h3_rasterize(
f.collect_list(f.struct("cellid", "value")),
4326, 0.01, 0.005, 0.005, 0.025, 0.025, 2, 2, "centroids", 0,
).alias("content")
).first()
+---------------+
|content |
+---------------+
|<GeoTIFF bytes>|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:4326. Pixels, north row first:
[2.0, -9999]
[1.0, 3.0 ])
rst_merge_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_merge_agg(tile) | BINARY |
| Python | rasterx.functions.rst_merge_agg(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
tile | TILE | The tiles of the group. |
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 BINARYIn 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.
- SQL
- Python
SELECT
scene_id,
gbx_rst_merge_agg(tile) as merged_scene
FROM satellite_tiles
GROUP BY scene_id;
# 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)|
+--------+---------------+
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
df = _get_multi_band_tiles_df(spark)
# The aggregate returns the mosaic's GeoTIFF bytes (BINARY) on every surface;
# rst_fromcontent turns them back into a tile.
merged = df.groupBy("region").agg(rx.rst_merge_agg("tile").alias("content"))
result = merged.select(
"region", rx.rst_fromcontent("content", f.lit("GTiff")).alias("mosaic")
).first()
+------+-----------------------------------------------------------+
|region|mosaic |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_merge_tvf
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_merge_tvf(rows) | rows |
| Python | rasterx.functions.rst_merge_tvf(df) | DataFrame |
Rows: key STRING, raster BINARY.
| Parameter | SQL type | Default | Description |
|---|---|---|---|
rows | TABLE | The 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).
- SQL
- Python
-- 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));
+---+---------------+
|key|raster |
+---+---------------+
|a |[B@... (BINARY)|
+---+---------------+
(one GeoTIFF mosaic per key: a 4 x 2 raster, [1, 1, 2, 2] in each row)
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
def tile(wkt, value, xmin, xmax):
return rx.rst_rasterize(
f.lit(wkt), f.lit(value), f.lit(xmin), f.lit(0.0), f.lit(xmax), f.lit(2.0),
f.lit(2), f.lit(2), f.lit(4326),
)
one = spark.range(1)
tiles = one.select(
f.lit("a").alias("key"),
tile("POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))", 1.0, 0.0, 2.0).alias("tile"),
).union(
one.select(
f.lit("a").alias("key"),
tile("POLYGON((2 0, 4 0, 4 2, 2 2, 2 0))", 2.0, 2.0, 4.0).alias("tile"),
)
)
+---+---------------+
|key|raster |
+---+---------------+
|a |<GeoTIFF bytes>|
+---+---------------+
(one GeoTIFF mosaic per key: a 4 x 2 raster, [1, 1, 2, 2] in each row)
rst_quadbin_rasterize_agg
SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rasterize_agg(cellid, value, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
cellid | BIGINT | The quadbin cell id. | |
value | DOUBLE | The 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_srid | INT | The EPSG code of the output CRS. | |
pixel_size | DOUBLE | The pixel size in CRS units; NULL takes it from the cells' resolution. | |
xmin | DOUBLE | The west edge of the canvas; NULL derives the canvas from the cells. | |
ymin | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | The east edge of the canvas. | |
ymax | DOUBLE | The north edge of the canvas. | |
width | INT | The canvas width in pixels. | |
height | INT | The canvas height in pixels. | |
mode | STRING | How the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'. | |
kring_pad | INT | Rings of padding around the derived canvas. | |
out_crs | STRING | NULL | The output CRS as EPSG:<n>. Set out_srid or out_crs, not both: setting both raises. |
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.
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.
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.
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.
out_crs parameterThe 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- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
from databricks.labs.gbx.manager import register as gbx_register
from pyspark.sql import functions as f
gbx_register(spark, only=["gbx_quadbin_pointascell"])
spark.sql("""
CREATE OR REPLACE TEMP VIEW _qb_cells AS
SELECT region,
gbx_quadbin_pointascell(cast(lon as double), cast(lat as double), 12) AS cellid,
cast(val as double) AS value
FROM (VALUES
('R1', -0.10, 51.50, 1.0),
('R1', -0.11, 51.51, 2.0),
('R1', -0.09, 51.49, 3.0)
) AS t(region, lon, lat, val)
""")
df = spark.table("_qb_cells")
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_quadbin_rasterize_agg(
"cellid",
"value",
f.lit(4326),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
"centroids",
f.lit(1),
).alias("tile")
)
.first()
)
spark.catalog.dropTempView("_qb_cells")
+------+-----------------------------------------------------------+
|region|tile |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
rst_quadbin_rasterize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rasterize(cells, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad, out_crs=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
cells | array<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_srid | INT | INT | The EPSG code of the output CRS. | |
pixel_size | DOUBLE | DOUBLE | The pixel size in CRS units; NULL takes it from the cells' resolution. | |
xmin | DOUBLE | DOUBLE | The west edge of the canvas; NULL derives the canvas from the cells. | |
ymin | DOUBLE | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | DOUBLE | The east edge of the canvas. | |
ymax | DOUBLE | DOUBLE | The north edge of the canvas. | |
width | INT | INT | The canvas width in pixels. | |
height | INT | INT | The canvas height in pixels. | |
mode | STRING | STRING | How the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'. | |
kring_pad | INT | INT | Rings of padding around the derived canvas. | |
out_crs | STRING | STRING | NULL | The 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.
- SQL
- Python
-- 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)
);
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:4326. Pixels: [1.0, 2.0, 3.0])
from databricks.labs.gbx.gridx.quadbin import functions as qx
from databricks.labs.gbx.manager import register as gbx_register
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
gbx_register(spark, only=["gbx_quadbin_pointascell"])
points = spark.createDataFrame(
[(-0.30, 51.40, 1.0), (-0.10, 51.40, 2.0), (0.10, 51.40, 3.0)],
"lon DOUBLE, lat DOUBLE, value DOUBLE",
)
cells = points.select(
qx.quadbin_pointascell("lon", "lat", 12).alias("cellid"), "value"
)
result = cells.agg(
rx.rst_quadbin_rasterize(
f.collect_list(f.struct("cellid", "value")),
4326, 0.2, -0.4, 51.3, 0.2, 51.5, 3, 1, "centroids", 0,
).alias("content")
).first()
+---------------+
|content |
+---------------+
|<GeoTIFF bytes>|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:4326. Pixels: [1.0, 2.0, 3.0])
rst_custom_rasterize_agg
SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_custom_rasterize_agg(cellid, value, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad) | BINARY |
| Python | rasterx.functions.rst_custom_rasterize_agg(cellid, value, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
cellid | BIGINT | The custom-grid cell id. | |
value | DOUBLE | The 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. | |
grid | 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_srid | INT | The EPSG code of the output CRS. | |
pixel_size | DOUBLE | The pixel size in CRS units; NULL takes it from the cells' resolution. | |
xmin | DOUBLE | The west edge of the canvas; NULL derives the canvas from the cells. | |
ymin | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | The east edge of the canvas. | |
ymax | DOUBLE | The north edge of the canvas. | |
width | INT | The canvas width in pixels. | |
height | INT | The canvas height in pixels. | |
mode | STRING | How the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'. | |
kring_pad | INT | Rings of padding around the derived canvas. |
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.
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.
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.
- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rasterx_api
from pyspark.sql import functions as f
gbx.register(spark)
# Custom grid: 4km BNG London square, root cell 4000m, splits=2 -> res 1 = four 2km cells.
_GRID_SQL = (
"gbx_custom_grid(529000, 533000, 179000, 183000, 2, 4000, 4000, 27700)"
)
# Compute cell IDs by calling gbx_custom_pointascell in a SELECT over a VALUES table
# (UDFs cannot appear in VALUES clauses directly — use SELECT-from-VALUES instead).
spark.sql(f"""
CREATE OR REPLACE TEMP VIEW _custom_rasterize_cells AS
SELECT region,
gbx_custom_pointascell(wkt, {_GRID_SQL}, 1) AS cellid,
val AS value
FROM (VALUES
('R1', 'POINT(530000 180000)', cast(1.0 as double)),
('R1', 'POINT(532000 180000)', cast(2.0 as double)),
('R1', 'POINT(530000 182000)', cast(3.0 as double))
) AS t(region, wkt, val)
""")
df = spark.table("_custom_rasterize_cells")
grid_col = f.call_function(
"gbx_custom_grid",
f.lit(529000), f.lit(533000), f.lit(179000), f.lit(183000),
f.lit(2), f.lit(4000), f.lit(4000), f.lit(27700),
)
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_custom_rasterize_agg(
"cellid",
"value",
grid_col,
f.lit(27700),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
f.lit(None),
"centroids",
f.lit(1),
).alias("tile")
)
.first()
)
spark.catalog.dropTempView("_custom_rasterize_cells")
+------+-----------------------------------------------------------+
|region|tile |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one v2 Tile per group — raster bytes populated, path null; three 2km custom-grid cells burned)
rst_custom_rasterize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rasterize(cells, grid, out_srid, pixel_size, xmin, ymin, xmax, ymax, width, height, mode, kring_pad) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
cells | array<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. | |
grid | 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> | 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_srid | INT | INT | The EPSG code of the output CRS. | |
pixel_size | DOUBLE | DOUBLE | The pixel size in CRS units; NULL takes it from the cells' resolution. | |
xmin | DOUBLE | DOUBLE | The west edge of the canvas; NULL derives the canvas from the cells. | |
ymin | DOUBLE | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | DOUBLE | The east edge of the canvas. | |
ymax | DOUBLE | DOUBLE | The north edge of the canvas. | |
width | INT | INT | The canvas width in pixels. | |
height | INT | INT | The canvas height in pixels. | |
mode | STRING | STRING | How the canvas is derived when no extent is given: 'centroids' or 'spatial_envelope'. | |
kring_pad | INT | INT | Rings 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.
- SQL
- Python
-- 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)
);
+---------------+
|content |
+---------------+
|[B@... (BINARY)|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:27700. Pixels, north row first:
[3.0, -9999]
[1.0, 2.0 ])
from databricks.labs.gbx.gridx.custom import functions as cx
from databricks.labs.gbx.manager import register as gbx_register
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
gbx_register(spark, only=["gbx_custom_grid", "gbx_custom_pointascell"])
grid = cx.custom_grid(*_CUSTOM_GRID_ARGS)
points = spark.createDataFrame(
[
("POINT(530000 180000)", 1.0),
("POINT(532000 180000)", 2.0),
("POINT(530000 182000)", 3.0),
],
"wkt STRING, value DOUBLE",
)
cells = points.select(
cx.custom_pointascell("wkt", grid, 1).alias("cellid"), "value"
)
result = cells.agg(
rx.rst_custom_rasterize(
f.collect_list(f.struct("cellid", "value")),
grid,
27700, 2000.0, 529000.0, 179000.0, 533000.0, 183000.0, 2, 2, "centroids", 0,
).alias("content")
).first()
+---------------+
|content |
+---------------+
|<GeoTIFF bytes>|
+---------------+
(GeoTIFF bytes, Float64, NoData -9999, EPSG:27700. Pixels, north row first:
[3.0, -9999]
[1.0, 2.0 ])
rst_rasterize_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_rasterize_agg(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid) | BINARY |
| Python | rasterx.functions.rst_rasterize_agg(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
geom | BINARY or STRING | The feature geometry: WKB, EWKB, WKT or EWKT. A NULL or unparseable one is skipped. | |
value | DOUBLE | The value burned where the geometry covers a pixel centre. A NULL value skips the row. | |
xmin | DOUBLE | The west edge of the output. | |
ymin | DOUBLE | The south edge. | |
xmax | DOUBLE | The east edge. | |
ymax | DOUBLE | The north edge. | |
width_px | INT | The output width in pixels. | |
height_px | INT | The output height in pixels. | |
out_srid | INT | The EPSG code of the output CRS. |
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).
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.
- SQL
- Python
-- 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;
# 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)|
+---------+---------------+
from databricks.labs.gbx.rasterx import functions as rasterx_api
from pyspark.sql import functions as f
from pyspark.sql.types import (
BinaryType,
DoubleType,
StringType,
StructField,
StructType,
)
# WKB POLYGON((0 0, 4 0, 4 4, 0 4, 0 0)) in EPSG:4326
poly = bytes.fromhex(
"0103000000010000000500000000000000000000000000000000000000"
"0000000000001040000000000000000000000000000010400000000000001040"
"000000000000000000000000000010400000000000000000"
"0000000000000000"
)
rows = [(poly, 1.0, "R1"), (poly, 2.0, "R1"), (poly, 3.0, "R1")]
schema = StructType(
[
StructField("geom", BinaryType()),
StructField("value", DoubleType()),
StructField("region", StringType()),
]
)
df = spark.createDataFrame(rows, schema)
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_rasterize_agg(
"geom",
"value",
f.lit(0.0),
f.lit(0.0),
f.lit(4.0),
f.lit(4.0),
f.lit(8),
f.lit(8),
f.lit(4326),
).alias("burned")
)
.first()
)
+------+-----------------------------------------------------------+
|region|burned |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(one GeoTIFF per group, returned as BINARY)
Constructor Functions
Create or load rasters from path, binary content, or bands (4 total).
rst_dtmfromgeoms
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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 |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
points_array | ARRAY<BINARY> or ARRAY<STRING> | ARRAY<GEOMETRY> | The points, each with a Z value: WKB, EWKB, WKT or EWKT, as an array. | |
breaklines_array | ARRAY<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_tolerance | DOUBLE | DOUBLE | Accepted for signature compatibility; not applied. | |
snap_tolerance | DOUBLE | DOUBLE | Accepted for signature compatibility; not applied. | |
xmin | DOUBLE | DOUBLE | The west edge of the output in the output CRS. | |
ymin | DOUBLE | DOUBLE | The south edge of the output. | |
xmax | DOUBLE | DOUBLE | The east edge of the output, above xmin. | |
ymax | DOUBLE | DOUBLE | The north edge of the output, above ymin. | |
width_px | INT | INT | The output width in pixels, above 0. | |
height_px | INT | INT | The output height in pixels, above 0. | |
out_srid | INT | INT | NULL | The 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_data | DOUBLE | DOUBLE | -9999.0 | The value of a pixel outside the points' hull. |
out_crs | STRING | STRING | NULL | The output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises. |
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.
out_crs parameterThe 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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|dtm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from pyspark.sql.types import StructType, StructField, ArrayType, BinaryType
gbx.register(spark)
# Create a synthetic survey point DataFrame with 4 points inset from the grid
# edges (Delaunay needs the hull to cover interior cells).
# POINT Z geometries: (100,100,50), (900,100,80), (900,900,120), (100,900,60)
# Using explicit schema to avoid type inference errors
survey_data = [
(
[
bytes.fromhex(
"0101000080000000000000594000000000000059400000000000004940"
),
bytes.fromhex(
"01010000800000000000208c4000000000000059400000000000005440"
),
bytes.fromhex(
"01010000800000000000208c400000000000208c400000000000005e40"
),
bytes.fromhex(
"010100008000000000000059400000000000208c400000000000004e40"
),
],
[],
)
]
schema = StructType(
[
StructField("points_wkb_array", ArrayType(BinaryType()), True),
StructField("breaklines_wkb_array", ArrayType(BinaryType()), True),
]
)
df = spark.createDataFrame(survey_data, schema=schema)
result = df.select(
rx_api.rst_dtmfromgeoms(
f.col("points_wkb_array"),
f.col("breaklines_wkb_array"),
f.lit(0.0),
f.lit(0.0),
f.lit(0.0),
f.lit(0.0),
f.lit(1000.0),
f.lit(1000.0),
f.lit(100),
f.lit(100),
f.lit(32618),
).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(TIN-interpolated DTM over specified extent and pixel count)
rst_frombands
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_frombands(bands) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_frombands(bands) | TILE |
| Python | rasterx.functions.rst_frombands(bands, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
bands | ARRAY<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. |
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.
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.
- SQL
- Python
SELECT
gbx_rst_frombands(array(band1, band2, band3)) as multi_band
FROM separated_bands;
+-----------------------------------------------------------+
|multi_band |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
# Build an array of per-band tiles (band 1, band 2, band 3) then stack
with_bands = df.select(
f.array(
rx_api.rst_band("tile", f.lit(1)),
rx_api.rst_band("tile", f.lit(2)),
rx_api.rst_band("tile", f.lit(3)),
).alias("bands")
)
result = with_bands.select(rx_api.rst_frombands("bands").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(3 per-band tiles stacked back into a 3-band tile; light tier returns a materialized v2 Tile)
rst_fromcontent
SQLUnity Catalog SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_fromcontent(content, driver) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_fromcontent(content, driver) | TILE |
| Python | rasterx.functions.rst_fromcontent(content, driver) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
content | BINARY | BINARY | The raster file's bytes, for example the content column of the binaryFile reader. | |
driver | STRING | STRING | The 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. |
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.
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.
- SQL
- Python
-- Load from binary table
SELECT
path,
gbx_rst_fromcontent(content, 'GTiff') as tile
FROM binary_raster_table;
+----+-----------------------------------------------------------+
|path|tile |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+
from ._fixtures import single_band_path
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
path = str(single_band_path())
binary_df = spark.read.format("binaryFile").load(path)
tile_df = binary_df.select(
rx.rst_fromcontent(f.col("content"), f.lit("GTiff")).alias("tile")
)
result = tile_df.select(rx.rst_format("tile").alias("format")).first()
+------+
|format|
+------+
|GTiff |
+------+
(format of the tile loaded from binary content via binaryFile reader)
rst_fromfile
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_fromfile(path, driver=None, geom=None, clip_crs=None, resolution=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
path | STRING or FILE | FILE | The 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. | |
driver | STRING | STRING | '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. |
geom | BINARY or STRING or GEOMETRY | GEOMETRY | NULL | An optional polygon to clip to, as WKB, EWKB, WKT or EWKT, or a GEOMETRY. Only the blocks the polygon covers are read. |
clip_crs | STRING | STRING | NULL | The 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. |
resolution | DOUBLE | DOUBLE | NULL | An 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
geomclips to a polygon. Pass aGEOMETRY, or WKB, EWKB, WKT or EWKT, in a session and on Unity Catalog alike, so one SQL text runs in both. Ageomthat misses the raster gives NULL.- An SRID in the geometry wins over
clip_crs. Ageomwithout an SRID takesclip_crs, or the raster's CRS whenclip_crsis NULL. resolutionis 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 withCAST_TO_FILE_TYPE.FROM_FILE. - Pass a
GEOMETRY(4326)column directly asgeom. 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:.
| Refused | Fix |
|---|---|
| A window over 64 MiB decoded | Pass a coarser resolution or a smaller geom. |
| A striped GeoTIFF | Write the file as a COG with cog_gbx. |
| A file that is not a TIFF | Run the function in a notebook or job session. Or read the bytes with read_files and call gbx_rst_fromcontent. |
| A header over 4 MiB | Write smaller COGs with cog_gbx, with a smaller raster per file. |
| A block table that names bytes outside the file | Write the file again as a COG with cog_gbx. |
| A fetch over 256 MiB | Pass 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.
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 capReading 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.
- SQL
- Python
-- 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;
# 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 |
+----+-----+------+
from databricks.labs import gbx
from ._fixtures import single_band_path
from databricks.labs.gbx.rasterx import functions as rx_api
gbx.register(spark)
path = str(single_band_path())
path_df = spark.createDataFrame([(path,)], ["path"])
# Default — a VIRTUAL v2 tile (same struct as always, just bytes-free):
+------------------------------------------------------------+
|tile |
+------------------------------------------------------------+
|{0, null, /Volumes/..., {0, 0, 236, 161}, ..., null, {...}} |
+------------------------------------------------------------+
(raster is null → bytes-free; path + whole-file window carry the reference)
# rst_fromfile("path", materialize=True) instead returns a MATERIALIZED v2 tile:
# {0, <raster bytes>, null, null, ..., {driver -> GTiff, ...}} (raster set)
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.
rst_fromcontentIf 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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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 |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
points_array | ARRAY<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_array | ARRAY<DOUBLE> | ARRAY<DOUBLE> | The value of each point, in the same order. | |
xmin | DOUBLE | DOUBLE | The west edge of the output in the output CRS. | |
ymin | DOUBLE | DOUBLE | The south edge of the output. | |
xmax | DOUBLE | DOUBLE | The east edge of the output, above xmin. | |
ymax | DOUBLE | DOUBLE | The north edge of the output, above ymin. | |
width_px | INT | INT | The output width in pixels, above 0. | |
height_px | INT | INT | The output height in pixels, above 0. | |
out_srid | INT | INT | NULL | The 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. |
power | DOUBLE | DOUBLE | 2.0 | The inverse-distance exponent, above 0. |
max_pts | INT | INT | 12 | The number of nearest points used per pixel, above 0. |
out_crs | STRING | STRING | NULL | The 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.
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.
out_crs parameterThe 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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|idw |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(IDW-interpolated tile over specified extent)
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from pyspark.sql.types import ArrayType, BinaryType, DoubleType
gbx.register(spark)
# Create a synthetic point cloud DataFrame with WKB points and values
# Using simple WKB POINT(2.0, 2.0) and POINT(4.0, 4.0)
point_data = [
(
[
bytes.fromhex("010100000000000000000000400000000000000040"),
bytes.fromhex("010100000000000000000008400000000000000840"),
],
[100.0, 110.0],
)
]
df = spark.createDataFrame(
point_data,
[
"points_wkb_array",
"values_array",
],
)
result = df.select(
rx_api.rst_gridfrompoints(
f.col("points_wkb_array"),
f.col("values_array"),
f.lit(0.0),
f.lit(0.0),
f.lit(1000.0),
f.lit(1000.0),
f.lit(256),
f.lit(256),
f.lit(32633),
).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_binpoints(x_array, y_array, z_array, xmin, ymin, xmax, ymax, width_px, height_px, srid, statistic=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
x_array | ARRAY<DOUBLE> | ARRAY<DOUBLE> | The x coordinate of each point. | |
y_array | ARRAY<DOUBLE> | ARRAY<DOUBLE> | The y coordinate of each point, in the same order. | |
z_array | ARRAY<DOUBLE> | ARRAY<DOUBLE> | The value of each point, in the same order. | |
xmin | DOUBLE | DOUBLE | The west edge of the output in the output CRS. | |
ymin | DOUBLE | DOUBLE | The south edge of the output. | |
xmax | DOUBLE | DOUBLE | The east edge of the output, above xmin. | |
ymax | DOUBLE | DOUBLE | The north edge of the output, above ymin. | |
width_px | INT | INT | The output width in pixels, above 0. | |
height_px | INT | INT | The output height in pixels, above 0. | |
srid | INT | INT | The EPSG or ESRI code of the output CRS. | |
statistic | STRING | STRING | '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.
- SQL
- Python
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;
+-----------------------------------------------------------+
|dsm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band Float32 DSM tile: max-z per 100 m cell over the 1 km extent)
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
df = spark.range(1).select(
f.array(f.lit(550100.0), f.lit(550200.0), f.lit(550300.0)).alias("x"),
f.array(f.lit(180100.0), f.lit(180200.0), f.lit(180500.0)).alias("y"),
f.array(f.lit(42.5), f.lit(45.1), f.lit(38.7)).alias("z"),
)
result = df.select(
rx_api.rst_binpoints(
"x", "y", "z",
f.lit(550000.0), f.lit(180000.0),
f.lit(551000.0), f.lit(181000.0),
f.lit(10), f.lit(10),
f.lit(27700),
).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(Float32 10×10 BNG tile; three points binned by max z-value, empty cells = NoData -9999.0; light tier returns a materialized v2 Tile)
rst_binpoints_agg
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_binpoints_agg(x, y, z, xmin, ymin, xmax, ymax, width_px, height_px, srid, [statistic]) | BINARY |
| Python | rasterx.functions.rst_binpoints_agg(x, y, z, xmin, ymin, xmax, ymax, width_px, height_px, srid, statistic=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
x | DOUBLE | The point's x. | |
y | DOUBLE | The point's y. | |
z | DOUBLE | The point's value. | |
xmin | DOUBLE | The west edge of the output. | |
ymin | DOUBLE | The south edge. | |
xmax | DOUBLE | The east edge. | |
ymax | DOUBLE | The north edge. | |
width_px | INT | The output width in pixels. | |
height_px | INT | The output height in pixels. | |
srid | INT | The EPSG code of the output CRS. | |
statistic | STRING | 'max' | 'max', 'min', 'mean', 'median', 'count' or 'percentile:<p>'. |
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.
- SQL
- Python
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;
+-------+--------------+
|tile_id|dsm |
+-------+--------------+
|1 |<raster bytes>|
+-------+--------------+
(BINARY raster bytes — wrap with gbx_rst_fromcontent(dsm, 'GTiff') to rebuild a tile struct)
from databricks.labs.gbx.rasterx import functions as rasterx_api
from pyspark.sql import functions as f
from pyspark.sql.types import (
DoubleType,
StringType,
StructField,
StructType,
)
rows = [
("R1", 550100.0, 180100.0, 42.5),
("R1", 550200.0, 180200.0, 45.1),
("R1", 550300.0, 180500.0, 38.7),
]
schema = StructType(
[
StructField("region", StringType()),
StructField("x", DoubleType()),
StructField("y", DoubleType()),
StructField("z", DoubleType()),
]
)
df = spark.createDataFrame(rows, schema)
result = (
df.groupBy("region")
.agg(
rasterx_api.rst_binpoints_agg(
"x",
"y",
"z",
f.lit(550000.0),
f.lit(180000.0),
f.lit(551000.0),
f.lit(181000.0),
f.lit(10),
f.lit(10),
f.lit(27700),
).alias("tile")
)
.first()
)
+------+-----------------------------------------------------------+
|region|tile |
+------+-----------------------------------------------------------+
|R1 |<GeoTIFF bytes> |
+------+-----------------------------------------------------------+
(Float32 10x10 BNG tile; three scalar points binned by max z-value, empty cells = NoData -9999.0)
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| Surface | Call | Returns |
|---|---|---|
| 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> |
| Python | rasterx.functions.rst_binpoints_partial(x, y, xmin, ymin, xmax, ymax, width_px, height_px) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
x | DOUBLE | DOUBLE | The point's x in the canvas CRS. | |
y | DOUBLE | DOUBLE | The point's y in the canvas CRS. | |
xmin | DOUBLE | DOUBLE | The west edge of the canvas in its CRS. | |
ymin | DOUBLE | DOUBLE | The south edge of the canvas. | |
xmax | DOUBLE | DOUBLE | The east edge of the canvas, above xmin. | |
ymax | DOUBLE | DOUBLE | The north edge of the canvas, above ymin. | |
width_px | INT | INT | The canvas width in pixels, above 0. | |
height_px | INT | INT | The 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.
- SQL
- Python
-- 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);
+----+----+------+
|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>)
from databricks.labs.gbx.rasterx import functions as rx
df = spark.createDataFrame(
[(1.5, 8.5), (0.5, 0.5), (0.0, 10.0), (10.0, 5.0)], "x DOUBLE, y DOUBLE"
)
return df.select(
"x",
"y",
rx.rst_binpoints_partial("x", "y", 0.0, 0.0, 10.0, 10.0, 10, 10).alias("px"),
).collect()
+----+----+------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_binpoints_finalize(cells, xmin, ymin, xmax, ymax, width_px, height_px, srid) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
cells | array<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. | |
xmin | DOUBLE | DOUBLE | The west edge of the output in its CRS. | |
ymin | DOUBLE | DOUBLE | The south edge of the output. | |
xmax | DOUBLE | DOUBLE | The east edge of the output, above xmin. | |
ymax | DOUBLE | DOUBLE | The north edge of the output, above ymin. | |
width_px | INT | INT | The output width in pixels, above 0. | |
height_px | INT | INT | The output height in pixels, above 0. | |
srid | INT | INT | The 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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(a 2 x 1 Float32 tile in EPSG:4326: [5.0, 7.0])
from pyspark.sql import functions as f
from databricks.labs.gbx.rasterx import functions as rx
points = spark.createDataFrame(
[(0.5, 0.5, 1.0), (0.6, 0.4, 5.0), (1.5, 0.5, 7.0)], "x DOUBLE, y DOUBLE, z DOUBLE"
)
binned = points.select(
rx.rst_binpoints_partial("x", "y", 0.0, 0.0, 2.0, 1.0, 2, 1).alias("px"), "z"
).where(f.col("px").isNotNull())
pixels = binned.groupBy("px.col", "px.row").agg(f.max("z").alias("value"))
result = pixels.agg(
rx.rst_binpoints_finalize(
f.collect_list(f.struct("col", "row", "value")),
0.0, 0.0, 2.0, 1.0, 2, 1, 4326,
).alias("tile")
).first()
+-----------------------------------------------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_isoband(tile, breaks) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to classify. | |
breaks | ARRAY<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.
- SQL
- Python
SELECT gbx_rst_isoband(tile, array(0.0, 50.0, 100.0, 150.0, 200.0)) AS patches
FROM dem_rasters;
+-----------------------------------------------------------+
|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)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
from ._fixtures import dem_tile_df
df = dem_tile_df(spark)
result = df.select(
rx.rst_isoband(
"tile",
f.array(
f.lit(0.0), f.lit(50.0), f.lit(100.0),
f.lit(150.0), f.lit(200.0), f.lit(311.0),
),
).alias("patches")
).first()
+-----------------------------------------------------------+
|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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_chm(dsm_tile, dem_tile) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_chm(dsm_tile, dem_tile) | TILE |
| Python | rasterx.functions.rst_chm(dsm_tile, dem_tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
dsm_tile | TILE | TILE | The Digital Surface Model tile. | |
dem_tile | TILE | TILE | The 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- SQL
- Python
SELECT gbx_rst_chm(tile, tile) AS chm FROM dem_rasters;
+-----------------------------------------------------------+
|chm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(Float32 CHM tile: clamp(DSM - DEM, min=0); NoData propagates from either input)
from databricks.labs.gbx.rasterx import functions as rx
from ._fixtures import dem_tile_df
df = dem_tile_df(spark)
result = df.select(rx.rst_chm("tile", "tile").alias("chm")).first()
+-----------------------------------------------------------+
|chm |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(Float32 CHM tile: clamp(DSM - DEM, min=0); NoData propagates from either input; light tier returns a materialized v2 Tile)
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).
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.
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)
+------+--------------+-----+----------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
assignment | STRING | STRING | '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. |
coverage | STRING | STRING | '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. |
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- SQL
- Python
-- 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;
+------+------+--------------+
|source|cellid|raster |
+------+------+--------------+
|... |TQ2979|<raster bytes>|
+------+------+--------------+
(SELECT t.* expands the v2-tile struct; cellid is the BNG grid-square STRING)
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
gbx.register(spark)
# A 2km x 2km square over central London, in EPSG:27700 metres.
london_wkt = (
"POLYGON((529000 179000, 531000 179000, "
"531000 181000, 529000 181000, 529000 179000))"
)
london = spark.range(1).select(
rx_api.rst_rasterize(
f.lit(london_wkt),
f.lit(1.0),
f.lit(529000.0),
f.lit(179000.0),
f.lit(531000.0),
f.lit(181000.0),
f.lit(200),
f.lit(200),
f.lit(27700),
).alias("tile")
)
london.createOrReplaceTempView("rasters")
return spark.sql(
"SELECT t.* FROM rasters, LATERAL gbx_rst_bng_tessellate(tile, 3) t"
).take(3)
+------+-----------------------------------------------------------+
|cellid|... |
+------+-----------------------------------------------------------+
|TQ2979|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
|TQ2980|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
|TQ3079|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+------+-----------------------------------------------------------+
(one v2-Tile row per 1km BNG cell overlapping the London raster; cellid is the
BNG grid-square STRING)
rst_h3_tessellate
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
assignment | STRING | STRING | '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. |
coverage | STRING | STRING | '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. |
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.
- SQL
- Python
-- 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;
+------+------------------+--------------+
|source|cellid |raster |
+------+------------------+--------------+
|... |599686042433355775|<raster bytes>|
+------+------------------+--------------+
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
return spark.sql(
"SELECT t.* FROM rasters, LATERAL gbx_rst_h3_tessellate(tile, 3) t"
).take(3)
+-------------------+-----------------------------------------------------------+
|cellid |... |
+-------------------+-----------------------------------------------------------+
|577586652210266111 |{..., <raster bytes>, ..., {driver -> GTiff, ...}} |
+-------------------+-----------------------------------------------------------+
(one v2-Tile row per H3 cell, cellid = the H3 index)
rst_maketiles
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_maketiles(tile, size_in_mb) | rows |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_maketiles(tile, size_in_mb) | rows |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
size_in_mb | INT | INT | The 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. |
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- SQL
- Python
-- 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;
+------+--------------+----+----------------------+
|cellid|raster |path|... |
+------+--------------+----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+----+----------------------+
(one row per sub-tile; t.* expands the v2-Tile struct fields)
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
# Subdivide raster into approximately 1.0 MB tiles
return spark.sql(
"SELECT t.* FROM rasters, " "LATERAL gbx_rst_maketiles(tile, 1.0) t"
).collect()
+------+--------------+-----+----------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
assignment | STRING | STRING | '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. |
coverage | STRING | STRING | '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. |
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- SQL
- Python
-- 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;
+------+-------------------+--------------+
|source|cellid |raster |
+------+-------------------+--------------+
|... |5250127588525215743|<raster bytes>|
+------+-------------------+--------------+
(SELECT t.* expands the v2-tile struct; cellid is the quadbin index)
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
return spark.sql(
"SELECT t.* FROM rasters, LATERAL gbx_rst_quadbin_tessellate(tile, 5) t"
).take(3)
+-------------------+-----------------------------------------------------------+
|cellid |... |
+-------------------+-----------------------------------------------------------+
|5250127588525215743|{..., <raster bytes>, ..., {driver -> GTiff, ...}} |
+-------------------+-----------------------------------------------------------+
(one v2-Tile row per quadbin cell, cellid = the quadbin index)
rst_custom_tessellate
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
assignment | STRING | STRING | '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. |
coverage | STRING | STRING | '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. |
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- SQL
- Python
-- 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;
+--------------+------------------------------------------------------+
|cellid |raster |
+--------------+------------------------------------------------------+
|<Long cell id>|{<Long>, <raster bytes>, null, {driver -> GTiff, ...}}|
+--------------+------------------------------------------------------+
(one v2 tile struct per cell; cellid is BIGINT encoding the custom cell)
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
gbx.register(spark)
# A 2km x 2km square over central London, in EPSG:27700 metres.
london_wkt = (
"POLYGON((529000 179000, 531000 179000, "
"531000 181000, 529000 181000, 529000 179000))"
)
london = spark.range(1).select(
rx_api.rst_rasterize(
f.lit(london_wkt),
f.lit(1.0),
f.lit(529000.0),
f.lit(179000.0),
f.lit(531000.0),
f.lit(181000.0),
f.lit(200),
f.lit(200),
f.lit(27700),
).alias("tile")
)
london.createOrReplaceTempView("london_rasters")
# Custom grid exactly covering the raster extent in EPSG:27700, resolution 1
# (four 1km cells subdividing the 2km root cell).
custom_grid_sql = "gbx_custom_grid(529000, 531000, 179000, 181000, 2, 2000, 2000, 27700)"
return spark.sql(
f"SELECT t.* FROM london_rasters, "
f"LATERAL gbx_rst_custom_tessellate(tile, {custom_grid_sql}, 1) t"
).take(3)
+--------------------+-----------------------------------------------------------+
|cellid |raster |
+--------------------+-----------------------------------------------------------+
|<custom cell bigint>|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+--------------------+-----------------------------------------------------------+
(one v2-Tile row per custom-grid cell; cellid is BIGINT encoding the custom cell)
rst_retile
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
tile_width | INT | INT | The sub-tile width in pixels. | |
tile_height | INT | INT | The sub-tile height in pixels. |
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- SQL
- Python
-- 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;
+------+--------------+----+----------------------+
|cellid|raster |path|... |
+------+--------------+----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+----+----------------------+
(one row per sub-tile; t.* expands the v2-Tile struct fields)
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
# Explode raster into 64x64-pixel tiles (returns array of tiles)
return spark.sql(
"SELECT t.* FROM rasters, " "LATERAL gbx_rst_retile(tile, 64, 64) t"
).take(3)
+------+--------------+-----+----------------------+
|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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_separatebands(tile) | rows |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_separatebands(tile) | rows |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. |
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- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+-----------------------------------------------------------+-----------------------------------------------------------+
|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, ...}}|
+----+-----------------------------------------------------------+-----------------------------------------------------------+-----------------------------------------------------------+
from databricks.labs import gbx
gbx.register(spark)
multiband_tile_df(spark).createOrReplaceTempView("multiband_rasters")
# Explode multiband raster into individual band tiles
return spark.sql(
"SELECT t.* FROM multiband_rasters, " "LATERAL gbx_rst_separatebands(tile) t"
).collect()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(one row per band: 3 rows for a 3-band raster)
rst_tooverlappingtiles
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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>.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to split. | |
tile_width | INT | INT | The width of each tile in pixels, above 0. | |
tile_height | INT | INT | The height of each tile in pixels, above 0. | |
overlap | INT | INT | The overlap as a percentage of the tile size, from 0 to below 100. Each edge overlaps by the tile size times this, rounded up. |
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- SQL
- Python
-- 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;
+------+--------------+----+----------------------+
|cellid|raster |path|... |
+------+--------------+----+----------------------+
|0 |<raster bytes>|... |{driver -> GTiff, ...}|
+------+--------------+----+----------------------+
(one row per overlapping tile; t.* expands the v2-Tile struct fields)
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
# 64x64 tiles with 8% overlap
return spark.sql(
"SELECT t.* FROM rasters, "
"LATERAL gbx_rst_tooverlappingtiles(tile, 64, 64, 8) t"
).take(3)
+------+--------------+-----+----------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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> |
| Python | gridx.h3.functions.h3_cell_bbox(cellid, srid=None, mode=None, kring_pad=None, out_crs=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
cellid | BIGINT | BIGINT | The H3 cell id. | |
srid | INT | INT | 4326 | The EPSG code of the output coordinates. |
mode | STRING | STRING | 'centroids' | 'centroids' wraps the cell centres, 'spatial_envelope' the whole hexagons. |
kring_pad | INT | INT | 0 | How many rings of neighbours to include before taking the box; 0 is the cell alone. |
out_crs | STRING | STRING | NULL | The output coordinate system as EPSG:<n>, ESRI:<n> or WKT; when set it wins over srid. On Unity Catalog WKT is refused. |
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- SQL
- Python
-- 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);
+------------------+------------------------------+
|cellid |bbox |
+------------------+------------------------------+
|617733151020810239|{-74.02, 40.70, -74.01, 40.71}|
+------------------+------------------------------+
(STRUCT<xmin, ymin, xmax, ymax> per H3 cell, in EPSG:4326)
from databricks.labs.gbx.gridx.h3 import functions as hx
from pyspark.sql import functions as f
df = spark.createDataFrame(
[(617733151020810239,), (617733151085035519,), (617733151021334527,)],
["cellid"],
)
return df.select(
"cellid",
hx.h3_cell_bbox("cellid", f.lit(4326), f.lit("centroids")).alias("bbox"),
).take(3)
+------------------+------------------------------+
|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)
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:
- 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 agridstruct column — one row per group containing the shared canvas. - For each threshold band, run
rst_h3_rasterize_aggwith those fixed bounds — all output tiles share the same origin and pixel grid. - Stack aligned bands with
rst_frombands_agg(ordered byband_index), or mosaic per-cell tiles withrst_merge_agg.
Parameters:
df— input Spark DataFrame containing H3 cell IDscell_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 groupsrid— EPSG code for the output CRS;4326for 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 (default1)
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| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_h3_rastertogrid_partial(tile, resolution, coverage=None, assignment=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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.
- SQL
- Python
-- 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);
+----+------------------+-----+---+
|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)
df = _london_wgs84_tile(spark)
return _partial_states(
spark, df, rx_api.rst_h3_rastertogrid_partial("tile", 6)
)
+----+------------------+-----+---+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridavg(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Mean pixel value per H3 cell.
Since v0.2.0- SQL
- Python
-- 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;
+----+------------------+-------+
|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.)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
# LATERAL UDTF returns [band, cellID, measure] columns directly
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridavg(tile, 4) t"
).take(5)
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|123.45 |
|1 |599686042433355776|124.20 |
+----+------------------+-------+
(one row per band × H3 cell)
rst_h3_rastertogridcount
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridcount(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Pixel count (Double) per H3 cell.
Since v0.2.0- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|256.0 |
|1 |599686043374559743|240.0 |
|2 |599686042433355775|256.0 |
+----+------------------+-------+
(pixel count per band×cell; measure is DOUBLE)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridcount(tile, 4) t"
).take(5)
+----+------------------------------+-------+
|band|cellID |measure|
+----+------------------------------+-------+
|1 |599686042433355775 |256 |
|1 |599686042433355776 |240 |
+----+------------------------------+-------+
(pixel count per band × H3 cell)
rst_h3_rastertogridmax
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridmax(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Max value per H3 cell.
Since v0.2.0- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|255.0 |
|1 |599686043374559743|254.0 |
|2 |599686042433355775|240.0 |
+----+------------------+-------+
(max value per band×cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmax(tile, 4) t"
).take(5)
+----+------------------------------+-------+
|band|cellID |measure|
+----+------------------------------+-------+
|1 |599686042433355775 |255.0 |
|1 |599686042433355776 |254.0 |
+----+------------------------------+-------+
(max value per band × H3 cell)
rst_h3_rastertogridmedian
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridmedian(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Median value per H3 cell.
Since v0.2.0- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|120.5 |
|1 |599686043374559743|122.0 |
|2 |599686042433355775|115.0 |
+----+------------------+-------+
(median value per band×cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmedian(tile, 4) t"
).take(5)
+----+------------------------------+-------+
|band|cellID |measure|
+----+------------------------------+-------+
|1 |599686042433355775 |120.5 |
|1 |599686042433355776 |122.0 |
+----+------------------------------+-------+
(median value per band × H3 cell)
rst_h3_rastertogridmin
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridmin(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Min value per H3 cell.
Since v0.2.0- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|0.0 |
|1 |599686043374559743|10.0 |
|2 |599686042433355775|5.0 |
+----+------------------+-------+
(min value per band×cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridmin(tile, 4) t"
).take(5)
+----+------------------------------+-------+
|band|cellID |measure|
+----+------------------------------+-------+
|1 |599686042433355775 |0.0 |
|1 |599686042433355776 |10.0 |
+----+------------------------------+-------+
(min value per band × H3 cell)
rst_h3_rastertogridstddev
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridstddev(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population standard deviation of pixel values per H3 cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|35.29 |
|1 |599686043374559743|37.27 |
|2 |599686042433355775|34.01 |
+----+------------------+-------+
(standard deviation per band×cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridstddev(tile, 4) t"
).take(5)
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|35.29 |
|1 |599686042433355776|37.27 |
+----+------------------+-------+
(standard deviation per band × H3 cell)
rst_h3_rastertogridsum
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridsum(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Sum of pixel values per H3 cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|31563.0|
|1 |599686043374559743|29488.0|
|2 |599686042433355775|28672.0|
+----+------------------+-------+
(sum of pixel values per band×cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridsum(tile, 4) t"
).take(5)
+----+------------------------------+--------+
|band|cellID |measure |
+----+------------------------------+--------+
|1 |599686042433355775 |31563.0 |
|1 |599686042433355776 |29488.0 |
+----+------------------------------+--------+
(sum of pixel values per band × H3 cell)
rst_h3_rastertogridvariance
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_h3_rastertogridvariance(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The H3 resolution, a whole number from 0 to 15. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population variance of pixel values per H3 cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------------------+-------+
|band|cellID |measure|
+----+------------------+-------+
|1 |599686042433355775|1245.5 |
|1 |599686043374559743|1389.2 |
|2 |599686042433355775|1156.0 |
+----+------------------+-------+
(variance per band×cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_h3_rastertogridvariance(tile, 4) t"
).take(5)
+----+------------------------------+-------+
|band|cellID |measure|
+----+------------------------------+-------+
|1 |599686042433355775 |1245.5 |
|1 |599686042433355776 |1389.2 |
+----+------------------------------+-------+
(variance per band × H3 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| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_quadbin_rastertogrid_partial(tile, resolution, coverage=None, assignment=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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.
- SQL
- Python
-- 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);
+----+-------------------+-----+---+
|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)
df = _london_wgs84_tile(spark)
return _partial_states(
spark, df, rx_api.rst_quadbin_rastertogrid_partial("tile", 12)
)
+----+-------------------+-----+---+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridavg(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Mean pixel value per quadbin cell.
Since v0.4.0- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |123.45 |
|1 |12346 |124.20 |
|2 |12345 |210.67 |
+----+------+-------+
(one row per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridavg(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |123.45 |
|1 |12346 |124.20 |
+----+------+-------+
(one row per band × Quadbin cell)
rst_quadbin_rastertogridcount
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridcount(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Pixel count (Double) per quadbin cell.
Since v0.4.0- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |256.0 |
|1 |12346 |240.0 |
|2 |12345 |256.0 |
+----+------+-------+
(pixel count per band×Quadbin cell; measure is DOUBLE)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridcount(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |256 |
|1 |12346 |240 |
+----+------+-------+
(pixel count per band × Quadbin cell)
rst_quadbin_rastertogridmax
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridmax(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Max pixel value per quadbin cell.
Since v0.4.0- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |255.0 |
|1 |12346 |254.0 |
|2 |12345 |240.0 |
+----+------+-------+
(max value per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmax(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |255.0 |
|1 |12346 |254.0 |
+----+------+-------+
(max value per band × Quadbin cell)
rst_quadbin_rastertogridmedian
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridmedian(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Median pixel value per quadbin cell.
Since v0.4.0- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |120.5 |
|1 |12346 |122.0 |
|2 |12345 |115.0 |
+----+------+-------+
(median value per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmedian(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |120.5 |
|1 |12346 |122.0 |
+----+------+-------+
(median value per band × Quadbin cell)
rst_quadbin_rastertogridmin
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridmin(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Min pixel value per quadbin cell.
Since v0.4.0- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |0.0 |
|1 |12346 |10.0 |
|2 |12345 |5.0 |
+----+------+-------+
(min value per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridmin(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |0.0 |
|1 |12346 |10.0 |
+----+------+-------+
(min value per band × Quadbin cell)
rst_quadbin_rastertogridstddev
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridstddev(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population standard deviation of pixel values per quadbin cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |35.29 |
|1 |12346 |37.27 |
|2 |12345 |34.01 |
+----+------+-------+
(standard deviation per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridstddev(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |35.29 |
|1 |12346 |37.27 |
+----+------+-------+
(standard deviation per band × Quadbin cell)
rst_quadbin_rastertogridsum
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridsum(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Sum of pixel values per quadbin cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |31563.0|
|1 |12346 |29488.0|
|2 |12345 |28672.0|
+----+------+-------+
(sum of pixel values per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridsum(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |31563.0|
|1 |12346 |29488.0|
+----+------+-------+
(sum of pixel values per band × Quadbin cell)
rst_quadbin_rastertogridvariance
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_quadbin_rastertogridvariance(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT | INT | The quadbin zoom level, a whole number from 0 to 20. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population variance of pixel values per quadbin cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |1245.5 |
|1 |12346 |1389.2 |
|2 |12345 |1156.0 |
+----+------+-------+
(variance per band×Quadbin cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
return spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_quadbin_rastertogridvariance(tile, 4) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |12345 |1245.5 |
|1 |12346 |1389.2 |
+----+------+-------+
(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.
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| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_bng_rastertogrid_partial(tile, resolution, coverage=None, assignment=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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.
- SQL
- Python
-- 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);
+----+------+-----+---+
|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)
df = _london_bng_tile(spark)
return _partial_states(
spark, df, rx_api.rst_bng_rastertogrid_partial("tile", 3)
)
+----+------+-----+---+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridavg(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Mean pixel value per BNG cell. The raster is reprojected to EPSG:27700 internally before sampling.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+------------------+
|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)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridavg(tile, 3) t"
).take(5)
+----+------+------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridcount(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Valid (non-NoData) pixel count per BNG cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|9.0 |
|1 |OW5575|21.0 |
|2 |OW5574|9.0 |
+----+------+-------+
(pixel count per band × BNG cell; measure is DOUBLE)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridcount(tile, 3) t"
).take(5)
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|9 |
|1 |OW5575|21 |
|2 |OW5574|9 |
+----+------+-------+
(pixel count per band × BNG cell)
rst_bng_rastertogridmax
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridmax(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Maximum pixel value per BNG cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|106.0 |
|1 |OW5575|118.0 |
|1 |OW5674|107.0 |
+----+------+-------+
(max value per band × BNG cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmax(tile, 3) t"
).take(5)
+----+------+-------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridmedian(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Median pixel value per BNG cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|88.0 |
|1 |OW5575|80.0 |
|1 |OW5674|81.0 |
+----+------+-------+
(median value per band × BNG cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmedian(tile, 3) t"
).take(5)
+----+------+-------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridmin(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Minimum pixel value per BNG cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|0.0 |
|1 |OW5575|54.0 |
|1 |OW5674|65.0 |
+----+------+-------+
(min value per band × BNG cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridmin(tile, 3) t"
).take(5)
+----+------+-------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridstddev(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population standard deviation (sqrt of the population variance) of pixel values per BNG cell — a single-pixel cell yields 0.0.
- SQL
- Python
-- 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;
+----+------+------------------+
|band|cellID|measure |
+----+------+------------------+
|1 |OW5574|31.043975181373415|
|1 |OW5575|21.543606571950388|
|1 |OW5674|14.023789311975086|
+----+------+------------------+
(population standard deviation per band × BNG cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridstddev(tile, 3) t"
).take(5)
+----+------+------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridsum(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Sum of pixel values per BNG cell.
Since v0.4.3- SQL
- Python
-- 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;
+----+------+-------+
|band|cellID|measure|
+----+------+-------+
|1 |OW5574|695.0 |
|1 |OW5575|1694.0 |
|1 |OW5674|774.0 |
+----+------+-------+
(sum of pixel values per band × BNG cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridsum(tile, 3) t"
).take(5)
+----+------+-------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_bng_rastertogridvariance(df, tile, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID STRING, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
resolution | INT or STRING | STRING | BNG resolution: an index (1 to 6, negative for a quadrant) or a size such as '1km' or '100m'. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population variance (÷ n, two-pass) of pixel values per BNG cell — a single-pixel cell yields 0.0.
- SQL
- Python
-- 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;
+----+------+------------------+
|band|cellID|measure |
+----+------+------------------+
|1 |OW5574|963.7283950617285 |
|1 |OW5575|464.126984126984 |
|1 |OW5674|196.66666666666666|
+----+------+------------------+
(population variance per band × BNG cell)
from databricks.labs import gbx
gbx.register(spark)
df = _get_multiband_df(spark)
df.createOrReplaceTempView("multiband_rasters")
result = spark.sql(
"SELECT t.* FROM multiband_rasters, LATERAL gbx_rst_bng_rastertogridvariance(tile, 3) t"
).take(5)
+----+------+------------------+
|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.
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| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_custom_rastertogrid_partial(tile, grid, resolution, coverage=None, assignment=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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.
- SQL
- Python
-- 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);
+----+-----------------+-----+---+
|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)
from pyspark.sql import functions as f
df = _london_bng_tile(spark)
grid = f.call_function(
"gbx_custom_grid",
f.lit(529000), f.lit(533000), f.lit(179000), f.lit(183000),
f.lit(2), f.lit(4000), f.lit(4000), f.lit(27700),
)
return _partial_states(
spark, df, rx_api.rst_custom_rastertogrid_partial("tile", grid, 1)
)
+----+-----------------+-----+---+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridavg(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Mean pixel value per custom-grid cell.
Since v0.5.1- SQL
- Python
-- 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;
+----+--------------+-----------------+
|band|cellID |measure |
+----+--------------+-----------------+
|1 |<Long cell id>|<avg pixel value>|
+----+--------------+-----------------+
(one row per band × custom-grid cell; cellID is a BIGINT)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridavg(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+-------+
|band|cellID |measure|
+----+--------------------+-------+
|1 |<custom cell bigint>|1.0 |
+----+--------------------+-------+
(one row per band × custom-grid cell; cellID is BIGINT, measure is DOUBLE mean)
rst_custom_rastertogridcount
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridcount(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Valid (non-NoData) pixel count per custom-grid cell (measure is DOUBLE).
Since v0.5.1- SQL
- Python
-- 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;
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<count>|
+----+--------------+-------+
(pixel count per band × custom-grid cell; measure is DOUBLE)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridcount(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+-------+
|band|cellID |measure|
+----+--------------------+-------+
|1 |<custom cell bigint>|1600.0 |
+----+--------------------+-------+
(pixel count per band × custom-grid cell; measure is DOUBLE)
rst_custom_rastertogridmax
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridmax(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Maximum pixel value per custom-grid cell.
Since v0.5.1- SQL
- Python
-- 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;
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<max> |
+----+--------------+-------+
(max pixel value per band × custom-grid cell)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridmax(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+-------+
|band|cellID |measure|
+----+--------------------+-------+
|1 |<custom cell bigint>|1.0 |
+----+--------------------+-------+
(max pixel value per band × custom-grid cell)
rst_custom_rastertogridmedian
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridmedian(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Median pixel value per custom-grid cell.
Since v0.5.1- SQL
- Python
-- 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;
+----+--------------+--------+
|band|cellID |measure |
+----+--------------+--------+
|1 |<Long cell id>|<median>|
+----+--------------+--------+
(median pixel value per band × custom-grid cell)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridmedian(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+--------+
|band|cellID |measure |
+----+--------------------+--------+
|1 |<custom cell bigint>|1.0 |
+----+--------------------+--------+
(median pixel value per band × custom-grid cell)
rst_custom_rastertogridmin
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridmin(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Minimum pixel value per custom-grid cell.
Since v0.5.1- SQL
- Python
-- 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;
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<min> |
+----+--------------+-------+
(min pixel value per band × custom-grid cell)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridmin(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+-------+
|band|cellID |measure|
+----+--------------------+-------+
|1 |<custom cell bigint>|1.0 |
+----+--------------------+-------+
(min pixel value per band × custom-grid cell)
rst_custom_rastertogridstddev
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridstddev(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population standard deviation (sqrt of the population variance) of pixel values per custom-grid cell — a single-pixel cell yields 0.0.
- SQL
- Python
-- 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;
+----+--------------+--------+
|band|cellID |measure |
+----+--------------+--------+
|1 |<Long cell id>|<stddev>|
+----+--------------+--------+
(population standard deviation of pixel values per band × custom-grid cell)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridstddev(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+--------+
|band|cellID |measure |
+----+--------------------+--------+
|1 |<custom cell bigint>|0.0 |
+----+--------------------+--------+
(population standard deviation per band × custom-grid cell; 0.0 when all pixels equal)
rst_custom_rastertogridsum
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridsum(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Sum of pixel values per custom-grid cell.
Since v0.5.1- SQL
- Python
-- 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;
+----+--------------+-------+
|band|cellID |measure|
+----+--------------+-------+
|1 |<Long cell id>|<sum> |
+----+--------------+-------+
(sum of pixel values per band × custom-grid cell)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridsum(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+--------+
|band|cellID |measure |
+----+--------------------+--------+
|1 |<custom cell bigint>|1600.0 |
+----+--------------------+--------+
(sum of pixel values per band × custom-grid cell)
rst_custom_rastertogridvariance
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_custom_rastertogridvariance(df, tile, grid, resolution, coverage=None, assignment=None) | DataFrame |
Rows: band INT, cellID BIGINT, measure DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to aggregate. | |
grid | 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> | 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. | |
resolution | INT | INT | The grid resolution: 0 is the root cells, each level splits a cell into cell_splits by cell_splits. | |
coverage | STRING | STRING | '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. |
assignment | STRING | STRING | '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. |
Population variance (÷ n, two-pass) of pixel values per custom-grid cell — a single-pixel cell yields 0.0.
- SQL
- Python
-- 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;
+----+--------------+----------+
|band|cellID |measure |
+----+--------------+----------+
|1 |<Long cell id>|<variance>|
+----+--------------+----------+
(population variance of pixel values per band × custom-grid cell)
_setup_custom_raster_view(spark)
return spark.sql(
f"SELECT t.* FROM custom_rasters, "
f"LATERAL gbx_rst_custom_rastertogridvariance(tile, {_CUSTOM_GRID_SQL}, 0) t"
).take(5)
+----+--------------------+----------+
|band|cellID |measure |
+----+--------------------+----------+
|1 |<custom cell bigint>|0.0 |
+----+--------------------+----------+
(population variance per band × custom-grid cell; 0.0 when all pixels equal)
Operations
Transform and analyze rasters (20 total).
rst_align_to
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_align_to(tile, reference_tile) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_align_to(tile, reference_tile) | TILE |
| Python | rasterx.functions.rst_align_to(tile, reference_tile, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to warp. | |
reference_tile | TILE | TILE | The tile whose grid (CRS, extent, width, height) the result takes. |
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.
- SQL
- Python
SELECT gbx_rst_align_to(tile, reference_tile) AS aligned FROM paired_rasters;
+-----------------------------------------------------------+
|aligned |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile warped to reference grid; output has reference tile's CRS, extent, width, height)
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import dem_path
dem = str(dem_path())
df = spark.read.format("binaryFile").load(dem).select(
rx_api.rst_fromcontent(f.col("content"), f.lit("GTiff")).alias("tile"),
rx_api.rst_fromcontent(f.col("content"), f.lit("GTiff")).alias("reference_tile"),
)
result = df.select(rx_api.rst_align_to("tile", "reference_tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile warped to reference grid; output has reference tile's CRS, extent, width, height; light tier returns a materialized v2 Tile)
rst_asformat
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_asformat(tile, new_format) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_asformat(tile, new_format) | TILE |
| Python | rasterx.functions.rst_asformat(tile, new_format, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to re-encode. | |
new_format | STRING | STRING | A GDAL driver short name that can write a raster, in any case: 'GTiff', 'PNG', 'COG'. A name that names none raises. |
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.
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- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+
|path|geotiff_tile |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(rx.rst_asformat("tile", f.lit("GTiff")).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(re-encoded tile in the requested GDAL format; light tier returns a materialized v2 Tile)
rst_clip
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_clip(tile, geom, cutline_all_touched, clip_crs=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to clip. | |
geom | BINARY or STRING | GEOMETRY | The cutline: a polygon as WKB, EWKB, WKT or EWKT. | |
cutline_all_touched | BOOLEAN | BOOLEAN | true 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_crs | STRING | STRING | NULL | The 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. |
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.
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.
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.
- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+
|path|clipped |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
# WKT polygon in raster's native CRS (upper-left quadrant of the tile extent)
clip_geom = "POLYGON((2121950 -10791280, 2123140 -10791280, 2123140 -10790470, 2121950 -10790470, 2121950 -10791280))"
result = df.select(
rx.rst_clip("tile", f.lit(clip_geom), f.lit(True)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(clipped tile; polygon is in the raster's native CRS (no SRID = no reprojection); light tier returns a materialized v2 Tile)
rst_percentile_stretch
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_percentile_stretch(tile, lo_pct, hi_pct, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to stretch. | |
lo_pct | DOUBLE | DOUBLE | The lower percentile, in [0, 100] and below hi_pct: the value at it becomes 0. | |
hi_pct | DOUBLE | DOUBLE | The upper percentile, in [0, 100]: the value at it becomes 255. |
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.
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.
- SQL
- Python
SELECT gbx_rst_percentile_stretch(tile, 2.0, 98.0) AS stretched
FROM multiband_rasters;
+-----------------------------------------------------------+
|stretched |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(multiband uint8: each band stretched independently to [0,255])
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_percentile_stretch("tile", 2.0, 98.0).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(stretched tile; UInt8 values 0-255, 0 is NoData; light tier returns a materialized v2 Tile)
rst_combineavg
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combineavg(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combineavg(tiles) | TILE |
| Python | rasterx.functions.rst_combineavg(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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.
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- SQL
- Python
SELECT gbx_rst_combineavg(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
# Aggregate the 3 per-band tiles into one array, then average per-pixel.
result = (
df.groupBy("region")
.agg(rx_api.rst_combineavg(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(averaged combined raster from 3 input tiles)
rst_combinecount
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combinecount(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combinecount(tiles) | TILE |
| Python | rasterx.functions.rst_combinecount(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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- SQL
- Python
SELECT gbx_rst_combinecount(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_combinecount(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(pixel-count raster: 3 valid inputs per pixel from 3 input tiles)
rst_combinemax
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combinemax(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combinemax(tiles) | TILE |
| Python | rasterx.functions.rst_combinemax(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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- SQL
- Python
SELECT gbx_rst_combinemax(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_combinemax(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(per-pixel maximum raster from 3 input tiles)
rst_combinemedian
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combinemedian(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combinemedian(tiles) | TILE |
| Python | rasterx.functions.rst_combinemedian(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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- SQL
- Python
SELECT gbx_rst_combinemedian(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_combinemedian(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(per-pixel median raster from 3 input tiles)
rst_combinemin
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combinemin(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combinemin(tiles) | TILE |
| Python | rasterx.functions.rst_combinemin(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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- SQL
- Python
SELECT gbx_rst_combinemin(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_combinemin(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(per-pixel minimum raster from 3 input tiles)
rst_combinestddev
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combinestddev(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combinestddev(tiles) | TILE |
| Python | rasterx.functions.rst_combinestddev(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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- SQL
- Python
SELECT gbx_rst_combinestddev(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_combinestddev(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(per-pixel population std-dev raster from 3 input tiles)
rst_combinesum
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_combinesum(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_combinesum(tiles) | TILE |
| Python | rasterx.functions.rst_combinesum(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The tiles to combine, in an array: aligned tiles that share size, extent and CRS (use gbx_rst_align_to first). |
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- SQL
- Python
SELECT gbx_rst_combinesum(array(tile)) AS combined FROM multiband_rasters;
+-----------------------------------------------------------+
|combined |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_combinesum(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(per-pixel sum raster from 3 input tiles)
rst_convolve
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_convolve(tile, kernel) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_convolve(tile, kernel) | TILE |
| Python | rasterx.functions.rst_convolve(tile, kernel, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to convolve. | |
kernel | ARRAY<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.
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.
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.
- SQL
- Python
-- Apply 3x3 kernel (e.g. blur); kernel format is driver-specific
SELECT path, gbx_rst_convolve(tile, kernel) as filtered FROM rasters_with_kernels;
+----+-----------------------------------------------------------+
|path|filtered |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
kernel = f.array(
f.array(f.lit(0.0), f.lit(0.0), f.lit(0.0)),
f.array(f.lit(0.0), f.lit(1.0), f.lit(0.0)),
f.array(f.lit(0.0), f.lit(0.0), f.lit(0.0)),
)
result = df.select(rx.rst_convolve("tile", kernel).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(convolved tile; kernel is a 3x3 identity; light tier returns a materialized v2 Tile)
rst_derivedband
SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_derivedband(tile, python_func, func_name) | TILE |
| Python | rasterx.functions.rst_derivedband(tile, python_func, func_name, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
tile | TILE | The tile whose bands are the pixel function's input. | |
python_func | STRING | Python 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_name | STRING | The name of the function in python_func. A source that does not parse, or that defines no such name, raises. |
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.
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.
- SQL
- Python
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;
+-----------------------------------------------------------+
|result |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
# GDAL VRT pixel-function that doubles band 1's pixel values in place.
python_func = (
"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"
)
result = df.select(
rx.rst_derivedband("tile", python_func, "double").alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(raster with derived band from Python UDF)
rst_filter
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_filter(tile, kernel_size, operation) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_filter(tile, kernel_size, operation) | TILE |
| Python | rasterx.functions.rst_filter(tile, kernel_size, operation, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to filter. | |
kernel_size | INT | INT | The side of the square window, a positive odd integer. | |
operation | STRING | STRING | 'min', 'max', 'mean' or 'median', in any case. Another word raises. |
See interpolation & fill to choose among sampling, resampling, and gap-filling.
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.
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- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+
|path|denoised |
+----+-----------------------------------------------------------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+----+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_filter("tile", f.lit(3), f.lit("median")).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(filtered tile; 3x3 median filter applied; light tier returns a materialized v2 Tile)
rst_initnodata
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_initnodata(tile) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_initnodata(tile) | TILE |
| Python | rasterx.functions.rst_initnodata(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to give a NoData value. |
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.
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- SQL
- Python
SELECT gbx_rst_initnodata(tile) as tile FROM rasters;
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile with NoData initialized)
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("rasters")
result = df.select(rx.rst_initnodata("tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile with NoData initialized; light tier returns a materialized v2 Tile)
rst_isempty
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_isempty(tile) | BOOLEAN |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_isempty(tile) | BOOLEAN |
| Python | rasterx.functions.rst_isempty(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
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.
- SQL
- Python
-- 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;
+--------+
|is_empty|
+--------+
|false |
+--------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_isempty("tile").alias("is_empty")).first()
+--------+
|is_empty|
+--------+
|false |
+--------+
rst_mapalgebra
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_mapalgebra(tiles, expression) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_mapalgebra(tiles, expression) | TILE |
| Python | rasterx.functions.rst_mapalgebra(tiles, expression, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<TILE> | ARRAY<TILE> | The input tiles. Band 1 of each tile binds to A, B, C and so on, in array order. | |
expression | STRING | STRING | The expression: a JSON envelope with a calc key, or a bare expression such as '(A - B) / (A + B)'. |
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.
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
calcexpression, 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.
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.
- SQL
- Python
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;
+-----------------------------------------------------------+
|ndvi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
ndvi_spec = (
'{"calc": "(A - B) / (A + B)", '
'"A_index": 0, "B_index": 0, "A_band": 2, "B_band": 1}'
)
result = df.select(
rx.rst_mapalgebra(f.array("tile"), f.lit(ndvi_spec)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band Float32 NDVI tile; per-pixel (NIR-Red)/(NIR+Red) in [-1, 1])
rst_merge
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_merge(tiles) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_merge(tiles) | TILE |
| Python | rasterx.functions.rst_merge(tiles, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tiles | ARRAY<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. |
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.
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- SQL
- Python
SELECT gbx_rst_merge(array(tile)) AS merged FROM multiband_rasters;
+-----------------------------------------------------------+
|merged |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
from ._fixtures import multi_band_tiles_df
df = multi_band_tiles_df(spark)
result = (
df.groupBy("region")
.agg(rx_api.rst_merge(f.collect_list("tile")).alias("tile"))
.first()
)
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(merged raster from co-registered input tiles)
rst_ndvi
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_ndvi(tile, red_idx, nir_idx, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The multi-band tile. | |
red_idx | INT | INT | The 1-based band of red. | |
nir_idx | INT | INT | The 1-based band of near infrared. |
A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.
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- SQL
- Python
SELECT gbx_rst_ndvi(tile, 1, 2) AS ndvi FROM multiband_rasters;
+-----------------------------------------------------------+
|ndvi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NDVI raster: (NIR-Red)/(NIR+Red))
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
result = df.select(rx.rst_ndvi("tile", f.lit(1), f.lit(2)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NDVI raster: (NIR-Red)/(NIR+Red))
rst_rastertoworldcoord
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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> |
| Python | rasterx.functions.rst_rastertoworldcoord(tile, x, y) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
x | INT | INT | The pixel column, counted from 0. | |
y | INT | INT | The pixel row, counted from 0. |
Powered by rasterio.
Pixel to world coordinates as a struct with .x and .y fields.
- SQL
- Python
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;
+---------------+-------+--------+
|world_coord |easting|northing|
+---------------+-------+--------+
|{500980.0, ...}|500980 |4599220 |
+---------------+-------+--------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = single_band_tile_df(spark)
# Pixel (100, 80) → world struct {x: <easting>, y: <northing>}
result = df.select(
rx.rst_rastertoworldcoord("tile", f.lit(100), f.lit(80)).alias("world_coord")
).first()
+-----------------------------+
|world_coord |
+-----------------------------+
|{2122955.0, -10791275.0} |
+-----------------------------+
(struct with x: DOUBLE, y: DOUBLE)
rst_rastertoworldcoordx
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_rastertoworldcoordx(tile, x, y) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_rastertoworldcoordx(tile, x, y) | DOUBLE |
| Python | rasterx.functions.rst_rastertoworldcoordx(tile, x, y) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
x | INT | INT | The pixel column, counted from 0. | |
y | INT | INT | The pixel row, counted from 0. |
Powered by rasterio.
World X / Y coordinate of a pixel.
Since v0.2.0- SQL
- Python
SELECT
gbx_rst_rastertoworldcoordx(tile, 100, 80) as easting
FROM rasters;
+-------+
|easting|
+-------+
|500980 |
+-------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = single_band_tile_df(spark)
# Pixel col=100 → easting
result = df.select(
rx.rst_rastertoworldcoordx("tile", f.lit(100), f.lit(80)).alias("easting")
).first()
+---------+
|easting |
+---------+
|2122955.0|
+---------+
rst_rastertoworldcoordy
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_rastertoworldcoordy(tile, x, y) | DOUBLE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_rastertoworldcoordy(tile, x, y) | DOUBLE |
| Python | rasterx.functions.rst_rastertoworldcoordy(tile, x, y) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
x | INT | INT | The pixel column, counted from 0. | |
y | INT | INT | The pixel row, counted from 0. |
Powered by rasterio.
World X / Y coordinate of a pixel.
Since v0.2.0- SQL
- Python
SELECT
gbx_rst_rastertoworldcoordy(tile, 100, 80) as northing
FROM rasters;
+--------+
|northing|
+--------+
|4599220 |
+--------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = single_band_tile_df(spark)
# Pixel row=80 → northing
result = df.select(
rx.rst_rastertoworldcoordy("tile", f.lit(100), f.lit(80)).alias("northing")
).first()
+------------+
|northing |
+------------+
|-10791275.0 |
+------------+
rst_resample
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_resample(tile, factor, [algorithm]) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_resample(tile, factor, [algorithm]) | TILE |
| Python | rasterx.functions.rst_resample(tile, factor, algorithm=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to resample. | |
factor | DOUBLE | DOUBLE | The multiplicative factor, above 0: above 1 upsamples, below 1 downsamples. | |
algorithm | STRING | STRING | '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.
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:.
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.
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.0doubles 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- SQL
- Python
-- Upsample 2x with bilinear interpolation. Output dims = source dims * 2.
SELECT gbx_rst_resample(tile, 2.0, 'bilinear') AS upsampled FROM rasters;
+-----------------------------------------------------------+
|upsampled |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_resample("tile", f.lit(2.0), f.lit("bilinear")).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(2x bilinear upsampled tile; source is 236x161 px; light tier returns a materialized v2 Tile)
rst_resample_to_res
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_resample_to_res(tile, x_res, y_res, algorithm=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to resample. | |
x_res | DOUBLE | DOUBLE | The size of a pixel along x in the units of the tile's CRS, above 0. | |
y_res | DOUBLE | DOUBLE | The size of a pixel along y in the units of the tile's CRS, above 0. | |
algorithm | STRING | STRING | '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. |
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.
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- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|coarse |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_resample_to_res(
"tile", f.lit(20.0), f.lit(20.0), f.lit("average")
).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(downsampled tile; 10 m to 20 m resolution; light tier returns a materialized v2 Tile)
rst_resample_to_size
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_resample_to_size(tile, width_px, height_px, algorithm=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to resample. | |
width_px | INT | INT | The width of the result in pixels, above 0. | |
height_px | INT | INT | The height of the result in pixels, above 0. | |
algorithm | STRING | STRING | '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. |
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.
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- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|sized |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_resample_to_size("tile", f.lit(100), f.lit(100), f.lit("near")).alias(
"tile"
)
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(resampled tile forced to 100x100 pixels; light tier returns a materialized v2 Tile)
rst_transform
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_transform(tile, srid) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_transform(tile, srid) | TILE |
| Python | rasterx.functions.rst_transform(tile, srid, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to reproject. | |
srid | INT | INT | The EPSG (or ESRI) code of the target CRS, a positive integer. |
Runs GDAL's own raster reproject algorithm in the worker, on every compute.
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.
- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+--------+
|path|wgs84_tile |new_srid|
+----+-----------------------------------------------------------+--------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|4326 |
+----+-----------------------------------------------------------+--------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(rx.rst_transform("tile", f.lit(4326)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(reprojected tile; source EPSG:32618 (UTM Zone 18N) to EPSG:4326; light tier returns a materialized v2 Tile)
rst_transformcrs
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_transformcrs(tile, target_crs) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_transformcrs(tile, target_crs) | TILE |
| Python | rasterx.functions.rst_transformcrs(tile, target_crs) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to reproject. | |
target_crs | STRING | STRING | The target CRS: an authority code such as 'EPSG:3857' or 'ESRI:54008', WKT, PROJJSON or PROJ4. An integer string is an EPSG code. |
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.
- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+---------+
|path|webmercator_tile |new_crs |
+----+-----------------------------------------------------------+---------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|EPSG:3857|
+----+-----------------------------------------------------------+---------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_crs(rx.rst_transformcrs("tile", f.lit("EPSG:3857"))).alias("crs")
).first()
+----------+
|crs |
+----------+
|EPSG:3857 |
+----------+
(CRS string of the reprojected tile; accepts authority codes, WKT, or PROJ4)
rst_tryopen
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_tryopen(tile) | BOOLEAN |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_tryopen(tile) | BOOLEAN |
| Python | rasterx.functions.rst_tryopen(tile) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. |
Powered by rasterio.
Validate raster can be opened.
Examples use the multiband fixture (rgb_nir_small.tif, committed to the repo, always openable).
- SQL
- Python
-- 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;
+--------+
|try_open|
+--------+
|true |
+--------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_tryopen("tile").alias("try_open")).first()
+--------+
|try_open|
+--------+
|true |
+--------+
rst_updatetype
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_updatetype(tile, new_type) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_updatetype(tile, new_type) | TILE |
| Python | rasterx.functions.rst_updatetype(tile, new_type, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to cast. | |
new_type | STRING | STRING | A GDAL data type name, in any case: Byte, Int8, UInt16, Int16, UInt32, Int32, Float32 or Float64. Another word raises. |
Powered by rasterio. Output is re-encoded as GeoTIFF; a NoData value that is not representable in the target type is dropped.
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- SQL
- Python
SELECT gbx_rst_updatetype(tile, 'Float32') as float_tile FROM rasters;
+-----------------------------------------------------------+
|float_tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_updatetype("tile", f.lit("Float32")).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(type-converted tile; use rst_type to confirm the new data type; light tier returns a materialized v2 Tile)
rst_worldtorastercoord
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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> |
| Python | rasterx.functions.rst_worldtorastercoord(tile, x, y) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
x | DOUBLE | DOUBLE | The x coordinate in the raster CRS. | |
y | DOUBLE | DOUBLE | The y coordinate in the raster CRS. |
Powered by rasterio.
World to pixel coordinates as a struct with .x and .y fields.
- SQL
- Python
-- 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;
+-----------+---------+---------+
|pixel_coord|pixel_col|pixel_row|
+-----------+---------+---------+
|{5490, ...}|5490 |5490 |
+-----------+---------+---------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = single_band_tile_df(spark)
# World (2122955, -10791275) in the raster CRS → pixel (100, 80) — the exact
# inverse of the rst_rastertoworldcoord example above.
result = df.select(
rx.rst_worldtorastercoord("tile", f.lit(2122955.0), f.lit(-10791275.0)).alias(
"pixel_coord"
)
).first()
+-----------+
|pixel_coord|
+-----------+
|{100, 80} |
+-----------+
(struct with x: INT, y: INT)
rst_worldtorastercoordx
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_worldtorastercoordx(tile, x, y) | INT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_worldtorastercoordx(tile, x, y) | INT |
| Python | rasterx.functions.rst_worldtorastercoordx(tile, x, y) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
x | DOUBLE | DOUBLE | The x coordinate in the raster CRS. | |
y | DOUBLE | DOUBLE | The y coordinate in the raster CRS. |
Powered by rasterio.
Pixel column / row for a world coordinate.
Since v0.2.0- SQL
- Python
SELECT
gbx_rst_worldtorastercoordx(tile, 2122955.0, -10791275.0) as pixel_col
FROM rasters;
+---------+
|pixel_col|
+---------+
|5490 |
+---------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = single_band_tile_df(spark)
# World (2122955, -10791275) → pixel column 100
result = df.select(
rx.rst_worldtorastercoordx("tile", f.lit(2122955.0), f.lit(-10791275.0)).alias(
"pixel_col"
)
).first()
+---------+
|pixel_col|
+---------+
|100 |
+---------+
rst_worldtorastercoordy
SQLUnity Catalog SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_worldtorastercoordy(tile, x, y) | INT |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_worldtorastercoordy(tile, x, y) | INT |
| Python | rasterx.functions.rst_worldtorastercoordy(tile, x, y) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
x | DOUBLE | DOUBLE | The x coordinate in the raster CRS. | |
y | DOUBLE | DOUBLE | The y coordinate in the raster CRS. |
Powered by rasterio.
Pixel column / row for a world coordinate.
Since v0.2.0- SQL
- Python
SELECT
gbx_rst_worldtorastercoordy(tile, 2122955.0, -10791275.0) as pixel_row
FROM rasters;
+---------+
|pixel_row|
+---------+
|5490 |
+---------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = single_band_tile_df(spark)
# World (2122955, -10791275) → pixel row 80
result = df.select(
rx.rst_worldtorastercoordy("tile", f.lit(2122955.0), f.lit(-10791275.0)).alias(
"pixel_row"
)
).first()
+---------+
|pixel_row|
+---------+
|80 |
+---------+
rst_tilexyz
SQLUnity Catalog SQLPythonScala| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_tilexyz(tile, z, x, y, format=None, size=None, resampling=None, rescale=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to render. | |
z | INT | INT | The zoom level of the web tile, from 0. | |
x | INT | INT | The tile column, from 0 to 2^z - 1. | |
y | INT | INT | The tile row (north-down slippy-map order), from 0 to 2^z - 1. | |
format | STRING | STRING | 'PNG' | 'PNG', 'JPEG' or 'WEBP', in any case. Any other word raises. |
size | INT | INT | 256 | The side of the output tile in pixels, in (0, 4096]. Any other value raises. |
resampling | STRING | STRING | 'bilinear' | The GDAL warp resampling: near, bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1 or q3. Any other word raises. |
rescale | STRING | STRING | '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. |
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.
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.
- SQL
- Python
-- 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;
+----+--------+
|path|tile_png|
+----+--------+
|... |[BINARY]|
+----+--------+
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
gbx.register(spark)
df = single_band_tile_df(spark)
# Render z=12, x=1234, y=1523 as a 256x256 PNG. rescale="none" keeps the raw
# dtype mapping (a slippy-map tile off the raster's footprint renders
# transparent — rst_tilexyz never returns null).
result = df.select(
rx_api.rst_tilexyz(
"tile",
f.lit(12),
f.lit(1234),
f.lit(1523),
f.lit("PNG"),
f.lit(256),
f.lit("bilinear"),
f.lit("none"),
).alias("png_bytes")
).first()
+----------+
|png_bytes |
+----------+
|[BINARY] |
+----------+
(PNG image bytes, 256×256 pixels)
rst_to_webmercator
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_to_webmercator(tile, [resampling]) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_to_webmercator(tile, [resampling]) | TILE |
| Python | rasterx.functions.rst_to_webmercator(tile, resampling=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to reproject. | |
resampling | STRING | STRING | '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. |
Runs GDAL's own raster reproject algorithm in the worker, on every compute.
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.
- SQL
- Python
-- 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;
+----+-----------------------------------------------------------+--------+
|path|web_tile |new_srid|
+----+-----------------------------------------------------------+--------+
|... |{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|3857 |
+----+-----------------------------------------------------------+--------+
from databricks.labs.gbx.rasterx import functions as rx
df = single_band_tile_df(spark)
# Reproject to Web Mercator (default bilinear resampling)
result = df.select(rx.rst_to_webmercator("tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(reprojected to Web Mercator, EPSG:3857)
rst_xyzpyramid
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to render. | |
min_z | INT | INT | The first zoom level, from 0. | |
max_z | INT | INT | The last zoom level, at least min_z and at most 20. | |
format | STRING | STRING | 'PNG' | 'PNG', 'JPEG' or 'WEBP', in any case. Any other word raises. |
size | INT | INT | 256 | The side of each output tile in pixels, in (0, 4096]. Any other value raises. |
resampling | STRING | STRING | 'bilinear' | The GDAL warp resampling, as for gbx_rst_tilexyz. Any other word raises. |
rescale | STRING | STRING | 'auto' | The 8-bit contrast, as for gbx_rst_tilexyz. |
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.
- SQL
- Python
-- 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;
+----+-+-+-+---------+
|path|z|x|y|png_bytes|
+----+-+-+-+---------+
|... |4|5|6|[BINARY] |
+----+-+-+-+---------+
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
# One row per (z, x, y) tile across zoom 0..1.
return spark.sql(
"SELECT t.* FROM rasters, "
"LATERAL gbx_rst_xyzpyramid(tile, 0, 1, 'PNG', 256, 'bilinear', 'none') t"
).take(3)
+---+---+---+--------+
|z |x |y |bytes |
+---+---+---+--------+
|0 |0 |0 |[BINARY]|
+---+---+---+--------+
(one row per XYZ tile: z, x, y, and the PNG image bytes)
Vector↔raster bridge
Move data between the raster (tile) and vector (geom) worlds.
rst_polygonize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_polygonize(tile, [band], [connectedness]) | rows |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_polygonize(tile, [band], [connectedness]) | rows |
| Python | rasterx.functions.rst_polygonize(df, tile, band=None, connectedness=None) | DataFrame |
Rows: geom_wkb BINARY, value DOUBLE.
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to polygonize. | |
band | INT | INT | 1 | The band to read, from 1. |
connectedness | INT | INT | 4 | 4 joins pixels that share an edge; 8 also joins pixels that touch at a corner. |
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- SQL
- Python
-- 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;
+--------+-----+
|geom_wkb|value|
+--------+-----+
|... |365.0|
+--------+-----+
(one row per contiguous-value region; the rasterize round-trip returns one row with value 42.0)
from databricks.labs import gbx
gbx.register(spark)
single_band_tile_df(spark).createOrReplaceTempView("rasters")
# Polygonize band 1 with 4-connectivity.
return spark.sql(
"SELECT t.* FROM rasters, LATERAL gbx_rst_polygonize(tile, 1, 4) t"
).take(3)
+---------+-----+
|geom_wkb |value|
+---------+-----+
|... |365.0|
+---------+-----+
(one row per contiguous region: geom_wkb is WKB binary, value is the region value)
rst_rasterize
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_rasterize(geom, value, xmin, ymin, xmax, ymax, width_px, height_px, out_srid=None, out_crs=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
geom | BINARY or STRING | GEOMETRY | The geometry: WKB, EWKB, WKT or EWKT. A geometry with an SRID is reprojected into the output CRS first. | |
value | DOUBLE | DOUBLE | The value burned into the pixels the geometry covers. | |
xmin | DOUBLE | DOUBLE | The west edge of the output in the output CRS. | |
ymin | DOUBLE | DOUBLE | The south edge of the output. | |
xmax | DOUBLE | DOUBLE | The east edge of the output, above xmin. | |
ymax | DOUBLE | DOUBLE | The north edge of the output, above ymin. | |
width_px | INT | INT | The output width in pixels, above 0. | |
height_px | INT | INT | The output height in pixels, above 0. | |
out_srid | INT | INT | NULL | The 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_crs | STRING | STRING | NULL | The output CRS as EPSG:<n>, ESRI:<n> or WKT. Set out_srid or out_crs, not both: setting both raises. |
Powered by rasterio (rasterio.features).
out_crs parameterThe 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- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(rasterized tile: pixels inside the polygon carry the burn value; outside = NoData)
from databricks.labs import gbx
from pyspark.sql import Row, functions as f
gbx.register(spark)
# Create a small synthetic geometry DataFrame with WKT polygon
df = spark.createDataFrame([Row(geom="POLYGON((2 2, 8 2, 8 8, 2 8, 2 2))")])
# Rasterize a square polygon (value=1.0, extent=(0,0,10,10), 10x10 pixels, EPSG:4326)
result = df.select(
rx_api.rst_rasterize(
f.col("geom"),
f.lit(1.0),
f.lit(0.0),
f.lit(0.0),
f.lit(10.0),
f.lit(10.0),
f.lit(10),
f.lit(10),
f.lit(4326),
).alias("tile")
).collect()
+-----------------------------------------------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_aspect(tile, trigonometric=None, zero_for_flat=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. | |
trigonometric | BOOLEAN | BOOLEAN | false | true gives counter-clockwise degrees from east; false gives compass degrees clockwise from north. |
zero_for_flat | BOOLEAN | BOOLEAN | false | true gives 0 for flat cells; false leaves them NoData. The border and the cells next to NoData stay NoData. |
A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|aspect |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(aspect in compass degrees: 0=N, 90=E, 180=S, 270=W)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = dem_tile_df(spark)
result = df.select(
rx.rst_aspect("tile", f.lit(False), f.lit(False)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_color_relief(tile, color_table) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_color_relief(tile, color_table) | TILE |
| Python | rasterx.functions.rst_color_relief(tile, color_table, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. | |
color_table | STRING | STRING | The 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. |
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.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|rgb |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(3-band RGB tile mapped through the color table)
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
gbx.register(spark)
df = dem_tile_df(spark)
# The color table is text: "elevation R G B A" per line, "nv" for the NoData color.
color_table = "\n".join(
[
"0 34 139 34 255",
"100 144 238 144 255",
"200 255 255 0 255",
"311 255 255 255 128",
"nv 0 0 0 0",
]
)
result = df.select(rx_api.rst_color_relief("tile", color_table).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(4-band RGBA tile mapped via gdaldem color table)
rst_hillshade
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_hillshade(tile, azimuth=None, altitude=None, z_factor=None, xscale=None, yscale=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. | |
azimuth | DOUBLE | DOUBLE | 315.0 | Sun azimuth in degrees clockwise from north. |
altitude | DOUBLE | DOUBLE | 45.0 | Sun elevation above the horizon in degrees. |
z_factor | DOUBLE | DOUBLE | 1.0 | Vertical exaggeration applied to the gradients. |
xscale | DOUBLE | DOUBLE | NULL | Vertical units per horizontal unit along x; set it with yscale. When both are NULL, the scale comes from the raster CRS. |
yscale | DOUBLE | DOUBLE | NULL | Vertical units per horizontal unit along y; set it with xscale. |
A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|hillshade |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(8-bit hillshade: 0..255, NW azimuth 45-degree altitude)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = dem_tile_df(spark)
result = df.select(
rx.rst_hillshade("tile", f.lit(315.0), f.lit(45.0), f.lit(1.0)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(8-bit hillshade: 0..255, NW azimuth 45-degree altitude)
rst_roughness
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_roughness(tile) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_roughness(tile) | TILE |
| Python | rasterx.functions.rst_roughness(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. |
A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.
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- SQL
- Python
-- Roughness: max absolute neighbour difference in a 3x3 window.
SELECT gbx_rst_roughness(tile) AS roughness FROM dem_rasters;
+-----------------------------------------------------------+
|roughness |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(roughness: max absolute difference in 3x3 window)
from databricks.labs.gbx.rasterx import functions as rx
df = dem_tile_df(spark)
result = df.select(rx.rst_roughness("tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(roughness: max absolute difference in 3x3 window)
rst_slope
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_slope(tile, [unit], [xscale], [yscale]) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_slope(tile, [unit], [xscale], [yscale]) | TILE |
| Python | rasterx.functions.rst_slope(tile, unit=None, xscale=None, yscale=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. | |
unit | STRING | STRING | 'degrees' | 'degrees' or 'percent'. |
xscale | DOUBLE | DOUBLE | NULL | Vertical units per horizontal unit along x; set it with yscale. When both are NULL, the scale comes from the raster CRS. |
yscale | DOUBLE | DOUBLE | NULL | Vertical units per horizontal unit along y; set it with xscale. |
Runs GDAL's own raster slope algorithm with Horn's method, on every compute. Edge pixels are NoData.
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).
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|slope |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(slope in degrees; auto-scaled from raster CRS units)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = dem_tile_df(spark)
result = df.select(
rx.rst_slope("tile", f.lit("degrees"), f.lit(1.0), f.lit(1.0)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(slope in degrees; auto-scaled from raster CRS units)
rst_tpi
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_tpi(tile) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_tpi(tile) | TILE |
| Python | rasterx.functions.rst_tpi(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. |
A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.
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- SQL
- Python
-- TPI: difference from neighbour-mean; +ve = ridge, -ve = valley.
SELECT gbx_rst_tpi(tile) AS tpi FROM dem_rasters;
+-----------------------------------------------------------+
|tpi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(TPI: positive=ridge, negative=valley)
from databricks.labs.gbx.rasterx import functions as rx
df = dem_tile_df(spark)
result = df.select(rx.rst_tpi("tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(TPI: positive=ridge, negative=valley)
rst_tri
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_tri(tile) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_tri(tile) | TILE |
| Python | rasterx.functions.rst_tri(tile, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The single-band DEM tile. |
A pixel whose 3×3 window holds NoData, and the one-pixel border, are NoData.
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- SQL
- Python
-- TRI: mean absolute neighbour difference; useful for landscape ecology.
SELECT gbx_rst_tri(tile) AS tri FROM dem_rasters;
+-----------------------------------------------------------+
|tri |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(TRI: mean absolute neighbour difference)
from databricks.labs.gbx.rasterx import functions as rx
df = dem_tile_df(spark)
result = df.select(rx.rst_tri("tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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 |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The multi-band tile. | |
red_idx | INT | INT | The 1-based band of red. | |
nir_idx | INT | INT | The 1-based band of near infrared. | |
blue_idx | INT | INT | The 1-based band of blue. | |
l | DOUBLE | DOUBLE | 1.0 | The canopy background adjustment. |
c1 | DOUBLE | DOUBLE | 6.0 | The aerosol coefficient for red. |
c2 | DOUBLE | DOUBLE | 7.5 | The aerosol coefficient for blue. |
g | DOUBLE | DOUBLE | 2.5 | The gain factor. |
A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.
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.
- SQL
- Python
SELECT gbx_rst_evi(tile, 1, 2, 3) AS evi FROM multiband_rasters;
+-----------------------------------------------------------+
|evi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band EVI raster: G*(NIR-Red)/(NIR+C1*Red-C2*Blue+L))
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
# EVI requires red (band 1), NIR (band 2), blue (band 3 as proxy)
result = df.select(
rx.rst_evi("tile", f.lit(1), f.lit(2), f.lit(3)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_index(tile, formula_name, band_map, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The multi-band tile. | |
formula_name | STRING | STRING | The index: ndvi, gndvi, msavi, ndvi_re, ndmi or ndsi (any case). | |
band_map | MAP<STRING,INT> | MAP<STRING,INT> | The 1-based band of each name the index needs, such as map('red', 1, 'nir', 2). |
A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.
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.
- SQL
- Python
SELECT gbx_rst_index(tile, 'ndvi', map('red', 1, 'nir', 2)) AS ndvi FROM multiband_rasters;
+-----------------------------------------------------------+
|ndvi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band index raster computed from named formula)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
# Compute NDVI via the generic index dispatcher with a red/NIR band map.
band_map = f.create_map(f.lit("red"), f.lit(1), f.lit("nir"), f.lit(2))
result = df.select(
rx.rst_index("tile", f.lit("ndvi"), band_map).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band index raster computed from named formula)
rst_land_cover
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_land_cover(tile, method=None, n_clusters=None, smooth=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | A tile of 3 or more bands: red, green, blue (and optionally near-infrared). | |
method | STRING | STRING | '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_clusters | INT | INT | 6 | The k-means cluster count ('kmeans' and 'hybrid'), 1 or more. |
smooth | INT | INT | 3 | The de-speckle window in pixels: isolated specks of a class are dropped; 0 turns it off. |
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.
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.
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.
- SQL
- Python
SELECT gbx_rst_land_cover(tile, 'spectral', 6, 0) AS lc
FROM multiband_rasters;
+-----------------------------------------------------------+
|lc |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band Int32: each pixel is a land-cover class id index)
import numpy as np
from pyspark.sql import functions as f
from rasterio.io import MemoryFile
from rasterio.transform import from_origin
from databricks.labs.gbx.rasterx import functions as rx_api
from databricks.labs.gbx.rasterx import helpers
# A 2 x 2 RGB tile: a green pixel, a light pixel, a grey pixel and a dark one.
a = np.array(
[[[30, 210], [100, 30]], [[200, 205], [100, 30]], [[40, 200], [100, 30]]],
np.uint8,
)
profile = dict(
driver="GTiff",
width=2,
height=2,
count=3,
dtype="uint8",
crs="EPSG:4326",
transform=from_origin(0, 2, 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 = tile_df.select(
rx_api.rst_land_cover("tile", "spectral", 6, 0).alias("tile")
).first()["tile"]
[[[0 1]
[2 3]]]
(class ids: 0 vegetation, 1 bare, 2 impervious, 3 dark; -1 is NoData)
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
]
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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_nbr(tile, nir_idx, swir_idx, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The multi-band tile. | |
nir_idx | INT | INT | The 1-based band of near infrared. | |
swir_idx | INT | INT | The 1-based band of shortwave infrared. |
A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.
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.
- SQL
- Python
SELECT gbx_rst_nbr(tile, 2, 3) AS nbr FROM multiband_rasters;
+-----------------------------------------------------------+
|nbr |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NBR raster: (NIR-SWIR)/(NIR+SWIR))
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
# Band 2 (NIR), band 3 (SWIR proxy)
result = df.select(rx.rst_nbr("tile", f.lit(2), f.lit(3)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NBR raster: (NIR-SWIR)/(NIR+SWIR))
rst_ndwi
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_ndwi(tile, green_idx, nir_idx, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The multi-band tile. | |
green_idx | INT | INT | The 1-based band of green. | |
nir_idx | INT | INT | The 1-based band of near infrared. |
A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.
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.
- SQL
- Python
SELECT gbx_rst_ndwi(tile, 3, 2) AS ndwi FROM multiband_rasters;
+-----------------------------------------------------------+
|ndwi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NDWI raster: (Green-NIR)/(Green+NIR))
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
# Use green (band 3) and NIR (band 2)
result = df.select(rx.rst_ndwi("tile", f.lit(3), f.lit(2)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band NDWI raster: (Green-NIR)/(Green+NIR))
rst_savi
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_savi(tile, red_idx, nir_idx, l=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The multi-band tile. | |
red_idx | INT | INT | The 1-based band of red. | |
nir_idx | INT | INT | The 1-based band of near infrared. | |
l | DOUBLE | DOUBLE | 0.5 | The soil-brightness correction; 0 reduces SAVI to NDVI. |
A pixel is NoData (-9999) where an input band is NoData, a value is NaN or infinite, or the denominator is 0.
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.
- SQL
- Python
SELECT gbx_rst_savi(tile, 1, 2, 0.5) AS savi FROM multiband_rasters;
+-----------------------------------------------------------+
|savi |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single-band SAVI raster: (NIR-Red)/(NIR+Red+L)*(1+L))
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
result = df.select(rx.rst_savi("tile", f.lit(1), f.lit(2)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_band(tile, band_index) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_band(tile, band_index) | TILE |
| Python | rasterx.functions.rst_band(tile, band_index, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to take a band from. | |
band_index | INT | INT | The 1-based band to extract, in [1 .. numbands]. |
Powered by rasterio.
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.
- SQL
- Python
-- Pull band 1 (1-based) as a fresh single-band tile.
SELECT gbx_rst_band(tile, 1) AS b1 FROM rasters;
+-----------------------------------------------------------+
|b1 |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("multiband_rasters")
result = df.select(rx.rst_band("tile", f.lit(1)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(single band extracted from the 3-band multiband fixture; light tier returns a materialized v2 Tile)
rst_buildoverviews
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_buildoverviews(tile, levels, [resampling]) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_buildoverviews(tile, levels, [resampling]) | TILE |
| Python | rasterx.functions.rst_buildoverviews(tile, levels, resampling=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to add overviews to. | |
levels | ARRAY<INT> | ARRAY<INT> | The decimation factors, such as array(2, 4, 8): each at least 2. | |
resampling | STRING | STRING | 'average' | The overview resampling: nearest, average, gauss, cubic, cubicspline, lanczos, bilinear or mode. Any other word raises. |
Powered by rasterio. Builds internal GeoTIFF overviews.
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.
- SQL
- Python
-- Add 2x / 4x overviews to the tile via the 'average' resampling.
SELECT gbx_rst_buildoverviews(tile, array(2, 4), 'average') AS withovr
FROM rasters;
+-----------------------------------------------------------+
|withovr |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx_api.rst_buildoverviews("tile", f.array(f.lit(2), f.lit(4))).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile with internal overviews at levels [2, 4] embedded; light tier returns a materialized v2 Tile)
rst_fillnodata
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_fillnodata(tile, max_search_dist=None, smoothing_iter=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to fill. | |
max_search_dist | DOUBLE | DOUBLE | 100.0 | How far, in pixels, to search for valid pixels to interpolate from. A whole number. |
smoothing_iter | INT | INT | 0 | The number of 3x3 smoothing passes over the filled pixels. A whole number. |
See interpolation & fill to choose among sampling, resampling, and gap-filling.
Runs GDAL's raster fill-nodata for each band, in the worker, on every compute.
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.
- SQL
- Python
-- Fill NoData holes searching up to 100 pixels in each direction.
SELECT gbx_rst_fillnodata(tile, 100.0, 0) AS filled FROM rasters;
+-----------------------------------------------------------+
|filled |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_fillnodata("tile", f.lit(100.0), f.lit(0)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(filled tile; NoData holes searched within 100 pixels; light tier returns a materialized v2 Tile)
rst_histogram
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_histogram(tile, n_buckets=None, min_val=None, max_val=None, include_nodata=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
n_buckets | INT | INT | 256 | The number of equal-width buckets across the range. |
min_val | DOUBLE | DOUBLE | NULL | The lower bound of the range; the band's smallest valid value when NULL. |
max_val | DOUBLE | DOUBLE | NULL | The upper bound of the range; the band's largest valid value when NULL. |
include_nodata | BOOLEAN | BOOLEAN | false | Whether NoData pixels are binned too; the default leaves them out. |
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.
- SQL
- Python
-- multiband_rasters view is from rgb_nir_small.tif (3 bands: red, NIR, green)
SELECT gbx_rst_histogram(tile) AS histogram FROM multiband_rasters;
+-------------------------------------------------+
|histogram |
+-------------------------------------------------+
|{band_1 -> [1, 0, 0, ...], band_2 -> [1, 0, 1,...|
+-------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
df = spark.table("multiband_rasters")
result = df.select(rx.rst_histogram("tile").alias("histogram")).first()
+--------------------------------------------------+
|histogram |
+--------------------------------------------------+
|{band_1 -> [1, 0, 0, ...], band_2 -> [1, 0, 1,... |
+--------------------------------------------------+
rst_sample
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_sample(tile, geom, [crs]) | array<double> |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_sample(tile, geom, [crs]) | array<double> |
| Python | rasterx.functions.rst_sample(tile, geom, crs=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The raster tile. | |
geom | BINARY or STRING | GEOMETRY | A POINT as WKB, EWKB, WKT or EWKT. | |
crs | STRING | STRING | NULL | The 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.
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.
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, …): callrst_sampleonce 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 asrst_h3_tessellatefor an index join. Then callrst_sample(tile, point)per row.
See Raster Sampling for the full workflow guide.
- SQL
- Python
-- 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;
+-------+
|values |
+-------+
|[302.0]|
+-------+
(array of sampled values, one per band)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = dem_tile_df(spark)
result = df.select(
rx.rst_sample("tile", f.lit("SRID=32618;POINT(500320 4500320)")).alias("values")
).first()
+-------+
|values |
+-------+
|[302.0]|
+-------+
(array of sampled values, one per band)
rst_setcrs
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_setcrs(tile, crs) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_setcrs(tile, crs) | TILE |
| Python | rasterx.functions.rst_setcrs(tile, crs) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to relabel. | |
crs | STRING | STRING | The 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. |
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|tagged |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_crs(rx.rst_setcrs("tile", f.lit("EPSG:32618"))).alias("crs")
).first()
+----------+
|crs |
+----------+
|EPSG:32618|
+----------+
(CRS string after stamping; does NOT reproject — use rst_transformcrs to reproject)
rst_setsrid
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_setsrid(tile, srid) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_setsrid(tile, srid) | TILE |
| Python | rasterx.functions.rst_setsrid(tile, srid, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to relabel. | |
srid | INT | INT | The code to stamp, an EPSG or ESRI code; 0 clears the CRS. A negative number, or a positive code that is neither, raises. |
Powered by rasterio. Stamps the CRS without reprojecting.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|tagged |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(rx.rst_setsrid("tile", f.lit(32618)).alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(tile with SRID stamped to 32618; does NOT reproject — use rst_transform to reproject; light tier returns a materialized v2 Tile)
rst_threshold
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_threshold(tile, [op], [value]) | TILE |
| SQL (Unity Catalog) | <catalog>.<schema>.gbx_rst_threshold(tile, [op], [value]) | TILE |
| Python | rasterx.functions.rst_threshold(tile, op=None, value=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to threshold. | |
op | STRING | STRING | '>' | The comparison: >, <, >=, <=, == or !=. |
value | DOUBLE | DOUBLE | 0.0 | The value to compare each pixel with. |
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.
- SQL
- Python
-- Keep the pixels above 100 m, set the others to NoData.
SELECT gbx_rst_threshold(tile, '>', 100.0) AS mask FROM rasters;
+-----------------------------------------------------------+
|mask |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = spark.table("rasters")
result = df.select(
rx.rst_threshold("tile", f.lit(">"), f.lit(0.0)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(pixels > 0.0 keep their value, others are NoData; returns a materialized v2 Tile)
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| Surface | Call | Returns |
|---|---|---|
| SQL (session) | gbx_rst_gdal(tile, command) | TILE |
| Python | rasterx.functions.rst_gdal(tile, command, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | Default | Description |
|---|---|---|---|
tile | TILE | The tile to process. | |
command | STRING | What 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. |
Runs GDAL's raster pipeline in the worker on every compute. GeoBrix adds the read and write steps itself.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+-----------------------------------------------------------+
|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)
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
gbx.register(spark)
df = dem_tile_df(spark)
result = df.select(
rx_api.rst_gdal(
"tile", f.lit("reproject --output-crs=EPSG:3857 ! slope --unit=percent")
).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(a GeoTIFF tile in EPSG:3857 holding the slope in percent)
rst_cog_convert
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_cog_convert(tile, compression=None, blocksize=None, overview_resampling=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to convert. | |
compression | STRING | STRING | '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. |
blocksize | INT | INT | 512 | The internal block size in pixels, square: a multiple of 16. Any other value raises. |
overview_resampling | STRING | STRING | 'AVERAGE' | The resampling of the overview pyramid, such as AVERAGE. |
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).
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|cog |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
from databricks.labs.gbx.rasterx import functions as rx_api
df = spark.table("rasters")
result = df.select(rx_api.rst_cog_convert("tile").alias("tile")).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(COG tile; a COG is a valid GeoTIFF with tiled internal layout; light tier returns a materialized v2 Tile)
rst_contour
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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>> |
| Python | rasterx.functions.rst_contour(tile, levels, interval=None, base=None, attr_field=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to trace. | |
levels | ARRAY<DOUBLE> | ARRAY<DOUBLE> | The values to trace; NULL or empty to use interval and base. | |
interval | DOUBLE | DOUBLE | 0.0 | The spacing of the lines, used when levels is empty; above 0. |
base | DOUBLE | DOUBLE | 0.0 | The value one line is drawn at, used with interval. |
attr_field | STRING | STRING | 'elev' | Accepted for compatibility; the value is always the struct field value. |
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------------------------------------------------------------+
|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)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = dem_tile_df(spark)
result = df.select(
rx.rst_contour("tile", f.lit([]), f.lit(50.0), f.lit(0.0), f.lit("elev")).alias(
"contours"
)
).first()
+-----------------------------------------------------------------------------------------------------------------+
|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| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.functions.rst_proximity(tile, target_values=None, dist_units=None, max_distance=None, virtualize_dir=None, virtualize_prefix=None, materialize=None) | Column |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The tile to measure: its first band. | |
target_values | STRING | STRING | NULL | The source pixel values as a comma-separated list, such as '1,2'. NULL makes every pixel that is not 0 a source. |
dist_units | STRING | STRING | 'GEO' | 'GEO' measures in the units of the tile's CRS; 'PIXEL' counts pixels. NULL is 'GEO'. |
max_distance | DOUBLE | DOUBLE | NULL | The largest distance to compute, above 0: farther pixels are NoData. NULL for no limit. |
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.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|dist |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(distance in pixels to nearest non-NoData pixel, capped at 100)
from databricks.labs.gbx.rasterx import functions as rx
from pyspark.sql import functions as f
df = dem_tile_df(spark)
result = df.select(
rx.rst_proximity("tile", f.lit(""), f.lit("PIXEL"), f.lit(100.0)).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(distance in pixels to nearest non-NoData pixel, capped at 100)
rst_viewshed
SQLUnity Catalog SQLPython| Surface | Call | Returns |
|---|---|---|
| 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 |
| Python | rasterx.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 |
| Parameter | SQL type | UC type | Default | Description |
|---|---|---|---|---|
tile | TILE | TILE | The DEM tile. | |
observer_geom | BINARY or STRING | GEOMETRY | The 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_height | DOUBLE | DOUBLE | 0.0 | The observer's height above the DEM, 0 or more. NULL is 0. |
target_height | DOUBLE | DOUBLE | 1.6 | The height of the target above the DEM at each cell, 0 or more. |
max_distance | DOUBLE | DOUBLE | NULL | The 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. |
crs | STRING | STRING | NULL | The CRS of the observer when it has no SRID (EPSG:n, ESRI:n or WKT). NULL means the DEM's CRS. |
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.
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.
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.
- SQL
- Python
-- 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;
+-----------------------------------------------------------+
|vs |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(binary viewshed: 255=visible, 0=not visible)
from databricks.labs import gbx
from databricks.labs.gbx.rasterx import functions as rx_api
from pyspark.sql import functions as f
gbx.register(spark)
df = dem_tile_df(spark)
result = df.select(
rx_api.rst_viewshed(
"tile",
f.lit("POINT(500320 4500320)"),
f.lit(100.0),
f.lit(1.6),
f.lit(500.0),
).alias("tile")
).first()
+-----------------------------------------------------------+
|tile |
+-----------------------------------------------------------+
|{0, <raster bytes>, <virtual path>, {driver -> GTiff, ...}}|
+-----------------------------------------------------------+
(binary viewshed: 255=visible, 0=not visible)
rst_viewshed_towers (Python / DataFrame helper)
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.
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 carrytower_id_colplus the projected observer coordinate columnsx_col/y_col(EPSG:3857 metres, matching the DSM grid). Whenobserver_heightis a column name, that column must also be present.dsm_tiles_df— bytes-free DSM tile manifest; must have columnspath(absolute COG path),txandty(integer grid indices). Collected once on the driver.radius_m— viewshed analysis radius in projected metres (> 0); also caps the DSM window and therst_viewshedmax-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 thetx/tyindices indsm_tiles_dfreference.tile_m— tile size in metres (> 0).target_height— receiver height above the DSM at each tested cell; defaults to1.6.to_crs— optional EPSG code to reproject the viewshed into (rst_transform, materialized once); when set, the result gainsvisible_px_reprojandtotal_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 (repartitionbytower_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
- GridX Function Reference
- VectorX Function Reference
- PMTiles Function Reference — Aggregator (
gbx_pmtiles_agg) for publishing tile pyramids - PMTiles Writer — DataSource for streaming large pyramids to a single
.pmtilesfile - RasterX Readers
- Helios notebooks — worked end-to-end example: Web Mercator reprojection, XYZ pyramid generation, COG conversion, and terrain analytics packaged into PMTiles archives over San Francisco.