diff --git a/NEWS.md b/NEWS.md index 7490e25..49fc0d6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -44,6 +44,11 @@ `fill_missing_ids = TRUE` and `group_by` leave combinations missing. - `constraint = "total"` no longer adds an index to the user's `land_use_data`. + - `constraint = "total"` and `"singly"` now treat each `group_by` + combination and each decay value as an independent system. Previously, + `"total"` split the regional total across groups and both blended + several decay values into one result. Detailed results now keep the + `group_by` and `decay_function_arg` columns (#66, @soukhova). - `cost_to_closest()` no longer returns `Inf` due to integer overflow with large opportunity counts. - `cumulative_cutoff()`: cutoffs with floating point noise (e.g. from diff --git a/R/constrained_accessibility.R b/R/constrained_accessibility.R index 62ed461..4a6c86b 100644 --- a/R/constrained_accessibility.R +++ b/R/constrained_accessibility.R @@ -36,6 +36,17 @@ #' This function covers the family of constrained accessibility measures #' proposed in \insertCite{soukhov2025family;textual}{accessibility}. #' +#' For these measures, each group or decay value is +#' treated as an independent land-use-transportation system. This is not a multimodal +#' model that splits demand or supply across groups. Instead, each group is +#' calculated as if the function were run separately on that group's rows of +#' `travel_matrix`. The total allocated within a group is the sum of the +#' opportunities (or population) associated with the ids that appear in that +#' group's rows. +#' +#' As well, when `fill_missing_ids = TRUE`, ids that are absent from a particular +#' group's rows are still returned with accessibility equal to 0. +#' #' ## Total Constrained Accessibility #' #' Allocates the system-wide total proportionally based on travel impedance @@ -199,7 +210,9 @@ #' and `flow`, holding the demand of each origin followed by the supply of #' each destination (so an id can appear twice). #' -#' Detailed results don't include the `group_by` columns. +#' For `constraint = "total"` and `"singly"`, detailed results include the +#' `group_by` columns and, when the decay function has several values, +#' `decay_function_arg`. #' #' @references #' \insertAllCited{} diff --git a/R/singly_constrained.R b/R/singly_constrained.R index cc2bf58..27c2607 100644 --- a/R/singly_constrained.R +++ b/R/singly_constrained.R @@ -64,6 +64,15 @@ singly_constrained <- function(travel_matrix, # Apply decay data <- apply_gravity_measure(data, decay_function, travel_cost) + if ("decay_function_arg" %in% names(data)) { + group_by <- c(group_by, "decay_function_arg") + } + + detail_cols <- c( + "from_id", + "to_id", + group_by + ) if (active) { # Supply-constrained (returns units of supply).. V_ij = (O_i f(c_ij) / sum_i O_i f(c_ij)) * D_j @@ -73,13 +82,17 @@ singly_constrained <- function(travel_matrix, data[, singly_access := kappa_singly * get(supply)] if (detailed_results) { - access <- data[, .( - from_id, - to_id, - kappa_singly, - supply = singly_access, - B_j = data.table::fifelse(denom_j > 0, 1 / denom_j, 0) - )] + access <- data[, c( + detail_cols, + "kappa_singly", + "singly_access", + "denom_j" + ), with = FALSE] + + data.table::setnames(access, "singly_access", "supply") + + access[, B_j := data.table::fifelse(denom_j > 0, 1 / denom_j, 0)] + access[, denom_j := NULL] } else { access <- data[, .(supply = sum(singly_access)), by = c("from_id", group_by)] if (fill_missing_ids) { @@ -100,13 +113,17 @@ singly_constrained <- function(travel_matrix, data[, singly_access := hatkappa_singly * get(demand)] if (detailed_results) { - access <- data[, .( - from_id, - to_id, - hatkappa_singly, - demand = singly_access, - A_i = data.table::fifelse(denom_i > 0, 1 / denom_i, 0) - )] + access <- data[, c( + detail_cols, + "hatkappa_singly", + "singly_access", + "denom_i" + ), with = FALSE] + + data.table::setnames(access, "singly_access", "demand") + + access[, A_i := data.table::fifelse(denom_i > 0, 1 / denom_i, 0)] + access[, denom_i := NULL] } else { access <- data[, .(demand = sum(singly_access)), by = c("to_id", group_by)] if (fill_missing_ids) { diff --git a/R/total_constrained.R b/R/total_constrained.R index 6f89364..10f42b9 100644 --- a/R/total_constrained.R +++ b/R/total_constrained.R @@ -19,7 +19,8 @@ utils::globalVariables(c( # common ids / columns "from_id", "to_id", "id", "opp_weight", "supply", "demand", "weighted_demand", "weighted_supply", # total-constrained - "kappa_total", "hatkappa_total", "K_total", "hatK_total", "constrained_opportunity", + "kappa_total", "hatkappa_total", "K_total", "hatK_total", "constrained_opportunity", "total_weighted_system", + "total_opportunities_region", # singly-constrained "denom_i", "denom_j", "kappa_singly", "hatkappa_singly", "A_i", "B_j", "singly_access", # doubly-constrained @@ -51,11 +52,8 @@ total_constrained <- function(travel_matrix, ) } merge_id <- "to_id" - group_id <- "from_id" weighted_col <- "weighted_supply" kappa_col <- "kappa_total" - total_col <- "K_total" - result_col <- "supply" opportunity_col <- supply } else { #passive accessibility @@ -67,11 +65,8 @@ total_constrained <- function(travel_matrix, ) } merge_id <- "from_id" - group_id <- "to_id" weighted_col <- "weighted_demand" kappa_col <- "hatkappa_total" - total_col <- "hatK_total" - result_col <- "demand" opportunity_col <- demand } @@ -103,40 +98,64 @@ total_constrained <- function(travel_matrix, # Apply decay data <- apply_gravity_measure(data, decay_function, travel_cost) + if ("decay_function_arg" %in% names(data)) { + group_by <- c(group_by, "decay_function_arg") + } # Core calculation data[, (weighted_col) := get(opportunity_col) * opp_weight] - total_weighted_system <- data[, sum(get(weighted_col))] + data[, total_weighted_system := sum(get(weighted_col)), by = group_by] data[, (kappa_col) := get(weighted_col) / total_weighted_system] - ids_for_total <- unique(data[[merge_id]]) # e.g., A,B,C when active=TRUE - total_opportunities_region <- sum( - land_use_data[[opportunity_col]][match(ids_for_total, land_use_data$id)], - na.rm = TRUE - ) + data[ + , + total_opportunities_region := sum(get(opportunity_col)[!duplicated(get(merge_id))]), + by = group_by + ] data[, constrained_opportunity := get(kappa_col) * total_opportunities_region] + detail_cols <- c( + "from_id", + "to_id", + group_by + ) + if (detailed_results) { if (!active) { - access <- data[, .( - from_id, - to_id, - weighted_demand, - hatkappa_total, - demand = constrained_opportunity, - hatK_total = total_opportunities_region / total_weighted_system - )] + access <- data[, c( + detail_cols, + "weighted_demand", + "hatkappa_total", + "constrained_opportunity", + "total_weighted_system", + "total_opportunities_region" + ), with = FALSE] + + data.table::setnames(access, "constrained_opportunity", "demand") + + access[, hatK_total := total_opportunities_region / total_weighted_system] + access[, total_weighted_system := NULL] + access[, total_opportunities_region := NULL] + } else { # supply-side details (active accessibility) - access <- data[, .( - from_id, - to_id, - weighted_supply, - kappa_total, - supply = constrained_opportunity, - K_total = total_opportunities_region / total_weighted_system - )] + access <- data[, c( + detail_cols, + "weighted_supply", + "kappa_total", + "constrained_opportunity", + "total_weighted_system", + "total_opportunities_region" + ), with = FALSE] + + data.table::setnames(access, "constrained_opportunity", "supply") + + access[, K_total := total_opportunities_region / total_weighted_system] + access[, total_weighted_system := NULL] + access[, total_opportunities_region := NULL] + + } } else { if (active) { @@ -150,6 +169,7 @@ total_constrained <- function(travel_matrix, access_col = "supply" ) } + } else { # demand aggregated by destination (to_id) access <- data[, .(demand = sum(constrained_opportunity)), by = c("to_id", group_by)] diff --git a/man/balancing_cost.Rd b/man/balancing_cost.Rd index ed54a55..a7c1d71 100644 --- a/man/balancing_cost.Rd +++ b/man/balancing_cost.Rd @@ -55,7 +55,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{fill_missing_ids}{A \code{logical}. Origins that never reach as many opportunities as there are people residing in them, as well as (when diff --git a/man/constrained_accessibility.Rd b/man/constrained_accessibility.Rd index 1574224..1592abe 100644 --- a/man/constrained_accessibility.Rd +++ b/man/constrained_accessibility.Rd @@ -80,7 +80,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{fill_missing_ids}{A \code{logical}. When calculating grouped accessibility estimates (i.e. when \code{group_by} is not empty), some combinations of groups @@ -122,7 +126,9 @@ and \code{flow}, holding the demand of each origin followed by the supply of each destination (so an id can appear twice). } -Detailed results don't include the \code{group_by} columns. +For \code{constraint = "total"} and \code{"singly"}, detailed results include the +\code{group_by} columns and, when the decay function has several values, +\code{decay_function_arg}. } \description{ Calculates accessibility using constraints, as proposed in @@ -134,6 +140,17 @@ constraint cases. Please see the Details section for more information. This function covers the family of constrained accessibility measures proposed in \insertCite{soukhov2025family;textual}{accessibility}. + +For these measures, each group or decay value is +treated as an independent land-use-transportation system. This is not a multimodal +model that splits demand or supply across groups. Instead, each group is +calculated as if the function were run separately on that group's rows of +\code{travel_matrix}. The total allocated within a group is the sum of the +opportunities (or population) associated with the ids that appear in that +group's rows. + +As well, when \code{fill_missing_ids = TRUE}, ids that are absent from a particular +group's rows are still returned with accessibility equal to 0. \subsection{Total Constrained Accessibility}{ Allocates the system-wide total proportionally based on travel impedance diff --git a/man/cost_to_closest.Rd b/man/cost_to_closest.Rd index 0545740..a654862 100644 --- a/man/cost_to_closest.Rd +++ b/man/cost_to_closest.Rd @@ -45,7 +45,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from diff --git a/man/cumulative_cutoff.Rd b/man/cumulative_cutoff.Rd index 02023c5..3e7b261 100644 --- a/man/cumulative_cutoff.Rd +++ b/man/cumulative_cutoff.Rd @@ -53,7 +53,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from diff --git a/man/cumulative_interval.Rd b/man/cumulative_interval.Rd index 7ec74f1..bc4c385 100644 --- a/man/cumulative_interval.Rd +++ b/man/cumulative_interval.Rd @@ -58,7 +58,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from diff --git a/man/floating_catchment_area.Rd b/man/floating_catchment_area.Rd index 6d05407..64bd354 100644 --- a/man/floating_catchment_area.Rd +++ b/man/floating_catchment_area.Rd @@ -58,7 +58,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{fill_missing_ids}{A \code{logical}. When calculating grouped accessibility estimates (i.e. when \code{group_by} is not empty), some combinations of groups diff --git a/man/gravity.Rd b/man/gravity.Rd index 0fac893..f6078bb 100644 --- a/man/gravity.Rd +++ b/man/gravity.Rd @@ -49,7 +49,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from diff --git a/man/roxygen/templates/group_by.R b/man/roxygen/templates/group_by.R index 7edc652..a18e6f0 100644 --- a/man/roxygen/templates/group_by.R +++ b/man/roxygen/templates/group_by.R @@ -4,3 +4,7 @@ #' departure time column, that specifies the departure time of each entry in #' the data frame, passing `"departure_time"` to this parameter results in #' accessibility estimates grouped by origin and by departure time. +#' +#' Accessibility is calculated separately for each unique combination of +#' grouping variables. For constrained accessibility measures, each group is +#' treated as an independent land-use-transportation system. diff --git a/man/spatial_availability.Rd b/man/spatial_availability.Rd index 6b96f57..6bad618 100644 --- a/man/spatial_availability.Rd +++ b/man/spatial_availability.Rd @@ -60,7 +60,11 @@ indicates the \code{travel_matrix} columns that should be used to group the accessibility estimates by. For example, if \code{travel_matrix} includes a departure time column, that specifies the departure time of each entry in the data frame, passing \code{"departure_time"} to this parameter results in -accessibility estimates grouped by origin and by departure time.} +accessibility estimates grouped by origin and by departure time. + +Accessibility is calculated separately for each unique combination of +grouping variables. For constrained accessibility measures, each group is +treated as an independent land-use-transportation system.} \item{fill_missing_ids}{A \code{logical}. When calculating grouped accessibility estimates (i.e. when \code{group_by} is not empty), some combinations of groups diff --git a/tests/testthat/test-assert_land_use_data.R b/tests/testthat/test-assert_land_use_data.R index 18c40ce..b7ee1b6 100644 --- a/tests/testthat/test-assert_land_use_data.R +++ b/tests/testthat/test-assert_land_use_data.R @@ -28,7 +28,7 @@ test_that("warns if travel_matrix contains ids that land_use_data does not", { ) ) ), - "treated as 0" + "treated[[:space:]]+as[[:space:]]+0" ) expect_warning( @@ -44,7 +44,7 @@ test_that("warns if travel_matrix contains ids that land_use_data does not", { ), active = FALSE ), - "treated as 0" + "treated[[:space:]]+as[[:space:]]+0" ) expect_warning( @@ -60,7 +60,7 @@ test_that("warns if travel_matrix contains ids that land_use_data does not", { ), active = NULL ), - "treated as 0" + "treated[[:space:]]+as[[:space:]]+0" ) expect_warning( @@ -76,7 +76,7 @@ test_that("warns if travel_matrix contains ids that land_use_data does not", { ), active = NULL ), - "treated as 0" + "treated[[:space:]]+as[[:space:]]+0" ) }) @@ -86,7 +86,7 @@ test_that("warns if either opportunity or demand cols contain NAs", { rbind(land_use_data, data.table::data.table(id = "hehe"), fill = TRUE), demand = "population" ), - "treated as 0" + "treated[[:space:]]+as[[:space:]]+0" ) }) @@ -103,6 +103,6 @@ test_that("errors if land_use_data has duplicated ids", { duplicated_land_use <- rbind(land_use_data, land_use_data[1]) expect_error( tester(duplicated_land_use), - regexp = "must not contain duplicated ids" + regexp = "duplicated[[:space:]]+ids" ) }) diff --git a/tests/testthat/test-assert_sociodemographic_data_warnings.R b/tests/testthat/test-assert_sociodemographic_data_warnings.R index bcc9dc7..03da8f9 100644 --- a/tests/testthat/test-assert_sociodemographic_data_warnings.R +++ b/tests/testthat/test-assert_sociodemographic_data_warnings.R @@ -88,6 +88,6 @@ test_that("errors if sociodemographic_data has duplicated ids", { duplicated_sociodem <- rbind(land_use_data, land_use_data[1]) expect_error( tester(duplicated_sociodem, population = "population"), - regexp = "must not contain duplicated ids" + regexp = "duplicated[[:space:]]+ids" ) }) diff --git a/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index 9bba5d2..403c4cc 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -24,7 +24,7 @@ make_lu_match20 <- function() { exp_decay_01 <- decay_exponential(decay_value = 0.1) pow_decay_3 <- decay_power(decay_value = 3) -# ------------------------------- TOTAL ------------------------------- +#------------------------------- TOTAL (6 tests) ------------------------------- test_that("total-constrained: preserves totals on supply/demand sides", { tm <- make_tm_3x3() lu <- make_lu_large() @@ -83,7 +83,543 @@ test_that("total-constrained: preserves totals on supply/demand sides", { expect_equal(sum(agg_demand$demand), sum(lu$population)) }) -# ------------------------------ SINGLY ------------------------------- +test_that("total-constrained active multiple decay results equal single-decay runs", { + + # creating a 11x11 OD matrix, meaning 121 OD pairs + ids <- as.character(1:11) + + tm <- data.table::CJ( + from_id = ids, + to_id = ids + ) + + # assigning travel times that are abs(i-j) * 15, and 180 between 1->11 and 11->1 + tm[, travel_time := abs( + as.integer(from_id) - as.integer(to_id)) * 15] + + tm[from_id == "1" & to_id == "11", travel_time := 180] + tm[from_id == "11" & to_id == "1", travel_time := 180] + + #assigning population, and jobs to each id. + lu <- data.table::data.table( + id = ids, + population = c( + 100, 0, 250, 50, 0, + 400, 120, 80, 0, 200, 25 + ), # sums to 1225 + jobs = c( + 0, 500, 50, 0, 100, + 250, 0, 300, 75, 0, 150 + ) # sums to 1425 + ) + + multi <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.05, 0.20)), + supply = "jobs", + active = TRUE + ) + + run_005 <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.05), + supply = "jobs", + active = TRUE + ) + + run_020 <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.20), + supply = "jobs", + active = TRUE + ) + + # Does the multi-decay run result exactly the same values as a standalone run with decay=0.05? + expect_equal( + multi[decay_function_arg == 0.05][order(from_id)]$supply, + run_005[order(from_id)]$supply + ) + + # Does the multi-decay run result exactly the same values as a standalone run with decay=0.20? + expect_equal( + multi[decay_function_arg == 0.20][order(from_id)]$supply, + run_020[order(from_id)]$supply + ) + + # Does each decay scenario preserve the regional total opportunities? + totals <- multi[ + , + .(total_supply = sum(supply)), + by = decay_function_arg + ] + + expect_equal( + totals$total_supply, + rep(sum(lu$jobs), 2) + ) +}) + +test_that("total-constrained passive multiple decay values equal separate runs", { + + ids <- as.character(1:11) + + tm <- data.table::CJ( + from_id = ids, + to_id = ids + ) + + tm[, travel_time := abs( + as.integer(from_id) - as.integer(to_id) + ) * 15] + + lu <- data.table::data.table( + id = ids, + population = c( + 100, 0, 250, 50, 0, + 400, 120, 80, 0, 200, 25 + ), + jobs = c( + 0, 500, 50, 0, 100, + 250, 0, 300, 75, 0, 150 + ) + ) + + multi <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.05, 0.20)), + demand = "population", + active = FALSE + ) + + run_005 <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.05), + demand = "population", + active = FALSE + ) + + run_020 <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.20), + demand = "population", + active = FALSE + ) + + expect_equal( + multi[decay_function_arg == 0.05][order(to_id)]$demand, + run_005[order(to_id)]$demand + ) + + expect_equal( + multi[decay_function_arg == 0.20][order(to_id)]$demand, + run_020[order(to_id)]$demand + ) + + totals <- multi[ + , + .(total_demand = sum(demand)), + by = decay_function_arg + ] + + expect_equal( + totals$total_demand, + rep(sum(lu$population), 2) + ) +}) + +test_that("total-constrained grouped results equal standalone results", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm) + ), + idcol = "mode" + ) + + grouped <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + supply = "jobs", + active = TRUE, + group_by = "mode" + ) + + standalone <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + supply = "jobs", + active = TRUE + ) + + expect_equal( + grouped[mode == "car"][order(from_id)]$supply, + standalone[order(from_id)]$supply + ) + + expect_equal( + grouped[mode == "bus"][order(from_id)]$supply, + standalone[order(from_id)]$supply + ) +}) + +test_that("total-constrained preserves grouping variables in detailed and aggregated outputs", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm) + ), + idcol = "mode" + ) + + decay <- decay_exponential(c(0.1, 0.5)) + + detailed <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay, + supply = "jobs", + active = TRUE, + group_by = "mode", + detailed_results = TRUE + ) + + aggregated <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay, + supply = "jobs", + active = TRUE, + group_by = "mode", + detailed_results = FALSE + ) + + # detailed output preserves grouping variables + + expect_true("mode" %in% names(detailed)) + expect_true("decay_function_arg" %in% names(detailed)) + + expect_equal( + sort(unique(detailed$mode)), + c("bus", "car") + ) + + expect_equal( + sort(unique(detailed$decay_function_arg)), + c(0.1, 0.5) + ) + + # aggregated output preserves grouping variables + + expect_true("mode" %in% names(aggregated)) + expect_true("decay_function_arg" %in% names(aggregated)) + + expect_equal( + sort(unique(aggregated$mode)), + c("bus", "car") + ) + + expect_equal( + sort(unique(aggregated$decay_function_arg)), + c(0.1, 0.5) + ) + + # 3 origins × 2 modes × 2 decay values + + expect_equal(nrow(aggregated), 12L) +}) + +test_that("total-constrained (active) fills missing group combinations", { + + tm <- make_tm_3x3() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm)[from_id != "3"] + ), + idcol = "mode" + ) + + result <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_modes, + land_use_data = make_lu_match20(), + travel_cost = "travel_time", + decay_function = exp_decay_01, + supply = "jobs", + active = TRUE, + group_by = "mode", + fill_missing_ids = TRUE + ) + + expect_equal( + result[from_id == "3" & mode == "bus"]$supply, + 0 + ) +}) + +test_that( + "total-constrained groups are allocated only opportunities present in that group's ids", + { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + # Active accessibility (bus has no trips to destination 3) + bus_active <- tm[to_id != "3"] + + grouped_active <- constrained_accessibility( + constraint = "total", + travel_matrix = data.table::rbindlist( + list( + car = tm, + bus = bus_active + ), + idcol = "mode" + ), + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + supply = "jobs", + active = TRUE, + group_by = "mode" + ) + + standalone_active <- constrained_accessibility( + constraint = "total", + travel_matrix = bus_active, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + supply = "jobs", + active = TRUE + ) + + expect_equal( + grouped_active[mode == "bus", sum(supply)], + standalone_active[, sum(supply)] + ) + + # Passive accessibility (bus has no trips from origin 3) + bus_passive <- tm[from_id != "3"] + + grouped_passive <- constrained_accessibility( + constraint = "total", + travel_matrix = data.table::rbindlist( + list( + car = tm, + bus = bus_passive + ), + idcol = "mode" + ), + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + active = FALSE, + group_by = "mode" + ) + + standalone_passive <- constrained_accessibility( + constraint = "total", + travel_matrix = bus_passive, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + active = FALSE + ) + + expect_equal( + grouped_passive[mode == "bus", sum(demand)], + standalone_passive[, sum(demand)] + ) + } +) + +test_that("total-constrained uses each group's own regional total", { + + # with decay_binary(20) the reachable pairs (from -> to) of the full matrix + # are 1->1, 3->1, 2->2, 1->3 and 3->3. jobs = 7, 5, 8; population = 4, 10, 6 + # + # active, "bus" has no trips to 3 (jobs in the region: 7 + 5 = 12) + # weighted supply: 1->1 = 7, 3->1 = 7, 2->2 = 5, total 19 + # supply: 1 = 7 / 19 * 12, 2 = 5 / 19 * 12, 3 = 7 / 19 * 12 + # with decay_binary(40) every pair is reachable: each origin gets 12 / 3 + # + # "car" covers every pair (jobs in the region: 20) + # weighted supply: 1->1 = 7, 3->1 = 7, 2->2 = 5, 1->3 = 8, 3->3 = 8, total 35 + # supply: 1 = 15 / 35 * 20, 2 = 5 / 35 * 20, 3 = 15 / 35 * 20 + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm)[to_id != "3"] + ), + idcol = "mode" + ) + + active <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_binary(c(20, 40)), + supply = "jobs", + active = TRUE, + group_by = "mode" + ) + data.table::setorderv(active, c("mode", "decay_function_arg", "from_id")) + + expect_equal( + active[mode == "bus" & decay_function_arg == 20]$supply, + c(7, 5, 7) / 19 * 12 + ) + expect_equal( + active[mode == "bus" & decay_function_arg == 40]$supply, + c(4, 4, 4) + ) + expect_equal( + active[mode == "car" & decay_function_arg == 20]$supply, + c(15, 5, 15) / 35 * 20 + ) + + # passive, "bike" has no trips from 3 (population in the region: 4 + 10 = 14) + # weighted demand: 1->1 = 4, 2->2 = 10, 1->3 = 4, total 18 + # demand: 1 = 4 / 18 * 14, 2 = 10 / 18 * 14, 3 = 4 / 18 * 14 + + tm_bike <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bike = data.table::copy(tm)[from_id != "3"] + ), + idcol = "mode" + ) + + passive <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_bike, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_binary(20), + demand = "population", + active = FALSE, + group_by = "mode" + ) + + expect_equal( + passive[mode == "bike"][order(to_id)]$demand, + c(4, 10, 4) / 18 * 14 + ) + + # the detailed results use the same per-group total + detailed <- constrained_accessibility( + constraint = "total", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_binary(20), + supply = "jobs", + active = TRUE, + group_by = "mode", + detailed_results = TRUE + ) + + expect_equal(unique(detailed[mode == "bus"]$K_total), 12 / 19) + expect_equal(unique(detailed[mode == "car"]$K_total), 20 / 35) + expect_equal(sum(detailed[mode == "bus"]$supply), 12) +}) + +test_that("total/singly-constrained: grouped results equal standalone runs when groups cover different ids", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + # "bus" misses destination 3, "bike" misses origin 3, "walk" misses 1->2 + subsets <- list( + car = data.table::copy(tm), + bus = data.table::copy(tm)[to_id != "3"], + bike = data.table::copy(tm)[from_id != "3"], + walk = data.table::copy(tm)[!(from_id == "1" & to_id == "2")] + ) + tm_modes <- data.table::rbindlist(subsets, idcol = "mode") + + run <- function(travel_matrix, constraint, active, ...) { + constrained_accessibility( + constraint = constraint, + travel_matrix = travel_matrix, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = if (constraint == "singly" || !active) "population", + supply = if (constraint == "singly" || active) "jobs", + active = active, + fill_missing_ids = FALSE, + ... + ) + } + + for (constraint in c("total", "singly")) { + for (active in c(TRUE, FALSE)) { + id_col <- if (active) "from_id" else "to_id" + value_col <- if (active) "supply" else "demand" + + grouped <- run(tm_modes, constraint, active, group_by = "mode") + + for (m in names(subsets)) { + standalone <- run(subsets[[m]], constraint, active) + + expect_equal( + grouped[mode == m][order(get(id_col))][[value_col]], + standalone[order(get(id_col))][[value_col]], + info = paste(constraint, active, m) + ) + } + } + } +}) + + +# ------------------------------ SINGLY (6 tests)------------------------------- test_that("singly-constrained: preserves totals and kappa properties", { tm <- make_tm_3x3() lu <- make_lu_large() @@ -151,6 +687,353 @@ test_that("singly-constrained: preserves totals and kappa properties", { expect_equal(sum(det_demand$hatkappa_singly), length(unique(det_demand$from_id))) }) +test_that("singly-constrained active multiple decay values equal separate runs", { + + ids <- as.character(1:11) + + tm <- data.table::CJ( + from_id = ids, + to_id = ids + ) + + tm[, travel_time := abs( + as.integer(from_id) - as.integer(to_id) + ) * 15] + + tm[from_id == "1" & to_id == "11", travel_time := 180] + tm[from_id == "11" & to_id == "1", travel_time := 180] + + lu <- data.table::data.table( + id = ids, + population = c( + 100, 0, 250, 50, 0, + 400, 120, 80, 0, 200, 25 + ), + jobs = c( + 0, 500, 50, 0, 100, + 250, 0, 300, 75, 0, 150 + ) + ) + + multi <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.05, 0.20)), + demand = "population", + supply = "jobs", + active = TRUE + ) + + run_005 <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.05), + demand = "population", + supply = "jobs", + active = TRUE + ) + + run_020 <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.20), + demand = "population", + supply = "jobs", + active = TRUE + ) + # Does the multi-decay run result exactly the same values as a standalone run with decay=0.05? + expect_equal( + multi[decay_function_arg == 0.05][order(from_id)]$supply, + run_005[order(from_id)]$supply + ) + # Does the multi-decay run result exactly the same values as a standalone run with decay=0.20? + expect_equal( + multi[decay_function_arg == 0.20][order(from_id)]$supply, + run_020[order(from_id)]$supply + ) + # Does each decay scenario preserve the regional total opportunities? + totals <- multi[ + , + .(total_supply = sum(supply)), + by = decay_function_arg + ] + + expect_equal( + totals$total_supply, + rep(sum(lu$jobs), 2) + ) +}) + +test_that("singly-constrained passive multiple decay values equal separate runs", { + + ids <- as.character(1:11) + + tm <- data.table::CJ( + from_id = ids, + to_id = ids + ) + + tm[, travel_time := abs( + as.integer(from_id) - as.integer(to_id) + ) * 15] + + lu <- data.table::data.table( + id = ids, + population = c( + 100, 0, 250, 50, 0, + 400, 120, 80, 0, 200, 25 + ), + jobs = c( + 0, 500, 50, 0, 100, + 250, 0, 300, 75, 0, 150 + ) + ) + + multi <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.05, 0.20)), + demand = "population", + supply = "jobs", + active = FALSE + ) + + run_005 <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.05), + demand = "population", + supply = "jobs", + active = FALSE + ) + + run_020 <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.20), + demand = "population", + supply = "jobs", + active = FALSE + ) + + expect_equal( + multi[decay_function_arg == 0.05][order(to_id)]$demand, + run_005[order(to_id)]$demand + ) + + expect_equal( + multi[decay_function_arg == 0.20][order(to_id)]$demand, + run_020[order(to_id)]$demand + ) + + totals <- multi[ + , + .(total_demand = sum(demand)), + by = decay_function_arg + ] + + expect_equal( + totals$total_demand, + rep(sum(lu$population), 2) + ) +}) + + +test_that("singly-constrained preserves grouping variables in detailed outputs", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm) + ), + idcol = "mode" + ) + + decay <- decay_exponential(c(0.1, 0.5)) + + # active detailed output + result_active <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay, + demand = "population", + supply = "jobs", + active = TRUE, + group_by = "mode", + detailed_results = TRUE + ) + + expect_true("mode" %in% names(result_active)) + expect_true("decay_function_arg" %in% names(result_active)) + + expect_equal( + sort(unique(result_active$mode)), + c("bus", "car") + ) + + expect_equal( + sort(unique(result_active$decay_function_arg)), + c(0.1, 0.5) + ) + + # passive detailed output + result_passive <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay, + demand = "population", + supply = "jobs", + active = FALSE, + group_by = "mode", + detailed_results = TRUE + ) + + expect_true("mode" %in% names(result_passive)) + expect_true("decay_function_arg" %in% names(result_passive)) + + expect_equal( + sort(unique(result_passive$mode)), + c("bus", "car") + ) + + expect_equal( + sort(unique(result_passive$decay_function_arg)), + c(0.1, 0.5) + ) +}) + +test_that("singly-constrained grouped results equal standalone results", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm) + ), + idcol = "mode" + ) + + # active + grouped_active <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + active = TRUE, + group_by = "mode" + ) + + standalone_active <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + active = TRUE + ) + + expect_equal( + grouped_active[mode == "car"][order(from_id)]$supply, + standalone_active[order(from_id)]$supply + ) + + expect_equal( + grouped_active[mode == "bus"][order(from_id)]$supply, + standalone_active[order(from_id)]$supply + ) + + # passive + grouped_passive <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + active = FALSE, + group_by = "mode" + ) + + standalone_passive <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + active = FALSE + ) + + expect_equal( + grouped_passive[mode == "car"][order(to_id)]$demand, + standalone_passive[order(to_id)]$demand + ) + + expect_equal( + grouped_passive[mode == "bus"][order(to_id)]$demand, + standalone_passive[order(to_id)]$demand + ) +}) + +test_that("singly-constrained (active) fills missing group combinations", { + + tm <- make_tm_3x3() + + tm_modes <- data.table::rbindlist( + list( + car = data.table::copy(tm), + bus = data.table::copy(tm)[from_id != "3"] + ), + idcol = "mode" + ) + + result <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm_modes, + land_use_data = make_lu_match20(), + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + active = TRUE, + group_by = "mode", + fill_missing_ids = TRUE + ) + + expect_equal( + result[from_id == "3" & mode == "bus"]$supply, + 0 + ) +}) + # ------------------------------ DOUBLY ------------------------------- test_that("doubly-constrained: errors when totals mismatch", { tm <- make_tm_3x3() @@ -175,7 +1058,6 @@ test_that("doubly-constrained: errors when totals mismatch", { }) - test_that("doubly-constrained: OD flows match marginals", { tm <- make_tm_3x3() lu <- make_lu_match20() @@ -223,7 +1105,6 @@ test_that("doubly-constrained: results don't depend on row order or sparsity", { lu <- make_lu_match20() # independent iterative proportional fitting, as reference - reference_flows <- function(weights) { a <- b <- rep(1, 3) for (k in 1:2000) { @@ -275,7 +1156,6 @@ test_that("doubly-constrained: results don't depend on row order or sparsity", { ) # pairs missing from the travel matrix are unreachable - sparse_weights <- exp(-0.1 * cost) sparse_weights["1", "3"] <- 0 expected <- reference_flows(sparse_weights) @@ -292,7 +1172,6 @@ test_that("doubly-constrained: results don't depend on row order or sparsity", { test_that("doubly-constrained: errors when totals don't match", { # the missing id counts as 0, so the totals no longer match. the validators # also warn about the missing id - expect_error( suppressWarnings(constrained_accessibility( constraint = "doubly", @@ -312,7 +1191,6 @@ test_that("doubly-constrained: NA values and missing ids count as 0", { # id "4" is in travel_matrix but has NA demand and supply (or is missing from # land_use_data). it counts as 0, so it gets no flows and the flows between # the other ids are the same as without it - tm_4 <- data.table::data.table( expand.grid(from_id = c("1", "2", "3", "4"), to_id = c("1", "2", "3", "4")) ) @@ -375,7 +1253,6 @@ test_that("doubly-constrained: converges with very small impedance weights", { lu <- make_lu_match20() # exp(-0.5 * c) is ~1e-13 to 1e-19 here - result <- expect_silent( constrained_accessibility( constraint = "doubly", @@ -416,7 +1293,7 @@ test_that("doubly-constrained: warns when balancing doesn't converge", { max_iterations = 1, detailed_results = TRUE ), - regexp = "did not converge" + regexp = "did[[:space:]]+not[[:space:]]+converge" ) }) @@ -425,7 +1302,6 @@ test_that("fill_missing_ids fills missing combinations when using group_by", { lu <- make_lu_match20() # bus doesn't serve origin 3, so the (3, bus) combination is missing - tm_modes <- data.table::rbindlist( list(car = tm, bus = tm[from_id != "3"]), idcol = "mode" @@ -452,7 +1328,6 @@ test_that("fill_missing_ids fills missing combinations when using group_by", { } # singly-constrained car results don't depend on the bus rows - result <- run("singly", tm_modes) ungrouped <- run("singly", tm, group_by = character(0)) car <- result[mode == "car"] @@ -466,7 +1341,6 @@ test_that("total-constrained: doesn't add an index to land_use_data", { lu <- make_lu_large() # data.table auto-indexing is only triggered with character ids - tm <- make_tm_3x3() tm[, `:=`(from_id = as.character(from_id), to_id = as.character(to_id))] diff --git a/tests/testthat/test-constrained-wrapper.R b/tests/testthat/test-constrained-wrapper.R index 8be4d6c..1acbf96 100644 --- a/tests/testthat/test-constrained-wrapper.R +++ b/tests/testthat/test-constrained-wrapper.R @@ -62,11 +62,11 @@ test_that("wrapper argument rules are enforced", { expect_error( tester("total", active = NULL), - regexp = "active must be TRUE or FALSE" + regexp = "active[[:space:]]+must[[:space:]]+be[[:space:]]+TRUE" ) expect_error( tester("singly", active = NULL), - regexp = "active must be TRUE or FALSE" + regexp = "active[[:space:]]+must[[:space:]]+be[[:space:]]+TRUE" ) # active is ignored when constraint = "doubly" diff --git a/tests/testthat/test-cumulative_cutoff.R b/tests/testthat/test-cumulative_cutoff.R index b757263..74917d3 100644 --- a/tests/testthat/test-cumulative_cutoff.R +++ b/tests/testthat/test-cumulative_cutoff.R @@ -425,7 +425,7 @@ test_that("raises a clear error if id types are incompatible", { expect_error( tester(int_matrix, chr_land_use, cutoff = 5, group_by = character(0)), - regexp = "must be of compatible types" + regexp = "compatible[[:space:]]+types" ) # integer vs double and factor vs character ids join fine, so no error diff --git a/tests/testthat/test-decay_linear.R b/tests/testthat/test-decay_linear.R index ddd84ef..900e82a 100644 --- a/tests/testthat/test-decay_linear.R +++ b/tests/testthat/test-decay_linear.R @@ -63,6 +63,9 @@ test_that("output fn returns empty numeric if receives empty numeric/integer", { }) test_that("raises an error if cutoff is 0", { - expect_error(tester(0), regexp = "Value must be greater than 0") - expect_error(tester(c(0, 30)), regexp = "Value must be greater than 0") + expect_error(tester(0), regexp = "greater[[:space:]]+than[[:space:]]+0") + expect_error( + tester(c(0, 30)), + regexp = "greater[[:space:]]+than[[:space:]]+0" + ) }) diff --git a/tests/testthat/test-gravity.R b/tests/testthat/test-gravity.R index 8df7490..e70004b 100644 --- a/tests/testthat/test-gravity.R +++ b/tests/testthat/test-gravity.R @@ -328,7 +328,7 @@ test_that("raises an error if travel_matrix contains negative travel costs", { expect_error( tester(travel_matrix = negative_matrix), - regexp = "Travel costs must not[[:space:]]+be[[:space:]]+negative" + regexp = "must[[:space:]]+not[[:space:]]+be[[:space:]]+negative" ) # NA costs are still allowed