Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exposed spatial predicates over Geometry #366

Merged
merged 5 commits into from
Feb 10, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 3 additions & 3 deletions src/raster/mdarray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,12 @@ impl<'a> MDArray<'a> {
Ok(())
}

/// Read a 'Buffer<T>' from this band. T implements 'GdalType'
/// Read a [`Vec<T>`] from this band, where `T` implements [`GdalType`].
///
/// # Arguments
/// * array_start_index - Values representing the starting index to read in each dimension (in `[0, aoDims[i].GetSize()-1]` range).
/// * `array_start_index` - Values representing the starting index to read in each dimension (in `[0, aoDims[i].GetSize()-1]` range).
/// Array of `GetDimensionCount()` values. Must not be empty, unless for a zero-dimensional array.
/// * count - Values representing the number of values to extract in each dimension. Array of `GetDimensionCount()` values.
/// * `count` - Values representing the number of values to extract in each dimension. Array of `GetDimensionCount()` values.
/// Must not be empty, unless for a zero-dimensional array.
metasim marked this conversation as resolved.
Show resolved Hide resolved
///
pub fn read_as<T: Copy + GdalType>(
Expand Down
12 changes: 6 additions & 6 deletions src/raster/rasterband.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ impl<'a> RasterBand<'a> {
(self.x_size(), self.y_size())
}

/// Read data from this band into a slice, where `T` implements ['GdalType']
/// Read data from this band into a slice, where `T` implements [`GdalType`]
///
/// # Arguments
///
Expand Down Expand Up @@ -293,7 +293,7 @@ impl<'a> RasterBand<'a> {
Ok(())
}

/// Read a 'Buffer<T>' from this band, where `T` implements ['GdalType'].
/// Read a [`Buffer<T>`] from this band, where `T` implements [`GdalType`].
///
/// # Arguments
///
Expand Down Expand Up @@ -373,7 +373,7 @@ impl<'a> RasterBand<'a> {

#[cfg(feature = "ndarray")]
#[cfg_attr(docsrs, doc(cfg(feature = "array")))]
/// Read a 'Array2<T>' from this band, where `T` implements ['GdalType'].
/// Read a [`Array2<T>`] from this band, where `T` implements [`GdalType`].
///
/// # Arguments
///
Expand All @@ -400,15 +400,15 @@ impl<'a> RasterBand<'a> {
)?)
}

/// Read the full band as a 'Buffer<T>', where `T` implements ['GdalType'].
/// Read the full band as a [`Buffer<T>`], where `T` implements [`GdalType`].
pub fn read_band_as<T: Copy + GdalType>(&self) -> Result<Buffer<T>> {
let size = self.size();
self.read_as::<T>((0, 0), (size.0, size.1), (size.0, size.1), None)
}

#[cfg(feature = "ndarray")]
#[cfg_attr(docsrs, doc(cfg(feature = "array")))]
/// Read a 'Array2<T>' from a 'Dataset' block, where `T` implements ['GdalType'].
/// Read a [`Array2<T>`] from a [`Dataset`] block, where `T` implements [`GdalType`].
///
/// # Arguments
/// * `block_index` - the block index
Expand Down Expand Up @@ -440,7 +440,7 @@ impl<'a> RasterBand<'a> {
Array2::from_shape_vec((size.1, size.0), data).map_err(Into::into)
}

/// Write a 'Buffer<T>' into a 'Dataset'.
/// Write a [`Buffer<T>`] into a [`Dataset`].
///
metasim marked this conversation as resolved.
Show resolved Hide resolved
/// # Arguments
///
Expand Down
16 changes: 16 additions & 0 deletions src/vector/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,17 @@ impl Geometry {
Ok(unsafe { Geometry::with_c_geometry(c_geom, true) })
}
}

/// Test if the geometry is valid.
///
/// This function is built on the GEOS library.
/// If OGR is built without the GEOS library, this function will always return `false`.
///
/// See: [`OGR_G_IsValid`](https://gdal.org/api/vector_c_api.html#_CPPv413OGR_G_IsValid12OGRGeometryH)
pub fn is_valid(&self) -> bool {
Copy link
Member

Choose a reason for hiding this comment

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

is there a way to determine if OGR was build with GEOS?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jdroenner I'll look into it. It might require build.rs calling into gdal_sys, which might be weird...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If build.rs can find gdalinfo in the path:

image

Copy link
Contributor Author

@metasim metasim Feb 6, 2023

Choose a reason for hiding this comment

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

@jdroenner I assume the implication of your question is that we'd want to optionally enable these GOES-dependent features? How about the case when someone compiles with GEOS support, but at runtime a different GDAL build is dynamically linked?

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, I don't think we should gate these methods on GEOS. GDAL always has them, we should probably match that.

Copy link
Contributor Author

@metasim metasim Feb 6, 2023

Choose a reason for hiding this comment

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

we should probably match that

WDYM? Assume GEOS is there? (Pretty sure you can build without it, although really rare).

If so, should I remove the caveat in these doc comments?

Copy link
Member

@lnicola lnicola Feb 6, 2023

Choose a reason for hiding this comment

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

I meant letting them compile and returning what GDAL returns.

Copy link
Member

Choose a reason for hiding this comment

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

I don't want a feature gate. However there should be a method you can call (at runtime) to get the information if GEOS was build in.

Copy link
Member

Choose a reason for hiding this comment

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

ah i guess its GDALVersionInfo and then looking if GEOS is in there. Maybe we can add a convenience method for that to our VersionInfo struct.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Great idea. On it! 🤠

let p = unsafe { gdal_sys::OGR_G_IsValid(self.c_geometry()) };
p != 0
}
}

impl Drop for Geometry {
Expand Down Expand Up @@ -689,13 +700,15 @@ mod tests {
let src = Geometry::from_wkt("POINT (0 0)").unwrap();
let dst = src.make_valid(&CslStringList::new());
assert!(dst.is_ok());
assert!(dst.unwrap().is_valid());
}

#[test]
/// Un-repairable geometry case
pub fn test_make_valid_invalid() {
let _nolog = SuppressGDALErrorLog::new();
let src = Geometry::from_wkt("LINESTRING (0 0)").unwrap();
assert!(!src.is_valid());
let dst = src.make_valid(&CslStringList::new());
assert!(dst.is_err());
}
Expand All @@ -704,8 +717,10 @@ mod tests {
/// Repairable case (self-intersecting)
pub fn test_make_valid_repairable() {
let src = Geometry::from_wkt("POLYGON ((0 0, 10 10, 0 10, 10 0, 0 0))").unwrap();
assert!(!src.is_valid());
let dst = src.make_valid(&CslStringList::new());
assert!(dst.is_ok());
assert!(dst.unwrap().is_valid());
}

#[cfg(all(major_ge_3, minor_ge_4))]
Expand All @@ -718,5 +733,6 @@ mod tests {
let opts = CslStringList::try_from(&[("STRUCTURE", "LINEWORK")]).unwrap();
let dst = src.make_valid(&opts);
assert!(dst.is_ok(), "{dst:?}");
assert!(dst.unwrap().is_valid());
}
}
1 change: 1 addition & 0 deletions src/vector/ops/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod geometry;
mod predicates;

pub use geometry::intersection::Intersection as GeometryIntersection;
182 changes: 182 additions & 0 deletions src/vector/ops/predicates.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use crate::vector::Geometry;

/// These methods define common [spatial relations](https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates) between
/// two geometries.
impl Geometry {
/// Tests if two geometries [_intersect_][DE-9IM];
/// `self` and `other` have at least one point in common.
///
/// If GEOS is enabled, then this is done in rigorous fashion, otherwise `true` is returned
/// if the envelopes (bounding boxes) of the two geometries overlap.
///
/// See: [`OGR_G_Intersects`][OGR_G_Intersects]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Intersects]: https://gdal.org/api/vector_c_api.html#ogr__api_8h_1acaed6926b75cd33a42b284c10def6e87
pub fn intersects(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Intersects(self.c_geometry(), other.c_geometry()) };
p != 0
}

/// Tests if this geometry [_contains_][DE-9IM] the other geometry;
/// `other` lies in `self`, and the interiors intersect.
///
/// # Notes
/// * Geometry validity is not checked, and invalid geometry will generate unpredictable results.
/// Use [`Geometry::is_valid`] if validity might be in question.
/// * If GEOS is *not* enabled, this function will always return `false`.
///
/// See: [`OGR_G_Contains`][OGR_G_Contains]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Contains]: https://gdal.org/api/vector_c_api.html#_CPPv414OGR_G_Contains12OGRGeometryH12OGRGeometryH
pub fn contains(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Contains(self.c_geometry(), other.c_geometry()) };
p != 0
}

/// Tests if this geometry and the other geometry are [_disjoint_][DE-9IM];
/// `self` and `other` form a set of disconnected geometries.
///
/// # Notes
/// * Geometry validity is not checked, and invalid geometry will generate unpredictable results.
/// Use [`Geometry::is_valid`] if validity might be in question.
/// * If GEOS is *not* enabled, this function will always return `false`.
///
/// See: [`OGR_G_Disjoint`][OGR_G_Disjoint]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Disjoint]: https://gdal.org/api/vector_c_api.html#_CPPv414OGR_G_Disjoint12OGRGeometryH12OGRGeometryH
pub fn disjoint(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Disjoint(self.c_geometry(), other.c_geometry()) };
p != 0
}

/// Tests if this geometry and the other geometry are [_touching_][DE-9IM];
/// `self` and `other` have at least one point in common, but their interiors do not intersect.
///
/// # Notes
/// * Geometry validity is not checked, and invalid geometry will generate unpredictable results.
/// Use [`Geometry::is_valid`] if validity might be in question.
/// * If GEOS is *not* enabled, this function will always return `false`.
///
/// See: [`OGR_G_Touches`][OGR_G_Touches]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Touches]: https://gdal.org/api/ogrgeometry_cpp.html#_CPPv4NK11OGRGeometry7TouchesEPK11OGRGeometry
pub fn touches(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Touches(self.c_geometry(), other.c_geometry()) };
p != 0
}

/// Tests if this geometry and the other geometry are [_crossing_][DE-9IM];
/// `self` and `other` have some but not all interior points in common, and the dimension of
/// the intersection is less than that of at least one of them.
///
/// # Notes
/// * Geometry validity is not checked, and invalid geometry will generate unpredictable results.
/// Use [`Geometry::is_valid`] if validity might be in question.
/// * If GEOS is *not* enabled, this function will always return `false`.
///
/// See: [`OGR_G_Crosses`][OGR_G_Crosses]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Crosses]: https://gdal.org/api/ogrgeometry_cpp.html#_CPPv4NK11OGRGeometry7CrossesEPK11OGRGeometry
pub fn crosses(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Crosses(self.c_geometry(), other.c_geometry()) };
p != 0
}

/// Tests if this geometry is [_within_][DE-9IM] the other;
/// `self` lies fully in the interior of `other`.
///
/// # Notes
/// * Geometry validity is not checked, and invalid geometry will generate unpredictable results.
/// Use [`Geometry::is_valid`] if validity might be in question.
/// * If GEOS is *not* enabled, this function will always return `false`.
///
/// See: [`OGR_G_Within`][OGR_G_Within]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Within]: https://gdal.org/api/ogrgeometry_cpp.html#_CPPv4NK11OGRGeometry6WithinEPK11OGRGeometry
pub fn within(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Within(self.c_geometry(), other.c_geometry()) };
p != 0
}

/// Tests if this geometry and the other [_overlap_][DE-9IM];
/// `self` and `other` they have some but not all points in common,
/// they have the same dimension,
/// and the intersection of the interiors has the same dimension as the geometries.
///
/// # Notes
/// * Geometry validity is not checked, and invalid geometry will generate unpredictable results.
/// Use [`Geometry::is_valid`] if validity might be in question.
/// * If GEOS is *not* enabled, this function will always return `false`.
///
/// See: [`OGR_G_Overlaps`][OGR_G_Overlaps]
///
/// [DE-9IM]: https://en.wikipedia.org/wiki/DE-9IM#Spatial_predicates
/// [OGR_G_Overlaps]: https://gdal.org/api/ogrgeometry_cpp.html#_CPPv4NK11OGRGeometry8OverlapsEPK11OGRGeometry
pub fn overlaps(&self, other: &Self) -> bool {
let p = unsafe { gdal_sys::OGR_G_Overlaps(self.c_geometry(), other.c_geometry()) };
p != 0
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_intersects() {
let poly = Geometry::from_wkt("POLYGON((0 0,5 5,10 0,0 0))").unwrap();
let point = Geometry::from_wkt("POINT(10 0)").unwrap();
assert!(poly.intersects(&point));
}

#[test]
fn test_contains() {
let poly = Geometry::from_wkt("POLYGON((0 0,5 5,10 0,0 0))").unwrap();
let point = Geometry::from_wkt("POINT(10 0)").unwrap();
assert!(!poly.contains(&point));
let point = Geometry::from_wkt("POINT(0.1 0.01)").unwrap();
assert!(poly.contains(&point));
}

#[test]
fn test_disjoint() {
let poly = Geometry::from_wkt("POLYGON((0 0,5 5,10 0,0 0))").unwrap();
let line = Geometry::from_wkt("LINESTRING(-1 -1, -2 -2)").unwrap();
assert!(poly.disjoint(&line));
}

#[test]
fn test_touches() {
let line1 = Geometry::from_wkt("LINESTRING(0 0, 10 10)").unwrap();
let line2 = Geometry::from_wkt("LINESTRING(0 0, 0 10)").unwrap();
assert!(line1.touches(&line2));
}

#[test]
fn test_crosses() {
let line1 = Geometry::from_wkt("LINESTRING(0 0, 10 10)").unwrap();
let line2 = Geometry::from_wkt("LINESTRING(10 0, 0 10)").unwrap();
assert!(line1.crosses(&line2));
}

#[test]
fn test_within() {
let poly1 = Geometry::from_wkt("POLYGON((0 0, 10 10, 10 0, 0 0))").unwrap();
let poly2 = Geometry::from_wkt("POLYGON((-90 -90, -90 90, 190 -90, -90 -90))").unwrap();
assert!(poly1.within(&poly2));
assert!(!poly2.within(&poly1));
}

#[test]
fn test_overlaps() {
let poly1 = Geometry::from_wkt("POLYGON((0 0, 10 10, 10 0, 0 0))").unwrap();
let poly2 = Geometry::from_wkt("POLYGON((0 -5,10 5,10 -5,0 -5))").unwrap();
assert!(poly1.overlaps(&poly2));
}
}