Skip to content
Merged
20 changes: 16 additions & 4 deletions crates/data/src/raster/cogwrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
//!
//! The untiled GeoTIFF ([`super::geotiff::write`]) is written here too, by [`write_strips`]: one
//! image in strips of rows, with the same predictors, Deflate effort and threads, and no overviews.
//!
//! Alpha: a float file's alpha is opaque at 1, so the alpha of an integer raster written as floats
//! is divided by its opaque value (255 for bytes), as the untiled writer does.

use std::io::{Seek, SeekFrom, Write};
use std::ops::Range;
Expand Down Expand Up @@ -137,10 +140,11 @@ fn fits_shorts(r: &Raster, b: usize) -> bool {
r.data_type == "UInt16" && nodata_ok && ((s.min >= 0.0 && s.max <= 65_535.0) || s.count == 0)
}

/// Chooses the file's samples like [`super::geotiff::write`] does: a colour raster's colour bands
/// (as bytes when they are bytes, alpha kept), otherwise `band` alone. 16-bit rasters stay 16-bit,
/// and a grey byte raster is written as bytes when no pixel needs a no-data value the bytes can't
/// hold. Grey with alpha keeps both bands; a palette raster keeps its colour table.
/// Chooses the file's samples like [`super::geotiff::write`] does, except for a colour cell with
/// no value under an opaque alpha: it is written see-through here (its alpha 0), not as floats
/// there. A colour raster's colour bands are written (as bytes when they are bytes, alpha kept),
/// otherwise `band` alone. 16-bit rasters stay 16-bit, and a grey byte raster is written as bytes
/// when no pixel needs a no-data value the bytes can't hold. Grey with alpha keeps both bands; a palette raster keeps its colour table.
fn plan(r: &Raster, band: usize) -> Result<Plan> {
let int_nodata = |max: f64| r.nodata.filter(|d| (0.0..=max).contains(d) && d.fract() == 0.0).map(|d| d as u16);
// The type of a set of bands: bytes, else 16-bit when that is what they are, else floats.
Expand Down Expand Up @@ -325,6 +329,7 @@ fn tile_samples(r: &Raster, plan: &Plan, lv: &Level, tx: u32, ty: u32) -> Vec<u8
let mut raw = Vec::with_capacity(t * t * spp * bps);
let float_pad = r.nodata.map_or(f32::NAN, |d| d as f32);
let int_pad = plan.nodata_int.unwrap_or(0);
let opaque = super::alpha_max(&r.data_type);
let mut px = vec![f32::NAN; spp];
for y in 0..t {
let oy = ty as usize * t + y;
Expand All @@ -342,6 +347,13 @@ fn tile_samples(r: &Raster, plan: &Plan, lv: &Level, tx: u32, ty: u32) -> Vec<u8
{
*alpha = 0.0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cloud-optimised writer now makes a NaN colour cell under an opaque alpha see-through (alpha 0) without any notice, where the GeoTIFF writers in the same PR report nothing either. The cell's opacity changes from 255 to 0 in the file. AGENTS.md's "Never silent" rule asks a writer that approximates data to say what, how much and where, and the docs paragraph is not a notice through Session::notify or ToolResult::messages. The see-through result may well be the right representation of a cell with no value, but it needs a count-based notice, or an explicit reason in the doc comment that the rule is met another way.

Category: agents-md

}
// A float file's alpha is opaque at 1: an integer raster's is divided by its opaque value.
// (No no-data tag goes with an alpha band, so none of its cells is a no-data one.)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment says no cell of the alpha band is a no-data one, but the source raster can still have a no-data value that equals an alpha value (for example an Int16 RGBA with no-data 32767 and alpha 32767). The COG file has no nodata tag, so after the division that cell is 1.0, an opaque pixel. The map draws the source cell see-through, because Raster::is_valid is false for it. The GeoTIFF path keeps it as no value, so the two files now differ. The visible result is the same as before this PR (the raw 32767 also read as opaque), so this is not a regression, but the comment is wrong and the division should skip the cells the source marks as no-data, the way float_alpha does. Confidence is moderate: I did not run the case.

Category: bug

if plan.sample == Sample::Float
&& let Some(alpha) = plan.alpha.and_then(|a| px.get_mut(a))
{
*alpha /= opaque;
}
for v in &px {
match plan.sample {
Sample::Byte => raw.push(if v.is_nan() { int_pad as u8 } else { v.round().clamp(0.0, 255.0) as u8 }),
Expand Down
186 changes: 174 additions & 12 deletions crates/data/src/raster/geotiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1923,10 +1923,18 @@ pub fn written_bands(r: &Raster, band: usize) -> Vec<usize> {
(0..if fourth { 4 } else { 3 }).collect()
}

/// An alpha cell `v` of `r` as a float file holds it: a float file's alpha is opaque at 1, so an
/// integer raster's is divided by its `opaque` value (see [`super::alpha_max`]). A cell with no
/// value (NaN, or the no-data value the file's tag names) stays as it is, so it still has none.
pub(super) fn float_alpha(r: &Raster, opaque: f32, v: f32) -> f32 {
if r.is_valid(v) { v / opaque } else { v }
}

/// Writes a raster as a Deflate-compressed GeoTIFF: a colour raster's colour bands (RGB(A) bytes
/// when they are 8-bit, else 32-bit floats, alpha kept), so it reads back in colour; otherwise
/// `band` (0-based), as bytes when it is an 8-bit band of whole bytes, else as 32-bit floats.
/// `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands,
/// An integer raster's alpha, when written as floats, is divided by its opaque value (1 is opaque
/// in a float file; see [`float_alpha`]). `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands,
/// as its 8-bit form did before. The strips go through the predictors and Deflate effort of the
/// COG writer ([`super::cogwrite::write_strips`]). A cancelled run stops it (with
/// [`DataError::Cancelled`]) within a strip.
Expand All @@ -1938,7 +1946,8 @@ pub fn write(r: &Raster, band: usize) -> Result<Vec<u8>> {
/// when that keeps them all. Otherwise: 8-bit samples when the raster is `UInt8` and every valid
/// value is a whole number in 0–255 (an empty cell only where no-data can mark it), else 32-bit
/// float samples (RGB first for a colour raster, and alpha after them when it has one). [`read`]
/// reads them back as the same bands.
/// reads them back as the same bands. An integer raster's alpha, when written as floats, is divided
/// by its opaque value, as [`write`] does.
pub fn write_all(r: &Raster) -> Result<Vec<u8>> {
encode(r, 0, true)
}
Expand Down Expand Up @@ -2004,10 +2013,26 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result<Vec<u8>> {
// The fourth sample of a colour file says what it is: alpha, or data (as RGB and near-infrared).
let fourth = || vec![if matches!(r.color, ColorHint::Rgb { alpha: true }) { 2 } else { 0 }];
// Without alpha or a no-data marker, byte samples cannot keep NaN holes (for example the
// cells outside a reprojected RGBI image). Keep those samples as floats instead.
let byte_holes = r.nodata.is_none()
&& matches!(r.color, ColorHint::Rgb { alpha: false })
&& written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize)));
// cells outside a reprojected RGBI image). Keep those samples as floats instead. With alpha,
// a hole its alpha hides is fine (the cell is see-through), but one under an opaque alpha
// would be written as an opaque 0. A pass over the bands: the byte branch asks it last.
let byte_holes = || {
let counted =
|| written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize)));
r.nodata.is_none()
&& match (&r.color, r.color.alpha(r.bands.len())) {
(ColorHint::Rgb { alpha: false }, _) => counted(),
(ColorHint::Rgb { alpha: true }, Some((_, colour))) => colour.into_iter().any(|b| {
r.bands
.get(b)
.zip(r.see_through_cells(b))
.is_some_and(|(band, hidden)| band.data.iter().enumerate().any(|(i, v)| !v.is_finite() && !hidden(i)))
}),
// No alpha band to hide a hole (alpha declared on three bands).
(ColorHint::Rgb { alpha: true }, None) => counted(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This arm changes output for existing files: an RGBA-hinted raster on three bands with a NaN colour cell used to be written as bytes (the NaN as an opaque 0). It is now written as floats. No test case covers it; the seven cases in nan_cells_of_byte_rasters_without_no_data_are_not_written_as_zero use four bands. Since this fixes a silent loss, the new behaviour needs a test case on both sides (a NaN gives floats, a clean three-band raster stays bytes), per the "test both ways" rule.

Category: quality

_ => false,
}
};
let all: Vec<usize> = (0..r.bands.len()).collect();
if every && written_bands(r, band).len() < all.len() {
// More bands than colour (or one grey band) takes: each a 32-bit float sample, the first
Expand Down Expand Up @@ -2039,22 +2064,23 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result<Vec<u8>> {
crate::progress::check()?;
}
// Every band holds `n` values (checked above), so none is filled in.
data.extend(r.bands.iter().map(|b| $sample(b.data.get(i).copied().unwrap_or(f32::NAN))));
data.extend(r.bands.iter().enumerate().map(|(bi, b)| $sample(bi, b.data.get(i).copied().unwrap_or(f32::NAN))));
}
put(image(&all[..], $kind, extras)?, &data, $le, &mut out)?;
}};
}
if as_bytes {
let nodata = r.nodata.map_or(0, |d| d as u8);
let byte = |v: f32| if r.is_valid(v) { v.clamp(0.0, 255.0) as u8 } else { nodata };
let byte = |_: usize, v: f32| if r.is_valid(v) { v.clamp(0.0, 255.0) as u8 } else { nodata };
wide!(byte, Sample::Byte, u8::to_le_bytes)
} else {
wide!(|v: f32| v, Sample::Float, f32::to_le_bytes)
let (opaque, alpha_band) = (super::alpha_max(&r.data_type), alpha.then_some(if rgb { 3 } else { 1 }));
wide!(|bi: usize, v: f32| if Some(bi) == alpha_band { float_alpha(r, opaque, v) } else { v }, Sample::Float, f32::to_le_bytes)
}
} else if rgb
&& !byte_holes
&& (!written_bands(r, band).contains(&3) || fits_bytes(r, 3))
&& let (Some(red), Some(green), Some(blue)) = (bytes(0), bytes(1), bytes(2))
&& !byte_holes()
Comment on lines 2103 to +2104

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The let chain builds bytes(0), bytes(1) and bytes(2) (each a full byte plane) before !byte_holes() is asked. For a raster that has holes and so goes to floats, those three planes (about 3 bytes per cell) are allocated and then dropped. The comment above says the byte branch asks byte_holes last so that work is skipped, but it is only skipped for rasters that don't fit bytes. The hole scan itself is also a new full pass over the colour bands with no progress::check, so Cancel isn't looked at during it. Asking it before the planes are built avoids the wasted copy:

Suggested change
&& let (Some(red), Some(green), Some(blue)) = (bytes(0), bytes(1), bytes(2))
&& !byte_holes()
&& !byte_holes()
&& let (Some(red), Some(green), Some(blue)) = (bytes(0), bytes(1), bytes(2))

Category: performance

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
let alpha = if written_bands(r, band).contains(&3) { bytes(3) } else { None };
let n = (w as usize) * (h as usize);
Expand All @@ -2073,14 +2099,16 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result<Vec<u8>> {
}
} else if rgb && let (Some(red), Some(green), Some(blue)) = (r.bands.first(), r.bands.get(1), r.bands.get(2)) {
// Colour bands that aren't bytes (three embedding dimensions): kept as 32-bit floats, with
// their alpha band when they have one.
// their alpha band when they have one, scaled by [`float_alpha`].
let n = (w as usize) * (h as usize);
let at = |b: &crate::raster::Band, i: usize| b.data.get(i).copied().unwrap_or(f32::NAN);
// Only a declared alpha: the fourth band of an RGBI image is data.
let opaque = if matches!(r.color, ColorHint::Rgb { alpha: true }) { super::alpha_max(&r.data_type) } else { 1.0 };
match r.bands.get(3).filter(|_| written_bands(r, band).contains(&3)) {
Some(alpha) => {
let mut data = Vec::with_capacity(n * 4);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This branch now takes every RGBA raster with a NaN colour under an opaque alpha, which used to be written as bytes (4 bytes per cell). It builds the whole image as f32 (n * 4 values, 16 bytes per cell, 4 times the 8-bit layer), with no room/memory::planned check before the allocation and no progress::check in its loop, so Cancel is not looked at while it runs. The PR body doesn't give what the change holds as a multiple of the layer, as AGENTS.md's "Size for real data" asks. Please state that multiple in the PR, and either write this in pieces or size it with memory::planned and refuse past the limit. This path was already there for three-embedding colour floats; the change is that more rasters reach it.

Category: agents-md

for i in 0..n {
data.extend([at(red, i), at(green, i), at(blue, i), at(alpha, i)]);
data.extend([at(red, i), at(green, i), at(blue, i), float_alpha(r, opaque, at(alpha, i))]);
}
put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, &mut out)?;
}
Expand Down Expand Up @@ -2722,6 +2750,140 @@ mod tests {
}
}

/// An 8-bit raster with no no-data value keeps a NaN cell as a NaN, in floats, never as 0: grey
/// with a second band (`write_all`), RGB without alpha, and RGBA with a NaN colour under an
/// opaque alpha (`write` and `write_all`). A NaN colour the alpha hides, and a raster with no
/// NaN, stay bytes. An RGBA raster written as floats keeps its alpha band and colour hint.
#[test]
fn nan_cells_of_byte_rasters_without_no_data_are_not_written_as_zero() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 };
let nan = f32::NAN;
let raster = |bands: Vec<Vec<f32>>, color| Raster::new("nan", 3, 1, bands, gt, Crs::LonLat, None, color, "UInt8").unwrap();
let rgb = |red: [f32; 3], blue: [f32; 3]| vec![red.to_vec(), vec![5.0; 3], blue.to_vec()];
let rgba = |red: [f32; 3], blue: [f32; 3], alpha: [f32; 3]| {
let mut bands = rgb(red, blue);
bands.push(alpha.to_vec());
raster(bands, ColorHint::Rgb { alpha: true })
};
let cases = [
("two bands, NaN", raster(vec![vec![1.0, nan, 2.0], vec![3.0; 3]], ColorHint::Gray), true),
("two bands, no NaN", raster(vec![vec![1.0, 4.0, 2.0], vec![3.0; 3]], ColorHint::Gray), false),
("RGB, NaN", raster(rgb([1.0, nan, 2.0], [6.0; 3]), ColorHint::Rgb { alpha: false }), true),
("RGB, no NaN", raster(rgb([1.0, 4.0, 2.0], [6.0; 3]), ColorHint::Rgb { alpha: false }), false),
("RGBA, NaN under an opaque alpha", rgba([1.0, nan, 2.0], [6.0, 6.0, nan], [255.0; 3]), true),
("RGBA, NaN under a clear alpha", rgba([1.0, nan, 2.0], [6.0, nan, 6.0], [255.0, 0.0, 255.0]), false),
("RGBA, no NaN", rgba([1.0, 4.0, 2.0], [6.0; 3], [255.0; 3]), false),
];
for (case, r, floats) in &cases {
for (writer, bytes) in [("write", write(r, 0).unwrap()), ("write_all", write_all(r).unwrap())] {
// `write` keeps one band of a two-band grey raster: only `write_all` is asked of it.
if writer == "write" && r.bands.len() == 2 {
continue;
}
let back = read(std::io::Cursor::new(bytes), "back").unwrap();
let at = format!("{case}, {writer}");
assert_eq!(back.data_type, if *floats { "Float32" } else { "UInt8" }, "{at}");
assert_eq!((back.band_count(), &back.color), (r.band_count(), &r.color), "{at}");
if *floats {
// An alpha band is on the float scale: `rgba_written_as_floats_keeps_its_opacity`.
let alpha = if r.color == (ColorHint::Rgb { alpha: true }) { Some(3) } else { None };
for (b, band) in r.bands.iter().enumerate().filter(|(b, _)| Some(*b) != alpha) {
let same = |(a, b): (&f32, &f32)| a == b || (a.is_nan() && b.is_nan());
assert!(band.data.iter().zip(&back.bands[b].data).all(same), "{at}, band {b}: {:?}", back.bands[b].data);
}
}
}
}
}

/// An RGBA raster written as floats keeps how see-through each pixel is: its alpha is on the
/// float scale (1 is opaque) once read back, whatever scale the integer raster had. The
/// colours stay as they are (a float raster is stretched by its own range when drawn).
#[test]
fn rgba_written_as_floats_keeps_its_opacity() {
use super::super::cogwrite;
let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 };
let rgba = |data_type: &str, red: [f32; 3], alpha: [f32; 3]| {
let bands = vec![red.to_vec(), vec![5.0; 3], vec![6.0; 3], alpha.to_vec()];
Raster::new("rgba", 3, 1, bands, gt, Crs::LonLat, None, ColorHint::Rgb { alpha: true }, data_type).unwrap()
};
// The opacity (0-255) the map draws a pixel with: its alpha over the type's opaque value.
let opacity =
|r: &Raster, i: usize| ((r.bands[3].data[i] / crate::raster::alpha_max(&r.data_type)).clamp(0.0, 1.0) * 255.0).round();
let nan = f32::NAN;
let cases = [
("UInt8, NaN colour", rgba("UInt8", [1.0, nan, 2.0], [255.0, 128.0, 255.0])),
("UInt16", rgba("UInt16", [1000.0, 2000.0, 3000.0], [65535.0, 32768.0, 65535.0])),
("Int16", rgba("Int16", [100.0, -200.0, 300.0], [32767.0, 16384.0, 32767.0])),
("Float32", rgba("Float32", [0.1, 0.2, 0.3], [1.0, 0.5, 1.0])),
("UInt8, five bands, NaN colour", {
let mut r = rgba("UInt8", [1.0, nan, 2.0], [255.0, 128.0, 255.0]);
r.bands.push(r.bands[1].clone());
r
}),
];
for (case, r) in &cases {
let mut files = vec![("write", write(r, 0).unwrap()), ("write_all", write_all(r).unwrap())];
// The COG writer makes a cell with a NaN colour fully see-through, by design.
if !case.contains("NaN") {
files.push(("cog", cogwrite::write(r, 0).unwrap()));
}
for (writer, bytes) in files {
let back = read(std::io::Cursor::new(bytes), "back").unwrap();
let at = format!("{case}, {writer}");
// `write` keeps the colour bands and alpha; `write_all` every band.
let kept = if writer == "write" { 4 } else { r.band_count() };
assert_eq!((back.band_count(), &back.color), (kept, &ColorHint::Rgb { alpha: true }), "{at}");
for i in 0..3 {
assert_eq!(opacity(&back, i), opacity(r, i), "{at}, pixel {i}: alpha {:?}", back.bands[3].data);
}
}
}
// Grey with alpha, past what `write` keeps (`write_all`): the same.
let grey = Raster::new(
"grey",
3,
1,
vec![vec![1.0, nan, 2.0], vec![255.0, 128.0, 255.0]],
gt,
Crs::LonLat,
None,
ColorHint::GrayAlpha,
"UInt8",
)
.unwrap();
let back = read(std::io::Cursor::new(write_all(&grey).unwrap()), "back").unwrap();
let opaque = crate::raster::alpha_max(&back.data_type);
assert_eq!((back.band_count(), &back.color), (2, &ColorHint::GrayAlpha));
assert_eq!(back.bands[1].data.iter().map(|a| (a / opaque * 255.0).round()).collect::<Vec<_>>(), [255.0, 128.0, 255.0]);
}

/// An alpha cell equal to the no-data value is no value, and stays one when written as floats:
/// it isn't scaled to 1 (opaque); the cells beside it are. (The COG writer has no no-data tag
/// beside an alpha band: its alpha says which pixels have no value.)
#[test]
fn alpha_equal_to_no_data_stays_no_data_when_written_as_floats() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 };
let rgba = |extra: usize| {
let mut bands = vec![vec![100.0; 3], vec![200.0; 3], vec![300.0; 3], vec![32767.0, 16384.0, 32767.0]];
bands.extend(vec![vec![5.0; 3]; extra]);
Raster::new("rgba", 3, 1, bands, gt, Crs::LonLat, Some(32767.0), ColorHint::Rgb { alpha: true }, "Int16").unwrap()
};
for (case, r) in [("four bands", rgba(0)), ("five bands", rgba(1))] {
let mut files = vec![("write_all", write_all(&r).unwrap())];
if r.band_count() == 4 {
files.push(("write", write(&r, 0).unwrap()));
}
for (writer, bytes) in files {
let back = read(std::io::Cursor::new(bytes), "back").unwrap();
let at = format!("{case}, {writer}");
assert_eq!(back.value(3, 0, 0), None, "{at}: {:?}", back.bands[3].data);
assert_eq!(back.value(3, 2, 0), None, "{at}");
assert!(back.value(3, 1, 0).is_some_and(|a| (a - 0.5).abs() < 1e-3), "{at}: {:?}", back.bands[3].data);
}
}
}

#[test]
fn rgbi_byte_export_does_not_turn_nir_into_alpha() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 };
Expand Down
8 changes: 7 additions & 1 deletion crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2188,7 +2188,13 @@ pub(crate) mod tests {
let cog = geotiff::read(std::io::Cursor::new(cogwrite::write(&r, 0).unwrap()), "cog").unwrap();
assert_eq!((back.data_type.as_str(), cog.data_type.as_str()), ("Float32", "Float32"));
}
assert_eq!(back.bands.iter().map(stats).collect::<Vec<_>>(), r.bands.iter().map(stats).collect::<Vec<_>>(), "{data_type}");
// The alpha band's top is its type's opaque value: a 16-bit one, written as floats, is
// opaque at 1 (its pixels are divided by 65535).
let mut same: Vec<_> = r.bands.iter().map(stats).collect();
if let Some(a) = same.get_mut(3).filter(|_| data_type == "UInt16") {
a.2 = 1.0;
}
assert_eq!(back.bands.iter().map(stats).collect::<Vec<_>>(), same, "{data_type}");
}
// As the map draws it: an alpha under half a 256th of opaque is see-through (16 bits: 100
// of 65535), one above it isn't (200).
Expand Down
Loading
Loading