Skip to content

Commit

Permalink
Add comparison operators for some geometry types. (#22)
Browse files Browse the repository at this point in the history
* implement ==, hash for AbstractPoint

* add tests for comparison operators

* implement isapprox for Points, with tests
  • Loading branch information
rschwarz authored and yeesian committed Apr 3, 2019
1 parent 1ab41f2 commit cb1a26e
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/GeoInterface.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ module GeoInterface
bbox(obj::AbstractFeatureCollection) = nothing
crs(obj::AbstractFeatureCollection) = nothing

include("operations.jl")
include("geotypes.jl")
include("plotrecipes.jl")
end
10 changes: 10 additions & 0 deletions src/operations.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Base: ==, hash, isapprox

# Compare points by coordinate values.
==(x::P, y::P) where {P <: AbstractPoint} = coordinates(x) == coordinates(y)

# Hash the coordinates for consistency.
hash(x::P) where {P <: AbstractPoint} = hash(coordinates(x))

# Compare points approximately by coordinate values.
isapprox(x::P, y::P; kwargs...) where {P <: AbstractPoint} = isapprox(coordinates(x), coordinates(y); kwargs...)
36 changes: 36 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
@@ -1 +1,37 @@
using GeoInterface
using Test

@testset "Comparison operators" begin
# Points are now compared by value:
pt1, pt2, pt3 = Point([0.0, 0.0]), Point([0.0, 0.0]), Point([0.0, 1.0])
@test pt1 == pt1
@test pt1 == pt2
@test pt1 != pt3

# Also, the hash is based on the coordinates
@test hash(pt1) == hash(pt1)
@test hash(pt1) == hash(pt2)
@test hash(pt1) != hash(pt3)

# Implicitly, this should also work for `isequal`:
@test isequal(pt1, pt1)
@test isequal(pt1, pt2)
@test !isequal(pt1, pt3)

# Can also do approximate comparisons
pt4 = Point([0.0, 1.001])
@test pt3 != pt4
@test pt3 pt4 atol=0.0001
@test pt3 pt4 rtol=0.0001
@test pt3 pt4 atol=0.001
@test pt3 pt4 rtol=0.001

# The same is not true for other geometry types: The representation is not
# unique, so comparing the coordinates directly might be misleading.
pg1 = Polygon([[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]])
pg2 = Polygon([[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]])
pg3 = Polygon([[[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]])
@test pg1 == pg1 # same objects
@test pg1 != pg2 # same values, but different objects
@test pg1 != pg3 # equivalent, but not same values
end

0 comments on commit cb1a26e

Please sign in to comment.