Created
February 27, 2024 18:47
-
-
Save PMassicotte/3aaf763e2bb3f3c2da8e1ff11133bb77 to your computer and use it in GitHub Desktop.
Rasterizing code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
library(terra) | |
library(tidync) | |
raster_template <- rast( | |
xmin = -71.1, | |
xmax = -50.7, | |
ymin = 39.05, | |
ymax = 51.45, | |
resolution = 0.05, | |
crs = "EPSG:4326" | |
) | |
nc_file <- "data/raw/CIOPSE_LH_12_06_19_06_traj.nc" | |
destination_folder <- "~/Desktop/tmp/" | |
time_step <- tidync(nc_file) |> | |
activate("D2") |> | |
hyper_tibble() |> | |
pull() | |
breaks <- seq(0, 1000, by = 50) | |
to_raster <- function(time_step, nc_file, breaks, raster_template, destination_folder) { | |
pts <- tidync(nc_file) |> | |
activate("D0,D1,D2") |> | |
hyper_filter(time = time == time_step) |> | |
hyper_tibble(force = TRUE) |> | |
select(lon, lat, zpo, time) |> | |
filter(lon != 0 | lat != 0) |> | |
filter(zpo <= 400) | |
if (nrow(pts) == 0) { | |
return() | |
} | |
pts <- pts |> | |
mutate(depth_bin = cut(zpo, breaks = breaks)) |> | |
mutate(depth_bin = str_remove(depth_bin, "\\(")) |> | |
mutate(depth_bin = str_remove(depth_bin, "\\]")) |> | |
mutate(depth_bin = str_replace(depth_bin, ",", "_")) |> | |
vect(geom = c("lon", "lat"), crs = "EPSG:4326") | |
filename <- paste0(destination_folder, "steptime_", time_step, ".tif") | |
r <- rasterize(pts, raster_template, fun = "count", by = "depth_bin") | |
# I am trying to fix what seems to be a bug when using the "by" argument. | |
# This hack seems to work for now. | |
# Issue opened here: https://github.com/rspatial/terra/issues/1435 | |
names(r) <- str_extract(names(r), "\\d+_\\d+") | |
writeRaster(r, filename, overwrite = TRUE) | |
} | |
walk( | |
time_step, | |
to_raster, | |
nc_file = nc_file, | |
breaks = breaks, | |
raster_template = raster_template, | |
destination_folder = destination_folder, | |
.progress = "Yo les jeunes" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment