Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ Every screenshot is RustGIS itself, rendered offscreen by `cargo run -p rustgis-
|---|---|
| **Data** | GeoJSON, CSV/TSV with x/y columns in other coordinate systems or WKT geometry, Excel and OpenDocument spreadsheets, GeoRSS, LandXML, encoded polylines, Shapefile (zipped too, in the browser as well), GeoPackage, GeoParquet, FlatGeobuf, KML/KMZ (with styles), GPX, GML, MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON, CityGML 1.0–3.0, AutoCAD DXF, dBASE tables, PDF and GeoPDF pages (desktop), LiDAR point clouds (LAS, LAZ, COPC) and geotagged photos (large GeoPackage, GeoParquet and FlatGeobuf files, and Shapefiles on the desktop, are read in place), files by their web address, every vector format GDAL reads when it is installed (desktop), Esri File Geodatabases without GDAL (desktop), enterprise geodatabases on SQL Server through their `.sde` files (desktop), PostGIS, MySQL, MariaDB and SQL Server tables read live (desktop), and SQL queries and DuckDB databases through DuckDB Spatial when DuckDB is installed (desktop); PMTiles archives (by web address, or a file on the desktop) and MBTiles files; GeoJSON, CSV, GeoPackage (also as a table added to an existing file), GeoParquet, Shapefile, FlatGeobuf, KML/KMZ, GPX and WKT out (GeoPackage and FlatGeobuf not from the web app); standalone tables; reusable connections; Reload Data for linked files (desktop); geocoding (Find Place, address tables); a Data Sources pane (favourites, recent, saved services, a library) and an SQL pane (desktop); supported QGIS and GeoLibre projects and layer styles; layer and map files, styles, templates and packages |
| **Open data** | STAC search (Planetary Computer assets), NASA Earthdata imagery and granule search (GeoTIFFs added on the desktop), Hugging Face, Overture Maps, Source Cooperative, OpenStreetMap by area, geoBoundaries, CKAN, Socrata and ArcGIS Hub portals; S3 buckets with signed connections and a bucket browser; a Data Cubes pane with a catalog of cubes for the time slider (added on the desktop) |
| **Rasters** | GeoTIFF and cloud-optimised GeoTIFF (any pixel type, tiled or striped, compressed), ASCII grids, GRIB 1 and 2 (simple packing on latitude/longitude grids), SRTM `.hgt` and DTED elevation, Zarr 2 and 3 stores (a variable at a time step, by web address, or folder on the desktop), and JPEG 2000, NetCDF, HDF, ERDAS Imagine and the other rasters GDAL reads when it is installed (desktop); reprojection by EPSG code; Stretch, RGB, Classify, Unique Values, Colormap and Shaded Relief; DRA, band combinations, brightness/contrast/gamma; raster functions, indices, change detection, classification, georeferencing; cloud-optimised GeoTIFF export (desktop); data cubes, point time-series charts (desktop), temporal summaries and trends (Sen's slope, Mann–Kendall); a spectral profile comparing a multiband raster's bands at points |
| **Rasters** | GeoTIFF and cloud-optimised GeoTIFF (any pixel type, tiled or striped, compressed), ASCII grids, GRIB 1 and 2 (simple packing, and GRIB2's complex packing, on latitude/longitude grids), SRTM `.hgt` and DTED elevation, Zarr 2 and 3 stores (a variable at a time step, by web address, or folder on the desktop), and JPEG 2000, NetCDF, HDF, ERDAS Imagine and the other rasters GDAL reads when it is installed (desktop); reprojection by EPSG code; Stretch, RGB, Classify, Unique Values, Colormap and Shaded Relief; DRA, band combinations, brightness/contrast/gamma; raster functions, indices, change detection, classification, georeferencing; cloud-optimised GeoTIFF export (desktop); data cubes, point time-series charts (desktop), temporal summaries and trends (Sen's slope, Mann–Kendall); a spectral profile comparing a multiband raster's bands at points |
| **Maps** | Multiple maps and layouts per project, renamed and duplicated from the Browser pane; a GPU renderer (beta) with smooth zoom and pan; tilt, rotation, terrain and a 3D globe; maps of the Moon, Mars and other celestial bodies; each layer kept and drawn in its own coordinate system, picked from PROJ 9.9's catalog by name, method, area or code, with datum grids downloaded on request; Web Mercator or another projection (Equal Earth, Robinson, Winkel Tripel, polar and regional presets, or a [supported](docs/user-guide/maps.md#projections) projected EPSG or ESRI code); a search box for layers, places and coordinates; UTM and MGRS readouts and an MGRS grid; an on-map right-click menu (copy the coordinate, quick buffer, viewshed and line of sight); identify pop-ups with links and pictures; bookmarks, extent history, coordinate navigation; five offline basemaps, with borders in 32 worldviews (31 downloaded when chosen) |
| **Web services** | WMS, WMTS, WFS, WCS, OGC API Features and Tiles, and ArcGIS REST (FeatureServer, MapServer, ImageServer, VectorTileServer) from their capabilities; CSW catalogue search; sign-in to ArcGIS Online and Enterprise, basic-auth and API-key logins; WMS and WMTS time on the time slider, legends and GetFeatureInfo |
| **Web tiles** | XYZ/TMS/WMS raster tiles, Mapbox Vector Tiles and MapLibre styles (sprites, patterns, expressions), cached and fetched in the background |
Expand Down
130 changes: 93 additions & 37 deletions crates/data/src/raster/grib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@
//! without GDAL. Each field is a band.
//!
//! Read: editions 1 and 2, simple packing (GRIB1's grid point data with simple packing, GRIB2's
//! data representation template 5.0), on a regular latitude/longitude grid (GRIB1 data
//! representation type 0, GRIB2 grid definition template 3.0), in any scanning order, with or
//! without a bitmap. Following WMO's Manual on Codes (WMO-No. 306), Volume I.2, FM 92 GRIB.
//! data representation template 5.0) and GRIB2's complex packing, with or without spatial
//! differencing (5.2 and 5.3), on a regular latitude/longitude grid (GRIB1 data representation
//! type 0, GRIB2 grid definition template 3.0), in any scanning order, with or without a bitmap.
//! Following WMO's Manual on Codes (WMO-No. 306), Volume I.2, FM 92 GRIB.
//!
//! Not read yet, and said: complex, JPEG 2000, PNG and the other packings; other grids (Gaussian,
//! rotated, projected, quasi-regular). A message the reader can't read is left out with a notice
//! naming why; a file with nothing it can read is an error naming why.
//! Not read yet, and said: GRIB1's second-order packing, JPEG 2000, PNG, CCSDS and the other
//! packings; other grids (Gaussian, rotated, projected, quasi-regular). A message the reader can't
//! read is left out with a notice naming why; a file with nothing it can read is an error naming
//! why.
//!
//! The fields on the grid of the first one read are the raster's bands, in file order; fields on
//! another grid are left out with a notice. Values are `(R + X × 2^E) / 10^D`, in the units the
//! file stores (kelvin stays kelvin), unpacked in `f64`; those `f32` changes are counted in
//! [`Raster::rounded`]. Points a bitmap masks are NaN. Rows are laid out north up,
//! and a grid round the whole globe runs from −180° (as GDAL lays it out).
//! [`Raster::rounded`]. Points a bitmap masks, or complex packing marks missing, are NaN.
//! Rows are laid out north up, and a grid round the whole globe runs from −180° (as GDAL lays it
//! out).

mod complex;

use super::{Crs, Exact, GeoTransform, Raster, Uncounted, max_samples};
use crate::{DataError, Result};
Expand Down Expand Up @@ -694,7 +699,8 @@ fn round6(v: f64) -> f64 {
(v * 1e6).round() / 1e6
}

/// One field: its band name, grid and values in scanning order (NaN where a bitmap masks).
/// One field: its band name, grid and values in scanning order (NaN where a bitmap masks, or the
/// packing marks them missing).
struct Field {
name: String,
grid: Grid,
Expand Down Expand Up @@ -780,6 +786,17 @@ fn signed(b: &[u8], o: usize, n: usize) -> i64 {
if v & sign != 0 { -(v & (sign - 1)) } else { v }
}

/// The `n` bits (at most 32) of `b` from bit `at`, unsigned, big-endian; 0 past the end.
fn bits(b: &[u8], at: u64, n: u32) -> u64 {
if n == 0 {
return 0;
}
// The 8 octets from the value's first: at most 7 bits before it, and its 32 at most.
let byte = (at / 8) as usize;
let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(b.get(byte + i).copied().unwrap_or(0)));
(word << (at % 8)) >> (64 - n)
}

/// An IBM System/360 single-precision number (GRIB1's reference value).
fn ibm(v: u32) -> f64 {
let sign = if v & 0x8000_0000 != 0 { -1.0 } else { 1.0 };
Expand All @@ -789,18 +806,19 @@ fn ibm(v: u32) -> f64 {
}

/// The `points` values of a field in scanning order, written straight into one vector: the
/// `count` values `next` gives (in `f64`), held as `f32`, over the points a bitmap keeps (NaN at
/// the others), or all of them without one. Also how many of them `f32` rounded, and how many
/// are past its range (about ±3.4 × 10^38, `f64`'s too): those have no value (NaN) rather than
/// an infinity. A sidecar's no-data value isn't counted either way ([`Uncounted`]'s rule), and
/// neither is a point of a repeated first column (`grid`'s, which [`to_raster`] doesn't lay out).
/// `count` values `next` gives (in `f64`; a missing one, `None`, is NaN), held as `f32`, over the
/// points a bitmap keeps (NaN at the others), or all of them without one. Also how many of them
/// `f32` rounded, and how many are past its range (about ±3.4 × 10^38, `f64`'s too): those have no
/// value (NaN) rather than an infinity. A sidecar's no-data value isn't counted either way
/// ([`Uncounted`]'s rule), and neither is a point of a repeated first column (`grid`'s, which
/// [`to_raster`] doesn't lay out).
/// The values are never held apart from the field, so it costs 4 bytes a point.
fn field_values(
(points, grid): (usize, &Grid),
mask: Option<&[u8]>,
count: usize,
uncounted: Uncounted,
mut next: impl FnMut() -> f64,
mut next: impl FnMut() -> Option<f64>,
) -> std::result::Result<(Vec<f32>, u64, u64), Skip> {
match mask {
None if count != points => return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())),
Expand All @@ -817,7 +835,10 @@ fn field_values(
let kept = mask.is_none_or(|bits| bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0));
if kept && left > 0 {
left -= 1;
let wide = next();
let Some(wide) = next() else {
out.push(f32::NAN);
continue;
};
let v = wide as f32;
let laid = u64::from(!repeats || grid.place(k).0 < columns);
match uncounted.decides(v, || Some(Exact::Float(wide))) {
Expand Down Expand Up @@ -863,6 +884,37 @@ fn unpack(
return Err(Skip::Damaged("a data section shorter than its values".to_string()));
}
reference(r)?;
let scale = scaling(r, e, d);
let mut bit = 0u64;
field_values(at, mask, count, uncounted, || {
let x = self::bits(data, bit, bits) as f64;
bit += u64::from(bits);
Some(scale(x))
})
}

/// [`unpack`] for complex packing ([`complex`]): `count` values from `data`, some of which it may
/// mark missing.
fn unpack_complex(
data: &[u8],
(count, packing): (usize, complex::Complex),
(r, e, d): (f64, i64, i64),
mask: Option<&[u8]>,
at: (usize, &Grid),
uncounted: Uncounted,
) -> std::result::Result<(Vec<f32>, u64, u64), Skip> {
reference(r)?;
let mut values = packing.values(data, count)?;
let scale = scaling(r, e, d);
let field = field_values(at, mask, count, uncounted, || values.next().map(&scale))?;
if values.too_large {
return Err(Skip::Damaged("differences that add up past any packed value".to_string()));
}
Ok(field)
}

/// What a packed value X stands for, `(R + X × 2^E) / 10^D`.
fn scaling(r: f64, e: i64, d: i64) -> impl Fn(f64) -> f64 {
// 2^E and 10^D, where `f64` holds them. Past that (no producer writes such an E or D, but
// they are kept), `R + X × 2^E` is divided by [`scaled_by`] where `f64` holds it (so a sum of
// 0 stays 0); where it is past `f64` but the division brings it back, the value is made as
Expand All @@ -871,13 +923,7 @@ fn unpack(
let two = (-1000..=1000).contains(&e).then(|| 2f64.powi(e as i32));
let ten = decimal(d);
let (base, step) = (scaled_by(r, 0, d), scaled_by(1.0, e, d));
let mut bit = 0u64;
field_values(at, mask, count, uncounted, || {
// The 8 octets from the value's first: at most 7 bits before it, and its 32 at most.
let byte = (bit / 8) as usize;
let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0)));
let x = ((word << (bit % 8)) >> (64 - bits)) as f64;
bit += u64::from(bits);
move |x| {
// X = 0 is R whatever E is (never 0 × ∞).
let sum = if x == 0.0 { r } else { two.map_or(f64::INFINITY, |s| r + x * s) };
let wide = ten.map_or(f64::INFINITY, |ten| sum / ten);
Expand All @@ -890,7 +936,7 @@ fn unpack(
} else {
base + x * step
}
})
}
}

/// 10^`d`, the decimal scale factor's divisor, where `f64` holds it at full precision.
Expand Down Expand Up @@ -942,7 +988,7 @@ fn constant(
reference(r)?;
// As in `unpack`: an `R` that isn't 0 divided down to 0 is counted as rounded.
let v = decimal(d).map(|ten| r / ten).filter(|v| *v != 0.0 || r == 0.0).unwrap_or_else(|| scaled_by(r, 0, d));
field_values(at, mask, count, uncounted, || v)
field_values(at, mask, count, uncounted, || Some(v))
}

/// `n` bitmap bits set among the first `points`.
Expand Down Expand Up @@ -1125,7 +1171,7 @@ fn grib2(b: &[u8], room: usize, mut first: Option<Grid>, uncounted: Uncounted) -
let mut reference = String::from("d=?");
let mut grid: Option<std::result::Result<Grid, Skip>> = None;
let mut product: Option<String> = None;
let mut packing: Option<std::result::Result<(usize, f64, i64, i64, u32), Skip>> = None;
let mut packing: Option<std::result::Result<(usize, f64, i64, i64, Packing), Skip>> = None;
let mut bitmap: Option<std::result::Result<Option<&[u8]>, Skip>> = None;
let mut previous_bitmap: Option<&[u8]> = None;
let mut held = 0usize;
Expand Down Expand Up @@ -1190,7 +1236,7 @@ fn grib2(b: &[u8], room: usize, mut first: Option<Grid>, uncounted: Uncounted) -
let field = (|| {
let grid = grid.clone().ok_or_else(|| Skip::Damaged("a field without a grid".to_string()))??;
let product = product.ok_or_else(|| Skip::Damaged("a field without its product definition".to_string()))?;
let (count, r, e, d, bits) = packing.ok_or_else(|| Skip::Damaged("a field without its packing".to_string()))??;
let (count, r, e, d, packing) = packing.ok_or_else(|| Skip::Damaged("a field without its packing".to_string()))??;
let mask = bitmap.ok_or_else(|| Skip::Damaged("a field without its bitmap section".to_string()))??;
if first.is_some_and(|g| !g.same(&grid)) {
return Err(Skip::OtherGrid);
Expand All @@ -1199,10 +1245,11 @@ fn grib2(b: &[u8], room: usize, mut first: Option<Grid>, uncounted: Uncounted) -
if mask.is_some_and(|m| kept(m, points) != count) || (mask.is_none() && count != points) {
return Err(Skip::Damaged("a field whose values don't fill its grid".to_string()));
}
let (values, rounded, past) = if bits == 0 {
constant((r, d), count, mask, (points, &grid), uncounted)?
} else {
unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, (points, &grid), uncounted)?
let (data, at) = (s.get(5..).unwrap_or_default(), (points, &grid));
let (values, rounded, past) = match packing {
Packing::Simple(0) => constant((r, d), count, mask, at, uncounted)?,
Packing::Simple(bits) => unpack(data, (count, bits), (r, e, d), mask, at, uncounted)?,
Packing::Complex(p) => unpack_complex(data, (count, p), (r, e, d), mask, at, uncounted)?,
};
held += points;
first.get_or_insert(grid);
Expand Down Expand Up @@ -1337,13 +1384,21 @@ fn scaled(s: &[u8], o: usize, value_signed: bool) -> String {
round6(v / 10f64.powi(signed(s, o, 1) as i32)).to_string()
}

/// A GRIB2 data representation section: template 5.0 (simple packing) only, as the number of
/// values, R, E, D and the bits a value.
fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), Skip> {
/// How a GRIB2 field's values are packed.
#[derive(Clone, Copy)]
enum Packing {
/// Simple packing (template 5.0), in this many bits a value (0: a constant field).
Simple(u32),
/// Complex packing (templates 5.2 and 5.3).
Complex(complex::Complex),
}

/// A GRIB2 data representation section (templates 5.0, 5.2 and 5.3): the number of values, R, E, D
/// and the packing.
fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, Packing), Skip> {
let template = be(s, 9, 2);
if template != 0 {
if !matches!(template, 0 | 2 | 3) {
let kind = match template {
2 | 3 => "complex packing",
4 => "IEEE floating point",
40 => "JPEG 2000",
41 => "PNG",
Expand All @@ -1355,8 +1410,9 @@ fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), S
if s.len() < 21 {
return Err(Skip::Damaged("a damaged data representation section".to_string()));
}
let packing = if template == 0 { Packing::Simple(u32::from(s[19])) } else { complex::Complex::of(s, template)? };
let r = f64::from(f32::from_bits(be(s, 11, 4)));
Ok((be(s, 5, 4) as usize, r, signed(s, 15, 2), signed(s, 17, 2), u32::from(s[19])))
Ok((be(s, 5, 4) as usize, r, signed(s, 15, 2), signed(s, 17, 2), packing))
}

#[cfg(test)]
Expand Down
Loading
Loading