davidiles / Landbird-Distribution-Modeling-ECCC

Analysis of landbird distributions for Environment Canada
1 stars 2 forks source link

unnecessary resample after project? #1

Open see24 opened 7 months ago

see24 commented 7 months ago

Hey Dave,

I noticed something in your code that seemed odd to me so I did some digging. I think what I found would make things slightly faster so I wanted to document it but let me know if an issue is an annoying way to do that!!

In Saskatchewan 3_Prepare_Covariates.R you have a bunch of spots where you project(x, y, align = TRUE) %>% resample(y). I was wondering why this was needed since I thought that project could handle both. Looking into it I learned that align is a poorly named argument and actually means align to the extent of x instead of the default when align = FALSE which aligns to the extent of y.

Here is a toy example showing what align really does:

library(terra)
#> terra 1.7.46

a <- rast(ncols=40, nrows=40, xmin=-110, xmax=-90, ymin=40, ymax=60, 
          crs="+proj=longlat +datum=WGS84")
values(a) <- 1:ncell(a)
newcrs="+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +datum=WGS84"
b <- rast(ncols=94, nrows=124, xmin=-944881, xmax=935118, ymin=4664377, ymax=7144377, crs=newcrs)

w <- project(a, b)
compareGeom(w, b)
#> [1] TRUE

w2 <- resample(w, b)
all.equal(w2, w)
#> [1] TRUE

w_align <- project(a, b, align = TRUE)
compareGeom(w_align, b)
#> Error: [compareGeom] extents do not match

w2_align <- resample(w_align, b)
compareGeom(w2_align, b)
#> [1] TRUE

# result is the same if you project with align = FALSE as if you project with
# align = TRUE and then resample
all.equal(w2_align, w)
#> [1] TRUE

Created on 2024-01-31 with reprex v2.0.2

see24 commented 7 months ago

FYI I posted an issue on the terra repo about the confusing name and they have renamed it to align_only https://github.com/rspatial/terra/issues/1416

davidiles commented 7 months ago

Awesome! Thanks for pointing this out.