Skip to content

Commit

Permalink
Fix CRU multi-site downscaling (#67)
Browse files Browse the repository at this point in the history
CRU downscaling from monthly to daily was done wrongly for multiple sites. This now fixes it.
  • Loading branch information
fabern committed Dec 6, 2024
1 parent 4884e0a commit b8b79b0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
20 changes: 9 additions & 11 deletions R/ingest_globalfields.R
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,9 @@ ingest_globalfields <- function(
# expand monthly to daily data

if (length(cruvars)>0){
df_out <- expand_clim_cru_monthly( mdf, cruvars ) %>%
right_join( df_out, by = "date" )
df_out <- left_join(df_out,
expand_clim_cru_monthly( mdf, cruvars ),
by = c("date", "sitename") )
}

if ("vpd" %in% getvars){
Expand Down Expand Up @@ -924,15 +925,12 @@ ingest_globalfields_cru_byvar <- function( siteinfo, dir, varnam ){

expand_clim_cru_monthly <- function( mdf, cruvars ){

# ensure this function is always called with a single site only
stopifnot(length(unique(mdf$sitename)) == 1)
# for multiple sites the code would need to be adapted, e.g.:
# ddf2 <- mdf |>
# group_split(sitename, year) |>
# purrr::map(\(df) expand_clim_cru_monthly_byyr(first(df$year), df, cruvars))

ddf <- purrr::map(as.list(unique(mdf$year)),
~expand_clim_cru_monthly_byyr( ., mdf, cruvars ) ) %>%
ddf <- mdf |>
# apply it separately for each site and each year
group_split(sitename, year) |>
purrr::map(\(df) expand_clim_cru_monthly_byyr(first(df$year), df, cruvars) |>
mutate(sitename = first(df$sitename)) #ensure to keep sitename
) |>
bind_rows()

return( ddf )
Expand Down
4 changes: 2 additions & 2 deletions tests/testthat/test_CRU_WFDEI_NDEP.R
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,8 @@ test_that("test CRU data multisite downscaling (monthly and downscaled daily)",
# getvars = c("temp", "ccov"), # , "prec" NOTE: we can't test prec, unless we specify a seed somewhere
# dir = "/data/archive/cru_harris_2024/data",
# timescale = "m")}) |> bind_rows() |> ungroup() |> unnest(data)

# Illustration of failing test
#
# # Illustration of failing test
# library(ggplot2)
# p1 <- ggplot(df_cru_monthly_combined, aes(y=temp, x=date, linetype=sitename, color=sitename)) + ggtitle("df_cru_monthly_combined") + geom_point() # CORRECT
# p2 <- ggplot(df_cru_daily_separate, aes(y=temp, x=date, linetype=sitename, color=sitename)) + ggtitle("df_cru_daily_separate") + geom_line() # CORRECT DOWNSCALING
Expand Down

0 comments on commit b8b79b0

Please sign in to comment.