rwarp
rwarp reprojects and resamples rasters. It is GDAL's warp pipeline in
Rust: coordinate transforms, approximate transforms, source window
planning and resampling kernels, with no runtime GDAL dependency. It
follows GDAL's algorithms closely, written with reference to the GDAL
source and checked against gdalwarp output, but it is an independent
implementation, not affiliated with or endorsed by the GDAL project.
Try it in the browser: the demo warps web map tiles into a projection of your choice, client-side, compiled to WebAssembly.
The usual way to do this
Most raster reprojection goes through GDAL's warper, whether you call it
yourself or not. On the command line it is gdalwarp, or
gdal raster reproject from GDAL 3.11. In R it is under terra::project(),
gdalraster::warp() and vapour::gdal_raster_data(), and in Python under
rasterio.warp.reproject() and rioxarray's .rio.reproject(). For
conservative regridding between model grids, the usual choice is ESMF,
through ESMPy or xESMF, or CDO's remapcon.
These are good defaults. They read and write almost any format, they have been used on a great deal of data, and they warp one file into another in a single call. If they already do what you need, there is no reason to change.
The same things in rwarp
rwarp has equivalents for most of what those tools do to the pixels, so what you know carries over:
| You may know it as | In rwarp | See |
|---|---|---|
gdalwarp's error threshold, -et 0.125 by default | ApproxTransformer | Transformers |
how gdalwarp splits a warp into chunks, set by -wm | plan_chunks, ChunkOptions | Planning reads |
gdalwarp -r near, bilinear, cubic, lanczos, average, mode | warp() with a ResampleAlg | Resampling |
ESMF's conserve; xESMF's conserve and conserve_normed | rwarp::weights | Conservative weights |
gdalwarp -geoloc, geolocation arrays | GeolocArrays | Curvilinear grids |
gdalwarp -cutline, -cblend | Cutline | Cutlines |
Where rwarp does something differently from GDAL, the GDAL parity page says what and why.
When you might reach for rwarp
GDAL's warper plans, reads, maps coordinates and resamples in one operation. rwarp keeps those steps apart, which helps in a few situations:
- You want to know what a warp will read before it reads anything. The plan lists the source pixels each target chunk needs, so a cache, tile server or planner can count the I/O first.
- Your pixels don't come through GDAL. rwarp does no I/O. You fetch the window it asks for from wherever the data lives: COG tiles, Zarr chunks, a byte-reference store, or a GDAL dataset if that is easiest.
- GDAL is hard to bring along, as in a web page. With the pure-Rust
proj4rsbackend rwarp builds for WebAssembly, which is what the demo runs on. - You regrid between the same grids many times. Conservative weights are computed once and applied to every band, time step or variable.
- You want to see exactly what gdalwarp does. rwarp's fixtures pin down how ties are broken, where edges fall and when kernels widen.
The usual tools stay the simpler choice for warping files into files, and ESMF for conservative weights with areas measured on the sphere (rwarp's are planar, in source pixel space, for now). The two also work side by side: the R example reads with gdalraster and warps with rwarp.
How it fits together
target grid
|
v
[plan] plan_chunks / compute_source_window
| which chunks, and which source pixels does each need?
| inspectable, serialisable, resumable
v
[read] the caller fetches bytes: COG tiles, Zarr chunks, byte-reference stores
|
v
[warp] warp(): NearestNeighbour, Bilinear, Cubic, Lanczos, Average, Mode
That makes it a building block for caches, tile servers, browser viewers and planners that need to know the I/O cost of a reprojection up front.
For readers who know GDAL's source, the pieces correspond to these:
| Piece | GDAL equivalent |
|---|---|
GenImgProjTransformer: pixel, geo and CRS steps | GDALGenImgProjTransform |
ApproxTransformer: adaptive interpolation | GDALApproxTransform |
GcpTransformer: polynomial order 1-3 | GDALGCPTransform |
GeolocArrays, GenImgGeolocTransformer: curvilinear source or target | geolocation arrays (alg/gdalgeoloc.cpp) |
plan_chunks + ChunkOptions, compute_source_window | GDALWarpOperation planning (CollectChunkList, ComputeSourceWindow) |
warp(), warp_chunks(): resampling kernels, kernel widening, nodata rules | gdalwarpkernel.cpp |
CRS transforms go through a small trait with two backends: libproj (the
default, full PROJ) or proj4rs (pure Rust, builds for
wasm32-unknown-unknown). See Getting started.
Status
The core API has been stable since 0.3; 0.4 changed only the
controlledburn types that appear in rwarp's API (see the
changelog). Types and functions marked #[non_exhaustive]
may gain new variants in minor releases; everything else follows semver.
Each component is validated against GDAL output; the
GDAL parity page lists what has been checked, how, and
where rwarp deliberately differs. Feedback and testing are very welcome at
github.com/hypertidy/rwarp.
R package
An R package lives in the rwarp-r/
subdirectory of this repository. It wraps the same planning and resampling
pipeline via extendr, exposing warp_plan(),
warp_exec(), warp_buffer(), pixel_transform() and crs_describe().
Its website is https://hypertidy.github.io/rwarp/r/. See the
R package chapter or install directly:
remotes::install_github("hypertidy/rwarp", subdir = "rwarp-r")
Python package
Python bindings are planned, through PyO3, with NumPy arrays as the pixel buffer type and the same API shape as the R package. The Python package chapter sketches the design; contributions are welcome.
Getting started
Add the crate
[dependencies]
rwarp = "0.5"
For unreleased changes on main, depend on the repository:
[dependencies]
rwarp = { git = "https://github.com/hypertidy/rwarp" }
Choose a CRS backend
| Feature | Backend | Accepts | Needs |
|---|---|---|---|
proj (default) | libproj, through the proj crate | anything PROJ does: WKT, EPSG codes, proj strings, datum grids | a native libproj (or the crate's bundled build) |
proj4rs | pure Rust | proj strings and EPSG:NNNN codes | nothing; builds for wasm32-unknown-unknown |
cargo test # libproj
cargo test --no-default-features --features proj4rs # pure Rust
cargo build --no-default-features --features proj4rs --target wasm32-unknown-unknown
Or bring your own: GenImgProjTransformer::with_backend takes any pair of
CrsTransform implementations (one each way), for example a JavaScript
PROJ build reached from WebAssembly.
A first warp
This plans and warps one 256 x 256 tile in a local Lambert azimuthal
equal-area projection from a Web Mercator tile pyramid. It is
examples/tile_laea.rs; run it with cargo run --example tile_laea.
use rwarp::source_window::compute_source_window;
use rwarp::transform::GenImgProjTransformer;
use rwarp::warp::{warp, Nodata, ResampleAlg, SourceBuffer, WarpOptions};
const WEBMERC_HALF: f64 = 20037508.342789244;
const LAEA_TAS: &str = "+proj=laea +lat_0=-42 +lon_0=147 +datum=WGS84 +units=m +no_defs";
fn main() -> Result<(), String> {
// Source: Web Mercator at zoom 8, as one virtual raster.
let n = 256 * (1 << 8);
let px = 2.0 * WEBMERC_HALF / n as f64;
let src_gt = [-WEBMERC_HALF, px, 0.0, WEBMERC_HALF, 0.0, -px];
let src_size = [n, n];
// Target: a 256 x 256 tile, 400 km across, centred on Tasmania.
let extent = 400_000.0;
let dst_gt = [-extent / 2.0, extent / 256.0, 0.0, extent / 2.0, 0.0, -extent / 256.0];
// 1. Transformer: target pixel -> source pixel, approximated as gdalwarp does.
let exact = GenImgProjTransformer::new("EPSG:3857", src_gt, LAEA_TAS, dst_gt)?;
let t = ApproxTransformer::new(exact, 0.125);
// 2. Plan: which source pixels does the tile need? No pixels are read.
let win = compute_source_window(&t, [0, 0], [256, 256], src_size, 1)
.ok_or("tile does not map onto the source")?;
println!(
"source window: offset ({}, {}), size {} x {} pixels",
win.xoff, win.yoff, win.xsize, win.ysize
);
// 3. Read: fetch that window (here, synthesise it).
let (w, h) = (win.xsize as usize, win.ysize as usize);
let data: Vec<f32> = (0..w * h).map(|i| (win.xoff as usize + i % w) as f32).collect();
let src = SourceBuffer {
data: &data,
ncol: w,
nrow: h,
nbands: 1,
col_off: win.xoff as usize,
row_off: win.yoff as usize,
};
// 4. Warp.
let opts = WarpOptions::new(ResampleAlg::Bilinear)
.with_src_nodata(Nodata::Value(f64::NAN));
let out = warp(&t, &src, 256, 256, &opts);
let valid = out.iter().filter(|v| !v.is_nan()).count();
println!("warped {} of {} target pixels", valid, out.len());
Ok(())
}
The four steps are the whole pipeline. For sources that cross 180 degrees, see Sources across 180 degrees before building the transformer.
- Transformer. Maps target pixels to source pixels. Wrapping it in
ApproxTransformerwith a 0.125 pixel error, as gdalwarp does by default, transforms a few points per scanline exactly and interpolates the rest. - Plan.
compute_source_windowfinds the source pixels the tile needs, without reading any. - Read. Fetch that window however your data is stored.
- Warp.
warpresamples into the target, with options for the method, kernel scaling, nodata and more (see Resampling).
R package
The rwarp-r/
subdirectory of this repository is an R package, also named rwarp, that
exposes the same planning and resampling pipeline via
extendr. Its website, with the function
reference and articles, is
https://hypertidy.github.io/rwarp/r/.
Installation
Requires a Rust toolchain (>= 1.86), pkg-config, and PROJ (>= 9.6.2):
# install.packages("remotes")
remotes::install_github("hypertidy/rwarp", subdir = "rwarp-r")
Core functions
| Function | What it does |
|---|---|
warp_plan() | Compute source windows for a destination grid (pure geometry, no I/O) |
warp_exec() | Execute a plan with a user-supplied read function |
warp_buffer() | Warp one source window you already have, as warp_exec() does each chunk |
warp_resample() | Deprecated: use warp_buffer() |
pixel_transform() | Map destination pixels to fractional source pixel coordinates |
crs_describe() | Describe a CRS string in all PROJ output formats |
Plan / execute pattern
The design mirrors the Rust API: planning and reading are always separate
steps. warp_plan() transforms grid corners and edge samples to find the
source window(s) that cover each destination tile. No pixels are touched.
warp_exec() calls a user-supplied read_fn once per chunk and composites
the results.
library(rwarp)
library(gdalraster)
## --- open source ---
url <- "/vsicurl/https://example.com/my.tif"
ds <- new(GDALRaster, url, read_only = TRUE)
src_crs <- ds$getProjectionRef()
src_gt <- ds$getGeoTransform()
src_dim <- c(ds$getRasterXSize(), ds$getRasterYSize())
## --- define destination grid ---
dst_crs <- "EPSG:3857"
dst_ext <- c(-20037508, 20037508, -20037508, 20037508)
dst_dim <- c(512L, 512L)
# geotransform: [xmin, xres, 0, ymax, 0, -yres]
dst_gt <- c(dst_ext[1],
(dst_ext[2] - dst_ext[1]) / dst_dim[1], 0,
dst_ext[4], 0,
-(dst_ext[4] - dst_ext[3]) / dst_dim[2])
## --- 1. Plan (no I/O) ---
plan <- warp_plan(
src_crs = src_crs, src_gt = src_gt, src_dim = as.integer(src_dim),
dst_crs = dst_crs, dst_gt = dst_gt, dst_size = dst_dim
)
## inspect fill ratio before spending any network budget
plan[[1]][[1]]$fill_ratio
## --- 2. Execute with a GDAL reader ---
result <- warp_exec(
plan,
read_fn = function(xoff, yoff, xsize, ysize)
as.integer(ds$read(1L, xoff, yoff, xsize, ysize, xsize, ysize)),
src_crs = src_crs, src_gt = src_gt,
dst_crs = dst_crs, dst_gt = dst_gt,
dst_size = dst_dim,
src_nodata = -32768L, dst_nodata = -32768L
)
ds$close()
## result is an integer matrix, dst_dim[2] rows by dst_dim[1] columns
## (warp_buffer() returns the same shape)
ximage::ximage(result, dst_ext)
Swapping the reader is the point. The same plan works with an HTTP byte-range reader, a Zarr chunk fetcher, or any other source that can return a rectangular pixel block:
## byte-range COG reader (sketch)
read_fn <- function(xoff, yoff, xsize, ysize) {
byte_range <- cog_tile_range(cog_url, xoff, yoff, xsize, ysize)
raw_bytes <- http_get_range(cog_url, byte_range)
decode_cog_tile(raw_bytes)
}
result <- warp_exec(plan, read_fn = read_fn, ...)
Inspecting the plan
warp_plan() returns a list holding one chunk list. Each chunk has its
destination window, its source window, its fill ratio and the kernel
scale it was planned for:
plan <- warp_plan(
src_crs = "EPSG:4326", src_gt = c(-180, 0.1, 0, 90, 0, -0.1),
src_dim = c(3600L, 1800L),
dst_crs = "EPSG:3857",
dst_gt = c(-20037508, 78271.5, 0, 20037508, 0, -78271.5),
dst_size = c(512L, 512L)
)
## how many chunks?
length(plan[[1]])
## the first chunk
str(plan[[1]][[1]])
# List of 11
# $ dst_xoff : int 0
# $ dst_yoff : int 0
# $ dst_xsize : int 512
# $ dst_ysize : int 512
# $ src_xoff : int 0
# $ src_yoff : int 0
# $ src_xsize : int 3600
# $ src_ysize : int 1800
# $ fill_ratio: num 1.06
# $ scale_x : num 0.143
# $ scale_y : num 0.778
warp_plan(min_fill_ratio = ) splits chunks with a low fill ratio into
smaller ones, so less is read. To skip chunks that contribute almost
nothing, drop them from the plan before executing it:
plan[[1]] <- Filter(function(ch) ch$fill_ratio >= 0.05, plan[[1]])
result <- warp_exec(plan, read_fn = read_fn, ...)
The chunks matter to the values, not only to memory: when the kernel
widens to downsample, each chunk estimates its own scale. By default
warp_plan() plans for one byte per pixel of working memory and never
splits on fill ratio, so a destination that gdalwarp splits can be one
chunk here. To get gdalwarp's chunks, and its values, describe the warp as
gdalwarp sees it and use its rules:
plan <- warp_plan(src_crs, src_gt, src_dim, dst_crs, dst_gt,
dst_size = dst_dim, resample = "cubic",
nbands = 3, working_type = "Float64", src_nodata = 0,
memory_limit = 64, # gdalwarp -wm
min_fill_ratio = 0.5, min_dst_size = 100L,
scale_origin = "output", split_antimeridian = FALSE)
CRS diagnostics
crs_describe() calls PROJ directly and returns every string form PROJ
can produce for a given input. Use it to debug CRS strings before passing
them to warp functions:
crs_describe("EPSG:3031")
# $proj4
# [1] "+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +type=crs"
#
# $wkt2
# [1] "PROJCRS[\"WGS 84 / Antarctic Polar Stereographic\", ..."
#
# $projjson
# ...
## bare +proj= string without +type=crs is treated as an operation, not a CRS
crs_describe("+proj=merc +datum=WGS84") # may fail
crs_describe("+proj=merc +datum=WGS84 +type=crs") # works
The CRS string pitfalls are covered in depth in the CRS Strings
vignette (vignette("crs-strings", package = "rwarp")).
Articles
| Article | What it shows |
|---|---|
| Get started | Plan, warp and check against gdalwarp, on a file shipped with vapour |
| Sentinel-2: two UTM zones onto one grid | Two Sentinel-2 tiles in different UTM zones, three bands as float reflectance, onto one Albers grid; checked against gdalwarp |
| GHRSST SST onto Antarctic polar stereographic | A window of a global COG to a polar grid, and the byte-range read path as a concept |
| Warp planning | Fill ratios, antimeridian splits, tiled execution loops |
| CRS strings | Diagnosing +proj= string pitfalls with crs_describe() |
Get started, warp planning and CRS strings are installed with the package
(vignette("rwarp", package = "rwarp")). The Sentinel-2 and GHRSST
articles read from the network, so they are on the website only.
Alongside vapour, gdalraster and terra
The usual way to reproject in R is through GDAL's warper:
vapour::gdal_raster_data() and the gdal_raster_* family,
gdalraster::warp() and terra::project(). For reading and writing
ordinary raster files they remain the natural choices. rwarp covers the
same reprojection, with the steps apart, which helps when:
- The read step should be user-supplied: any source, not just GDAL files.
- The plan should be inspectable: fill ratios and source windows are available before any I/O.
- The warp kernel should be pure Rust: no GDAL warp dependency, so it can compile to WebAssembly and run in the browser.
The two work together: the example above reads with gdalraster and warps with rwarp.
Source and issues
The R package lives in
rwarp-r/.
Issues and pull requests are welcome at
github.com/hypertidy/rwarp.
Python package
A Python package, also named rwarp, is planned. It would expose the same planning and resampling pipeline via PyO3.
Status: planned, not started. There is no
rwarp-py/in the repository yet; this page sketches the intended API and packaging. Feedback on the API shape is welcome via issues.
Planned install
pip install rwarp
Or from source, once rwarp-py/ exists (requires a Rust toolchain >= 1.86
and maturin):
cd rwarp-py
pip install maturin
maturin develop
Planned API
The Python API is intended to mirror the R package closely, with NumPy arrays as the pixel buffer type.
import rwarp
import numpy as np
# --- define source and destination grids ---
src_crs = "EPSG:4326"
src_gt = (-180.0, 0.1, 0.0, 90.0, 0.0, -0.1) # (xmin, xres, 0, ymax, 0, -yres)
src_dim = (3600, 1800)
dst_crs = "EPSG:3857"
dst_gt = (-20037508.0, 78271.5, 0.0, 20037508.0, 0.0, -78271.5)
dst_dim = (512, 512)
# --- 1. Plan (no I/O) ---
plan = rwarp.warp_plan(
src_crs=src_crs, src_gt=src_gt, src_dim=src_dim,
dst_crs=dst_crs, dst_gt=dst_gt, dst_size=dst_dim,
)
# inspect fill ratio before any read
print(plan[0].fill_ratio)
# --- 2. Execute with a NumPy-returning read function ---
def read_fn(xoff, yoff, xsize, ysize):
# return a 1-D int32 array of length xsize * ysize
return my_source.read(xoff, yoff, xsize, ysize).ravel().astype(np.int32)
result = rwarp.warp_exec(
plan,
read_fn=read_fn,
src_crs=src_crs, src_gt=src_gt,
dst_crs=dst_crs, dst_gt=dst_gt,
dst_size=dst_dim, nodata=-32768,
)
# result is a 1-D int32 ndarray, length dst_dim[0] * dst_dim[1]
grid = result.reshape(dst_dim[1], dst_dim[0])
Core functions (planned)
| Function | What it does |
|---|---|
warp_plan() | Compute source windows for a destination grid (pure geometry, no I/O) |
warp_exec() | Execute a plan with a user-supplied read function |
warp_buffer() | Warp one source window you already have |
pixel_transform() | Map destination pixels to fractional source pixel coordinates |
crs_describe() | Describe a CRS string in all PROJ output formats |
Why PyO3
PyO3 compiles the same Rust core to a Python extension module. The warp kernel and the planning geometry would be identical to the R package and the WebAssembly build; only the FFI layer differs.
NumPy arrays are meant to pass in and out without copying: the read
function returns a NumPy array and warp_exec returns one, so the data
stays in Rust-managed memory and Python sees a view.
Integration ideas
Because the read function is user-supplied, any array source works:
# rasterio
import rasterio
with rasterio.open("my.tif") as ds:
def read_fn(xoff, yoff, xsize, ysize):
window = rasterio.windows.Window(xoff, yoff, xsize, ysize)
return ds.read(1, window=window).ravel().astype(np.int32)
result = rwarp.warp_exec(plan, read_fn=read_fn, ...)
# xarray / zarr
import xarray as xr
da = xr.open_zarr("store.zarr")["sst"]
def read_fn(xoff, yoff, xsize, ysize):
return da.isel(x=slice(xoff, xoff+xsize),
y=slice(yoff, yoff+ysize)).values.ravel().astype(np.int32)
result = rwarp.warp_exec(plan, read_fn=read_fn, ...)
Source and issues
The Python package will live in rwarp-py/ in this repository.
Issues and contributions are welcome at
github.com/hypertidy/rwarp.
Transformers
A transformer maps coordinates between target pixels and source pixels. Every
part of rwarp that needs coordinates (planning, kernels) takes anything that
implements the Transformer trait, so they compose freely.
pub trait Transformer {
/// dst_to_src = true: input is target pixel/line, output is source pixel/line.
fn transform(&self, dst_to_src: bool, x: &mut [f64], y: &mut [f64]) -> Vec<bool>;
}
It follows GDAL's transformer callback: coordinate arrays are modified in place, and one flag per point says whether it transformed. The warp kernels always call it target to source.
The transformers
| Transformer | Maps | Use it for |
|---|---|---|
GenImgProjTransformer | pixel to geo (geotransform), CRS to CRS, geo to pixel | ordinary rasters with a geotransform on both sides |
ApproxTransformer<T> | wraps any transformer, interpolating between exactly transformed points within a maximum error | speed; gdalwarp uses 0.125 pixels by default |
GcpTransformer | polynomial fitted to ground control points, order 1 to 3 | unrectified imagery with GCPs |
GeolocArrays | pixel to geo through 2D coordinate arrays | swaths and curvilinear model grids |
GenImgGeolocTransformer | either side a geotransform or geolocation arrays, plus a CRS step | warping from, or onto, a curvilinear grid |
Geotransforms are in GDAL's order, [x0, dx, rx, y0, ry, dy]. Pixel
coordinates are continuous: pixel i covers [i, i + 1), so its centre is
i + 0.5.
Sources across 180 degrees
A lon/lat source stored as 170..190, as -190..-170, or as a 0..360 global
grid has longitudes the CRS step never returns: inverse projections give
-180..180. gdalwarp handles this by wrapping the source's longitudes
around its centre (GDAL's CENTER_LONG), and GenImgProjTransformer
does the same once it knows the source raster's size:
use rwarp::transform::{CenterLong, GenImgProjTransformer};
let t = GenImgProjTransformer::new("EPSG:4326", src_gt, dst_crs, dst_gt)?
.with_source_size([src_width, src_height]);
// the middle of the source's corner longitudes, to six digits as GDAL
let centre = t.center_long();
Target to source, a longitude more than 180 degrees from the centre is
brought back by 360 (once), so a target crossing 180 finds both halves of
the source; source to target, the same is done before the CRS step. Only
a source CRS that is geographic in degrees is wrapped, as in GDAL. A source
wider than 360 degrees is not, unless the target is lon/lat too and its
extent crosses 180 (give it with with_target_extent, gdalwarp's -te).
with_center_long(CenterLong::Off) turns it off (gdalwarp does, for
cutlines) and CenterLong::At(lon) sets the centre. A transformer from
with_backend does not know its CRSs, so CenterLong::Auto does nothing
there; use CenterLong::At(source_center_long(&src_gt, size, None).unwrap())
for GDAL's value. Without with_source_size, nothing is wrapped, as in
rwarp 0.3.0.
CRS backends
The CRS step goes through the CrsTransform trait:
pub trait CrsTransform {
fn convert(&self, x: f64, y: f64) -> Option<(f64, f64)>;
}
Its direction is fixed at construction. Geographic coordinates are always
longitude, latitude in degrees, whichever backend is used. crs_pair builds
the two directions with the backend compiled in; with_backend
constructors accept your own.
Vector quantities
For velocity fields and other (u, v) quantities stored in grid
coordinates, reprojecting the scalar values is not enough: the vectors also
rotate with the local frame. Transformer::jacobian gives the local 2 x 2
derivative of a transform at a point (by finite differences unless an
implementation overrides it), the piece a vector-preserving warp needs.
Planning reads
Planning answers "which source pixels does this target need?" before any pixels are read. It needs only a transformer and the source raster's size.
One window
let win = compute_source_window(&t, dst_off, dst_size, src_raster_size, resample_padding)?;
// win.xoff, win.yoff, win.xsize, win.ysize: the source window in pixels
// win.fill_ratio: how much of the unclamped window lies inside the source
This follows GDAL's ComputeSourceWindow: it samples the target window's
edges (and, if that fails, a grid over its interior), transforms them to the
source, and takes their bounding box, padded for the resampling kernel
(0 for nearest, 1 for bilinear, 2 for cubic, 3 for lanczos). It returns
None if too few points transform.
A low fill_ratio means much of the window falls outside the source, or
the target straddles a discontinuity such as the antimeridian.
compute_source_window is a quick estimate that pads one pixel beyond the
kernel radius and skips GDAL's forward probe and special points. For the
window exactly as gdalwarp computes it, use
ChunkPlanner::new(&t, src_size, dst_size, opts).source_window(dst_off, dst_size).
Splitting into chunks
use rwarp::plan::{plan_chunks, ChunkOptions};
let opts = ChunkOptions::gdalwarp(ResampleAlg::Bilinear)
.with_memory_limit(64.0 * 1024.0 * 1024.0) // gdalwarp -wm
.with_pixel_cost(DataType::Float32, 1, true, true); // with nodata
let plan = plan_chunks(&approx, src_size, dst_size, &opts);
for c in plan.live() {
// c.dst_off, c.dst_size: a piece of the target
// c.src_off, c.src_size: what it reads from the source
// c.fill_ratio, c.scale: GDAL's fill ratio and kernel scale
let tile = warp(&approx, &read(c.src_off, c.src_size), c.dst_size[0], c.dst_size[1],
&c.warp_options(&WarpOptions::new(ResampleAlg::Bilinear)));
}
This is gdalwarp's planning (CollectChunkList): the source window of
the whole target is computed, and while it would take more working memory
than the limit, or its fill ratio is below 0.5 (much of it outside the
source), the target is halved along its longer side and each half planned
again. Each chunk is then warped on its own, with the kernel scale GDAL
would estimate for it. Chunks are sorted top to bottom, then left to
right, as GDAL warps them.
The chunk boundaries matter to the output, not only to memory: they set
the kernel scale, the edges where kernels are clipped, and the scanlines
the approximate transformer interpolates over. With
ChunkOptions::gdalwarp and the same memory limit, the plan and the
output equal gdalwarp's for a whole raster (see
GDAL parity). ChunkOptions::new differs in two
documented places: each chunk's kernel scale is estimated over the chunk
(GDAL estimates every chunk at the output's top-left), and source
windows are padded for a fixed kernel scale.
A few inputs need the caller: GDAL's special points (longitude 0 at
latitude +-89.9999, in target pixels, which make every chunk sample a
grid when one falls in the target) need the CRSs, and the target's block
size matters only for a tiled target (OPTIMIZE_SIZE).
warp_chunks runs a whole plan
from a source buffer in memory, which is how the parity tests use it.
warp_chunks_par runs it on several threads, with the same values bit
for bit. As for warp_par (Resampling), it
takes a closure that builds a transformer for each thread:
let out: Vec<f32> = warp_chunks_par(make, &plan, &src, &opts, 8)?;
Each chunk's rows are cut into bands, about four a thread over the plan.
So a plan of one chunk runs on every thread, and one of many chunks
warps several at once. Each band is warped as warp_chunks warps those
rows. A chunk's source window is copied when its first band starts
(borrowed if it is whole rows of the buffer) and dropped when its last
is done. Bands go into the target in the plan's order, so the two chunks
of an antimeridian gap, which share a target window, land as they do on
one thread. A 0.1° global grid to 4000 by 4000 pixels of south polar
stereographic, through libproj, in 8 chunks of a 16 MB memory limit:
| 1 thread | 8 | 32 | |
|---|---|---|---|
| Bilinear | 1.48 s | 0.26 s | 0.18 s |
| Cubic | 3.09 s | 0.46 s | 0.23 s |
| Average | 2.38 s | 0.38 s | 0.19 s |
| Bilinear, one chunk | 0.94 s | 0.19 s | 0.11 s |
At the antimeridian
with_split_antimeridian(true) adds the split of 0.2's
collect_chunk_list: a chunk whose source window spans the whole source
width (as at 180 degrees) is split where source x jumps, so a tile
straddling 180 degrees becomes tiles each side with compact source
windows rather than one spanning the globe (a 70 times reduction in
pixels read for a GEBCO tile over Fiji). GDAL reaches a similar result
only through its memory limit. A window that spans the width with no
jump (a narrow source the target covers whole), or one round a pole,
where splitting at the jump reads no less, is planned by GDAL's rule, so
the plan is gdalwarp's plus the splits at jumps.
Why planning is separate
Because the plan is just data (target windows and source windows), it can
be inspected, costed, cached, serialised (the serde feature) and
resumed. You can count the
COG tiles or Zarr chunks a reprojection touches, pick an overview level
from the scale before reading, or batch requests across many targets, all
before any I/O.
Resampling
warp resamples a source window into a target, for any sample type
(u8, i8, u16, i16, u32, i32, f32, f64) and any number of
pixel-interleaved bands, in one pass:
let out = warp(&transformer, &SourceBuffer { .. }, dst_ncol, dst_nrow, &opts);
SourceBuffer is the window you read, laid out (row, col, band), with
its offset in the full source image. WarpOptions holds everything else;
WarpOptions::default() is nearest neighbour with GDAL's defaults. Build
it with WarpOptions::new(alg) and the with_ methods, one per option:
let opts = WarpOptions::new(ResampleAlg::Average)
.with_footprint(Footprint::Exact { densify: 1 })
.with_src_nodata(Nodata::Value(-9999.0));
WarpOptions and the option enums are #[non_exhaustive], so new options
can arrive in minor releases. Outside rwarp this means no struct literals
for WarpOptions, GeolocOptions or AverageThresholds, and a _ arm
when matching on the enums.
| Option | Choices | GDAL equivalent |
|---|---|---|
alg | NearestNeighbour, Bilinear, Cubic, Lanczos, Average, Mode | -r |
scaling | WidenWhenDownsampling (default), Fixed { x, y }, Point | -wo XSCALE=, -wo YSCALE= |
footprint | GdalBox (default), Exact { densify }, Adaptive { densify, tolerance } | (average and mode only) |
mode_ties | First (default), Min, Max | -wo MODE_TIES= |
average | thresholds and excluded values | NODATA_VALUES_PCT_THRESHOLD, EXCLUDED_VALUES, EXCLUDED_VALUES_PCT_THRESHOLD |
band_nodata | Partial (default), Unified, PerBand, AnyBand | -wo UNIFIED_SRC_NODATA= |
nodata, mask_band | a nodata value; an alpha band | -srcnodata, -dstnodata, alpha |
dst_col_off, dst_row_off | offset of this tile in a larger target | the chunk's destination offset |
cutline | a Cutline (see Cutlines) | -cutline, -cblend, -wo CUTLINE_ALL_TOUCHED= |
Threads
warp_par and warp_to_par give warp's and warp_to's values bit for
bit, on up to threads threads (0 for all available). They take a
closure that builds the transformer instead of the transformer:
let make = || GenImgProjTransformer::new(src_crs, src_gt, dst_crs, dst_gt)
.map(|t| ApproxTransformer::new(t, 0.125));
let out = warp_par(make, &src, dst_ncol, dst_nrow, &opts, 8)?;
As with GDAL's -wo NUM_THREADS, each thread warps bands of the
target's rows through a transformer of its own, since a libproj
transformer can't be shared between threads. A Sync one can serve them
all as || Ok(&t). What a warp works out once is still worked out once:
the cutline's density over the source, and the kernel scale over the
whole target. So every row comes from the same steps as on one thread.
With one thread nothing is spawned. A whole plan of chunks runs on
threads with warp_chunks_par (Planning reads).
A 0.1° global grid to 2000 by 2000 pixels of south polar stereographic, through libproj and the approximate transformer, on a 32-core machine:
| 1 thread | 8 | 32 | |
|---|---|---|---|
| Bilinear | 0.48 s | 0.08 s | 0.04 s |
| Cubic | 0.89 s | 0.15 s | 0.06 s |
| Average | 0.86 s | 0.14 s | 0.05 s |
Average, Exact { densify: 2 } | 3.44 s | 0.45 s | 0.15 s |
Kernel widening when downsampling
When the output is coarser than the source, GDAL widens the bilinear, cubic and lanczos kernels to cover each output pixel's source area. rwarp does the same by default:
WidenWhenDownsamplingestimates the target/source scale over the target window, as GDAL does per warp chunk, then widens the kernel support toceil(radius / scale)on any axis where the scale is below 1. Upsampling never narrows the kernel.Fixed { x, y }gives the scale, like GDAL'sXSCALEandYSCALE. Use it to make results independent of how the target is tiled.Pointkeeps the fixed 2 x 2, 4 x 4 and 6 x 6 support at every ratio, which isgdalwarp -wo XSCALE=1 -wo YSCALE=1.
As in GDAL, bilinear and cubic widen only once the scale reaches 0.5 or less; lanczos widens at any scale below 1.
One deliberate difference: rwarp estimates the scale over the window actually being warped. GDAL takes its estimate at the top-left of the whole output for every chunk, so a chunked gdalwarp can widen by the wrong amount away from the origin (see GDAL parity).
Average and mode
Both weigh the source pixels a target pixel's footprint covers, measuring area in source pixel space:
Footprint::GdalBoxis GDAL's footprint: the axis-aligned box between the transformed top-left and bottom-right corners of the target pixel, with fractional weights at its edges. It matches gdalwarp, quirks included; under rotation or strong curvature the box can be far from the true footprint.Footprint::Exact { densify }transforms the target pixel's outline and intersects it exactly with the source pixels. With renormalisation over valid pixels,Averageis then first-order conservative remapping. It costs about 25 times the box. The same overlaps are available as a weight table; see Conservative weights.Footprint::Adaptive { densify, tolerance }is the exact footprint with each segment bisected where the transform bends it, until the outline is withintolerance(source pixels) of the true curve. Where the transform is affine it isExact { densify }bit for bit.
Mode counts covered area per value and breaks ties with ModeTies.
Counts are re-compared every time a value's count grows, in scan order, so
First is the tied value that reached the winning count first. GDAL does
this for 8- and 16-bit data; rwarp does it for every type.
Output values
- Integer outputs are clamped to the type and rounded half up,
floor(v + 0.5), as GDAL does with an integer working type. Nearest and mode copy source values and never round. - Nodata avoidance: a resampled value equal to the nodata value is moved off it by one step, so a valid pixel never reads back as missing.
- Source bounds: sample points outside
[0, n)of the source are off the source for every method except average and mode, which use footprints.
Conservative weights
Footprint::Exact measures how much of each source pixel every target
pixel's outline covers, then averages and throws the measurements away.
rwarp::weights keeps them: a sparse table with one entry per overlapping
(target cell, source cell) pair. That table is the weight matrix of
first-order conservative remapping, ESMF's conserve method. Compute it
once, then apply it to every band, time step or variable on the same grids.
use rwarp::weights::{exact_weights, ApplyOptions, GridWindow, Normalization, WeightOptions};
// The source grid needs no data, only its size (and offset, for a window).
let src = GridWindow::new(src_ncol, src_nrow);
let w = exact_weights(&transformer, &src, dst_ncol, dst_nrow, &WeightOptions::new(4));
// Apply to any pixel-interleaved buffer on that source grid.
let opts = ApplyOptions::new().with_src_nodata(Nodata::Value(-9999.0));
let out: Vec<f32> = w.apply(&source_buffer, Normalization::FracArea, &opts);
The transformer is the same one warp() takes (target pixel to source
pixel), so anything rwarp can warp it can make weights for.
What's in a Weights
| Field | Per | Meaning |
|---|---|---|
dst_row, dst_col | entry | target cell, full-grid indices (offsets applied) |
src_row, src_col | entry | source cell, full-grid indices |
frac | entry | area of the overlap as a fraction of the source cell, unrounded f64 |
dst_area | target cell | area of the target cell's outline, in source cells (in world units for a geolocation or mesh source); NaN if it failed to transform |
src_cell_area | entry | for a geolocation or mesh source, the source cell's world area; from PolyMesh::weights_to, the face's area; empty otherwise |
dst_off, dst_size | the target window the weights are for |
Areas are measured in source pixel space, where a source cell has area 1.
For a source on a regular grid in its own CRS that is area in the source
CRS, up to a constant. Target cells have edges straight in target pixel
space, each split into densify segments whose end points go through the
transformer exactly.
A geolocation source (geolocation arrays on the source side of
GenImgGeolocTransformer) is measured in its own world coordinates
instead, since its pixels are not the same size there. The outline's
points go to source world coordinates and are joined by straight lines
there. Each source pixel is the quadrilateral through its corners' world
positions, and the outline is walked onto those cells as
QuadMesh::burn walks a polygon. frac is then a fraction of the
cell's world area, Weights::src_area(k) is that area, and dst_area
is the outline's world area. This is planar area in the arrays'
coordinates: square degrees for longitude and latitude, true area for
arrays in an equal-area CRS. Arrays whose cells are not whole fall back
to source pixel space; see Limits.
A curvilinear grid given by its cells' corners, such as an ocean model's
tripolar grid, is a source through MeshTransformer (in rwarp::mesh).
It is measured the same way, in the mesh's world coordinates, and the
outlines are walked across the mesh's seam and fold. See
Curvilinear grids.
A mesh is a target through MeshTarget: each of its cells is a target
pixel, its outline the cell itself (sides straight in the mesh's
coordinates, densified), measured in the source's space. So frac is a
cell's share of each source pixel, under any measure the source takes
(lonlat_measure for areas on the sphere), and dst_area is the cell's
measure there. See Curvilinear grids.
frac is relative to the source cell, not the target, so it doesn't depend
on how the target is normalised. dst_area gives either normalisation:
With a the source cell's area (Weights::src_area, 1 in source pixel
space):
Normalization::FracArea:S = frac a / (sum of frac a over the target cell), the area-weighted mean over the part of the cell that has source. This is whatwarp()computes. In ESMF it'sfracarea; in xESMF,conserve_normed.Normalization::DestArea:S = frac a / dst_area. A cell half off the source gets half the weight, sosum(value * dst_area)over the target equals the integral of the source over the region the target covers. ESMFdestarea, xESMFconserve.
The default is FracArea, which is not ESMF's: ESMF's default is
destarea, as is xESMF's conservative. To compare with them, ask for
Normalization::DestArea.
Weights::normalised(norm) returns S per entry. Weights::apply
also skips source nodata: FracArea renormalises over the valid entries,
and DestArea doesn't (a missing source cell counts as zero).
Conservation
Neighbouring target cells build their outlines from the same transformed
points, so together they tile source pixel space with no gaps or overlaps.
For every source cell the target grid covers completely, its frac sums
to 1 over the target cells. Where the grid's edge cuts a source cell, the
sum is the covered fraction. This needs no reference to check, and
tests/weights.rs checks it against the coverage of the target grid's
outer boundary:
| Case | Worst |sum - 1| (covered) | Worst |sum - covered fraction| (edge) | Integral, DestArea (relative) |
|---|---|---|---|
| regular to rotated (0.3 rad, 2.3:1), densify 1 / 4 | 2.8e-14 / 1.2e-14 | 7.5e-15 / 5.2e-15 | 1.6e-15 / 1.8e-15 |
| lon/lat 0.5° to EPSG:3031 at 25 km, densify 1 / 4 | 6.0e-14 / 1.6e-14 | 3.3e-14 / 1.2e-14 | 3.8e-15 / 3.1e-15 |
| lon/lat 0.5° to LAEA at 20 km, densify 1 / 4 | 2.1e-15 / 4.4e-16 | 3.3e-16 / 3.3e-16 | 1.9e-15 / 2.4e-15 |
Second order
First order gives each target cell the area-weighted mean of the source
values. ESMF's conserve_2nd (Kritsikis et al. 2017) gives each source
cell a plane instead, f + g · (x − c), and each overlap the plane's
mean over it. The result is still conservative, and a smooth field comes
out far closer.
let opts = WeightOptions::new(densify).with_moments(true);
let w = exact_weights(&t, &src, ncol, nrow, &opts);
let values: Vec<f32> = w.apply_second_order(&buf, Normalization::FracArea, &ApplyOptions::new());
with_moments(true)records each overlap's first moments (Weights::moment), from which its centroid follows. controlledburn's window computes them exactly, beside the area.- The gradient
gcomes from the cell's eight neighbours, by Green's theorem round the polygon of their centres, as ESMF does. It is zero, so first order for that cell, where the neighbours don't surround the cell's centre: at a corner of the source window. cis the centre of the part of the cell the table covers, as in ESMF. The gradient terms then integrate to zero over that part, so underDestAreathe integral is conserved exactly, even where a target's edge or a mask cuts a source cell.apply_second_orderestimates the gradients from the field it is given. A neighbour without data drops out of them, as a cell without data drops out ofapply.Weights::second_order(&src, valid, areas)folds the gradients into one table, as ESMF's weight files hold it. Some of its weights are negative. Use it to write files, for a fixed set of cells with data.areasisNonefor a source measured in its pixels, andweights::source_cell_areas(&t, &src)for one with world cells.
What it gives, from tests/second_order.rs and
tests/esmf_second_order.rs:
- Linear fields come out exactly. A field linear in source pixels is exact to 1e-14 in the interior, planar and on the sphere, where first order is off by 0.16.
- The error is second order. On a quadratic, halving the cell size quarters it exactly. On a smooth sine it is 57 times smaller than first order's.
- The weights are ESMF's, to 6e-14, for a grid onto a grid, inside the source and over its corner. Projected (0.5° lon/lat to EPSG:3031) they differ by up to 0.022. There every overlap is a general polygon, and ESMF centres it on the mean of its vertices rather than its centroid, so ESMF's second order is off by up to 0.035 on a linear field and rwarp's by 1e-14. With ESMF's vertex means in its place, rwarp's table is ESMF's to 1e-12, away from target corners that fall exactly on a source cell's wall.
Moments come from any grid source: a regular grid, planar or under
lonlat_measure, and a grid with world cells (geolocation arrays, a
QuadMesh through MeshTransformer, a MeshSet), onto a grid or onto
a mesh (PolyMesh::weights_onto, MeshSet::weights_onto). For world
cells the planes are in the cells' index space, where rwarp measures
their overlaps: each cell there is a unit square holding its world area
evenly, so the moments are exact centroids and the neighbours are the
eight round a cell in the full grid, whatever piece or band they're in.
That is exact for a field linear in the grid's indices, and second order
for a smooth field on a smooth grid, but not exact for a field linear in
world coordinates (ESMF works in world coordinates instead). On a curved
grid a world quadratic's error falls 3.9 times as the cells halve
(tests/second_order_world.rs).
From a PolyMesh's faces to a grid (weights_to with moments), the
faces have no index space, so their planes are in the grid's, where the
overlaps are measured: its pixels, or a curvilinear grid's indices.
let w = mesh.weights_to(&t, &grid, &WeightOptions::new(densify).with_moments(true))?;
let values: Vec<f32> = mesh.apply_second_order(&w, &faces, Normalization::FracArea, &ApplyOptions::new());
let folded = mesh.second_order(&w, None);
A face's neighbours are the faces sharing a node with it, as in ESMF, each
centred on the part of it the table covers. A field linear in the grid's
space comes out exact to 3e-14 where the faces are whole in the grid
(first order is off by 2.3), and on a quadratic halving both mesh and
grid divides the error by 3.9 (tests/second_order_faces.rs). For a mesh
in longitude and latitude onto a grid in them, the planes are linear in
longitude and latitude. Across a global grid's seam the table carries
the grid's period (Weights::period, for a grid that wraps every whole
number of its columns). So a face the seam cuts has a plane like any
other, and the faces either side take each other as neighbours. With the
seam on the far side of the globe the same mesh comes out the same
(tests/second_order_period.rs). A face round a pole, whose cells take
every column, is first order. Without a period, as at a world-cell grid's
seam in its indices, the gradients there are one-sided: a face the seam
cuts is first order, and a face's neighbour across it is left out.
A limiter. Next to a sharp front a plane can reach past the values round it, so a second-order value overshoots what it is drawn from: below the lowest of its sources, or above the highest. ESMF has no limiter, and none is the default. Ask for Barth and Jespersen's:
let opts = ApplyOptions::new().with_limiter(Limiter::BarthJespersen);
let values: Vec<f32> = w.apply_second_order(&buf, Normalization::FracArea, &opts);
Each source cell's gradient is scaled so that its plane, at each of its
overlaps' centroids, stays within the values of the cell and its
neighbours; under FracArea each target value is then within its
sources' and theirs. One factor per cell keeps the integral as it was.
It works for grids, grids with world cells and a mesh's faces, band by
band (tests/second_order_limiter.rs). It costs some accuracy on a smooth
field, as it flattens planes at extrema too: on a sine, 16 to 72% in rms,
the more the less the field is resolved, still 7 to 49 times closer than
first order. It depends on the field, so a folded table can't hold it.
On the sphere rwarp's planes are in longitude and latitude, under the
spherical measure, and ESMF's in three dimensions, so the two are
different second-order methods, and tests/esmf_second_order_sphere.rs
compares their accuracy, each against exact cell means in its own cells.
Onto a grid both are second order, close for lon/lat onto lon/lat, rwarp
19 times closer projected; onto a mesh rwarp is 5 to 17 times closer
(ESMF centres an overlap on its vertices' mean). From a mesh's faces,
below 60° of latitude rwarp is 1.7 to 4.9 times closer, next to the
grid's seam and away from it alike. Nearer the poles, where a plane in
longitude and latitude fits less well, ESMF is 1.6 times closer for a
geodesic mesh and rwarp 2.5 times for its dual.
Meshes of polygons
An unstructured mesh, ICON's triangles, MPAS's hexagons, a UGRID or ESMF
mesh, is a PolyMesh (in rwarp::mesh): its nodes' coordinates and, for
each face, its nodes in order round it. weights_onto gives the weights
from a grid onto the mesh, and weights_to from the mesh to the grid:
use rwarp::mesh::{PolyMesh, WORLD_GT};
use rwarp::transform::GenImgProjTransformer;
use rwarp::weights::{lonlat_measure, GridWindow, WeightOptions};
// faces as UGRID's face_node_connectivity: up to 6 nodes a face, 0-based,
// padded with -1; straight edges, the shorter way round in longitude
let mesh = PolyMesh::from_padded(lon, lat, &face_nodes, 6, 0)?.with_period(360.0)?;
// or, for an ICON or MPAS mesh, great circles between the nodes:
// let mesh = PolyMesh::from_padded(lon, lat, &face_nodes, 6, 0)?.with_great_circles()?;
// from the mesh's coordinates to the grid's pixels
let t = GenImgProjTransformer::new("EPSG:4326", grid_gt, "EPSG:4326", WORLD_GT)?
.with_source_size([ncol, nrow]);
let grid = GridWindow::new(ncol, nrow);
let opts = WeightOptions::new(4).with_measure(lonlat_measure(grid_gt).unwrap());
let onto = mesh.weights_onto(&t, &grid, &opts)?; // grid to mesh
let to = mesh.weights_to(&t, &grid, &opts)?; // mesh to grid
Each face is measured as a target pixel is. Its edges are cut into
densify pieces in the mesh's coordinates (or refined to
refine_tolerance), go through the transformer to the grid's pixels, and
are measured there under the grid's measure, across the seam and round a
pole as above. Both directions come from the same overlaps, one turned
round, so the pair is consistent. Faces that share an edge get bitwise
the same points on it, so they tile the grid: where the mesh covers a
grid cell, its frac sums to 1 over the faces, as in
Conservation.
- Onto the mesh, face
fis target cell(0, f):dst_sizeis[nface, 1],dst_areathe faces' areas, andapplytakes the grid's values and gives one per face. - From the mesh,
src_colis the face,src_cell_areaits area, andapplytakes the faces' values as a buffernfacewide and 1 high.
weights_onto_par and weights_to_par do the same on threads, with a
transformer built on each (|| GenImgProjTransformer::new(...)), and give
the same table bit for bit.
Edges are straight in the mesh's coordinates, or with
with_great_circles() great circles between nodes in longitude and
latitude, as ICON's and MPAS's are. Great circles need densify above 1
or a refine_tolerance to bend (at densify 1 an edge is its chord in the
grid's pixels). An edge across the equator is cut there first, and a node
on a pole joins its edges along their meridians, whatever longitude it is
written with. Each face's area then converges on its spherical excess and
the faces tile the grid at every tolerance.
Against ESMF, Cartesian (hexagons and triangles over part of a grid,
tests/esmf_mesh.rs), the weights agree to 6e-14 both ways. On the
sphere (a geodesic mesh and its dual with a global 5° grid) the faces'
areas agree to 8e-8, and the weights differ by the grid's cells, which
rwarp bounds by parallels and ESMF by great circles (S to 3.8e-3).
The grid can also be one whose cells are in its world coordinates, as for
exact_weights: geolocation arrays (GenImgGeolocTransformer), a
curvilinear grid by its corners (MeshTransformer over a QuadMesh) or a
whole ocean grid in pieces (SetTransformer over a MeshSet), each with
destination geotransform WORLD_GT, so that its destination coordinates
are the mesh's. Each face is then measured in the source's world and
walked onto its cells, frac is a fraction of a cell's world area
(src_cell_area), and the measure must be planar. For a set, each face
goes to every band's world and is left out of one where it comes out
inside out, such as round the far pole of a polar projection.
Densify
Both settings conserve: conservation comes from the shared edges, not from
how straight they are. They define slightly different cells. With
densify 1 a target cell is the quadrilateral through its four transformed
corners in source pixel space; with more, its edges follow the curve the
target's straight edges map to. Under an affine transform the two agree to
rounding (4e-14). For lon/lat to LAEA at 20 km, frac differs by up to
7e-5 and dst_area by up to 6e-7 relative between densify 1 and 4. Cost
grows with densify (the transform dominates): 4 is about 4 times 1 when
target cells are smaller than source cells.
WeightOptions::with_refine_tolerance(t) (and Footprint::Adaptive { densify, tolerance } in warp()) refines instead of guessing a count.
Each segment is bisected while its transformed midpoint strays more than
t from the chord, d3-geo's adaptive resampling through bigcurve, one
transformer call per level. t is in source pixels, or in world units
for a geolocation or mesh source, where it is one length for every cell.
The error in frac follows t about one to one, and the points grow as
t to the power -1/2. That is the rate a fixed densify has too, so the
gain is in where the points go: only to the edges that bend. On a test
map that bends at one end (tests/adaptive.rs), tolerance 1e-4 matches
densify 64's error with under half its points. Where the transform is
affine nothing is added, and the weights are densify's bit for bit.
Tiles and threads still give the whole grid's weights, since a segment's
points depend only on its ends.
Same numbers as warp()
warp() with Footprint::Exact and ResampleAlg::Average uses the same
lattice and the same per-pixel coverage step. For compatibility with
rwarp 0.2 it snaps coverage within 1e-6 of 1 to 1, drops coverage at or
below 1e-6 and rounds the rest to f32. exact_weights keeps every
positive overlap, unrounded, by default. With
WeightOptions::warp_compatible(densify) it does what warp() does, and
apply(FracArea) then gives warp()'s output bit for bit (tested on the
exact-footprint kernel fixtures and on lon/lat to LAEA with two bands,
nodata, NaN, every BandNodata rule, a mask band and Int16 to Byte).
warp() reduces directly and never stores weights. Use it for a one-off.
Use weights when the same grids are applied many times, when you need
DestArea, or when the weights are the product.
Tiling and streaming
WeightOptions::with_dst_offset(col, row) computes the weights of a target
window, with full-grid indices. A window's lattice is the whole grid's, so
tiles give exactly the whole grid's entries: row bands concatenate, and
column offsets agree too when densify is a power of two.
exact_weights_with(.., |cell| ..) calls back once per target cell with
its entries, storing nothing, for problems too big to hold. Entries cost
24 bytes each (four u32 and an f64). Over a 0.25° global source:
| Target | Entries per target cell | warp() exact | exact_weights | apply |
|---|---|---|---|---|
| LAEA 400 x 400 at 10 km | 2.2 (354 k, 9.8 MB) | 81 ms | 90 ms | 12 ms |
| LAEA 160 x 160 at 50 km | 45 (1.1 M, 28 MB) | 42 ms | 61 ms | 26 ms |
| EPSG:3031 200 x 240 at 12.5 km | 4.6 (220 k, 5.7 MB) | 39 ms | 41 ms | 6 ms |
(densify 1, release build, one thread, PROJ backend.)
exact_weights_par(make, &src, dst_ncol, dst_nrow, &opts, threads) gives
exact_weights' table entry for entry and bit for bit, on several
threads. As for warp_par (Resampling), make
builds a transformer for each thread. Each thread takes bands of the
target's rows into a table of its own, and the tables are joined in row
order. A 0.1° global source to 1000 by 1000 pixels of south polar
stereographic at densify 2 (6.7 M entries) takes 3.0 s on one thread,
0.58 s on 8 and 0.29 s on 32. Through a SetTransformer, the same gives
a whole ocean grid's weights to a grid on threads: ORCA2 to 1° at
densify 8, 2.3 s on one thread and 0.35 s on 8.
Weight files
rwarp has no I/O. Writing ESMF/SCRIP netCDF, xESMF's format or Parquet is wxylib's job, and the columns map directly. With the full grids' widths:
| ESMF / SCRIP | rwarp |
|---|---|
row (1-based, target) | dst_row * dst_ncol_full + dst_col + 1 |
col (1-based, source) | src_row * src_ncol_full + src_col + 1 |
S | normalised(norm) |
area_b | dst_area (in source cells, not steradians) |
frac_b | dst_covered() / dst_area |
Weights::esmf_row_col(dst_ncol_full, src_ncol_full) returns the two index
columns.
Limits
- The measure is the source side's: planar in source pixel space, on
the sphere for a regular longitude/latitude source (
lonlat_measure), or planar in a geolocation or mesh source's world coordinates. A destination in longitude and latitude with a projected source has itsdst_areaplanar in source pixel space, not on the sphere: a destination-side measure waits for a use (decision C4). ESMF measures on the sphere with great-circle edges on both sides. - The antimeridian needs the transformer to say the source wraps. A
target cell whose outline crosses a geographic source's seam is unwrapped
and measured on both sides of it, and one around a pole is closed along
the pole's row, when the transformer reports the source's longitude
period (
Transformer::source_wrap).GenImgProjTransformerdoes for a north-up source of at most 360 degrees once it has the source size (with_source_size, which also gives GDAL'sCENTER_LONG); a transformer that does not report it gets no unwrapping, and such cells are wrong as before. A geolocation source withwith_lon_wrap(true)is handled the same way in its world coordinates, a turn being 360 degrees. - Geolocation sources need whole cells.
GeolocArrays::world_cells()says whether a source is measured in world coordinates, and if not, why. It isn't for arrays with a missing sample, arrays that fold (cells of both orientations, as where a scanning swath's scans overlap), or, withlon_wrap, a swath over a pole (its longitudes don't unwrap consistently) or one spanning more than 360 degrees. Arrays that cross the antimeridian are fine. Those it isn't for are measured in source pixel space as before, which on a curved grid is off by about 1% of a cell along each outline. The choice is made once per set of arrays, so every chunk of a warp uses the same measure. - Destination cells are what a transformer describes. A curvilinear
target works through
GenImgGeolocTransformerwith its bilinear cell definition, or as a mesh throughMeshTarget, whose cells are the mesh's. Onto a mesh, the overlaps are measured in the source's space, so a cell's sides are only as straight there asdensifymakes them: near a pole, in longitude and latitude, use more.
Curvilinear grids
Many datasets have no geotransform: satellite swaths, ocean models on
rotated or tripolar grids, and anything else whose cell positions are given
by 2D longitude and latitude arrays. rwarp handles these with geolocation
arrays, following GDAL's geolocation transformer (alg/gdalgeoloc.cpp).
The model
Each geolocation sample is a point. Between four neighbouring samples, positions are interpolated bilinearly; beyond the outermost samples, they are extrapolated from the closest grid square. Going the other way, from a coordinate to a pixel, rwarp finds the quadrilateral of samples that contains the point and solves the exact inverse bilinear interpolation (two ways to find it, below).
Where a sample sits within its pixel is set by GeolocConvention:
PixelCenter: samples are cell centres, as for CF coordinate variables. Cell edges then fall at the midpoint between neighbouring centres (in the arrays' own coordinates), the outer edges half a spacing beyond the outermost centres, and each corner at the mean of four centres.TopLeftCorner: samples are top-left pixel corners. This is GDAL's default whenGEOREFERENCING_CONVENTIONis not set, so centre coordinates read through the default land half a cell off. Say which one you have.
GeolocOptions also carries pixel and line offsets and steps (for arrays
that sample every Nth pixel), a nodata value for the X array, and whether
longitudes wrap at the antimeridian.
Warping from a swath
GenImgGeolocTransformer puts geolocation arrays on either side of the
usual CRS step. This is examples/curvilinear_swath.rs
(cargo run --example curvilinear_swath):
use rwarp::geoloc_transform::{
GenImgGeolocTransformer, GeolocArrays, GeolocConvention, GeolocOptions, PixelGeo,
};
use rwarp::warp::{warp, Nodata, ResampleAlg, SourceBuffer, WarpOptions};
fn main() -> Result<(), String> {
let (ncol, nrow) = (24, 18);
let mut lon = Vec::with_capacity(ncol * nrow);
let mut lat = Vec::with_capacity(ncol * nrow);
for j in 0..nrow {
for i in 0..ncol {
let (i, j) = (i as f64, j as f64);
lon.push(142.0 + 0.30 * i + 0.08 * j + 0.004 * j * j);
lat.push(-42.0 - 0.22 * j + 0.05 * i - 0.002 * i * i);
}
}
// Coordinates are cell centres, as CF coordinate variables are. GDAL's
// default convention is TopLeftCorner, so say so explicitly.
let opts = GeolocOptions::default()
.with_convention(GeolocConvention::PixelCenter)
.with_lon_wrap(true);
let swath = GeolocArrays::new(lon, lat, ncol, nrow, opts)?;
// Target: a 40 x 32 grid of 10 km pixels in a local LAEA.
let dst_crs = "+proj=laea +lat_0=-45 +lon_0=146 +datum=WGS84 +units=m +no_defs";
let dst_gt = [-420000.0, 10000.0, 0.0, 330000.0, 0.0, -10000.0];
let t = GenImgGeolocTransformer::new(
PixelGeo::Geoloc(swath),
"+proj=longlat +datum=WGS84 +no_defs",
PixelGeo::affine(dst_gt)?,
dst_crs,
)?;
let data: Vec<i32> = (0..nrow)
.flat_map(|r| (0..ncol).map(move |c| (c + 1000 * r) as i32))
.collect();
let src = SourceBuffer { data: &data, ncol, nrow, nbands: 1, col_off: 0, row_off: 0 };
let wopts = WarpOptions::new(ResampleAlg::NearestNeighbour)
.with_src_nodata(Nodata::Value(-1.0));
let out = warp(&t, &src, 40, 32, &wopts);
let covered = out.iter().filter(|&&v| v != -1).count();
println!("{covered} of {} target pixels fall on the swath", out.len());
// The centre row, as source (col, row) pairs.
let row: Vec<String> = out[16 * 40..17 * 40]
.iter()
.map(|&v| if v < 0 { ".".to_string() } else { format!("{},{}", v % 1000, v / 1000) })
.collect();
println!("centre row: {}", row.join(" "));
Ok(())
}
823 of the 1280 target pixels fall on the swath, the same count gdalwarp gives for this grid.
Warping onto a curvilinear grid
The same transformer works the other way round: put the geolocation arrays
on the target side to resample a regular grid onto a swath or model grid.
This is GDAL's DST_METHOD=GEOLOC_ARRAY, and rwarp matches gdalwarp there
too.
Two inverse methods
From a coordinate to a pixel, both methods find a quadrilateral of
samples that contains the point and solve the same exact inverse bilinear
interpolation in it. They differ in how they find it, chosen with
GeolocOptions::with_inverse:
GeolocInverse::QuadIndex(the default) indexes every quadrilateral, plus one ring of extrapolated ones outside the arrays, and takes the first that contains the point in row-major order. Its domain is the union of the quadrilaterals.GeolocInverse::Backmapis GDAL's method (GEOLOC_INVERSE_METHODBACKMAP, GDAL's default): a float32 raster over the arrays' extent, filled by forward-projecting the arrays and patching holes as GDAL does, gives an approximate pixel, and a spiral search of up to 3 squares around it (5 near the poles) finds the quadrilateral. It is ported in GDAL's arithmetic order, so warps through it are identical to gdalwarp's, pixel for pixel.GeolocInverse::BackmapEstimatestops at the backmap's estimate (GDAL_GEOLOC_USE_MAX_ACCURACY=NO). The backmap's oversampling iswith_backmap_oversample(GEOLOC_BACKMAP_OVERSAMPLE_FACTOR, 1.3).
let opts = GeolocOptions::default()
.with_convention(GeolocConvention::PixelCenter)
.with_lon_wrap(true) // what GDAL does for lon/lat in [-180, 180]
.with_inverse(GeolocInverse::Backmap);
Use Backmap to reproduce gdalwarp, and QuadIndex where the answer
should not depend on a sampled raster. On a grid whose quadrilaterals do
not overlap, the two agree wherever both succeed inside the raster. On
the test cases (tests/geoloc_backmap.rs, 2600 to 4900 target pixels
each, nearest neighbour):
| Case | Target pixels that differ | Why |
|---|---|---|
| curved swath, by centres or corners, to lon/lat or polar stereographic | 0 | |
| swath across the antimeridian | 0 | |
| swath with holes in its arrays and source nodata | 0 | |
| overlapping scans ("bow-ties") | 19 of 2880 | where scans overlap, the quad index takes the earlier scan, GDAL the later; each pixel is one row apart |
| ring of cells around the south pole, crossing the antimeridian | 53 of 4900 | the arrays wrap 360 degrees with no quadrilateral across the seam between their last and first column. GDAL's backmap, averaged across the antimeridian, sends the search to the last columns for points whose quadrilateral is in the first few, beyond its radius: GDAL leaves 51 pixels empty along the antimeridian that the quad index fills. Over the seam itself the extrapolated quadrilaterals of both sides overlap, and 2 pixels go the other way |
Outside the raster GDAL's search also succeeds at more points (squares further than one beyond the top and left edges, within its search radius), which no kernel reads.
Cells for coverage: QuadMesh
The geolocation transformer is GDAL's point model. For coverage and
area methods, rwarp::mesh::QuadMesh treats the same grid as cells: the
straight-edged quadrilaterals through the corners (from_corners, or
from_centres with corners at the mean of four centres). It maps world
points to index space and back, and finds the owning cell, optionally
walking from a hint.
CellMap::Bilinear is GDAL's interior map (and matches
GeolocArrays::geo_to_pixel with corner samples). CellMap::EqualArea
splits each cell into four triangles so that areas in index space are
the same fractions of the cell as in the world. That is what makes a
burn in index space give world-area coverage on a curvilinear grid
(design/curvilinear-frontend.md), so coverage always uses it: the
CellMap a mesh is built with, Bilinear by default, is the map of its
point methods (to_index, to_world). The module needs no CRS backend.
QuadMesh::burn takes polygons and points in the grid's coordinates
and returns controlledburn's tables with the grid's own (row, col):
fractions are of each cell's world area, exact for polygon edges that
are straight in those coordinates. It walks each ring through the cells'
triangles, inserting a vertex wherever the ring crosses a cell side or
split spoke, and closes any part outside the grid along the grid's
boundary.
QuadMesh::cover_ring does the same for one small ring into a reused
CoverageWindow, and mesh::Rectilinear is the front end for grids
given by column and row edges. Lines and approx mode are not supported
yet.
For polygons in another CRS, with edges straight there (longitude and
latitude onto a grid in a polar projection, say), burn_from(geoms, to_world, from_world, tolerance, opts) densifies them into the grid's
coordinates first. Each edge is cut into pieces no longer than the
grid's tallest cell is high, then bisected by bigcurve until no chord is
more than tolerance (world units) from the edge's image. The polygons
are cut to the grid's latitudes (its y range in their CRS) first, so the
far hemisphere doesn't come out of a polar projection inside out. With a
declared period, rings are unwrapped across the seam. from_world is
the inverse, used to find where the grid's cells are in the polygons'
CRS; crs_pair(grid_crs, geoms_crs) gives both.
let (to_world, from_world) = rwarp::crs::crs_pair("EPSG:3413", "EPSG:4326")?;
let r = mesh.burn_from(&countries, &*to_world, &*from_world, 1.0, BurnMode::Coverage)?;
use controlledburn::{BurnOptions, Coord, Geometry, Polygon};
use rwarp::mesh::{CellMap, QuadMesh};
let (ncol, nrow) = (3, 2);
let (mut x, mut y) = (Vec::new(), Vec::new());
for j in 0..=nrow {
for i in 0..=ncol {
let (r, a) = (10.0 + 5.0 * j as f64, (30.0 * i as f64).to_radians());
x.push(r * a.cos());
y.push(r * a.sin());
}
}
let mesh = QuadMesh::from_corners(ncol, nrow, x, y, CellMap::EqualArea).unwrap();
let ring = vec![
Coord { x: 5.0, y: 5.0 },
Coord { x: 30.0, y: 5.0 },
Coord { x: 30.0, y: 12.0 },
Coord { x: 5.0, y: 12.0 },
Coord { x: 5.0, y: 5.0 },
];
let res = mesh
.burn(&[Geometry::Polygon(Polygon { rings: vec![ring] })], BurnOptions::coverage())
.unwrap();
assert!(!res.edges.is_empty());
Seams and folds
Outer walls that meet in the world are crossed like any side, with
nothing to declare. That covers a periodic grid whose seam has no jump in
its coordinates (column line ncol on column line 0) and a tripolar ocean
grid, whose last row line folds onto itself. Give the grid its corners in
a projection in which it is one sheet. For an ocean grid's tripolar
north, Lambert azimuthal equal-area on the north pole does this, and its
planar areas are true areas. It holds down to the Southern Ocean. Near
80 S it flattens cells 500 to 1, and an ice-shelf row there can become a
bow-tie, which is refused. A tripolar grid can't be a mesh in longitude
and latitude, since the geographic pole is inside one of its cells.
Coordinates that jump at the seam, such as longitudes, put its two walls
in different places in the plane: declare the period
(below).
Coordinates that jump at the seam (longitudes 360 apart) are not handled
yet.
CF bounds and ocean-model halos
QuadMesh::from_cf_bounds builds a mesh from each cell's own four
vertices: CF's lon_bnds(j, i, 4), or SCRIP's grid_corner_lon(grid_size, 4) with grid_dims giving the columns, then the rows. The vertex order
is found from the data (CF's, or any rotation or reflection of it), and
neighbours must agree on the corners they share.
Ocean-model files store some cells twice (a halo), and those copies have
to go or they are counted twice. A Halo names the columns and rows to
drop. Halo::NEMO_F_PIVOT (eORCA1, ORCA1) and Halo::NEMO_T_PIVOT
(ORCA2) are NEMO's layout as CMIP6 files have it: the last two columns
repeat the first two; the first row is land with collapsed bounds; the
last row repeats one below it. At a T pivot the fold runs through the
centres of the row before that one, so each of its cells is the same
ground as its mirror. The mesh keeps the half of each below the fold, and
a model cell there is two mesh cells, one half each.
The cells round the grid's other points meet the fold elsewhere. U
cells (centred on U points, their corners V points), V cells (corners U
points) and F cells (corners T points) take Halo::nemo(pivot, point),
of which NEMO_F_PIVOT and NEMO_T_PIVOT are the T cells':
| cells | F-point pivot | T-point pivot |
|---|---|---|
| T, U | the last row | the last row, the fold through the centres of the one below |
| V, F | the last row, the fold through the centres of the one below | the last two rows |
The halo also records which grid it is, so a MeshSet pairs a fold
row's halves by NEMO's mirror for its point and knows the pivot for
fill_halo. U cells at a T pivot and V cells at an F pivot have a side
through each pivot, its own mirror, which is cut at its lower end.
A wrong layout is refused rather than counted twice. Neighbours that
don't share corners are refused, and so are cells that overlap, which is
what a halo left in gives (QuadMesh::find_overlap). The flag for the
centre fold is refused on a row that doesn't mirror itself.
use rwarp::mesh::{CellMap, Halo, QuadMesh};
// vertices_longitude / vertices_latitude (ny, nx, 4) from an eORCA1 file,
// projected to Lambert azimuthal equal-area on the north pole
let mesh = QuadMesh::from_cf_bounds(nx, ny, &xb, &yb, Halo::NEMO_F_PIVOT, CellMap::EqualArea)?;
// mesh cell (row, col) is the file's (row + 1, col)
On IPSL's CMIP6 eORCA1 north of 76 S and ORCA2 north of 49 N, mesh cell
areas agree with areacello to 1e-4 in total. A cap north of 60 N, across
the fold, both pivots and the seam, is covered to 1e-10 of its area.
Neither whole file builds as it stands; the cells that stop them are all
land:
- eORCA1's rows south of 76 S are too flattened in that projection.
- IPSL's ORCA2 bounds are corrupt over land between 9 N and 49 N.
Drop such rows with the halo's rows, or repair the bounds, for now.
Longitude: a declared period
A grid in longitude and latitude has its seam's two walls 360 degrees
apart, so they don't meet in the plane. Declare the period with
with_period(360.0), on a QuadMesh or a Rectilinear:
burntakes each polygon at each whole period at which it overlaps the grid, and adds up the pieces. Polygons given from -180 to 180 burn onto a grid from 0 to 360, and one across the seam covers cells at both ends. Polygons are taken as they are in the plane. Give one across the antimeridian with continuous longitudes (170 to 190), and close one round a pole along the pole, as Natural Earth's Antarctica is.locate,to_indexandRectilinear::cellfind a point at any whole period.MeshTransformerunwraps each target pixel's outline and walks it at each whole period at which it reaches the mesh. An outline round a pole is closed along latitude 90 or -90.
Where the seam is makes no difference beyond rounding.
The corners must be continuous. Longitudes stored with a jump, from
[-180, 180) or [0, 360), are refused with a hint. unwrap_grid
(corners or centres) and unwrap_bounds (CF bounds, SCRIP corners)
unwrap them:
use rwarp::mesh::{unwrap_bounds, CellMap, Halo, QuadMesh};
// ORCA2's bounds as CMIP6 stores them, longitudes in [-180, 180): the
// cyclic columns and the northern rows dropped
unwrap_bounds(182, 149, &mut lon_bnds, 360.0)?;
let halo = Halo { cols: [1, 1], rows: [1, 55], ..Halo::NONE };
let mesh = QuadMesh::from_cf_bounds(182, 149, &lon_bnds, &lat_bnds, halo, CellMap::EqualArea)?
.with_period(360.0)?;
with_period refuses a cell half a period wide or more, which is a cell
round a pole, such as the one over the North Pole on a tripolar grid.
Give a tripolar grid's north in a polar projection, as above. Areas in longitude and latitude are planar in
square degrees: a weight is the covered share of a cell's square degrees.
Warping from a mesh
MeshTransformer makes a mesh the source of a warp, with one value per
cell: new(mesh, mesh_crs, dst_gt, dst_crs). It is a Transformer whose
source pixels are the mesh's cells, so exact_weights gives conservative
weights from the mesh to the grid, and warp with Footprint::Exact and
an area method regrids the data. Each target pixel's outline goes to the
mesh's coordinates and is walked onto its cells, across the seam and the
fold. A weight is the share of a cell's area that the outline covers.
use rwarp::mesh::MeshTransformer;
use rwarp::weights::{exact_weights, ApplyOptions, Normalization, WeightOptions};
// the eORCA1 mesh above, in LAEA on the north pole, to 0.5 degrees north of 60 N;
// buf is a SourceBuffer of the mesh's cells, one value each
let laea = "+proj=laea +lat_0=90 +lon_0=0 +R=6371229 +units=m";
let dst_gt = [-180.0, 0.5, 0.0, 90.0, 0.0, -0.5];
let t = MeshTransformer::new(mesh, laea, dst_gt, "+proj=longlat +R=6371229")?;
let w = exact_weights(&t, &t.source_window(), 720, 60, &WeightOptions::new(4));
let sst: Vec<f32> = w.apply(&buf, Normalization::FracArea, &ApplyOptions::new());
The buffer holds the mesh's cells row-major, so mesh cell (row, col) is
source pixel (col, row). Point kernels such as Bilinear map a target
pixel into the mesh's index space through its cell map. They read
neighbouring cells in index space, not across the seam or fold. A mesh
in longitude and latitude with a declared period takes target pixels
across its seam and round a pole, as above.
Against ESMF, on an analytic tripolar cap with a seam and a fold
(tests/esmf_tripolar.rs), with weights from MeshTransformer:
- ESMF in the same plane (Cartesian) has the same cells. The weights agree to rounding.
- ESMF on the sphere joins corners by great circles, and rwarp joins them by straight lines in the projection. For cells 13 to 363 km across, weights differ by up to 2.6e-3 and cell areas by up to 9e-4. The area difference falls with the square of cell size.
Warping onto a mesh
MeshTarget makes a mesh the target: its pixels are the mesh's cells,
ncol by nrow (target_size), one value each. Each target pixel goes to
the mesh's coordinates and then to the source. from_grid does that for a
grid with a CRS, wrapping a longitude/latitude source's longitudes as
gdalwarp does, so cells across its seam or over a pole are measured
whole. MeshTarget::new(mesh, inner) takes any transformer whose
destination geotransform is WORLD_GT: geolocation arrays, or another
mesh through MeshTransformer.
use rwarp::mesh::MeshTarget;
use rwarp::weights::{exact_weights, lonlat_measure, GridWindow, WeightOptions};
// a global 0.25 degree grid onto the eORCA1 mesh above, in LAEA on the
// north pole; areas on the sphere
let laea = "+proj=laea +lat_0=90 +lon_0=0 +R=6371229 +units=m";
let src_gt = [-180.0, 0.25, 0.0, 90.0, 0.0, -0.25];
let t = MeshTarget::from_grid("+proj=longlat +R=6371229", src_gt, [1440, 720], mesh, laea)?;
let [w, h] = t.target_size();
let opts = WeightOptions::new(8).with_measure(lonlat_measure(src_gt).unwrap());
let wts = exact_weights(&t, &GridWindow::new(1440, 720), w, h, &opts);
Each cell is measured on its own, so the mesh's seam and fold don't
matter on this side. Its outline is the cell, sides straight in the
mesh's coordinates, taken to the source at densify points per side and
joined straight there. Near the pole, in longitude and latitude, that
needs a higher densify: the cell over the pole has its corners 90
degrees of longitude apart. warp onto the mesh works the same way, with
point kernels such as Bilinear sampling each cell's centre.
Against ESMF, on the same tripolar cap as the target:
- ESMF in the same plane (Cartesian) has the same cells, and the weights agree to rounding. That holds from a grid in the plane, and mesh to mesh from a lon/lat grid's corners in the plane.
- ESMF on the sphere. The weights differ more this way round, by up to 3e-2 on the cap's smallest cells, 13 to 55 km across near its grid poles. There, a long source edge drawn as a great circle rather than a straight line moves a large share of a small cell. From a grid in the plane, over cells more than 100 km across, the difference is 3e-3, as in the other direction.
Whole ORCA files
One mesh can't hold a whole tripolar ocean grid. North-polar LAEA turns its far south into bow-ties, and longitude and latitude can't hold the cell over the North Pole. Model files also have land cells with damaged bounds: IPSL's CMIP6 eORCA1 has thin flipped strips south of 75 S, and its ORCA2 has garbled cells between 9 N and 49 N. No ocean cell is damaged in either.
MeshSet takes the whole file. Its rows are split into bands, each in a
projection that holds it. Cells that aren't valid there, or overlap
others, are left out where a mask allows: give it the land. What's left
is covered by rectangular pieces, each a mesh of its own, so a cell left
out is a hole and every other cell keeps the file's geometry.
use rwarp::mesh::{Band, Halo, MeshSet, MeshTransformer};
// lon_b, lat_b: the file's bounds (182 x 149 x 4 for ORCA2); land: !(areacello > 0)
// south and north: lon/lat to south- and north-polar LAEA on the model's sphere,
// as CrsTransforms; crs: the same two as CRS strings
let bands = [
Band { rows: 0..54, to_world: &south }, // to about 20 S
Band { rows: 54..147, to_world: &north },
];
let set = MeshSet::from_cf_bounds(182, 149, &lon_b, &lat_b, Halo::NEMO_T_PIVOT, &bands, Some(&land))?;
// conservative weights to a 1 degree grid, sources in the set's numbering
let gt = [-180.0, 1.0, 0.0, 90.0, 0.0, -1.0];
let opts = WeightOptions::new(2);
let w = set.weights_to(|band, mesh| MeshTransformer::new(mesh, crs[band], gt, "+proj=longlat +R=6371229"), 360, 180, &opts)?;
weights_onto goes the other way, onto the set's cells. Both bands are
equal-area on one sphere, so areas from either are square metres of it
and weights add up across them. Where the bands meet, each side's cells
are straight in their own projection and bow apart between corners,
leaving a thin gap covered by neither. At the equator it takes about
dlam² / (6 dphi) of each cell next to it, where dlam and dphi are the
cells' width and height in radians: 2.3% for ORCA2's 2 by 0.5 degree cells
there. So split where the cells are taller, south of the equatorial
refinement; at 20 S it is under 1%.
On IPSL's CMIP6 files (checked in scratch, not in CI), split at 20 S:
| eORCA1 | ORCA2 | |
|---|---|---|
| Built in | 0.13 s, 50 pieces | 0.05 s, 56 pieces |
| Land cells left out | 716 (no ocean) | 801 (no ocean) |
Ocean area vs areacello | 0.9999 | 0.9994; 0.9998 without the halved fold row, whose cells areacello counts whole |
| To 1°: every cell shared out to | 1e-12 (1.0 s) | 8e-14 (1.2 s) |
| From 1°, onto the set: covered to | 5e-10 (0.4 s) | 1e-9 (0.1 s) |
The worst cells covered are 0.03 km² slivers next to the grid poles, where 5e-10 is rounding on a cell a millionth of a source pixel.
weights_to_par and weights_onto_par take the same closures and a
thread count, and give the same tables bit for bit. A piece with at
least its share of the set's cells (the main body of each band) is
measured on every thread, through exact_weights_par. The strips and
other small pieces are measured at the same time, one a thread. To 1°
at densify 8, eORCA1's weights_to takes 3.0 s on one thread and 0.42 s
on 8, ORCA2's 3.6 s and 0.52 s.
SetTransformer makes the set the source of a warp, so warp() takes a
field on the whole grid, one value per cell in the set's numbering, with
any method:
use rwarp::mesh::SetTransformer;
use rwarp::warp::{warp, Footprint, ResampleAlg, SourceBuffer, WarpOptions};
// tos_file: the file's field, halo and all (182 x 149 for ORCA2), NaN on land
let tos = set.from_file_layout(&tos_file, 1)?;
let t = SetTransformer::new(&set, &crs, gt, "+proj=longlat +R=6371229")?;
let [ncol, nrow] = set.size();
let src = SourceBuffer { data: &tos, ncol, nrow, nbands: 1, col_off: 0, row_off: 0 };
let opts = WarpOptions::new(ResampleAlg::Average).with_footprint(Footprint::Exact { densify: 2 });
let out = warp(&t, &src, 360, 180, &opts);
With the exact footprint, each destination pixel's outline goes to both
bands' projections and is walked onto every piece it reaches. So
Average, Mode, Min, Max and the rest see every cell under the
pixel, each weighted by its area. Average is weights_to and apply
bit for bit, and quicker: 0.9 s on either file at densify 2, against 1.1
and 1.2 s. Point kernels find the piece whose cell holds the pixel's
centre and read neighbours in the set's numbering, across pieces and
bands, as GDAL reads geolocation arrays (0.02 s). A polar projection
can't hold its far pole: a pixel round the South Pole comes out round
the whole north band there, turned the other way. An outline turned
against its band isn't measured in it, so an Antarctic grid takes
nothing from the north band.
The other way, onto the set (weights_onto and apply, or burn),
gives a value per cell of the set. to_file_layout puts them back on the
file's grid, its halo masked as CMIP6 files have it, and fill_halo
writes NEMO's halo: the last two columns repeat the first two, and the
north-fold row repeats the row below the fold, mirrored. At ORCA2's
T-point pivot, each cell of the last row is two of the set's cells, and
to_file_layout gives it their mean by area. On both files, cell
centres taken to the set and back, halo filled, come back to 2e-16 in
every row but the first, which holds no cells.
Components of a vector in the grid's own directions (along its rows and
columns, as NEMO's velocities are) on the set's cells, T points, take
to_file_layout_vector and fill_halo_vector. The grid turns half
round across the fold, so the fold's copies change sign (NEMO's psgn = -1), and at a T pivot each half's value is turned round before the two
are averaged. Components east and north are scalars here. On both
files, components of a smooth field along each cell's own directions,
worked out from its bounds, come back to 1e-16, halo and all; as
scalars, the fold row comes back with its sign changed. NEMO turns
round the T pivot's cells too, which are their own mirrors and have no
directions.
Both fills take the point the field is at: Stagger::T, or a field of
the same grid's U, V or F points (the middles of the T cells' east and
north sides, and their north-east corners), whose folds land on other
columns and rows. They follow NEMO 4.0's fold (3.6's takes the last
column of U and F points at an F pivot from the wrong column). On both
files, the positions of all four points and the components along the
cells' sides at U and V points, worked out from the T cells' bounds,
come back exactly with the halo masked and filled.
use rwarp::mesh::Stagger;
// uo_file: a U-point field on the file's grid, its halo masked
set.fill_halo_vector(&mut uo_file, 1, Stagger::U)?;
A set of U, V or F cells (Halo::nemo) takes its own point's fields the
same way. On both files, sets of each point's cells, their corners
worked out from the T cells' bounds (V points the middles of the T
cells' north sides, U points of their east sides, T points their
centres), cover the cap north of 60 N to 2e-7 of its area. Fields of
their cells' centres come back to 2e-16 through the set with the halo
filled, and every kept cell of a fold row through centres pairs with
NEMO's mirror.
warp_to_par gives the same values on several threads, each with a
SetTransformer of its own: || SetTransformer::new(&set, &crs, gt, dst_crs). ORCA2's Average at densify 8 takes 2.3 s on one thread,
0.34 s on 8 and 0.14 s on 32.
MeshSet::burn burns polygons and points in longitude and latitude
onto the set's cells. It takes the bands the set was built with and a
tolerance in the bands' world units, and returns controlledburn's tables
in the set's numbering:
use controlledburn::BurnMode;
// countries: Vec<Geometry> in lon/lat (edges straight in degrees)
let r = set.burn(&countries, &bands, 1.0, BurnMode::Coverage)?;
// r.runs and r.edges: (row, col) of the set's cells, fraction of each cell's area
Each band takes the part of each polygon within its cells' latitudes, widened by its tallest cell. A polar LAEA can't hold the far pole, so without that cut Antarctica in the north band, or a whole-world box, would come out inside out. Edges are straight in longitude and latitude. bigcurve densifies them into each band's projection until no chord is further than the tolerance from the edge's image. A fraction is then good to about the tolerance times the length of edge in the cell, over the cell's area. A polygon cut at 180° or closed along a pole comes out of a polar projection with both sides of the cut on one line. Each ring is split where it meets itself, and that line is taken out before the walk. Where the bands meet, the thin gap between their cells is burned onto no cell.
On the same files (scratch), at a tolerance of 1 m:
| eORCA1 | ORCA2 | |
|---|---|---|
| A whole-world box | every cell kept covered in full | the same |
Five boxes on 1° lines (Arctic, Antarctic, across 180°, across 20 S), against weights_onto from a 1° indicator at densify 64 | 8e-6 | 6e-6 |
| Natural Earth 10 m countries (258, 548k vertices) | 0.70 s | 0.96 s |
The same with burn_par on 8 threads | 0.40 s | 0.44 s |
The same with burn_par_with on 8 threads | 0.15 s | 0.18 s |
The comparison is two separate walks: a polygon into the mesh's index space, and each cell's outline into the source's pixels. On a 30° wide land cell of ORCA2 the two differed by 1e-3 at densify 16, and the gap fell sixteenfold at densify 64, as the outlines' error should. Antarctica lands only in the south band.
Each piece walks only what can reach it. A one-row piece round most of a latitude circle has a box the size of its band's disk. A grid of tiles marks where its cells are, so polygons elsewhere are skipped, and long runs of edges away from it are cut short, 32 edges at a time where their box is away from it. That doesn't change the result: the walk sees the same crossings and the same winding round its interior point. What's left of the time is projecting the polygons and walking the edges that are near.
MeshSet::burn_par(geoms, bands, tolerance, opts, threads) gives the
same records on several threads. The pieces filter, walk and burn their
polygons in parallel. Projecting into each band stays on the calling
thread, since a libproj transform can't be shared between threads. That
is the floor: about 0.3 s for the countries at 1 m, and 1.6 s at
0.01 m, where 8 threads take ORCA2 from 5.6 s to 2.2 s.
MeshSet::burn_par_with(geoms, bands, tolerance, opts, threads, to_world) projects on the threads too, each through a transform of its
own. to_world(k) builds band k's, the same as bands[k].to_world:
let lonlat = "+proj=longlat +R=6371229";
let laea = ["+proj=laea +lat_0=-90 +R=6371229", "+proj=laea +lat_0=90 +R=6371229"];
let to_world = |k: usize| rwarp::crs::crs_pair(lonlat, laea[k]).map(|(_, f)| f);
let r = set.burn_par_with(&countries, &bands, 1.0, BurnMode::Coverage, 8, to_world)?;
The records are the same again. On 8 threads ORCA2 takes 0.92 s at 0.01 m. A libproj transform takes about 5 ms to build, and many threads building at once slow each other down, so on a light burn the most threads isn't always fastest. For the countries at 1 m through libproj, 16 threads took 0.20 s and 32 took 0.31 s.
Overlapping swaths
A mesh is one sheet: from_corners refuses cells of both orientations,
which is what a swath whose scans overlap (the MODIS bow-tie) gives when
its scans are stored as one array. Each scan alone is one sheet, so build
one mesh per scan and offset its rows to the swath's:
let n = rows * ncol; // pixels per scan
for s in 0..nscan {
let (sx, sy) = (&x[s * n..(s + 1) * n], &y[s * n..(s + 1) * n]);
let mesh = QuadMesh::from_centres(ncol, rows, sx, sy, CellMap::EqualArea).unwrap();
let res = mesh.burn(&geoms, BurnOptions::coverage()).unwrap();
// res holds the scan's rows: swath row = s * rows + row
}
Each source pixel gets its own coverage. Where scans overlap, the ground
is covered twice and each scan reports it in full; how to combine them
there (sum, mean, the first scan only) is the caller's choice. The full
example, which checks the area each scan covers, is in the
mesh module docs.
A row or column stored twice, such as an ocean model's halo, keeps its
orientation, and from_corners doesn't check for it (the check costs
about what building the mesh does). QuadMesh::find_overlap finds it,
and from_cf_bounds refuses it.
mesh is public and unstable: it changes more often than the rest of
the crate and may break at any 0.x minor release, though not at a patch
release.
Area methods from a swath
The exact footprint (Footprint::Exact, and exact_weights) measures a
geolocation source with these cells. Each target pixel's outline goes to
the source's world coordinates and is walked onto a QuadMesh of the
source window. Each pixel is the quadrilateral through the positions of
its four corners. So weights are fractions of each source pixel's world
area, and Average weights each pixel by its world area. With
TopLeftCorner samples at whole-number steps that is GDAL's bilinear
model exactly. With PixelCenter the corners are the means of four
centres, as from_centres makes them.
With with_lon_wrap(true), a swath across the antimeridian works the
same way. Its longitudes are unwrapped by continuity, so cells across the
seam are whole, and so is each destination pixel's outline. A destination
pixel round a pole is closed along latitude 90 or -90. Where the arrays
store their seam makes no difference to the weights, beyond rounding.
GeolocArrays::world_cells() says whether this applies to a set of
arrays: not with a missing sample, not where the swath folds, and not for
a swath over a pole, whose longitudes don't unwrap consistently. Those
fall back to source pixel space. Point kernels are unchanged.
Other differences from GDAL
- rwarp treats NaN samples as missing, as well as the X array's nodata value; GDAL compares with the nodata value only.
- Whether longitudes wrap at the antimeridian is the explicit
with_lon_wrap. GDAL decides it from the SRS (geographic, every longitude in[-180, 180]) or forces it withGEOLOC_NORMALIZE_LONGITUDE_MINUS_180_PLUS_180. SWAP_XYand GDAL's experimental quadtree inverse (GDAL_GEOLOC_INVERSE_METHOD=QUADTREE) are not implemented. GDAL keeps the backmap of arrays of 24 megapixels or more in temporary files, with the same arithmetic; rwarp keeps it in memory.
Cutlines
A cutline limits a warp to the source pixels inside a polygon, as
gdalwarp -cutline does. rwarp takes the polygon in source pixel/line
coordinates of the full source image, which is where gdalwarp puts it
before warping:
use rwarp::cutline::{Cutline, CutlineRule};
// Polygons: an exterior ring and its holes, each ring a list of [x, y].
let cut = Cutline::new(vec![vec![exterior, hole]]);
let opts = WarpOptions::new(ResampleAlg::Bilinear).with_cutline(cut);
let out = warp(&transformer, &source_buffer, dst_ncol, dst_nrow, &opts);
Several polygons are a multipolygon (their union).
From world coordinates
-
Cutline::from_geotransform(polygons, src_gt): the polygons are in the source raster's CRS. The map to pixels is affine, so nothing is densified, as in gdalwarp. -
Cutline::from_transformer(polygons, &transformer): the polygons are in whatever aTransformermaps to source pixels. For a cutline in another CRS, build aGenImgProjTransformerfrom that CRS to the source with the identity geotransform[0, 1, 0, 0, 0, 1]on the cutline side, so its "pixels" are CRS coordinates:let t = GenImgProjTransformer::new(src_crs, src_gt, "EPSG:4326", [0.0, 1.0, 0.0, 0.0, 0.0, 1.0])?; let cut = Cutline::from_transformer(lonlat_polygons, &t)?;Edges are densified as gdalwarp densifies them, so that each transformed edge is about one source pixel long.
Rules
| Rule | A source pixel counts when | GDAL |
|---|---|---|
CutlineRule::Centre (default) | its centre is inside | default |
CutlineRule::AllTouched | the polygon covers any of it | -wo CUTLINE_ALL_TOUCHED=YES |
CutlineRule::Exact | always, weighted by the fraction of it covered | (none) |
with_blend_dist(d) is gdalwarp's -cblend d: within d source pixels of
the boundary the density ramps from 1 inside to 0 outside, 0.5 on the line.
Centre ties. A pixel centre exactly on the boundary follows GDAL: on a left edge it is out, on a right edge in, on a top edge in, on a bottom edge out, and a hole whose top edge runs along a line of centres does not cut that line. Ties are decided exactly, and match GDAL on diagonal edges through centres too.
All touched counts a pixel the polygon covers by more than 1e-9 of its area. GDAL walks each boundary line instead, which differs in three places: GDAL also burns a pixel the boundary only touches at its corner (below-right of the corner), skips an edge within 1e-4 of a pixel wall, and burns a single column for an edge less than 0.01 pixels from vertical.
What a cutline does to each method
The cutline becomes a density per source pixel, computed over the source buffer only.
- Point methods (nearest, bilinear, cubic, cubic spline, lanczos): a target pixel whose sample point lands outside the cutline gets no value; pixels outside are dropped from every kernel, like nodata, so cubic falls back to bilinear near the boundary.
- Area methods (average, mode, min, max, quantiles, RMS): pixels outside the cutline are left out, as nodata pixels are.
- Blend distance: point methods interpolate the density along with the value. With a destination nodata the value is kept wherever the density is at least 0.0001; without one it is multiplied by the density, fading to the zero fill, which is what gdalwarp does when warping into a new file. Area methods only use the density as validity, so for them the blend distance widens the cutline.
- Exact: area methods weight each pixel by footprint times coverage
(so a pixel half inside counts half in
Average); point kernels weight each tap by its coverage, and a target pixel gets a value when its sample point's pixel is at least half covered.
Cost
The cutline is rasterized once per warp call, over the source buffer:
the centre rule with controlledburn's centre-rule burn, all touched and
exact with its sparse coverage burn, and the blend ramp only within the
blend distance of each edge. For a 14-vertex star over a 4096 x 4096
buffer that is about 15 ms (centre), 20 ms (all touched, exact) and 20 ms
(blend distance 10) in a release build.
GDAL parity
rwarp is checked against GDAL output, component by component. The test
fixtures are generated by scripts in tests/fixtures/ from a stated GDAL
build, and the tests compare rwarp's results to them.
What has been checked
| Component | Test data | Result |
|---|---|---|
GenImgProjTransformer | Sentinel-2 B04 | 65536 of 65536 pixels identical to pixel_extract |
ApproxTransformer | same | bit-identical to GDALApproxTransform |
compute_source_window | GEBCO global, Fiji LCC | matches GDAL's source windows |
plan_chunks (with ChunkOptions::gdalwarp) | whole lon/lat sources to Mercator, south polar stereographic (pole in the target) and an overhanging LAEA across 180 degrees, -wm 100000 or the default, MEM and 32x32-tiled targets (16 cases, 1 to 28 chunks) | chunk list (target and source windows) identical; kernel scale per chunk within GDAL's logged precision |
Whole-raster chunked warp (warp_chunks) | same, near, bilinear, cubic, lanczos, nodata outside the source | identical to gdalwarp, every pixel, with both CRS backends |
Longitude wrapping (CENTER_LONG), GenImgProjTransformer::with_source_size | regional lon/lat sources across 180 degrees stored as 170..190, -190..-170 and 140..200, a global source in 0..360 and one 361 degrees wide under a -te of 90..270; to LAEA centred on 170 and 180, Mercator windows across 180 and whole-world, south polar stereographic and lon/lat targets (11 cases, near, bilinear, cubic; chunked and in one chunk) | centre longitude as GDAL's (%g); 162 target-to-source and source-to-target points per case through the exact transformer within 7e-13 px of GDAL's (libproj; proj4rs the same away from the poles, where it fails and PROJ returns a point); chunk lists and every output pixel identical to gdalwarp with both CRS backends. Without the wrap, 17% to 61% of each target differs |
| Retry of points just off the source window | same (LAEA, near) | 2 pixels per 10000 differ without it |
| Nearest neighbour | Sentinel-2, IBCSO Mawson | 65536 of 65536 identical to gdalwarp -r near |
| Bilinear, cubic, lanczos | GEBCO at about 1:1 | 65536 of 65536 identical |
| Kernel widening, scale estimate | synthetic, 1.5:1 to 4:1, anisotropic, nodata | within 1e-6 relative of gdalwarp |
| Point kernels at any ratio | same, against -wo XSCALE=1 -wo YSCALE=1 | within 1e-6 relative |
| Average, GDAL box | plus upsampling, overhanging and 30 degree rotated targets | within 1e-6 relative of -r average |
| Average, exact footprint | axis-aligned cases against the box; a 45 degree diamond against the analytic mean | within 1e-5 |
Mode, all MODE_TIES | categorical Byte/Int16/Int32/Float32, 4:1 and 2.78:1, nodata, rotation | identical to -r mode (26 cases) |
| Nodata, per band and unified, average thresholds | single- and three-band Float32, every method | within 1e-6 relative (30 cases) |
| Rounding, clamping, nodata avoidance, source bounds | Byte/Int16/Int32/Float32 | identical (12 cases) |
| Antimeridian split read | GEBCO, Fiji tile | 70 times fewer source pixels than a naive read |
| Geolocation arrays | synthetic swath, both conventions, curvilinear source and target, both inverse methods | coordinates within 1e-6 px; nearest warps identical to gdalwarp -et 0 |
Geolocation backmap inverse (GeolocInverse::Backmap) | 9 synthetic cases: a curved swath by cell centres and by corners to lon/lat (fine and coarse) and south polar stereographic, a polar ring and a swath across the antimeridian, holes in the arrays with source nodata, overlapping scans; -et 0, and -et 0.125 for two | success identical to GDAL's transformer at every target pixel centre (31,356), positions within 5e-10 px; the backmap's estimate (GDAL_GEOLOC_USE_MAX_ACCURACY=NO) the same; 24 warps (near, bilinear, cubic) identical to gdalwarp, every pixel, with proj4rs and the fixtures' PROJ; with an older libproj the nearest warps are identical and interpolated values within 2e-8 relative |
Neighbour on the edge of the transformer's domain (GWKAdjustSrcOffsetOnEdge) | the holes case above | 12 of 4560 pixels differ without it |
| Cutline: centre rule, all touched, blend distance | synthetic Float32; edges and vertices through pixel centres, holes, multipolygons, source nodata, every method but mode, 1:1, 2.78:1 and upsampled, 30 degree rotated, LAEA to lon/lat with the cutline in either CRS | within 1e-6 relative of gdalwarp (67 cases; the reprojected ones identical with libproj and proj4rs) |
| Cutline tie rules | GDAL's own rasterizer on centre-tie polygons | identical, including centres exactly on diagonal edges |
The fixtures use GDAL 3.14.0dev (739fcf03bf). The first geolocation
fixture was made with GDAL 3.8.4; regenerated with 3.14 only the CRS
step's last digits moved (1e-8 px), and GDAL's geolocation code is the
same from 3.12 to 3.14.
Longitude wrapping (CENTER_LONG)
For a source CRS that is geographic in degrees and has a geotransform,
GDALCreateGenImgProjTransformer2 (and so gdalwarp) wraps source
longitudes around the source raster's centre: InsertCenterLong takes the
middle of the smallest and largest x of the raster's four corners, writes
it with %g (six significant digits: a raster centred on 147.1284567 is
wrapped at 147.128), and gives it to the coordinate transformation as its
source centre. OGRProjCT then adds 360 to a source longitude below
centre - 180 and takes 360 from one above centre + 180, once, on the
way into the forward transform and on the way out of the reverse one that
the warper uses. A raster wider than 360 degrees gets no centre, unless the
target is geographic too and gdalwarp's -te crosses 180 degrees. gdalwarp
turns it off (INSERT_CENTER_LONG=FALSE) only to bring a cutline into
source pixels.
rwarp does the same in GenImgProjTransformer once it knows the source
raster's size (with_source_size; with_target_extent for -te).
CenterLong::Off and CenterLong::At choose otherwise, and
source_center_long gives GDAL's value for a transformer built with
with_backend, which does not know its CRSs. Whether a CRS is geographic
in degrees is decided as GDAL does: with libproj, a bound CRS by its base
and a compound CRS by its horizontal part; NTF (Paris), in grads, is not.
Where rwarp deliberately differs
| Behaviour | GDAL | rwarp | Why |
|---|---|---|---|
| Kernel scale estimate in a chunked warp | taken at the top-left of the whole output for every chunk | taken over the window being warped (ScaleOrigin::Chunk, the default; ScaleOrigin::Output or ChunkOptions::gdalwarp for GDAL's) | GDAL's sample points omit the chunk offset; chunked and single-chunk gdalwarp output differ. On the Mercator lanczos fixture, half the pixels differ |
Source window padding under XSCALE/YSCALE | padded for the estimated scale | padded for the smaller of the given and estimated scales (ChunkOptions::pad_for_fixed_scale, default on; off in ChunkOptions::gdalwarp) | a kernel stretched by the given scale is otherwise clipped at the window edge, so tiles warped on their own differ there |
MODE_TIES for 32/64-bit and float data | Min/Max skipped for a value's first occurrence | the 8/16-bit behaviour for every type | the same data should not give different modes by type |
| Geolocation inverse, by default | backmap plus local search | index of all quadrilaterals (GeolocInverse::QuadIndex); GDAL's is GeolocInverse::Backmap, identical to gdalwarp | the index does not depend on a sampled raster. Same answer inside the raster on grids without overlapping quadrilaterals; differs at folds and at the seam of a grid wrapping 360 degrees, where GDAL leaves pixels empty; see Curvilinear grids |
| Cutline all touched | centre rule plus each boundary line walked pixel to pixel, with tolerances | pixels with any covered area (above 1e-9) | GDAL also burns pixels touched only at a corner (below-right of it), skips edges within 1e-4 of a pixel wall, and burns one column for an edge within 0.01 px of vertical even where the polygon is in the column to its left |
Cutline::from_transformer densification | skipped when -cblend is given (unless GDALWARP_DENSIFY_CUTLINE=YES) | always | the helper does not know about blending; densifying only makes the transformed cutline more accurate |
| Longitude wrapping of a geographic source | on whenever the source has a geotransform (the dataset gives its size) | on once GenImgProjTransformer::with_source_size is given | GenImgProjTransformer::new takes no source size; a transformer built as in 0.3.0 wraps nothing, as before |
Not modelled
- The
CENTER_LONGconfiguration option (--config CENTER_LONG), which GDAL applies to the target CRS as well as the source;CenterLong::Atwraps the source only, as aCENTER_LONGin the source CRS does. CHECK_WITH_INVERT_PROJ,STREAMABLE_OUTPUT, and GDAL's shortcut for a translation by whole pixels in chunk planning.- Geolocation:
SWAP_XY, GDAL's experimental quadtree inverse (GDAL_GEOLOC_INVERSE_METHOD=QUADTREE), and its temporary-file backmap for arrays of 24 megapixels or more (same arithmetic as the in-memory one rwarp ports). GDAL's alpha and cutline-density variant of the domain-edge neighbour (GWKAdjustSrcOffsetOnEdgeUnifiedSrcDensity).
GDAL's retry of a sample point just off the source window with the exact
transformer is done: warp() transforms such a point again on its own,
which through ApproxTransformer (exact for five points or fewer, as
GDAL's) is exact, so the kernel stays independent of transformer type.
GDAL issues found along the way
Matching gdalwarp closely turned up behaviour in GDAL itself that looks
unintended: the chunk-offset scale estimate, MODE_TIES by data type, the
MODE_TIES=FIRST documentation, edge weights above 1 in average when a
target pixel overhangs the source, destination nodata avoidance with a float
working type, and two different rounding rules into integer outputs. They
are written up with repros in
mdsumner/osgeo-upstream.
The CENTER_LONG work found that GDAL computes its special points (the
poles, which force grid sampling of a chunk that contains one) without
reprojecting them when the source CRS is geographic:
GDALTransformLonLatToDestGenImgProjTransformer takes (0, +-89.9999) as
target coordinates, so for a projected target they land at its false
origin. On the chunk fixtures this changes no chunk list.
The cutline work found more, not yet in that write-up: all-touched burns
pixels the boundary touches only at a corner, and a whole column along an
edge within 0.01 pixels of vertical; blend distance dilates the cutline for the area methods instead
of feathering it; and -cblend turns off cutline densification.
The geolocation backmap port found these: the inverse's spiral search
admits a square when iX >= -1 || iY >= -1 (probably meant &&), so it
reaches extrapolated squares well beyond the top and left edges but only
one beyond the right and bottom; on arrays wrapping 360 degrees the
backmap averages positions from both ends of the rows across the
antimeridian, and the search radius of 3 cannot recover, leaving a line of
empty pixels along the antimeridian (51 of 4900 in the polar test case);
next to a missing sample PixelLineToXY extrapolates past the last line
along the line only, folding the extrapolated square back over the grid;
isPointOnRingBoundary tests for an exactly zero cross product (an OGR
FIXME), so only vertices and axis-aligned edges count as on the boundary;
GenerateBackMap casts a negative sample position to unsigned; and its
per-block sample ranges drop the last samples beyond the arrays' edge
when the edge falls within two samples of a multiple of 256 (they land in
a block that is never processed). In the warp kernel,
GWKAdjustSrcOffsetOnEdge gives a source pixel that is nodata the value
of a neighbour whenever a corner near it fails to transform, so source
nodata next to holes in geolocation arrays is filled.
API documentation
- This version (built from
mainwith this site): api/rwarp/ - Released versions: docs.rs/rwarp
The crate documentation goes into more detail than this guide on each module, including the GDAL source each part follows, with file and line references.
| Module | Contents |
|---|---|
transform | Transformer trait, GenImgProjTransformer, scanline helpers |
approx | ApproxTransformer |
gcp_transform | GcpTransformer |
geoloc_transform | GeolocArrays, GenImgGeolocTransformer, PixelGeo |
crs | CrsTransform trait and the proj / proj4rs backends |
source_window | compute_source_window |
plan | plan_chunks, ChunkPlanner, ChunkOptions, WarpPlan, Chunk, warp_chunks |
warp | warp, WarpOptions, SourceBuffer, Sample, kernels |
weights | exact_weights, exact_weights_with, Weights, WeightOptions, Normalization, ApplyOptions, GridWindow |
Changelog
All notable changes to rwarp. Dates are when the change reached main.
0.5.1 (unreleased)
Added
-
rwarp::view: which chunks, at which level, a view on a screen needs from a chunked source with resolution levels (a Zarr with multiscales, a COG with overviews), as a value, with no I/O.plan_viewtakes aView(extent and screen size), aSource(per level a geotransform, a size and a chunk shape; whether its CRS wraps, and its poles) and the CRS transforms, and returns aViewPlan: chunk keys nearest the centre first, and per screen tile the level it needs. The screen is planned in tiles of 64 pixels, each with its own level from the local scale (the Jacobian of screen pixel to source,Need::AreaorNeed::Shortest; gdalwarp's-ovr AUTOrule per tile) and its own footprint, unwrapped across the source's seam; a tile holding a pole takes the full row of longitudes; tiles at the limb of a globe are sampled a pixel at a time.ViewOptions::max_chunksandmax_cellsare a budget, met by moving the outermost tiles coarser;ViewPlan::diffgives what to fetch and drop on a pan.plan_single_boxis the one box, one level rule most viewers use, for comparison: for a polar view of a global lon/lat pyramid it asks for 6.5 times the cells, across 180 degrees 8.5 times. The cases are data (tests/fixtures/view/cases.json) for other planners to run. Withserde, the inputs and the plan derive it. In rwarp-wasm:planView,planSingleBox,planViewWith. -
Footprint::Adaptive { densify, tolerance }andWeightOptions::refine_tolerance(with_refine_tolerance): the exact footprint with each segment of the outline bisected where the transform bends it, until it is within the tolerance of the true curve (curvilinear stage 5a, #38). It is d3-geo's adaptive resampling through bigcurve, one transformer call per level. The tolerance is in source pixels, or in world units for a source with cells (geolocation, mesh,SetTransformer). The error follows the tolerance, and the points grow as its inverse square root, as a fixeddensify's do, but they go only where edges bend. Where the transform is affine the weights areExact { densify }'s bit for bit. Tiles, threads andwarp()againstapplyagree bit for bit as before.Footprintisnon_exhaustive, so the new variant is not breaking. -
QuadMesh::burn_fromandRectilinear::burn_from(and_par): polygons and points in another CRS, their edges straight there, densified into the grid's world by bigcurve to a tolerance in world units (curvilinear stage 5b, #38). Each edge is first cut at the grid's tallest cell, and the polygons are cut to the grid's y range in their CRS, asMeshSet::burndoes for a band, so a polygon round the far pole doesn't come out inside out. With a declared period, rings are unwrapped across the seam, and one round a pole is refused. The area burned converges on the closed form at the tolerance's rate, with the points growing as its inverse square root. -
mesh::PolyMesh, a mesh of polygonal faces (ICON's triangles, MPAS's hexagons, a UGRID or ESMF mesh;newfrom compressed rows,from_paddedfrom a padded table), and conservative weights between it and a grid both ways:weights_onto(grid to mesh) andweights_to(mesh to grid), one table of overlaps turned round (conservative stage 5, #39). Each face is measured asexact_weightsmeasures a destination pixel: its edges densified (or refined by bigcurve) through the transformer into the grid's pixels, under the grid's measure, across a seam and round a pole. Faces that share an edge get bitwise the same points on it, so they tile the grid. With a period (with_period), edges go the shorter way round. Against ESMF (Cartesian, hexagons and triangles over part of a grid) the weights agree to 6e-14 both ways. -
PolyMesh::with_great_circles: edges on great circles, as ICON's and MPAS's are, nodes in longitude and latitude (conservative stage 5b, #39). Each edge is cut atdensifyequal angles, or refined by bigcurve's great-circle model; one across the equator is cut there first, where its curve in longitude and latitude turns and refinement can't see it. A node on a pole joins its edges along their meridians, whatever longitude it is written with. Each face's area converges on its spherical excess, at the tolerance's rate (densify's inverse square), and the faces tile a global grid at every tolerance. Against ESMF's spherical maps (a geodesic mesh and its dual, both ways, with a global 5 degree grid) the faces' areas agree to 8e-8; the weights differ by the grid's cells, which rwarp bounds by parallels and ESMF by great circles (Sto 3.8e-3). -
PolyMesh::weights_ontoandweights_towith a grid whose cells are in its world coordinates: geolocation arrays (GenImgGeolocTransformer), aQuadMesh(MeshTransformer) or aMeshSet(SetTransformer), each with destination geotransformWORLD_GT(conservative stage 5c, #39). Each face is measured as such a source measures a destination pixel: its outline in the source's world, walked onto its cells, across a seam and round a pole; for a set, in each band's world, left out of one where it comes out inside out, judged against the face's own turn. Onto a curvilinear mesh the fractions are the faces' clipped overlaps to 1.1e-13; onto a set the faces tile every cell to 1e-12. The world-cell measure is factored out of the exact footprint's lattice (WorldCells); warp and weights hashes are unchanged. -
PolyMesh::weights_onto_parandweights_to_par: on threads, a transformer built on each, the faces in ranges taken in turn and joined in order, the serial table bit for bit (conservative stage 5, #39). A geodesic mesh of 20480 great-circle triangles onto a global 0.25 degree grid, refined: 0.52 s serial, 0.12 s on 8 threads; to the grid 0.63 s and 0.25 s.weights_tonow groups its entries by cell with a counting sort (same order, faster). -
Second-order conservative remapping (conservative stage 6a, #40): ESMF's
conserve_2nd.-
What it does: each source cell's value becomes a plane over the cell, and each overlap takes the plane's mean over it.
-
The API:
WeightOptions::with_moments(true)records each overlap's first moments (Weights::moment), from controlledburn'sCoverageWindow::set_moments.Weights::apply_second_orderremaps a field with them, andWeights::second_orderfolds the gradients into one table, as ESMF's weight files hold it. -
As ESMF does it: the gradient comes from the cell's eight neighbours by Green's theorem, zero where they don't surround the cell. It is centred on the part of the cell the table covers, so the integral is conserved exactly under
DestArea.apply_second_ordertakes the gradients from the field, so neighbours without data drop out of them. -
Checks: fields linear in source pixels come out exact to 1e-14, planar and on the sphere. Halving the cell size quarters the error on a quadratic. The folded table is ESMF's to 6e-14 for a grid onto a grid (new fixtures
<case>.cart2.txt). -
One difference from ESMF: ESMF centres each overlap on the mean of its polygon's vertices, not its centroid. So where a projected grid cuts general polygons from a lon/lat one, ESMF is off by up to 0.035 on a linear field and rwarp is exact. Given ESMF's vertex means, rwarp gives ESMF's table to 1e-12.
-
Scope: any grid source, a grid onto a mesh, and a
PolyMesh's faces onto a grid. -
Sources with world cells (6b): geolocation arrays, a
QuadMeshthroughMeshTransformer, aMeshSet(throughSetTransformerorweights_to), and a grid onto aPolyMesh(weights_onto) or a set (weights_onto). The planes are in the cells' index space under the walk's equal-area map, where the overlaps are measured (decided 2026-11-19). The moments there are exact centroids: they are the overlaps clipped against each cell's four triangles to 3e-15. A field linear in the grid's indices comes out exact to 1e-14. A world quadratic on a curved grid is second order (its error falls 3.9 times as the cells halve) though not exact, as the map is affine only on each quarter of a cell.Weights::second_order(src, valid, areas)takes the window's world cell areas for such a source, from the newweights::source_cell_areas, as a gradient draws on cells the table may not reach. An empty table takes them too (it can't say what its source was). -
A
PolyMesh's faces as sources (6c):PolyMesh::weights_to(and_par) records moments, about each overlap's grid cell corner, and the newPolyMesh::apply_second_orderandPolyMesh::second_orderremap and fold with them. A face's plane is in the grid's space, where its overlaps are measured (its pixels, or a curvilinear grid's indices), as decided on 2026-11-19. Its neighbours are the faces sharing a node, as in ESMF, each centred on the part of it the table covers. A field linear in the grid's space comes out exact to 3e-14, in pixels, on the sphere and in a curvilinear grid's indices (first order is off by 1.2 to 2.3). On a quadratic, halving mesh and grid divides the error by 3.9. At a seam without a period in the table (see below for one with it), the gradients are one-sided: a face the seam cuts is first order (its cells aren't one piece), and a neighbour across the seam is left out (its cells aren't next to the face's). Without moments the tables are as before, bit for bit. -
A limiter (6d), opt-in:
ApplyOptions::with_limiter(Limiter::BarthJespersen)(newweights::Limiter,Offby default, as in ESMF). Barth and Jespersen's: each source cell's gradient scaled so its plane, at each of its overlaps' centroids, stays within the values of the cell and its neighbours. Next to a sharp front, values overshot their sources by 0.1 to 7 without it (fronts over grid cells, world cells and a mesh's faces); with it, each destination value (FracArea) is within its sources' and their neighbours' values to 1e-15, band by band, cells without data left out. It is a factor per cell, so the integral is conserved as before. Inside a window a linear field comes out as without it; on a smooth sine it costs 16 to 72% in rms (planes at extrema are flattened too) and stays 7 to 49 times closer than first order. It depends on the field, so it is forapply_second_orderonly; a folded table can't hold it. Overlaps under 1e-12 of their cell (rounding, 2 to 4% of a table's entries, centroids up to 45 cells off) are left out of the factor and take their cell's value.ApplyOptionsisnon_exhaustive, so the new field is not breaking. -
On the sphere, against ESMF (6d): new fixtures
<case>.sph2.txt, ESMF's sphericalconserve_2nd, for the three second-order grid cases and both sphere meshes both ways (tests/esmf_second_order_sphere.rs). ESMF's method works in three dimensions, rwarp's in longitude and latitude, so the comparison is of accuracy: each against exact cell means in its own cells (great circles for ESMF's, parallels for rwarp's). A grid onto a grid: both second order, 15 to 1,300 times closer than first inside, close to each other for lon/lat onto lon/lat and rwarp 19 times closer projected. A grid onto a mesh: rwarp 5 to 17 times closer than ESMF everywhere (ESMF's vertex means). A mesh onto a grid: below 60 degrees of latitude rwarp is 1.7 to 4.9 times closer, next to the grid's seam (with its period, below) and away from it. Nearer the poles, where a plane in longitude and latitude fits less well, ESMF is 1.6 times closer for the geodesic mesh and rwarp 2.5 times for its dual. -
Across a global grid's seam: a table made with moments on a grid that wraps round the globe every whole number of its columns (
Transformer::source_wrap) records that number in the newWeights::period. That coversexact_weights,PolyMesh::weights_ontoandPolyMesh::weights_to, and their_parforms. It isNonewithout moments, for world cells, or for a period that isn't whole. Second order then takes neighbours across the seam:- a grid cell on the seam takes the cells at the grid's other end;
- a mesh face the seam cuts has its cells taken across it to meet, so it has a plane;
- a face's neighbour across the seam is moved by whole periods to it;
- a face whose cells take every column (round a pole) is first order and no one's neighbour.
With the seam on the far side of the globe, the same mesh comes out the same to 1e-10 (its faces' refinement differs by as much in first order); without the period, by up to 0.22. Within 15 degrees of the seam and below 60 degrees of latitude, a mesh onto a global grid had been near first order (rms 5.3e-2 and 8.1e-2). It is now 9.2e-3 and 1.4e-2, as away from the seam, against ESMF's 1.6e-2 and 6.0e-2 (
tests/second_order_period.rs,tests/esmf_second_order_sphere.rs).Weightsisnon_exhaustive, so the field isn't breaking, and tables without it come out as before, bit for bit. -
Inside, relative to the polygon: a cell's centre is outside its neighbours' polygon if it is past an edge by more than ESMF's 1e-14, or by an angle of more than 1e-9 seen from the edge's start. A centre on an edge by symmetry (as for a geodesic mesh's faces at a pole) had been in or out as the faces' measure rounded. So a whole face's plane came and went with where the seam was. The ORCA2 and second-order bitwise checks and the ESMF comparisons are unchanged.
-
Dependency: controlledburn 0.3.3 (from 0.3.1), for
set_moments.
-
Changed
- Decision N2 (#44): the equal-area split's fallback for a non-convex cell whose balanced line misses its kernel (the best kernel point, the cell flagged inexact) now panics in a debug build, naming the decision, and runs only in a release build. A property test searches for such a cell (59,754 simple non-convex cells in four variants, all exact), as do eORCA1's and ORCA2's sets (6 non-convex cells, all exact).
- Decisions C1 to C4 (#48 to #51) are recorded:
u32indices per axis,FracAreathe default normalisation (now said prominently, with what to ask for to compare with ESMF'sDSTAREAdefault), the lattice shared bywarp()andexact_weights, and the measure on the source side only, said in the docs. - Decision N5 (#47), built: the curvilinear walk (
QuadMesh::burn,cover_ring,ring_to_index, and a mesh source's exact footprint) keeps plainf64orientation tests, made consistent where near-degenerate input meets them. A ring vertex within 1e-12 (index space) of its cell's corner or side is put on it, and a crossing within 1e-12 of an edge's end is put at the end, so a ring through the mesh's own corners covers its cells exactly once and their neighbours not at all (it gave a neighbour a sliver up to 2e-16 before). Each segment is walked from its lexicographically smaller end, so a side two polygons share has bitwise the same path from both (they could differ by 3e-12 in coverage). Property tests (tests/mesh_walk_degenerate.rs, 71,000 checks, 290,000 at twenty times the cases) search vertices on and within rounding of corners, sides, spokes and centres, segments through them, along sides and at shallow angles, against the world clip, complementary tilings and the ring reversed. No failure is left, so adaptive predicates aren't needed. Output changes only in rounding: on ORCA2 as a set,warp()andweights_ontoare bit for bit the same, andweights_toloses 560 entries of at most 1.4e-14 (1,171 at densify 4) and moves no other by more than 1.8e-12.
Fixed
- The curvilinear walk (
QuadMesh::burn,cover_ring,ring_to_index) no longer loses a segment that starts an ulp off a corner (found by the N5 property tests). Such a point can be owned, to rounding, by a cell whose bounding box it is just outside, and the flood of cells along the segment then stopped at that cell. The segment was taken as outside the mesh, and the ring closed by a boundary arc, covering cells it doesn't reach. The owner now counts as touched. Likewise a segment that enters the mesh within rounding of an outer corner (an ulp off it, next to 0) was missed: whether it meets an outer side is now decided by the orientation tests' signs, not a box test they could contradict. And a segment that leaves just past an outer corner now leaves through the wall, not from inside the mesh by up to 1e-12 of its length: short pieces of it are kept. ChunkOptions::split_antimeridianwith the fill ratio split (with_fill_ratio_split) no longer loses that split on a window that spans the source width with no jump in source x (#76), such as a narrow source the target covers whole. Such a window was marked for a split at the jump, its fill ratio replaced, and with no jump found it was split for memory only. Now the jump is looked for first, and a window not split at one, for want of a jump or because splitting saves nothing (round a pole), takes GDAL's rule with its own fill ratio. So vapour'ssst.tif(143 x 286, 140 to 150 E) to EPSG:3031 at 10 km is gdalwarp's 9 chunks, not 1 (a new gdalwarp fixture,narrow_stere_bilinear), and every gdalwarp fixture's plan is gdalwarp's with the option on. Plans that split at a jump are unchanged. rwarp-r gets this with its next crate update.
0.5.0 (2026-11-18)
Whole ocean-model grids as mesh::MeshSet (regridding to and from them,
burning onto them, warping from them, NEMO's halos), curvilinear sources
measured in their own world coordinates, and threads for warps, chunked
warps and weights.
Upgrading from 0.4:
- No public item of 0.4.1 is removed or has a new signature.
Transformergainssource_cellsandsource_wrap, both with defaults. - Values change for the exact footprint (
Footprint::Exact,exact_weights) over geolocation sources, now measured in the source's world coordinates, and across a geographic source's antimeridian and round its poles (see below). Point kernels, the GDAL box footprint and affine sources are unchanged bit for bit. - Mesh burns change on meshes with cells of no area inside them, and for a ring touching a mesh at one point (see Fixed). Other meshes give the same records bit for bit.
- New blanket impls:
Transformerfor&T, andCrsTransformforBox<C>and&C. A crate that implements either trait for a reference or a box of its own type conflicts with them; drop that impl. meshis unstable (decision N4): it may break at a 0.x minor release.
Changed
- The exact footprint (
Footprint::Exact,exact_weights) over a geolocation source measures in the source's world coordinates (#36, stage 3 ofdesign/curvilinear-frontend.md). Each destination pixel's outline goes to source world coordinates and is walked onto the source window's cells under the equal-area map. Each source pixel is the quadrilateral through its corners' positions. So weights are fractions of each cell's world area, andAverageandModeweight each source pixel by its world area. Before, the outline went through the inverse geolocation transform and was measured in source pixel space.- Effect: for a destination pixel inside the source, weight times cell area now sums to the outline's area to 2e-13 (relative). The old measure was off by up to 3e-3 on a polar-sector grid, and 6e-3 on a curved longitude/latitude grid to polar stereographic.
- Across the antimeridian (#72): with
lon_wrap, the arrays' longitudes are unwrapped by continuity, so cells across the seam are whole. Each outline is unwrapped too and walked at each whole turn that reaches the cells, and one that goes round a pole is closed along latitude 90 or -90. The same swath stored with its seam in different places gives the same weights (to 1e-11, the rounding of areas at longitude 180), and weight times cell area sums to the outline's area across the seam. - Fallback: arrays with a missing sample, arrays that fold, and, with
lon_wrap, arrays whose longitudes don't unwrap consistently (a swath over a pole) or span more than 360 degrees keep the old measure, decided once per set of arrays (GeolocArrays::world_cells). - Values change for exact-footprint warps and weights from geolocation sources. Point kernels, the GDAL box footprint and affine sources are unchanged bit for bit. rwarp-r doesn't expose geolocation sources.
- Speed: 3 to 9 times the old measure at densify 2 (4 to 6 microseconds a pixel in the timings for #36).
exact_weights_with'sCellWeightsgainssrc_area, each entry's source cell measure.- The mesh walk (
QuadMesh::ring_to_index, and soburn,burn_parandcover_ring) is 4 to 30 times faster, with the same output bit for bit (checked over 17,806 rings). The changes:- outer sides are found through a bucket index, instead of every outer side being tested for each segment that leaves the mesh;
- a cell is clipped only if the segment meets its bounding box;
- the flood's buffers are reused along a ring.
Natural Earth 10m land onto the warped 1440 x 720 mesh of
examples/mesh_burn_par.rsnow takes 0.24 s withburn(1.15 s before), and 0.06 s at 8 threads (0.23 s).
- Decision N1 (#43): coverage uses the equal-area map on every mesh.
QuadMesh::ring_to_index,burn,burn_parandcover_ringno longer refuse a mesh built withCellMap::Bilinear; they give the same records as on aCellMap::EqualAreamesh. A mesh'sCellMapis now the map of its point methods only (to_index,to_world,local,world),Bilinearby default for GDAL parity. meshsays what "unstable" means (decision N4): the module may break at a 0.x minor release, not at a patch release. Its docs show one mesh per scan for a swath whose scans overlap (decision N3; a doctest), andQuadMesh::from_cornerssays that overlap keeping orientation (a row or column stored twice, such as an ocean model's halo) isn't detected yet.
Fixed
-
QuadMesh::ring_to_index(and soburn,burn_par,cover_ring) on meshes with cells of no area inside them, such as a T-point pivot of a tripolar grid, a collapsed column, or a pole row in a polar projection (stage 4b, #37). Four fixes:- A ring crossing such a cell jumps in index space at one world point. It was joined straight to the next piece's end, misplacing the following cell's coverage. It's now linked through the collapsed cell, and, where that cell is on the boundary, across the walls. A jump the walk can't follow is an error, not a wrong ring.
- The equal-area split of a cell with a side of no length (a triangle) put its centre on the collapsed corner and its unit centre outside the unit square, so it was inexact and placed index points outside the cell. It's now exact.
- A vertex at a collapsed corner took a position from another of the cell's triangles.
- A ring starting on a corner whose owner had no area was taken as starting outside the mesh.
- Bounded meshes without such cells give the same output bit for bit.
- Also: a cell's area that is zero to rounding is now zero, so a cell collapsed onto a line, with its corners not quite on it, no longer takes an orientation and gets the mesh refused as folded.
-
QuadMesh::ring_to_indexfor a ring that touches the mesh at a single boundary point from outside: it left and re-entered at the same point, and the walk closed it along the whole boundary, soburnandcover_ringcovered every cell. Now the ring misses the mesh. A ring around the whole mesh that touches it at one point still covers it. -
The exact footprint (
Footprint::Exact,exact_weights) across a geographic source's antimeridian and around a pole (#36, the cases #11's comparison found). A destination pixel whose outline crosses the source's seam is unwrapped and measured at each whole-period offset that reaches the source; one that goes around a pole is closed along the pole's row. On a global 1 degree grid to 41 x 41 polar stereographic pixels, the weights no longer depend on where the source's seam is (to 5e-14), every pixel's weights sum to its outline's area, and the pole pixel's converge to the polar cap at second order in densify; before, weights across the seam were off by up to 0.92.
Added
-
mesh::MeshSet: a whole curvilinear grid as rectangular pieces, each aQuadMeshin the projection of its band of rows, for an ocean model's whole global grid (stage 4g ofdesign/curvilinear-frontend.md, #37).MeshSet::from_cf_bounds(ncol, nrow, xb, yb, halo, bands, droppable)projects eachBandto its own world. It leaves out cells that are bow-ties there, turned the wrong way or overlapping others, wheredroppableallows (land), and refuses them otherwise. The rest are covered byPieces, so a cell left out is a hole.weights_toandweights_ontogive conservative weights from and onto the whole grid as oneWeightsin the file's numbering, fromexact_weightsthrough aMeshTransformerorMeshTargetper piece. Each piece is measured only over the pixels it reaches.- For ORCA: bands in north-polar and south-polar LAEA on the model's sphere, both equal-area, so areas add up across them. Where they meet the cells bow apart, a gap of about dlam^2 / (6 dphi) of a cell (under 1% at 20 S on ORCA2).
- Checks (
tests/mesh_set.rs): an analytic global tripolar grid with damaged land, conservation to 7e-15, the gap within its bound, the rest unchanged by the damage. On CMIP6's eORCA1 and ORCA2 whole (in scratch): every ocean cell kept, 716 and 801 land cells left out, to 1 degree in about 1 s each. MeshSet::burn(geoms, bands, tolerance, opts)(stage 4h) burns polygons and points in the bounds' coordinates (longitude and latitude) onto the set. It returns controlledburn's tables in the set's numbering, as fractions of each cell's area.- Edges are straight in the bounds' coordinates. bigcurve densifies
them into each band's world to
tolerance(world units). - Each band takes only the polygons' part within its cells' y range, so a polygon round the far pole isn't turned inside out.
- Rings are split where a cut at 180 or along a pole brings them back onto themselves.
- Checks: boxes on the analytic grid against closed-form areas, to
8e-8. On eORCA1 and ORCA2 (scratch): a whole-world box covers
every kept cell, and boxes agree with
weights_ontoto 8e-6. Natural Earth's 10 m countries burn in 0.7 to 1.1 s. - Each piece walks only what can reach it. Tiles mark where its cells are, so polygons elsewhere are skipped and runs of edges away from it cut short, with the same result bit for bit. On ORCA2 the countries went from 3.0 s to 1.1 s.
- Each ring's edges are tested against a piece 32 at a time by their box, one by one only near it, and far runs are cut short a chunk at a time, again bit for bit. On one thread ORCA2's countries take 0.96 s at 1 m (1.1 s before) and 4.6 s at 0.01 m (5.6 s).
MeshSet::burn_par(geoms, bands, tolerance, opts, threads)gives the same records on several threads. Pieces filter, walk and burn their polygons in parallel. Projection stays on the calling thread, since a band's transform needn't be thread-safe. On 8 threads ORCA2's countries take 0.44 s.MeshSet::burn_par_with(geoms, bands, tolerance, opts, threads, to_world)projects on the threads too: each thread builds its own copy of bandk's transform withto_world(k). The records are the same again. On 8 threads ORCA2's countries take 0.18 s at 1 m and 0.92 s at 0.01 m (2.2 s withburn_par).
- Edges are straight in the bounds' coordinates. bigcurve densifies
them into each band's world to
- New dependency: bigcurve 0.3 (pure Rust, no dependencies of its own, builds for wasm).
-
MeshSet::from_file_layout,to_file_layoutandfill_halo: fields between the file's grid (halo and all) and the set's numbering.MeshSetkeeps the file's size and halo (file_size,halo).from_file_layoutdrops the halo, for aSetTransformer's source buffer.to_file_layoutputs a field back with the halo masked by a fill. Where the fold runs through the last row's centres (T cells at a T-point pivot), the two halves of a model cell give it their mean by area.fill_halo(file, nbands, point)writes NEMO's halo for a set with a NEMO halo: the cyclic columns and the north fold's rows, for a field at the grid's T, U, V or F points (Stagger), as NEMO 4.0 writes them (3.6 takes the last column of U and F points at an F pivot from the wrong column). On eORCA1 and ORCA2, cell centres taken to the set and back, halo filled, match the file's to 2e-16 in every row but the first, and the positions of all four points from the T cells' bounds come back exactly.to_file_layout_vectorandfill_halo_vector, for components of a vector in the grid's directions: the fold's copies change sign (NEMO'spsgn = -1), and a fold row's halves are turned round before their mean. Components east and north are scalars here. On both files, components along each cell's own directions come back to 1e-16, halo and all.
-
Sets of NEMO's U, V and F cells:
Halo::nemo(pivot, cells), withPivotand the cells'Stagger(Halo::NEMO_F_PIVOTandNEMO_T_PIVOTare the T cells'). V and F cells at a T pivot drop the last two rows; the fold runs through the centres of the last row kept for T and U cells at a T pivot and for V and F cells at an F pivot.Halo::nemorecords the grid (the fieldnemo: Option<Nemo>), forfill_halo's pivot and to pair a fold row's halves by NEMO's mirror for the cells' point. On both files, each point's cells cover the cap north of 60 N to 2e-7 of its area. -
MeshSet::weights_to_parandweights_onto_par:weights_toandweights_ontoon up tothreadsthreads, the same tables bit for bit. Pieces with at least1 / threadsof the set's cells are measured one after another, each on every thread (exact_weights_par, a transformer per thread from the closure); the rest at once, one a thread, the most cells first; merged in the pieces' order. To 1 degree at densify 8: eORCA1'sweights_to3.0 s on one thread, 0.42 s on 8. -
weights::exact_weights_par:exact_weightson up tothreadsthreads, the same table entry for entry and bit for bit.- Each thread builds its own transformer and takes bands of the target's rows into a table of its own, with one lattice moved to each band; the tables are joined in row order.
- A 0.1 degree global source to 1000 x 1000 south polar stereographic
at densify 2 (6.7 M entries) through libproj: 3.0 s on one thread,
0.58 s on 8. Through a
SetTransformer, ORCA2 to 1 degree at densify 8: 2.3 s and 0.35 s.
-
plan::warp_chunks_par:warp_chunkson up tothreadsthreads, with the same values bit for bit.- Each thread builds its own transformer, and takes bands of each chunk's rows from one queue, about four bands a thread over the plan. So a plan of one chunk runs on every thread, and one of many warps several chunks at once.
- A chunk's source window is copied when its first band starts (borrowed when it is whole rows of the buffer) and dropped after its last. Bands go into the target in the plan's order, as on one thread (the two chunks of an antimeridian gap share a target window).
- A 0.1 degree global grid to 4000 x 4000 south polar stereographic pixels through libproj, 8 chunks: bilinear 1.48 s on one thread, 0.26 s on 8; cubic 3.09 s and 0.46 s.
-
Targets are filled with their nodata by copying (
slice::repeat), not pixel by pixel.warp_chunksof a one-chunk plan to 16 million pixels took 0.94 s on one thread, 1.03 s before. -
warp::warp_parandwarp_to_par:warpandwarp_toon up tothreadsthreads, with the same values bit for bit.- Each thread builds its own transformer with a closure, as GDAL's
-wo NUM_THREADSclones one a thread (a libproj transformer can't be shared). It takes bands of the target's rows from one queue. - What a warp works out once (the cutline's density over the source, the kernel scale over the whole target) is worked out once. The exact footprint's lattice is built once a thread and moved to each band.
- A 0.1 degree global grid to 2000 x 2000 south polar stereographic pixels through libproj: bilinear 0.48 s on one thread, 0.08 s on 8; the exact-footprint average 3.4 s and 0.45 s.
Transformerfor&T, so aSynctransformer serves every thread as|| Ok(&t).
- Each thread builds its own transformer with a closure, as GDAL's
-
mesh::SetTransformer: aMeshSetas a warp source (stage 4i ofdesign/curvilinear-frontend.md, #37), forwarp()andexact_weightsfrom a whole ocean grid in pieces with every method.- Source pixels are the set's cells in its numbering, so a field on the whole grid (less its halo) is one source buffer.
- Area methods with the exact footprint walk each destination pixel's
outline in every band's world onto each piece it reaches, into one
reduction.
Averageisweights_toandapplybit for bit, and on ORCA2 to 1 degree 0.88 s against 1.21 s. An outline turned inside out round a polar projection's far pole isn't measured in that band. - Point kernels map into the set's index space through the piece that holds the point, and read neighbours across pieces and bands.
-
SourceCellsgainsworlds,dst_to_world_inandsheets(withSourceSheet), defaulted to one world and one sheet, for sources whose cells are in several worlds.MeshTargetpasses them on. Sources that are one sheet warp and weigh as before, bit for bit. -
CrsTransformforBox<C>and&C(C: CrsTransform + ?Sized), socrs_pair's boxed transforms go where aT: CrsTransformis asked for, such asMeshSet::burn_par_with'sto_world. -
mesh::MeshTarget: aQuadMeshas a warp target, for regridding onto a curvilinear grid given by its corners, such as an ocean model's tripolar grid (stage 4f ofdesign/curvilinear-frontend.md, #37).- How: target pixel
(col, row)is mesh cell(row, col). A target pixel goes to the mesh's world coordinates and then through an inner transformer to the source.from_grid(src_crs, src_gt, src_size, mesh, mesh_crs)makes that aGenImgProjTransformer, wrapping a lon/lat source's longitudes as gdalwarp does.new(mesh, inner)takes any transformer whose destination geotransform ismesh::WORLD_GT: geolocation arrays, or another mesh (MeshTransformer), for mesh to mesh. - What it gives:
exact_weightsmeasures each cell as a target pixel in the source's space, under any measure (lonlat_measurefor areas on the sphere), across a lon/lat source's seam and over its pole.warp()regrids onto the mesh with any kernel; point kernels sample each cell's centre. - Checks (
tests/mesh_target.rs): in one plane, the overlaps are the mesh source's transposed (2e-14), and mesh to mesh is symmetric. From a global lon/lat grid every cell is covered in full and the seam's position doesn't matter.warp()isWeights::applybit for bit. - Against ESMF onto the tripolar cap (
tests/esmf_tripolar.rs, newonto_tripolarfixtures fromgen.py; the existing fixtures are unchanged bit for bit): Cartesian in the plane to rounding (3e-13); spherical recorded, S up to 3e-2 on the cap's smallest cells and 3e-3 over cells more than 100 km across.
- How: target pixel
-
A declared period for coordinates that jump at the seam, such as longitude:
QuadMesh::with_periodandRectilinear::with_period(stage 4e ofdesign/curvilinear-frontend.md, #37).- Polygons:
burn,burn_parandcover_ringtake each polygon at each whole period at which it overlaps the grid, so polygons from -180 to 180 burn onto a grid from 0 to 360, and across its seam. - Points:
locate,locate_all,to_indexandRectilinear::cellfind a point at any whole period. - A mesh source:
MeshTransformerover a mesh with a period takes target pixels across its seam, and round a pole (closed along latitude 90 or -90). mesh::unwrap_gridandmesh::unwrap_boundsmake longitudes stored with a jump ([-180, 180),[0, 360)) continuous;from_cornersandfrom_cf_boundsname them when they refuse such corners.- Refused: a cell half a period wide or more (round a pole, as at a
tripolar grid's north), and a mesh that goes round more than once.
find_overlapincludes the period once it is declared. - Checks (
tests/mesh_period.rs): generator 5, a regular global grid with its columns rotated, against controlledburn's regular burn (bitwise atf32); the same weights wherever a mesh's seam is, for a lon/lat destination and a polar one whose centre pixel holds the pole;warp()againstWeights::apply. - Meshes without a period are unchanged bit for bit.
- Polygons:
-
mesh::MeshTransformer: aQuadMeshas a warp source, for data with one value per cell on a curvilinear grid given by its corners, such as an ocean model's tripolar grid (stage 4d ofdesign/curvilinear-frontend.md, #37).- Constructors:
new(mesh, mesh_crs, dst_gt, dst_crs)with the CRS backend, orwith_backendwith your ownCrsTransforms. - What it gives: it reports the mesh as the source's cells
(
Transformer::source_cells). Soexact_weightsgives conservative weights from the mesh, as fractions of each cell's world area across the seam and fold, andwarp()withFootprint::Exactregrids with the area methods. - Point kernels go through the mesh's cell map (
QuadMesh::to_index). - Checks:
warp()withAverageisWeights::apply(FracArea)bit for bit, every cell's weights sum to 1, and source windows tile the mesh (tests/mesh_transformer.rs).
- Constructors:
-
QuadMesh::window: a window's cells as a mesh of their own. -
ESMF on a tripolar grid (stage 4c of
design/curvilinear-frontend.md, #37;tests/esmf_tripolar.rs). The weights come fromexact_weightsthroughMeshTransformer, on an analytic tripolar cap with a seam into one pole and an F-point fold. They are compared on two destinations: a grid in the cap's own plane, and lon/lat up to the pole.- Cartesian ESMF in the plane: the weights agree to rounding (3e-14).
- Spherical ESMF: the differences are great-circle edges, recorded as ceilings. S differs by up to 2.6e-3 and areas by up to 9e-4, and the area difference falls with the square of cell size.
- The NEMO layout of the same grid gives the same mesh to the bit.
- Fixtures come from
tests/fixtures/esmf/gen.py, which now takes case names. Its existing fixtures are unchanged bit for bit.
-
QuadMesh::from_cf_bounds: a mesh from each cell's own four vertices, CF bounds (lon_bnds(j, i, 4)) or SCRIP corners (grid_corner_lon(grid_size, 4)), with aHaloof rows and columns dropped first (stage 4b, #37, decision N3).- Vertex order: found from the data (CF's or any rotation or reflection of it).
- Shared corners: neighbours must share them, to a thousandth of a cell.
- Overlap: refused, as a halo left in gives.
- NEMO:
Halo::NEMO_F_PIVOTandHalo::NEMO_T_PIVOTare the ORCA layouts as CMIP6 files have them (the last two columns, the first row and the last row), for the T cells;Halo::nemogives the cells round the grid's other points (above). At a T pivot the row the fold runs through is halved, and its model cells are two mesh cells. - Real data: checked on IPSL's eORCA1 and ORCA2. Areas agree with
areacelloto 1e-4 in total, and a cap over the fold is covered to 1e-10 of its area. Both files have land cells (eORCA1 south of 76 S, flattened by a north-polar projection; corrupt bounds in ORCA2) that are refused, so for now those rows are dropped.
-
QuadMesh::find_overlap: two cells that overlap, a point inside one owned by the other too, for copies that keep orientation, whichfrom_cornersdoesn't check. -
QuadMesh::ring_to_index, and soburn,burn_parandcover_ring, cross outer walls that meet in the world: a periodic grid's seam (column linencolon column line 0) and a tripolar grid's fold (the last row line on itself, cornerion cornerncol - i), with nothing declared (stage 4a ofdesign/curvilinear-frontend.md, #37). Give the grid's corners in a projection in which it is one sheet: for an ocean grid's tripolar north, Lambert azimuthal equal-area on the north pole, whose planar areas are true areas. The walls need to agree only to rounding.- Before: a ring crossing a seam or fold was joined across the mesh in index space, and cells along the crossing were off by up to a whole cell.
- Bounded meshes: the same output bit for bit. Tested against the
per-cell world clip on an annulus, a fold and a tripolar disk
(
tests/mesh_glued.rs). - Not yet: coordinates that jump at the seam (longitudes 360 apart).
-
Transformer::source_cellsandtransform::SourceCells: a transformer reports a source whose pixels are cells in its own world coordinates. It provides the map from destination pixels to source world coordinates (dst_to_world) and the cells of a source window (mesh), for the exact footprint. DefaultNone.GenImgGeolocTransformerwith geolocation arrays on the source side, andGeolocArrayson its own, report it whenGeolocArrays::world_cells()isOk;ApproxTransformerpasses it through, withdst_to_worldunapproximated.SourceCells::lon_wrap(defaultfalse) says world x is longitude that wraps. -
GeolocArrays::world_cells, whether the exact footprint measures a source with these arrays in world coordinates (and if not, why), andGeolocArrays::window_mesh, a source window's cells. -
Weights::src_cell_area: each entry's source cell area, for a geolocation source (empty otherwise, and not serialised when empty).Weights::src_areauses it. -
Transformer::source_wrapandtransform::SourceWrap: a transformer reports a source that wraps in longitude (its period in source pixels and the rows of the poles), for the exact footprint. DefaultNone;GenImgProjTransformerreports it for a north-up geographic source of at most 360 degrees wrapped around a centre longitude (afterwith_source_size), andApproxTransformerpasses it through.
0.4.1 (2026-11-16)
Added
QuadMesh::burn_parandRectilinear::burn_par: the mesh burns on up tothreadsthreads (0 for all available), with the same result asburn, record for record. The ring walk into index space runs on contiguous chunks of the geometries of about equal vertex counts, taken in turn by the threads, and the burn uses controlledburn'sburn_par. Natural Earth 10m land (6,837 polygons, 446,175 vertices) onto a warped 1440 x 720 mesh: 1.16 s withburn; 0.58 s, 0.31 s and 0.24 s at 2, 4 and 8 threads, and no faster past 8, as one geometry is never split (the largest, 19% of the vertices, takes 0.33 s alone).examples/mesh_burn_par.rstimes it.
0.4.0 (2026-11-12)
Changed
- controlledburn 0.3.1 (from 0.2.4). Breaking for rwarp because its types
are in rwarp's API (
weights::Measure, andGeometry,BurnOptionsandBurnResultinQuadMesh::burnandRectilinear::burn). Options are#[non_exhaustive]in 0.3, so build them withBurnOptions::coverage()and thewith_*methods. A multi-part geometry now gets one record per cell in a mesh burn (merge_parts, on by default);BurnOptions::paritykeeps one per part. Cutlines burn each polygon separately and are unchanged. Otherwise the test suite gives the same results as on 0.2.4.
0.3.3 (2026-11-12)
Changed
ChunkOptions::split_antimeridianno longer reads the whole source width for the columns at the jump (the gap). Each gap pixel needs only one edge of the source, so the gap becomes two chunks on the same target window, one source window at each edge, sampled every half pixel and padded for the gap's own kernel scale. A 384x384 Lambert azimuthal target centred on 180 degrees over GEBCO at overview 3 reads 200,600 source pixels instead of 2,257,200, with the same values (exact transformer; nearest, bilinear and cubic; Int16, Float32 and Byte).- The split is kept only when it reads under half of the full-width window, so a target around a pole (where every longitude is needed) keeps GDAL's plan, and it no longer depends on the fill ratio split being on.
warp_chunksplaces only the pixels a chunk wrote (not equal to the fill, NaN equal to NaN), through the newplan::merge_tile. For chunks that don't overlap this is the plain copy it was.
0.3.2 (2026-11-04)
Added
- The curvilinear front end, stage 2 of
design/curvilinear-frontend.md(unstable):QuadMesh::ring_to_indexwalks a world ring into the mesh's index space, cutting each segment at every cell side and split spoke it crosses (Cyrus-Beck clipping per triangle over a flood of the cells it passes, so vertices, corners and centres on a segment need no special case). A cut point is placed by its parameter along the edge's canonical direction, so rings sharing an edge get bitwise the same point. Stretches outside the mesh are replaced by the boundary arc whose loop with the excursion does not wind around the mesh; a ring around the whole mesh gives its outline.QuadMesh::burnburns polygons (holes, multipolygons) and points through controlledburn with the mesh's own(row, col)and fractions of each cell's world area;QuadMesh::cover_ringdoes one small ring through a reusedCoverageWindow.mesh::Rectilinearis the same for grids given by column and row edges (cut at every wall, piecewise linear per axis). Checked against world-space clipping of every cell (Sutherland-Hodgman per split triangle) on rotated, jittered, non-convex, polar, sheared and flipped meshes with polygons crossing the boundary, holes and vertices steered onto corners and centres; against the affine burn for a rotated grid; and rectilinear against the mesh, all to 2e-6 (controlledburn'sf32fractions). Lines and approx mode are refused for now. (2026-11-01) meshmodule, stage 1 ofdesign/curvilinear-frontend.md(unstable):QuadMeshholds a curvilinear grid as straight-edged quadrilateral cells (from_corners,from_centres), refuses bow-ties and folds, and maps between world coordinates and index space withCellMap::Bilinear(GDAL's model; equal toGeolocArrays::geo_to_pixelwith corner samples, to 1e-9) orCellMap::EqualArea(four triangles per cell with matching area shares, so index-space area fractions are world-area fractions; checked to 1e-9 on jittered, non-convex, polar and sheared grids, where the bilinear measure is off by more than 1e-3). Every point has at most one owning cell: side orientations are computed once in a canonical direction, and points on a shared wall go to the low-index cell.locatewalks from a hint and falls back to CSR buckets built on first use;locate_allreturns every owner (for checks). No CRS: builds with--no-default-features. (2026-10-31)- A spherical measure for conservative weights (stage 3a of
design/conservative.md):WeightOptions::with_measurewithweights::lonlat_measure(src_gt)measures areas on the sphere for a source on a regular longitude/latitude grid, through controlledburn'sMeasure::CosLatitude(closed-form edge integrals ofcos(lat); the cell partition and conservation are unchanged).Weightsrecords themeasure,Weights::src_area(k)gives an entry's source cell measure, andnormalised,dst_coveredandapplyweight overlaps by it; for the default planar measure every cell is 1 and results are unchanged, bit for bit. Exact against closed-form lon/lat box overlaps on the sphere (to 1e-14). Needs controlledburn 0.2.4. (2026-10-29) - ESMF oracle suite (stage 2 of
design/conservative.md,tests/esmf.rs): six cases, each against ESMPy 8.9.1's first-order conservative weights in Cartesian source pixel space (rwarp's cell definition: equal to about 1e-12) and on the sphere with great-circle edges (differences recorded as ceilings to shrink). Fixtures fromtests/fixtures/esmf/gen.py, run inghcr.io/hypertidy/gdal-r-esmfby.github/workflows/esmf-fixtures.yml. (2026-10-29)
Changed
- The
serdefeature also enables controlledburn's, forMeasureinWeightOptionsandWeights. (2026-10-29)
0.3.1 (2026-10-28)
Added
- Longitude wrapping of a geographic source, GDAL's
CENTER_LONG:GenImgProjTransformer::with_source_sizelets the transformer wrap source longitudes around the source raster's centre as gdalwarp does (InsertCenterLong,OGRProjCT), so a source stored as 170..190, -190..-170 or 0..360 is found by a target crossing 180 degrees.CenterLong(Auto, the default;Off;At(lon),#[non_exhaustive]) withwith_center_long,with_target_extentfor gdalwarp's-te,center_long(),source_center_longfor GDAL's centre, andcrs::is_geographic_degrees. A transformer built withoutwith_source_sizewraps nothing, as before. Checked against GDAL 3.14.0dev on 11 cases across 180 degrees (LAEA, Mercator, polar stereographic, lon/lat targets; chunked and whole): centres, exact transformer points, chunk lists and every output pixel, with both CRS backends. The LAEA chunk fixtures are back across 180 degrees. Theprojfeature now also depends onproj-sys(already a dependency ofproj), to ask PROJ whether a CRS is geographic. weightsmodule: conservative remapping weights from the exact footprint, as values (stage 1 ofdesign/conservative.md).exact_weightsreturnsWeights, one entry per overlapping (target cell, source cell) pair with full-grid indices and the overlap as an unroundedf64fraction of the source cell, plus each target cell's outline area in source pixel space (dst_area,NaNwhere it failed).Weights::normalisedgives ESMF'sSunderNormalization::FracAreaorDestArea;Weights::applyapplies the weights to one or more bands, skipping source nodata;Weights::esmf_row_colgives ESMF/SCRIP's 1-based flattened indices.exact_weights_withstreams them per target cell.WeightOptions(densify, target offset for tiling, drop and snap tolerances,f32rounding;WeightOptions::warp_compatible),ApplyOptionsandGridWindow, all#[non_exhaustive]with builders; serde derives behindserde.apply(FracArea)with warp-compatible weights reproduceswarp()withFootprint::ExactandAveragebit for bit.warp()shares the lattice and per-pixel coverage step and its output is unchanged. (2026-10-28)- GDAL's backmap geolocation inverse, as an option beside the quad index:
GeolocOptions::with_inverse(GeolocInverse::Backmap)(GeolocInverse:QuadIndex, the default;Backmap;BackmapEstimateforGDAL_GEOLOC_USE_MAX_ACCURACY=NO;#[non_exhaustive]), withwith_backmap_oversample(GEOLOC_BACKMAP_OVERSAMPLE_FACTOR) andGeolocArrays::backmap_grid. Ported from GDAL 3.14 in its arithmetic order (float32 backmap,GDALFillNodatahole filling, the spiral search), by way of wxylib'swxy-warp(geoloc.rs, GDAL 3.12; the geolocation code is unchanged since), addingPIXEL_OFFSET/STEP. Checked against GDAL 3.14.0dev on 9 new cases (swath by centres and by corners, lon/lat and polar stereographic targets, a polar ring and a swath across the antimeridian, holes in the arrays with source nodata, overlapping scans): success and position at every target pixel, the backmap's estimate, and 24 warps (near, bilinear, cubic;-et 0and0.125) identical to gdalwarp, every pixel, with proj4rs and the fixtures' PROJ (with an older libproj, nearest identical and interpolated values within 2e-8 relative). Where the two inverses differ, and why, is in the curvilinear guide. (2026-10-28)
Changed
- The chunk fixtures' special points are computed as GDAL computes them for
a geographic source (not reprojected; see
ChunkOptions::special_points). No chunk list changes. warp()does GDAL'sGWKAdjustSrcOffsetOnEdge: when a corner of the source buffer fails to transform forward and a sample point lands on an invalid source pixel whose corners fail too, a valid neighbour (right, below, left, above) is used instead. This changes output only where the transformer has holes or edges inside the source, as geolocation arrays with missing samples do (12 of 4560 pixels in the holes test case, now identical to gdalwarp).warp()therefore calls the transformer source to destination too, for such pixels only. Point methods; GDAL's variant for alpha and cutline densities is not reproduced. (2026-10-28)- The geolocation swath fixture is regenerated with GDAL 3.14.0dev (was 3.8.4): positions moved by up to 3e-8 pixels (PROJ), nothing else.
- controlledburn 0.2.3 (corner passes, near-coincident edges, exact centre
ties). The cutline centre rule now matches gdalwarp on centres exactly on
diagonal edges: 5 pixels of the
mask_diamond_tiefixture that differed now agree. They came from controlledburn 0.2.2's rounded intercepts; the parity page had put them down to GDAL.
0.3.0 (2026-10-28)
This release changes the API: options types are #[non_exhaustive].
Changed
warp()retries a sample point that lands less than one pixel outside the source buffer by transforming it again on its own, as GDAL does (GWKCheckAndComputeSrcOffsets). ThroughApproxTransformerthat is exact, so interpolation error no longer drops pixels at the edge of a chunk's source window; with an exact transformer nothing changes. Point methods only (nearest, bilinear, cubic, cubic spline, lanczos), as in GDAL. (2026-10-28)WarpOptions,GeolocOptionsandAverageThresholdsare#[non_exhaustive], as areResampleAlg,KernelScaling,Footprint,BandNodata,Nodata,DstNodata,DataTypeandGeolocConvention. New options and methods can then come in minor releases. Outside rwarp, build options withWarpOptions::new(alg)and thewith_methods (GeolocOptions::default().with_convention(..), and so on) instead of struct literals, and add a_arm when matching on the enums. Fields stay public for reading and assignment.
Added
WarpOptions::newandwith_builder methods onWarpOptions,GeolocOptionsandAverageThresholds.planmodule:plan_chunksandChunkPlannergive gdalwarp's chunk list as values (WarpPlanofChunks: target window, source window, fill ratio, kernel scale), following GDAL 3.14'sCollectChunkListandComputeSourceWindowexactly: warp memory limit (-wm) and per-pixel cost, fill ratio splits,OPTIMIZE_SIZEon target blocks, special points, the forward probe,SAMPLE_GRID,SAMPLE_STEPS,SOURCE_EXTRA.ChunkOptions(builders,#[non_exhaustive]);ChunkOptions::gdalwarpfor gdalwarp's planning exactly; an optional round-trip check for backends that do not fail at a projection's antipode; the antimeridian split of 0.2'scollect_chunk_listassplit_antimeridian.warp_chunkswarps a plan from a source buffer in memory. Ported from wxylib'swxy-warp(chunked.rs). (2026-10-28)serdefeature:Serialize/DeserializeforWarpPlanandChunk. (2026-10-28)- Parity fixtures for whole rasters warped in many chunks
(
tests/chunks.rs,tests/fixtures/chunks/): seven gdalwarp cases, chunk lists and output identical. (2026-10-28) - Cutlines (gdalwarp
-cutline):WarpOptions::cutline/with_cutline, and thecutlinemodule withCutline(polygons in source pixel/line),CutlineRule::Centre(GDAL's default, with its tie rules),CutlineRule::AllTouched(CUTLINE_ALL_TOUCHED), blend distance (-cblend), andCutlineRule::Exact, which weights each source pixel by the fraction of it the cutline covers (not a GDAL mode).Cutline::from_geotransformandCutline::from_transformer(densified as gdalwarp does) map world geometry to source pixels;Cutline::densityis the per-pixel density the warp uses. The cutline is rasterized over the source buffer only, withcontrolledburn.
Removed
source_window::collect_chunk_listandChunkPlan: useplan::plan_chunks(withChunkOptions::split_antimeridianfor the same split at the antimeridian).compute_source_windowstays. (2026-10-28)
0.2.0 (2026-10-28)
This release changes the API: warp() with WarpOptions and
SourceBuffer replaces the warp entry points of 0.1, and ResampleAlg
gains variants.
Added
-
geoloc_transform: geolocation-array transformers, for a curvilinear source (gdalwarp -geoloc), a curvilinear target (DST_METHOD=GEOLOC_ARRAY), or both. Both of GDAL's georeferencing conventions; offsets and steps; nodata; antimeridian handling. (2026-10-28) -
warp(),WarpOptions,SourceBuffer: one entry point for every sample type, method and option.WarpOptionscarries a destination offset for warping one tile of a larger grid. (2026-10-28) -
KernelScaling: GDAL's kernel widening when downsampling, now the default;FixedandPointalternatives.estimate_scaleis public. (2026-10-28) -
ResampleAlg::Average, withFootprint::GdalBox(gdalwarp's) andFootprint::Exact(first-order conservative).controlledburnis a new dependency. (2026-10-28) -
ResampleAlg::ModewithModeTies(MODE_TIES). (2026-10-28) -
BandNodata(UNIFIED_SRC_NODATA) andAverageThresholds(NODATA_VALUES_PCT_THRESHOLD,EXCLUDED_VALUES). (2026-10-28) -
ResampleAlg::CubicSpline,Min,Max,Med,Q1,Q3andRms, andResampleAlg::is_area(). (2026-10-28) -
Samplefori64,u64, andhalf::f16behind a newf16feature. (2026-10-28) -
warp_to::<S, D>: a different output type from the source's, through GDAL's working type (DataType::working) andGDALCopyWordsconversion. (2026-10-28) -
NodataandDstNodata: source and destination nodata per band, as gdalwarp's-srcnodataand-dstnodata. (2026-10-28) -
Examples:
tile_laea,curvilinear_swath. -
A documentation site, with the browser demo under
/demo/.
Changed
- Integer outputs round half up and clamp, and a resampled value equal to nodata is moved off it, as gdalwarp does with an integer working type.
- Sample points outside
[0, n)of the source are off the source for every point method, as in GDAL. - Lanczos clips its window and renormalises at edges and nodata, and a target pixel whose centre lands on nodata gets no value, for every interpolating kernel. Some edge and nodata pixels change compared with 0.1.
- Multi-band nodata follows GDAL's default (a pixel is nodata only where
every band is); the 0.1 rule is
BandNodata::AnyBand. SamplerequiresPartialOrd.Footprint::Exactis 2 to 6x faster. The destination pixel lattice is transformed once per row band (shared corners and edge points) instead of four points per pixel, and coverage comes fromcontrolledburn::CoverageWindow(0.2.2) instead of oneburncall per pixel. With an exact transformer the output is unchanged, except for pixels straddling the antimeridian, which the exact footprint does not handle (it gave a different wrong answer before). The lattice's row lines go to the transformer as scanlines, so anApproxTransformernow approximates them, as for the box footprint; before, it transformed the exact footprint's points exactly.WarpOptionsis not generic:nodata: Option<T>is replaced bysrc_nodata: Nodataanddst_nodata: DstNodata.- Bilinear uses GDAL's general formula for types and cases where GDAL does, which can change the last bit (and so integer rounding near 2^40 for 64-bit values).
Deprecated
warp_resample_tandwarp_resample_u8, kept as shims with the 0.1 point-kernel behaviour. Usewarp().
Fixed
- Nearest neighbour mapped source coordinates in (-1, 0) to pixel 0.
ApproxTransformerleft one point untransformed and reported it failed when subdivision reached a left half of two points, which happens on strongly curved transforms or with a small error threshold (whole columns of a polar warp came out as nodata). GDAL transforms it.
0.1.2 (2026-03-11, not on crates.io)
- Use the system libproj through
proj0.31.
Not released to crates.io. On main after it (2026-09 to 2026-10):
rwarp-wasm: browser shim and demo (OSM, WMTS, ArcGIS tile services, COG sources),Warper.withTransformsfor JavaScript CRS transforms.- A generic
Samplekernel overu8tof64, interleaved bands, nodata as a value or an alpha band. - The
CrsTransformtrait withprojandproj4rsbackends; builds forwasm32-unknown-unknown.
0.1.1 (2026-03-06)
GcpTransformer: polynomial transformer from ground control points, order 1 to 3.- Use the published
vastercrate; crate documentation.
0.1.0 (2026-03-06)
- First release, extracted from cogcache:
GenImgProjTransformer,ApproxTransformer,compute_source_window,collect_chunk_listand the nearest, bilinear, cubic and lanczos kernels.
Applications
Browser demo
Open the demo. A Leaflet map in a projection of your
choice (a local Lambert azimuthal equal-area by default, centred wherever
you like) whose tiles are warped client-side from web map tiles, WMTS,
ArcGIS tile services or a Cloud Optimized GeoTIFF. rwarp runs in a Web
Worker, compiled to WebAssembly with the pure-Rust proj4rs backend: no
server, no libproj.
The shim is rwarp-wasm/ in the repository. Its JavaScript API plans a
source window and warps RGBA or float tiles:
const w = new Warper(srcCrs, srcGt, dstCrs, dstGt, maxError);
const win = w.source_window(dstW, dstH, srcW, srcH, padding);
const rgba = w.warp_rgba(srcRgba, srcW, srcH, xoff, yoff, dstW, dstH, "nearest");
Warper.withTransforms accepts CRS transforms as JavaScript functions, so
a page can lend rwarp a projection library (proj4js, a PROJ build) when
proj4rs declines a CRS. See rwarp-wasm/README.md.
cogcache
rwarp was extracted from cogcache, which plans warps from a target tile back to the source chunks it needs, and caches both the raw encoded source chunks and the warped target tiles. rwarp is the planning and resampling core.
Reference for array planning
The ArrIR design for portable array operation plans defines resampling independently of GDAL, and uses rwarp and gdalwarp together to pin down what gdalwarp actually does: how ties are broken, how edges are placed for curvilinear grids, where kernels widen. rwarp's fixtures are the evidence for those answers.
R package
The rwarp R package wraps the same planning and
resampling pipeline via extendr.
Install from the rwarp-r/ subdirectory of this repository:
remotes::install_github("hypertidy/rwarp", subdir = "rwarp-r")
It exposes warp_plan(), warp_exec(), warp_buffer(),
pixel_transform() and crs_describe(). The plan/execute split and
the user-supplied read function work the same way as in the Rust API.
A Python package is planned, with the same API via PyO3 and NumPy arrays as the pixel buffer type.
Using rwarp in your project
If you build on rwarp, an issue or pull request adding your project here is welcome.