diff --git a/src/datasets/geotiff.jl b/src/datasets/geotiff.jl index cc388042..672b48a3 100644 --- a/src/datasets/geotiff.jl +++ b/src/datasets/geotiff.jl @@ -1,9 +1,21 @@ -function _find_span(n, m, M, pos) +function _find_span(n, m, M, pos, side) + side in [:left, :right, :bottom, :top] || throw(ArgumentError("side must be one of :left, :right, :bottom, top")) + pos > M && return nothing pos < m && return nothing stride = (M - m) / n centers = (m + 0.5stride):stride:(M-0.5stride) - span_pos = last(findmin(abs.(pos .- centers))) + pos_diff = abs.(pos .- centers) + pos_approx = isapprox.(pos_diff, 0.5stride) + if any(pos_approx) + if side in [:left, :bottom] + span_pos = findlast(pos_approx) + elseif side in [:right, :top] + span_pos = findfirst(pos_approx) + end + else + span_pos = last(findmin(abs.(pos .- centers))) + end return (stride, centers[span_pos], span_pos) end @@ -64,10 +76,10 @@ function geotiff( #global left_pos, right_pos #global bottom_pos, top_pos - lon_stride, left_pos, min_width = _find_span(width, minlon, maxlon, left) - _, right_pos, max_width = _find_span(width, minlon, maxlon, right) - lat_stride, top_pos, max_height = _find_span(height, minlat, maxlat, top) - _, bottom_pos, min_height = _find_span(height, minlat, maxlat, bottom) + lon_stride, left_pos, min_width = _find_span(width, minlon, maxlon, left, :left) + _, right_pos, max_width = _find_span(width, minlon, maxlon, right, :right) + lat_stride, top_pos, max_height = _find_span(height, minlat, maxlat, top, :top) + _, bottom_pos, min_height = _find_span(height, minlat, maxlat, bottom, :bottom) max_height, min_height = height .- (min_height, max_height) .+ 1 diff --git a/test/subsetting.jl b/test/subsetting.jl index 3bf6214d..f8d4caa4 100644 --- a/test/subsetting.jl +++ b/test/subsetting.jl @@ -6,18 +6,25 @@ temp = SimpleSDMPredictor(WorldClim, BioClim, 1) @test size(temp) == (1080, 2160) coords = (left = -145.0, right = -50.0, bottom = 20.0, top = 75.0) -layer = temp[coords] -@test size(layer) == (330, 570) +l1 = temp[coords] +l2 = SimpleSDMPredictor(WorldClim, BioClim, 1; coords...) -@test layer.left == coords.left -@test layer.right == coords.right -@test layer.bottom == coords.bottom -@test layer.top == coords.top +@test size(l1) == size(l2) +@test l1.grid == l2.grid -@test stride(layer) == stride(temp) -@test longitudes(layer)[1] == -144.91666666666666 -@test longitudes(layer)[end] == -50.083333333333336 -@test latitudes(layer)[1] == 20.083333333333332 -@test latitudes(layer)[end] == 74.91666666666667 +for l in (l1, l2) + @test size(l) == (330, 570) + + @test l.left == coords.left + @test l.right == coords.right + @test l.bottom == coords.bottom + @test l.top == coords.top + + @test stride(l) == stride(temp) + @test longitudes(l)[1] == -144.91666666666666 + @test longitudes(l)[end] == -50.083333333333336 + @test latitudes(l)[1] == 20.083333333333332 + @test latitudes(l)[end] == 74.91666666666667 +end end \ No newline at end of file