PecanProject / pecan

The Predictive Ecosystem Analyzer (PEcAn) is an integrated ecological bioinformatics toolbox.
www.pecanproject.org
Other
199 stars 230 forks source link

aggregate.R created #3317

Open Snafkin547 opened 4 days ago

Snafkin547 commented 4 days ago

Description

The aggregate function, created using exactextractr, enables the aggregation (sum and average) of previously downscaled carbon flux output from the NA_downscale function. Users can aggregate data for spatial areas of their choice by providing appropriate polygon data.

Motivation and Context

This change is required to enable the aggregation of downscaled carbon flux data to user-specified spatial units. It solves the problem of needing to summarize large-scale raster data into meaningful aggregated values (sum and average) for specific areas, aiding in spatial analysis and decision-making.

Review Time Estimate

Types of changes

Checklist:

Snafkin547 commented 4 days ago

You can run this function in this way:

Download a shapefile of U.S. states (if not already available)

url <- "https://www2.census.gov/geo/tiger/GENZ2020/shp/cb_2020_us_state_20m.zip"
download.file(url, destfile = "polygon/us_states.zip")
unzip("polygon/us_states.zip", exdir = "polygon/us_states")

Load the shapefile

us_states <- st_read("polygon/us_states/cb_2020_us_state_20m.shp")
saveRDS(us_states, "polygon/polygon_us_states.rds")

Load the downscale_output list

downscale_output <- readRDS("path/to/your raster file")

read_raster <- function(file_path) {
  rast(file_path)
}

downscale_output$maps <- lapply(downscale_output$maps, read_raster)
us_states <- readRDS("polygon/us_states.rds")
state = "MA"
polygon_data <- st_transform(us_states[us_states$STUSPS == state, ], crs = "EPSG:4326")

massachusetts <- aggregate_by_state(downscale_output, polygon_data)

print(massachusetts)
plot(st_geometry(massachusetts))