Skip to content
Merged
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
149 changes: 109 additions & 40 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,16 @@ const IDW_SAFE_SCALE: f64 = 1e-200;
/// are added in the same order on any thread, and enough for the compiler to add them in vectors.
const IDW_LANES: usize = 8;

/// The points a run of cells takes at a time at a power of 2: their x, dy² and values stay in
/// the processor's nearest cache while each cell of the run goes over them, so they aren't fetched
/// again for every cell. A multiple of [`IDW_LANES`], so a point's lane is the same whatever the
/// block.
const IDW_BLOCK: usize = 512;
const _: () = assert!(IDW_BLOCK.is_multiple_of(IDW_LANES));

/// The cells of a row weighed together at a power of 2.
const IDW_CELLS: usize = 16;

/// The points of an [`idw`] from every point as separate x, y and value columns, which a cell's
/// pass reads in step, and so in vectors.
struct IdwColumns {
Expand All @@ -868,33 +878,40 @@ impl IdwColumns {
}
}

/// The value at `c`, east-west distances times `kx`: that of the first point within
/// [`IDW_EXACT_D2`] of it, else the mean of every point's value weighted by 1/dᵖ.
/// At a power of 2, the values of a run of cells at `y`, one at each of `xs` (at most
/// [`IDW_CELLS`]; the rest of the array is not a cell's), east-west distances times `kx`.
///
/// At a power of 2 that is one pass, with w = 1/d², at most 1e24 once no point is within
/// [`IDW_EXACT_D2`]. At any other power, or should the sums overflow (from huge values) or
/// their terms underflow (from tiny values or distances near f64's limit, below
/// [`IDW_SAFE_SCALE`]), a first pass finds the nearest point and a second weighs each by
/// (dₙ²/d²)^(p/2): the same ratios, which keep the nearest point's weight at 1 and can't
/// overflow for a high power.
fn at(&self, c: Coord, kx: f64, power: f64) -> f64 {
let nearest = if power == 2.0 {
let (num, den, nearest) = self.sums(c, kx, |d2| 1.0 / d2);
/// Each is one pass with w = 1/d², at most 1e24 once no point is within [`IDW_EXACT_D2`].
/// A cell on a point, or one whose sums overflow (from huge values) or whose terms underflow
/// (from tiny values or distances near f64's limit, below [`IDW_SAFE_SCALE`]), goes
/// [`Self::by_nearest`].
fn at_power_two(&self, xs: &[f64], y: f64, kx: f64, dy2: &mut [f64; IDW_BLOCK]) -> [f64; IDW_CELLS] {
let sums = self.run_sums(xs, y, kx, dy2);
let mut values = [f64::NAN; IDW_CELLS];
for ((value, x), (num, den)) in values.iter_mut().zip(xs).zip(sums) {
let c = Coord::new(*x, y);
// With every value 0 the sum is exactly 0, whatever underflowed.
let scaled = den >= IDW_SAFE_SCALE && (self.largest == 0.0 || den * self.largest >= IDW_SAFE_SCALE);
if nearest >= IDW_EXACT_D2 && num.is_finite() && den.is_finite() && scaled {
return num / den;
}
nearest
} else {
self.nearest(c, kx)
};
// A point within `IDW_EXACT_D2` alone weighs 1/`IDW_EXACT_D2` or more: with a smaller
// sum there is none, and no need to look for the nearest.
let stands = scaled && num.is_finite() && den.is_finite() && (den < 1.0 / IDW_EXACT_D2 || self.nearest(c, kx) >= IDW_EXACT_D2);
*value = if stands { num / den } else { self.by_nearest(c, kx, 2.0) };
}
values
}

/// The value at `c` at any power: that of the first point within [`IDW_EXACT_D2`] of it, else
/// the mean of every point's value weighted by 1/dᵖ. A first pass finds the nearest point and
/// a second weighs each by (dₙ²/d²)^(p/2): the same ratios, which keep the nearest point's
/// weight at 1 and can't overflow for a high power.
fn by_nearest(&self, c: Coord, kx: f64, power: f64) -> f64 {
let nearest = self.nearest(c, kx);
if nearest < IDW_EXACT_D2 {
let on = self.x.iter().zip(&self.y).zip(&self.v).find(|((x, y), _)| d2(c, kx, **x, **y) < IDW_EXACT_D2);
return on.map_or(f64::NAN, |(_, v)| *v);
}
let half = power / 2.0;
let (num, den, _) = self.sums(c, kx, |d2| {
let (num, den) = self.sums(c, kx, |d2| {
// Past f64's range the squared ratio would vanish where the ratio of distances, raised
// to a small power, still weighs something: then the distances are taken.
let ratio = nearest / d2;
Expand All @@ -920,18 +937,16 @@ impl IdwColumns {
}

/// Over every point, the sums of w·v and of w, w the `weight` of its squared distance from
/// `c`, and the smallest squared distance: in [`IDW_LANES`] lanes, each sum in an array of its
/// own so they go in vectors, added up in a fixed order.
/// `c`: in [`IDW_LANES`] lanes, each sum in an array of its own so they go in vectors, added up
/// in a fixed order.
#[inline(always)]
fn sums(&self, c: Coord, kx: f64, weight: impl Fn(f64) -> f64) -> (f64, f64, f64) {
let (mut num, mut den, mut near) = ([0.0; IDW_LANES], [0.0; IDW_LANES], [f64::INFINITY; IDW_LANES]);
fn sums(&self, c: Coord, kx: f64, weight: impl Fn(f64) -> f64) -> (f64, f64) {
let (mut num, mut den) = ([0.0; IDW_LANES], [0.0; IDW_LANES]);
let mut add = |x: &[f64], y: &[f64], v: &[f64]| {
for (((((n, dn), m), x), y), v) in num.iter_mut().zip(den.iter_mut()).zip(near.iter_mut()).zip(x).zip(y).zip(v) {
let d = d2(c, kx, *x, *y);
let w = weight(d);
for ((((n, dn), x), y), v) in num.iter_mut().zip(den.iter_mut()).zip(x).zip(y).zip(v) {
let w = weight(d2(c, kx, *x, *y));
*n += w * v;
*dn += w;
*m = smaller(*m, d);
}
};
let (xs, x_rest) = self.x.as_chunks::<IDW_LANES>();
Expand All @@ -941,7 +956,47 @@ impl IdwColumns {
add(x, y, v);
}
add(x_rest, y_rest, v_rest);
(num.into_iter().sum(), den.into_iter().sum(), near.into_iter().fold(f64::INFINITY, smaller))
(num.into_iter().sum(), den.into_iter().sum())
}

/// [`Self::sums`] with w = 1/d² for each of up to [`IDW_CELLS`] cells at `y`, one at each of
/// `xs`, bit for bit. The points go a block at a time through all the cells, each point's dy²
/// (the same along the row) made once into `dy2`.
fn run_sums(&self, xs: &[f64], y: f64, kx: f64, dy2: &mut [f64; IDW_BLOCK]) -> [(f64, f64); IDW_CELLS] {

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 PR's central claim is that run_sums gives the same bits as sums for every cell, but no test pins that. idw_on_several_threads_is_idw_on_one only compares thread counts, and idw_at_power_two_is_the_general_paths_surface compares against a reference with a tolerance. A later change to the block or lane order could break the bit-for-bit promise without any test failing.

A small test next to this function would close the gap. For a set of points that spans more than two blocks and ends in a partial lane set (the 1,101-point fixture is already right), with a row of 16 cells plus a partial run, assert that run_sums(xs, y, kx, &mut dy2) matches sums(c, kx, |d2| 1.0 / d2) per cell with to_bits() equality on both the numerator and denominator.

This is a test for code that already works, so it is a quality point. The PR's own timing and output comparisons are not in the repository.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Leaving this for the release quality pass: it's an extra test for code that works, and the bit-for-bit output was checked on nine cases for this PR.

let (mut num, mut den) = ([[0.0; IDW_LANES]; IDW_CELLS], [[0.0; IDW_LANES]; IDW_CELLS]);
for ((x, py), v) in self.x.chunks(IDW_BLOCK).zip(self.y.chunks(IDW_BLOCK)).zip(self.v.chunks(IDW_BLOCK)) {
for (d, py) in dy2.iter_mut().zip(py) {
let dy = py - y;
*d = dy * dy;
}
let (x, x_rest) = x.as_chunks::<IDW_LANES>();
let (v, v_rest) = v.as_chunks::<IDW_LANES>();
let (dy, _) = dy2.as_chunks::<IDW_LANES>();
// The points past the last whole set of lanes, only ever in the last block.
let dy_rest = dy2.get(x.len() * IDW_LANES..).unwrap_or_default();
for ((cx, num), den) in xs.iter().zip(&mut num).zip(&mut den) {
// Copies, which the compiler keeps in registers over the block.
let (mut n, mut dn) = (*num, *den);
let mut add = |x: &[f64], dy2: &[f64], v: &[f64]| {
for ((((n, dn), x), dy2), v) in n.iter_mut().zip(dn.iter_mut()).zip(x).zip(dy2).zip(v) {
let dx = (x - cx) * kx;
let w = 1.0 / (dx * dx + dy2);
*n += w * v;
*dn += w;
}
};
for ((x, dy2), v) in x.iter().zip(dy).zip(v) {
add(x, dy2, v);
}
add(x_rest, dy_rest, v_rest);
(*num, *den) = (n, dn);
}
}
let mut sums = [(0.0, 0.0); IDW_CELLS];
for ((sum, num), den) in sums.iter_mut().zip(num).zip(den) {
*sum = (num.into_iter().sum(), den.into_iter().sum());
}
sums
}
}

Expand Down Expand Up @@ -1000,7 +1055,7 @@ fn idw_on(
let squared = power == 2.0;
let geographic = crs.is_geographic();
let exact = if squared { IDW_EXACT_D2 } else { 1e-12 };
// With every point weighed, each cell takes one pass over them as columns, with no buffer.
// With every point weighed, the cells pass over them as columns, with no buffer of distances.
let every_point = k == points.len();
// Each row on its own, on several threads when the work is large (#1252); a thread's
// distances for the nearest few go into its own buffer.
Expand All @@ -1019,24 +1074,37 @@ fn idw_on(
let every = every_point.then(|| IdwColumns::new(points));
let mut data = new_band(w, h, NODATA)?;
crate::control::begin(h);
let stored = |v: f64| if v.is_finite() { v as f32 } else { NODATA };
crate::parallel::for_each_row(
data.chunks_mut(w),
threads,
|| (Vec::with_capacity(if every_point { 0 } else { points.len() }), crate::control::Pace::default()),
|(near, pace): &mut (Vec<(f64, f64)>, crate::control::Pace), row, out: &mut [f32]| {
|| (Vec::with_capacity(if every_point { 0 } else { points.len() }), crate::control::Pace::default(), [0.0; IDW_BLOCK]),
|(near, pace, dy2): &mut (Vec<(f64, f64)>, crate::control::Pace, [f64; IDW_BLOCK]), row, out: &mut [f32]| {
let y = extent.max_y - (row as f64 + 0.5) * cell;
let x = |col: usize| extent.min_x + (col as f64 + 0.5) * cell;
// East-west degrees shrink with latitude, which only changes by row; a projected
// system's units don't.
let kx = if geographic { (extent.max_y - (row as f64 + 0.5) * cell).to_radians().cos() } else { 1.0 };
let kx = if geographic { y.to_radians().cos() } else { 1.0 };
// Each cell weighs every point, so a wide row of many points takes long without a cap:
// Cancel is looked at within it, between runs of cells or single cells.
if let Some(every) = every.as_ref().filter(|_| squared) {
for (run, out) in out.chunks_mut(IDW_CELLS).enumerate() {
if pace.stop(points.len().saturating_mul(out.len())) {
return;
}
let xs: [f64; IDW_CELLS] = std::array::from_fn(|i| x(run * IDW_CELLS + i));
let values = every.at_power_two(xs.get(..out.len()).unwrap_or(&xs), y, kx, dy2);
out.iter_mut().zip(values).for_each(|(o, v)| *o = stored(v));
}
return;
}
for (col, o) in out.iter_mut().enumerate() {
// Each cell weighs every point, so a wide row of many points takes long without a
// cap: Cancel is looked at within it.
if pace.stop(points.len()) {
return;
}
let c = Coord::new(extent.min_x + (col as f64 + 0.5) * cell, extent.max_y - (row as f64 + 0.5) * cell);
let c = Coord::new(x(col), y);
if let Some(every) = &every {
let v = every.at(c, kx, power);
*o = if v.is_finite() { v as f32 } else { NODATA };
*o = stored(every.by_nearest(c, kx, power));
continue;
}
near.clear();
Expand All @@ -1062,7 +1130,7 @@ fn idw_on(
});
num / den
};
*o = if v.is_finite() { v as f32 } else { NODATA };
*o = stored(v);
}
},
)?;
Expand Down Expand Up @@ -2962,9 +3030,10 @@ mod tests {
/// the nearest few, and a cell on a point still takes its value.
#[test]
fn idw_at_power_two_is_the_general_paths_surface() {
let pts: Vec<(Coord, f64)> = (0..400)
// More than two blocks of points, with some past the last whole set of lanes.
let pts: Vec<(Coord, f64)> = (0..1100)
.map(|i| {
let (x, y) = ((i * 37 % 400) as f64 / 40.0, (i * 91 % 400) as f64 / 40.0);
let (x, y) = ((i * 37 % 1100) as f64 / 110.0, (i * 91 % 1100) as f64 / 110.0);
(Coord::new(x, 40.0 + y), (x * 1.3).sin() * 100.0 + y * 7.0)
})
.chain([(Coord::new(0.05, 49.95), 1234.5)])
Expand Down
Loading