Rasters.jl icon indicating copy to clipboard operation
Rasters.jl copied to clipboard

Comparing R Terra and Julia Rasters crop function: alignment y to the geometry of x

Open Rapsodia86 opened this issue 8 months ago • 6 comments

Hello! I have my code written in R using terra package (https://github.com/rspatial/terra), where I get pixel count based on different masks from rasters & polygons.

In a simple experiment, I cropped a raster with a smaller one. (Pixels are the same resolution and they 100% overlap). And so, due to differences in crop approach, I am getting different results.

In terra's crop function, as a default, there is a parameter snap set as "near" for the alignment y to the geometry of x. I do not care about touches because it is for polygons only. (https://rdrr.io/cran/terra/man/crop.html) Depending on the settings, I get:

(1) snap="in"
dimensions  : 901, 1760, 1  (nrow, ncol, nlyr)
extent      : -1986126, -1106126, 1312602, 1763102  (xmin, xmax, ymin, ymax)
(2) snap="out"
dimensions  : 903, 1760, 1  (nrow, ncol, nlyr)
extent      : -1986126, -1106126, 1312102, 1763602  (xmin, xmax, ymin, ymax)
(3) snap="near" #This is a default approach I use in my original code, and this I what I would like to have in Julia.
dimensions  : 902, 1760, 1  (nrow, ncol, nlyr)
extent      : -1986126, -1106126, 1312102, 1763102  (xmin, xmax, ymin, ymax)

In Julia Rasters, the control is via touches: If touches=false:

1760×901 Raster{Float32,2} with dimensions: 
  X Projected{Float64} LinRange{Float64}(-1.98613e6, -1.10663e6, 1760) ForwardOrdered Regular Intervals crs: WellKnownText,
  Y Projected{Float64} LinRange{Float64}(1.7626e6, 1.3126e6, 901) ReverseOrdered Regular Intervals crs: WellKnownText     
and reference dimensions: 
  Band Categorical{String} String["TSen_Slope"] Unordered
extent: Extent(X = (-1.986125753830057e6, -1.1061257538300573e6), Y = (1.3126021807256853e6, 1.7631021807256853e6))       
missingval: NaN32

If touches=true:

1762×903 Raster{Float32,2} with dimensions: 
  X Projected{Float64} LinRange{Float64}(-1.98663e6, -1.10613e6, 1762) ForwardOrdered Regular Intervals crs: WellKnownText,
  Y Projected{Float64} LinRange{Float64}(1.7631e6, 1.3121e6, 903) ReverseOrdered Regular Intervals crs: WellKnownText     
and reference dimensions: 
  Band Categorical{String} String["TSen_Slope"] Unordered
extent: Extent(X = (-1.9866257538300573e6, -1.105625753830057e6), Y = (1.3121021807256853e6, 1.7636021807256856e6))       
missingval: NaN32

So the comparable result (based on pixel dimension) is when in terra I set snap="in" while in Julia Raster's touches=false. But all my original R scripts are based on default snap="near". Also, I have seen https://github.com/rafaqz/Rasters.jl/issues/312 for boundary using mask. Would you consider adding alignment control?

Thank you!

Rapsodia86 avatar Nov 08 '23 17:11 Rapsodia86