Skip to content

Commit

Permalink
Normalise value of cal_interpolate()
Browse files Browse the repository at this point in the history
  • Loading branch information
joeroe committed Oct 17, 2024
1 parent c05996d commit 234fcb1
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
8 changes: 7 additions & 1 deletion R/cal.R
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,14 @@ cal_age_common <- function(x, resolution = 1) {

#' Interpolate a cal vector over the given range
#'
#' Result is normalised
#'
#' @noRd
#' @keywords internal
cal_interpolate <- function(x, range = cal_age_common(x)) {
new_cal(furrr::future_map(vec_data(x), \(x) approx_df(x, range, ties = "ordered")))
new_cal(furrr::future_map(vec_data(x), function(x) {
x <- approx_df(x, range, ties = "ordered")
x$pdens <- x$pdens / sum(x$pdens, na.rm = TRUE)
x
}))
}
2 changes: 1 addition & 1 deletion R/cal_aggregate.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ cal_sum <- function(x, range = cal_age_common(x), normalise = FALSE, ...) {
x <- cal_interpolate(x, range)

pdens_sum <- furrr::future_pmap_dbl(cal_pdens(x), \(...) sum(..., na.rm = TRUE))
if (isTRUE(normalise)) pdens_sum <- pdens_sum / sum(pdens_sum)
if (isTRUE(normalise)) pdens_sum <- pdens_sum / sum(pdens_sum, na.rm = TRUE)

new_cal(list(data.frame(age = cal_age(x)[[1]], pdens = pdens_sum)))
}
4 changes: 4 additions & 0 deletions tests/testthat/test-cal.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ test_that("cal_age_common() returns a yr vector", {
# TODO: somehow test the expected length?
expect_vector(cal_age_common(y), y_yr_ptype)
})

test_that("cal_interpolate() is normalised", {
expect_equal(sum(cal_pdens(cal_interpolate(x))[[1]]), 1)
})

0 comments on commit 234fcb1

Please sign in to comment.