use crate::accum::Accum;
use crate::types::{Coord2d, LinearRing, Polygon};
use arithmetica::expansion::{grow_expansion, two_product};
pub(crate) fn certified_twice_area_edges<I>(edges: I) -> f64
where
I: Iterator<Item = (Coord2d, Coord2d)> + Clone,
{
let mut acc = Accum::new();
let mut abs_sum = 0.0_f64;
let mut terms = 0.0_f64;
for (a, b) in edges.clone() {
acc.add_product(a.x, b.y);
acc.add_product(-b.x, a.y);
abs_sum += (a.x * b.y).abs() + (b.x * a.y).abs();
terms += 2.0;
}
let r = acc.value();
if !r.is_finite() || !abs_sum.is_finite() {
return r;
}
if sign_is_certified(r, abs_sum, terms) {
return r;
}
exact_twice_area_edges(edges)
}
fn certified_twice_area<'a, I>(rings: I) -> f64
where
I: Iterator<Item = &'a LinearRing> + Clone,
{
certified_twice_area_edges(rings.flat_map(LinearRing::edges))
}
pub fn signed_area_ring(ring: &LinearRing) -> f64 {
certified_twice_area(std::iter::once(ring)) * 0.5
}
fn sign_is_certified(r: f64, abs_sum: f64, terms: f64) -> bool {
let eps = f64::EPSILON * 0.5;
let gamma = terms * eps / (1.0 - terms * eps);
let bound = 4.0 * (eps * r.abs() + gamma * gamma * abs_sum);
r.abs() > bound
}
pub(crate) fn exact_twice_area_edges<I>(edges: I) -> f64
where
I: Iterator<Item = (Coord2d, Coord2d)>,
{
let mut e: Vec<f64> = Vec::new();
let mut h: Vec<f64> = Vec::new();
for (a, b) in edges {
for (x, y) in [(a.x, b.y), (-b.x, a.y)] {
let (hi, lo) = two_product(x, y);
for t in [lo, hi] {
h.resize(e.len() + 1, 0.0);
let len = grow_expansion(&e, t, &mut h);
h.truncate(len);
std::mem::swap(&mut e, &mut h);
}
}
}
e.iter().sum()
}
pub fn signed_area(polygon: &Polygon) -> f64 {
certified_twice_area(std::iter::once(polygon.exterior()).chain(polygon.holes().iter())) * 0.5
}
pub fn area(polygon: &Polygon) -> f64 {
signed_area(polygon)
}
#[cfg(test)]
#[allow(
clippy::float_cmp,
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::range_plus_one,
clippy::no_effect_underscore_binding
)]
mod tests {
use super::*;
use crate::types::CoordSeq;
fn ring(pts: &[(f64, f64)]) -> LinearRing {
let v: Vec<Coord2d> = pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect();
LinearRing::new(CoordSeq::new(v)).expect("valid ring")
}
#[test]
fn area_of_a_polygon_with_a_self_crossing_hole_is_its_signed_sum() {
let ext = ring(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
let spiral = ring(&[
(10.0, 10.0),
(10.0, 90.0),
(90.0, 90.0),
(90.0, 20.0),
(20.0, 20.0),
(20.0, 80.0),
(80.0, 80.0),
(80.0, 30.0),
(30.0, 30.0),
(30.0, 70.0),
(70.0, 70.0),
(70.0, 40.0),
(40.0, 40.0),
(40.0, 60.0),
(60.0, 60.0),
(60.0, 10.0),
]);
let p = Polygon::new(ext, vec![spiral]).expect("constructible: simplicity is not checked");
assert!(!crate::ops::is_valid(&p));
assert_eq!(area(&p), -1400.0);
}
#[test]
fn exact_path_gives_the_exact_sign_of_a_sliver_the_compensated_sum_cannot_certify() {
let o = 1.0e9_f64;
let ccw = ring(&[(o, o), (o + 4.0, o + 1.0), (o + 3.0, o + 1.0)]);
let cw = ring(&[(o, o), (o + 3.0, o + 1.0), (o + 4.0, o + 1.0)]);
assert_eq!(signed_area_ring(&ccw), 0.5);
assert_eq!(signed_area_ring(&cw), -0.5);
}
#[test]
fn exactly_collinear_ring_far_from_the_origin_has_exactly_zero_area() {
let o = 1.0e9_f64;
let r = ring(&[(o, o), (o + 1.0, o + 1.0), (o + 2.0, o + 2.0)]);
assert_eq!(signed_area_ring(&r), 0.0);
}
#[test]
fn certification_accepts_a_clear_sign_and_refuses_one_inside_the_error_bound() {
assert!(sign_is_certified(2.0, 4.0, 8.0));
assert!(sign_is_certified(-2.0, 4.0, 8.0));
let eps = f64::EPSILON * 0.5;
let gamma = 8.0 * eps / (1.0 - 8.0 * eps);
assert!(!sign_is_certified(gamma * gamma * 1.0e18, 1.0e18, 8.0));
assert!(!sign_is_certified(0.0, 1.0, 8.0));
assert!(!sign_is_certified(1.0e-30, 1.0e18, 8.0));
assert!(sign_is_certified(1.0e-3, 1.0e18, 8.0));
assert!(!sign_is_certified(1.0e-3, 1.0e18, 8.0e6));
}
#[test]
fn a_far_square_is_still_certified_without_the_exact_path() {
let near = ring(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]);
let far = ring(&[
(1e9, 1e9),
(1e9 + 1.0, 1e9),
(1e9 + 1.0, 1e9 + 1.0),
(1e9, 1e9 + 1.0),
]);
let cert = |r: &LinearRing| {
let (mut acc, mut s, mut m) = (Accum::new(), 0.0_f64, 0.0_f64);
for (a, b) in r.edges() {
acc.add_product(a.x, b.y);
acc.add_product(-b.x, a.y);
s += (a.x * b.y).abs() + (b.x * a.y).abs();
m += 2.0;
}
sign_is_certified(acc.value(), s, m)
};
assert!(cert(&near));
assert!(
cert(&far),
"area 1 vs S ~ 1e18: 4 gamma^2 S ~ 1e-12, still certified"
);
}
#[test]
fn exact_twice_area_matches_a_hand_computed_value() {
let r = ring(&[(0.0, 0.0), (3.0, 0.0), (3.0, 2.0), (0.0, 2.0)]);
assert_eq!(exact_twice_area_edges(r.edges()), 12.0);
}
#[test]
fn the_edge_form_reproduces_the_ring_form_bit_for_bit() {
let o = 1.0e9_f64;
let sliver = ring(&[(o, o), (o + 4.0, o + 1.0), (o + 3.0, o + 1.0)]);
let far = ring(&[(o, o), (o + 1.0, o), (o + 1.0, o + 1.0), (o, o + 1.0)]);
let ext = ring(&[
(o, o),
(o + 1000.0, o),
(o + 1000.0, o + 1000.0),
(o, o + 1000.0),
]);
let d = 2f64.powi(-20);
let hole = ring(&[
(o + d, o + d),
(o + d, o + 1000.0 - d),
(o + 1000.0 - d, o + 1000.0 - d),
(o + 1000.0 - d, o + d),
]);
let p = 1.0e15_f64;
let far_sliver = ring(&[(p, p), (p + 4.0, p + 1.0), (p + 3.0, p + 1.0)]);
let certified = |edges: Vec<(Coord2d, Coord2d)>| {
let (mut acc, mut s, mut m) = (Accum::new(), 0.0_f64, 0.0_f64);
for (a, b) in edges {
acc.add_product(a.x, b.y);
acc.add_product(-b.x, a.y);
s += (a.x * b.y).abs() + (b.x * a.y).abs();
m += 2.0;
}
sign_is_certified(acc.value(), s, m)
};
assert!(certified(sliver.edges().collect()));
assert!(certified(far.edges().collect()));
assert!(certified(ext.edges().chain(hole.edges()).collect()));
assert!(
!certified(far_sliver.edges().collect()),
"takes the exact fallback"
);
let before: [(&str, f64, u64); 4] = [
(
"sliver",
certified_twice_area(std::iter::once(&sliver)),
0x3ff0_0000_0000_0000,
),
(
"far square",
certified_twice_area(std::iter::once(&far)),
0x4000_0000_0000_0000,
),
(
"thin annulus",
certified_twice_area([&ext, &hole].into_iter()),
0x3f7f_3fff_ff80_0000,
),
(
"sliver at 1e15",
certified_twice_area(std::iter::once(&far_sliver)),
0x3ff0_0000_0000_0000,
),
];
for (name, now, bits) in before {
assert_eq!(
now.to_bits(),
bits,
"{name}: {now:e} vs {:e}",
f64::from_bits(bits)
);
}
assert_eq!(
certified_twice_area_edges(ext.edges().chain(hole.edges())).to_bits(),
0x3f7f_3fff_ff80_0000
);
assert_eq!(
certified_twice_area_edges(far_sliver.edges()).to_bits(),
0x3ff0_0000_0000_0000
);
}
#[test]
fn overflow_is_reported_as_non_finite_not_a_made_up_sign() {
let r = ring(&[(0.0, 0.0), (1e200, 0.0), (1e200, 1e200), (0.0, 1e200)]);
assert!(!signed_area_ring(&r).is_finite());
}
}