From 4128f39fd40a61a2cb9f309cd7a9eb177361f8f8 Mon Sep 17 00:00:00 2001 From: soukhova Date: Sat, 24 Oct 2026 11:20:40 -0400 Subject: [PATCH 1/7] implemented fix for multi-decay support in total and singly constrained accessibility + tests --- R/singly_constrained.R | 3 + R/total_constrained.R | 12 +- tests/testthat/test-constrained-essentials.R | 1119 +++++++++++------- 3 files changed, 730 insertions(+), 404 deletions(-) diff --git a/R/singly_constrained.R b/R/singly_constrained.R index cc2bf58..1224527 100644 --- a/R/singly_constrained.R +++ b/R/singly_constrained.R @@ -64,6 +64,9 @@ 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") + } if (active) { # Supply-constrained (returns units of supply).. V_ij = (O_i f(c_ij) / sum_i O_i f(c_ij)) * D_j diff --git a/R/total_constrained.R b/R/total_constrained.R index 6f89364..192180f 100644 --- a/R/total_constrained.R +++ b/R/total_constrained.R @@ -51,11 +51,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 +64,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,12 +97,16 @@ 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)], diff --git a/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index 9bba5d2..6faabf7 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -24,462 +24,787 @@ make_lu_match20 <- function() { exp_decay_01 <- decay_exponential(decay_value = 0.1) pow_decay_3 <- decay_power(decay_value = 3) -# ------------------------------- TOTAL ------------------------------- -test_that("total-constrained: preserves totals on supply/demand sides", { - tm <- make_tm_3x3() - lu <- make_lu_large() +# # ------------------------------- TOTAL ------------------------------- +# test_that("total-constrained: preserves totals on supply/demand sides", { +# tm <- make_tm_3x3() +# lu <- make_lu_large() +# +# # Supply-side output (returns accessible opportunities) +# det_supply <- constrained_accessibility( +# constraint = "total", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = NULL, +# supply = "jobs", +# detailed_results = TRUE, +# active = TRUE +# ) +# agg_supply <- constrained_accessibility( +# constraint = "total", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = NULL, +# supply = "jobs", +# detailed_results = FALSE, +# active = TRUE +# ) +# +# # Demand-side output (returns accessible population) +# det_demand <- constrained_accessibility( +# constraint = "total", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = NULL, +# detailed_results = TRUE, +# active = FALSE +# ) +# agg_demand <- constrained_accessibility( +# constraint = "total", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = NULL, +# detailed_results = FALSE, +# active = FALSE +# ) +# +# expect_equal(sum(det_supply$supply), sum(lu$jobs)) +# expect_equal(sum(agg_supply$supply), sum(lu$jobs)) +# expect_equal(sum(det_demand$demand), sum(lu$population)) +# expect_equal(sum(agg_demand$demand), sum(lu$population)) +# }) +# +# # ------------------------------ SINGLY ------------------------------- +# test_that("singly-constrained: preserves totals and kappa properties", { +# tm <- make_tm_3x3() +# lu <- make_lu_large() +# +# # Supply-constrained (returns accessible opportunities) +# det_supply <- constrained_accessibility( +# travel_matrix = tm, +# land_use_data = lu, +# constraint = "singly", +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# active = TRUE +# ) +# agg_supply <- constrained_accessibility( +# constraint = "singly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = FALSE, +# active = TRUE +# ) +# +# # Demand-constrained (returns accessible population) +# det_demand <- constrained_accessibility( +# constraint = "singly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# active = FALSE +# ) +# agg_demand <- constrained_accessibility( +# constraint = "singly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = FALSE, +# active = FALSE +# ) +# +# # Totals +# expect_equal(sum(det_supply$supply), sum(lu$jobs)) +# expect_equal(sum(agg_supply$supply), sum(lu$jobs)) +# expect_equal(sum(det_demand$demand), sum(lu$population)) +# expect_equal(sum(agg_demand$demand), sum(lu$population)) +# +# # κ normalization properties (these DO hold for singly) +# by_to <- det_supply[, .(sum_k = sum(kappa_singly)), by = to_id] +# by_from <- det_demand[, .(sum_k = sum(hatkappa_singly)), by = from_id] +# expect_true(all(abs(by_to$sum_k - 1) < 1e-8)) # per-destination sums == 1 +# expect_true(all(abs(by_from$sum_k - 1) < 1e-8)) # per-origin sums == 1 +# expect_equal(sum(det_supply$kappa_singly), length(unique(det_supply$to_id))) +# expect_equal(sum(det_demand$hatkappa_singly), length(unique(det_demand$from_id))) +# }) +# +# # ------------------------------ DOUBLY ------------------------------- +# test_that("doubly-constrained: errors when totals mismatch", { +# tm <- make_tm_3x3() +# lu_bad <- data.table::copy(make_lu_match20()) +# lu_bad[id == "3", jobs := jobs + 1] # break equality +# +# expect_error( +# constrained_accessibility( +# constraint = "doubly", +# travel_matrix = tm, +# land_use_data = lu_bad, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# active = NULL +# ), +# # cli wraps long messages, so spaces may be line breaks +# "sum of origins must equal the sum of[[:space:]]+destinations" +# ) +# }) +# +# +# +# test_that("doubly-constrained: OD flows match marginals", { +# tm <- make_tm_3x3() +# lu <- make_lu_match20() +# decay <- pow_decay_3 +# +# det <- constrained_accessibility( +# constraint = "doubly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = decay, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# active = NULL +# ) +# +# # Robustly pick the numeric flow column +# candidate_cols <- c("flow", "supply", "demand") +# value_col <- intersect(candidate_cols, names(det))[1] +# expect_true(!is.null(value_col), info = "No flow/supply/demand column in detailed output") +# expect_true(is.numeric(det[[value_col]]), info = "Flow column must be numeric") +# +# # Sum flows by origin and destination +# by_origin <- det[, .(sum_flow = sum(get(value_col))), by = from_id] +# by_dest <- det[, .(sum_flow = sum(get(value_col))), by = to_id] +# +# # Build expected marginals from land use +# O <- lu[match(by_origin$from_id, lu$id), population] +# D <- lu[match(by_dest$to_id, lu$id), jobs] +# +# expect_equal(by_origin$sum_flow, O, tolerance = 1e-3) +# expect_equal(by_dest$sum_flow, D, tolerance = 1e-3) +# }) +# +# +# test_that("doubly-constrained: results don't depend on row order or sparsity", { +# ids <- c("1", "2", "3") +# cost <- matrix( +# c(0, 10, 25, 15, 0, 5, 30, 20, 0), +# nrow = 3, +# byrow = TRUE, +# dimnames = list(ids, ids) +# ) +# lu <- make_lu_match20() +# +# # independent iterative proportional fitting, as reference +# +# reference_flows <- function(weights) { +# a <- b <- rep(1, 3) +# for (k in 1:2000) { +# a <- 1 / as.vector(weights %*% (b * lu$jobs)) +# b <- 1 / as.vector(t(weights) %*% (a * lu$population)) +# } +# flows <- outer(a * lu$population, b * lu$jobs) * weights +# dimnames(flows) <- list(ids, ids) +# flows +# } +# +# run_doubly <- function(tm, land_use = lu) { +# constrained_accessibility( +# constraint = "doubly", +# travel_matrix = tm, +# land_use_data = land_use, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# error_threshold = 1e-10, +# improvement_threshold = 0 +# ) +# } +# +# to_major <- data.table::data.table( +# expand.grid(from_id = ids, to_id = ids, stringsAsFactors = FALSE) +# ) +# to_major[, travel_time := cost[cbind(from_id, to_id)]] +# from_major <- to_major[order(from_id, to_id)] +# shuffled <- to_major[c(5, 9, 1, 7, 3, 8, 2, 6, 4)] +# +# expected <- reference_flows(exp(-0.1 * cost)) +# for (tm in list(to_major, from_major, shuffled)) { +# result <- run_doubly(tm) +# expect_equal( +# result$flow, +# expected[cbind(result$from_id, result$to_id)], +# tolerance = 1e-6 +# ) +# } +# +# result <- run_doubly(to_major, lu[c(3, 1, 2)]) +# expect_equal( +# result$flow, +# expected[cbind(result$from_id, result$to_id)], +# tolerance = 1e-6 +# ) +# +# # pairs missing from the travel matrix are unreachable +# +# sparse_weights <- exp(-0.1 * cost) +# sparse_weights["1", "3"] <- 0 +# expected <- reference_flows(sparse_weights) +# +# result <- run_doubly(shuffled[!(from_id == "1" & to_id == "3")]) +# expect_equal( +# result$flow, +# expected[cbind(result$from_id, result$to_id)], +# tolerance = 1e-6 +# ) +# expect_identical(result[from_id == "1" & to_id == "3"]$flow, 0) +# }) +# +# 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", +# travel_matrix = make_tm_3x3(), +# land_use_data = make_lu_match20()[1:2], +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE +# )), +# regexp = "sum[[:space:]]+of[[:space:]]+origins[[:space:]]+must" +# ) +# }) +# +# 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")) +# ) +# tm_4[, travel_time := 10 + 5 * abs(as.integer(from_id) - as.integer(to_id))] +# tm_3 <- tm_4[from_id != "4" & to_id != "4"] +# +# lu_na <- rbind( +# make_lu_match20(), +# data.table::data.table(id = "4", population = NA, jobs = NA) +# ) +# +# run <- function(tm, lu) { +# suppressWarnings(constrained_accessibility( +# constraint = "doubly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE +# )) +# } +# +# expected <- run(tm_3, make_lu_match20()) +# +# for (lu in list(lu_na, make_lu_match20())) { +# result <- run(tm_4, lu) +# +# expect_identical(result[from_id == "4" | to_id == "4"]$flow, rep(0, 7)) +# expect_equal( +# result[from_id != "4" & to_id != "4"]$flow, +# expected$flow, +# tolerance = 1e-6 +# ) +# } +# }) +# +# test_that("doubly-constrained: errors when total demand and supply are 0", { +# lu_zero <- make_lu_match20()[, `:=`(population = NA, jobs = 0)] +# +# expect_error( +# suppressWarnings(constrained_accessibility( +# constraint = "doubly", +# travel_matrix = make_tm_3x3(), +# land_use_data = lu_zero, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE +# )), +# regexp = "total[[:space:]]+demand[[:space:]]+and[[:space:]]+supply" +# ) +# }) +# +# test_that("doubly-constrained: converges with very small impedance weights", { +# tm <- make_tm_3x3() +# tm[, travel_time := travel_time + 60] +# lu <- make_lu_match20() +# +# # exp(-0.5 * c) is ~1e-13 to 1e-19 here +# +# result <- expect_silent( +# constrained_accessibility( +# constraint = "doubly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = decay_exponential(decay_value = 0.5), +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE +# ) +# ) +# +# by_origin <- result[, .(flow = sum(flow)), by = from_id] +# by_destination <- result[, .(flow = sum(flow)), by = to_id] +# expect_equal( +# by_origin$flow, +# lu$population[match(by_origin$from_id, lu$id)], +# tolerance = 1e-3 +# ) +# expect_equal( +# by_destination$flow, +# lu$jobs[match(by_destination$to_id, lu$id)], +# tolerance = 1e-3 +# ) +# }) +# +# test_that("doubly-constrained: warns when balancing doesn't converge", { +# expect_warning( +# constrained_accessibility( +# constraint = "doubly", +# travel_matrix = make_tm_3x3(), +# land_use_data = make_lu_match20(), +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# max_iterations = 1, +# detailed_results = TRUE +# ), +# regexp = "did not converge" +# ) +# }) +# +# test_that("fill_missing_ids fills missing combinations when using group_by", { +# tm <- make_tm_3x3() +# 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" +# ) +# +# run <- function(constraint, travel_matrix, group_by = "mode") { +# constrained_accessibility( +# constraint = constraint, +# travel_matrix = travel_matrix, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# active = TRUE, +# group_by = group_by +# ) +# } +# +# for (constraint in c("total", "singly")) { +# result <- run(constraint, tm_modes) +# expect_identical(nrow(result), 6L) +# expect_identical(result[from_id == "3" & mode == "bus"]$supply, 0) +# } +# +# # 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"] +# expect_equal( +# car$supply, +# ungrouped$supply[match(car$from_id, ungrouped$from_id)] +# ) +# }) +# +# 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))] +# +# constrained_accessibility( +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# supply = "jobs", +# demand = "population", +# constraint = "total", +# decay_function = exp_decay_01, +# active = TRUE +# ) +# +# expect_true(is.null(attr(lu, "index"))) +# }) + +# test_that("total-constrained active multiple decay resultes 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( +# 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 + ) - # Supply-side output (returns accessible opportunities) - det_supply <- constrained_accessibility( - constraint = "total", - travel_matrix = tm, - land_use_data = lu, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = NULL, - supply = "jobs", - detailed_results = TRUE, - active = TRUE + tm[, travel_time := abs( + as.integer(from_id) - as.integer(to_id) + ) * 15] + + lu <- 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 + ) ) - agg_supply <- constrained_accessibility( + + multi <- constrained_accessibility( constraint = "total", travel_matrix = tm, land_use_data = lu, travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = NULL, - supply = "jobs", - detailed_results = FALSE, - active = TRUE + decay_function = decay_exponential(c(0.05, 0.20)), + demand = "population", + active = FALSE ) - # Demand-side output (returns accessible population) - det_demand <- constrained_accessibility( + run_005 <- constrained_accessibility( constraint = "total", travel_matrix = tm, land_use_data = lu, travel_cost = "travel_time", - decay_function = exp_decay_01, + decay_function = decay_exponential(0.05), demand = "population", - supply = NULL, - detailed_results = TRUE, active = FALSE ) - agg_demand <- constrained_accessibility( + + run_020 <- constrained_accessibility( constraint = "total", travel_matrix = tm, land_use_data = lu, travel_cost = "travel_time", - decay_function = exp_decay_01, + decay_function = decay_exponential(0.20), demand = "population", - supply = NULL, - detailed_results = FALSE, active = FALSE ) - expect_equal(sum(det_supply$supply), sum(lu$jobs)) - expect_equal(sum(agg_supply$supply), sum(lu$jobs)) - expect_equal(sum(det_demand$demand), sum(lu$population)) - expect_equal(sum(agg_demand$demand), sum(lu$population)) -}) + expect_equal( + multi[decay_function_arg == 0.05][order(to_id)]$demand, + run_005[order(to_id)]$demand + ) -# ------------------------------ SINGLY ------------------------------- -test_that("singly-constrained: preserves totals and kappa properties", { - tm <- make_tm_3x3() - lu <- make_lu_large() + expect_equal( + multi[decay_function_arg == 0.20][order(to_id)]$demand, + run_020[order(to_id)]$demand + ) - # Supply-constrained (returns accessible opportunities) - det_supply <- constrained_accessibility( - travel_matrix = tm, - land_use_data = lu, - constraint = "singly", - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = TRUE, - active = TRUE + totals <- multi[ + , + .(total_demand = sum(demand)), + by = decay_function_arg + ] + + expect_equal( + totals$total_demand, + rep(sum(lu$population), 2) ) - agg_supply <- constrained_accessibility( - constraint = "singly", - travel_matrix = tm, - land_use_data = lu, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = FALSE, - active = TRUE +}) +# +# 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( +# 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( + 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 + ) ) - # Demand-constrained (returns accessible population) - det_demand <- constrained_accessibility( + multi <- constrained_accessibility( constraint = "singly", travel_matrix = tm, land_use_data = lu, travel_cost = "travel_time", - decay_function = exp_decay_01, + decay_function = decay_exponential(c(0.05, 0.20)), demand = "population", supply = "jobs", - detailed_results = TRUE, active = FALSE ) - agg_demand <- constrained_accessibility( + + run_005 <- constrained_accessibility( constraint = "singly", travel_matrix = tm, land_use_data = lu, travel_cost = "travel_time", - decay_function = exp_decay_01, + decay_function = decay_exponential(0.05), demand = "population", supply = "jobs", - detailed_results = FALSE, active = FALSE ) - # Totals - expect_equal(sum(det_supply$supply), sum(lu$jobs)) - expect_equal(sum(agg_supply$supply), sum(lu$jobs)) - expect_equal(sum(det_demand$demand), sum(lu$population)) - expect_equal(sum(agg_demand$demand), sum(lu$population)) - - # κ normalization properties (these DO hold for singly) - by_to <- det_supply[, .(sum_k = sum(kappa_singly)), by = to_id] - by_from <- det_demand[, .(sum_k = sum(hatkappa_singly)), by = from_id] - expect_true(all(abs(by_to$sum_k - 1) < 1e-8)) # per-destination sums == 1 - expect_true(all(abs(by_from$sum_k - 1) < 1e-8)) # per-origin sums == 1 - expect_equal(sum(det_supply$kappa_singly), length(unique(det_supply$to_id))) - expect_equal(sum(det_demand$hatkappa_singly), length(unique(det_demand$from_id))) -}) - -# ------------------------------ DOUBLY ------------------------------- -test_that("doubly-constrained: errors when totals mismatch", { - tm <- make_tm_3x3() - lu_bad <- data.table::copy(make_lu_match20()) - lu_bad[id == "3", jobs := jobs + 1] # break equality - - expect_error( - constrained_accessibility( - constraint = "doubly", - travel_matrix = tm, - land_use_data = lu_bad, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = TRUE, - active = NULL - ), - # cli wraps long messages, so spaces may be line breaks - "sum of origins must equal the sum of[[:space:]]+destinations" - ) -}) - - - -test_that("doubly-constrained: OD flows match marginals", { - tm <- make_tm_3x3() - lu <- make_lu_match20() - decay <- pow_decay_3 - - det <- constrained_accessibility( - constraint = "doubly", + run_020 <- constrained_accessibility( + constraint = "singly", travel_matrix = tm, land_use_data = lu, travel_cost = "travel_time", - decay_function = decay, + decay_function = decay_exponential(0.20), demand = "population", supply = "jobs", - detailed_results = TRUE, - active = NULL - ) - - # Robustly pick the numeric flow column - candidate_cols <- c("flow", "supply", "demand") - value_col <- intersect(candidate_cols, names(det))[1] - expect_true(!is.null(value_col), info = "No flow/supply/demand column in detailed output") - expect_true(is.numeric(det[[value_col]]), info = "Flow column must be numeric") - - # Sum flows by origin and destination - by_origin <- det[, .(sum_flow = sum(get(value_col))), by = from_id] - by_dest <- det[, .(sum_flow = sum(get(value_col))), by = to_id] - - # Build expected marginals from land use - O <- lu[match(by_origin$from_id, lu$id), population] - D <- lu[match(by_dest$to_id, lu$id), jobs] - - expect_equal(by_origin$sum_flow, O, tolerance = 1e-3) - expect_equal(by_dest$sum_flow, D, tolerance = 1e-3) -}) - - -test_that("doubly-constrained: results don't depend on row order or sparsity", { - ids <- c("1", "2", "3") - cost <- matrix( - c(0, 10, 25, 15, 0, 5, 30, 20, 0), - nrow = 3, - byrow = TRUE, - dimnames = list(ids, ids) - ) - lu <- make_lu_match20() - - # independent iterative proportional fitting, as reference - - reference_flows <- function(weights) { - a <- b <- rep(1, 3) - for (k in 1:2000) { - a <- 1 / as.vector(weights %*% (b * lu$jobs)) - b <- 1 / as.vector(t(weights) %*% (a * lu$population)) - } - flows <- outer(a * lu$population, b * lu$jobs) * weights - dimnames(flows) <- list(ids, ids) - flows - } - - run_doubly <- function(tm, land_use = lu) { - constrained_accessibility( - constraint = "doubly", - travel_matrix = tm, - land_use_data = land_use, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = TRUE, - error_threshold = 1e-10, - improvement_threshold = 0 - ) - } - - to_major <- data.table::data.table( - expand.grid(from_id = ids, to_id = ids, stringsAsFactors = FALSE) + active = FALSE ) - to_major[, travel_time := cost[cbind(from_id, to_id)]] - from_major <- to_major[order(from_id, to_id)] - shuffled <- to_major[c(5, 9, 1, 7, 3, 8, 2, 6, 4)] - expected <- reference_flows(exp(-0.1 * cost)) - for (tm in list(to_major, from_major, shuffled)) { - result <- run_doubly(tm) - expect_equal( - result$flow, - expected[cbind(result$from_id, result$to_id)], - tolerance = 1e-6 - ) - } - - result <- run_doubly(to_major, lu[c(3, 1, 2)]) expect_equal( - result$flow, - expected[cbind(result$from_id, result$to_id)], - tolerance = 1e-6 + multi[decay_function_arg == 0.05][order(to_id)]$demand, + run_005[order(to_id)]$demand ) - # pairs missing from the travel matrix are unreachable - - sparse_weights <- exp(-0.1 * cost) - sparse_weights["1", "3"] <- 0 - expected <- reference_flows(sparse_weights) - - result <- run_doubly(shuffled[!(from_id == "1" & to_id == "3")]) expect_equal( - result$flow, - expected[cbind(result$from_id, result$to_id)], - tolerance = 1e-6 - ) - expect_identical(result[from_id == "1" & to_id == "3"]$flow, 0) -}) - -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", - travel_matrix = make_tm_3x3(), - land_use_data = make_lu_match20()[1:2], - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = TRUE - )), - regexp = "sum[[:space:]]+of[[:space:]]+origins[[:space:]]+must" - ) -}) - -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")) + multi[decay_function_arg == 0.20][order(to_id)]$demand, + run_020[order(to_id)]$demand ) - tm_4[, travel_time := 10 + 5 * abs(as.integer(from_id) - as.integer(to_id))] - tm_3 <- tm_4[from_id != "4" & to_id != "4"] - lu_na <- rbind( - make_lu_match20(), - data.table::data.table(id = "4", population = NA, jobs = NA) - ) - - run <- function(tm, lu) { - suppressWarnings(constrained_accessibility( - constraint = "doubly", - travel_matrix = tm, - land_use_data = lu, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = TRUE - )) - } - - expected <- run(tm_3, make_lu_match20()) - - for (lu in list(lu_na, make_lu_match20())) { - result <- run(tm_4, lu) - - expect_identical(result[from_id == "4" | to_id == "4"]$flow, rep(0, 7)) - expect_equal( - result[from_id != "4" & to_id != "4"]$flow, - expected$flow, - tolerance = 1e-6 - ) - } -}) - -test_that("doubly-constrained: errors when total demand and supply are 0", { - lu_zero <- make_lu_match20()[, `:=`(population = NA, jobs = 0)] - - expect_error( - suppressWarnings(constrained_accessibility( - constraint = "doubly", - travel_matrix = make_tm_3x3(), - land_use_data = lu_zero, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - detailed_results = TRUE - )), - regexp = "total[[:space:]]+demand[[:space:]]+and[[:space:]]+supply" - ) -}) - -test_that("doubly-constrained: converges with very small impedance weights", { - tm <- make_tm_3x3() - tm[, travel_time := travel_time + 60] - lu <- make_lu_match20() - - # exp(-0.5 * c) is ~1e-13 to 1e-19 here - - result <- expect_silent( - constrained_accessibility( - constraint = "doubly", - travel_matrix = tm, - land_use_data = lu, - travel_cost = "travel_time", - decay_function = decay_exponential(decay_value = 0.5), - demand = "population", - supply = "jobs", - detailed_results = TRUE - ) - ) + totals <- multi[ + , + .(total_demand = sum(demand)), + by = decay_function_arg + ] - by_origin <- result[, .(flow = sum(flow)), by = from_id] - by_destination <- result[, .(flow = sum(flow)), by = to_id] expect_equal( - by_origin$flow, - lu$population[match(by_origin$from_id, lu$id)], - tolerance = 1e-3 + totals$total_demand, + rep(sum(lu$population), 2) ) - expect_equal( - by_destination$flow, - lu$jobs[match(by_destination$to_id, lu$id)], - tolerance = 1e-3 - ) -}) - -test_that("doubly-constrained: warns when balancing doesn't converge", { - expect_warning( - constrained_accessibility( - constraint = "doubly", - travel_matrix = make_tm_3x3(), - land_use_data = make_lu_match20(), - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - max_iterations = 1, - detailed_results = TRUE - ), - regexp = "did not converge" - ) -}) - -test_that("fill_missing_ids fills missing combinations when using group_by", { - tm <- make_tm_3x3() - 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" - ) - - run <- function(constraint, travel_matrix, group_by = "mode") { - constrained_accessibility( - constraint = constraint, - travel_matrix = travel_matrix, - land_use_data = lu, - travel_cost = "travel_time", - decay_function = exp_decay_01, - demand = "population", - supply = "jobs", - active = TRUE, - group_by = group_by - ) - } - - for (constraint in c("total", "singly")) { - result <- run(constraint, tm_modes) - expect_identical(nrow(result), 6L) - expect_identical(result[from_id == "3" & mode == "bus"]$supply, 0) - } - - # 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"] - expect_equal( - car$supply, - ungrouped$supply[match(car$from_id, ungrouped$from_id)] - ) -}) - -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))] - - constrained_accessibility( - travel_matrix = tm, - land_use_data = lu, - travel_cost = "travel_time", - supply = "jobs", - demand = "population", - constraint = "total", - decay_function = exp_decay_01, - active = TRUE - ) - - expect_true(is.null(attr(lu, "index"))) }) From 27e0438224fba24fa71d8d776452414b48e5bbee Mon Sep 17 00:00:00 2001 From: soukhova Date: Sat, 24 Oct 2026 13:06:05 -0400 Subject: [PATCH 2/7] Fix group_by and multi-decay handling in total and singly constrained accessibility --- R/singly_constrained.R | 56 +- R/total_constrained.R | 67 +- tests/testthat/test-constrained-essentials.R | 987 ++++++++++++------- 3 files changed, 722 insertions(+), 388 deletions(-) diff --git a/R/singly_constrained.R b/R/singly_constrained.R index 1224527..ae133b4 100644 --- a/R/singly_constrained.R +++ b/R/singly_constrained.R @@ -68,6 +68,12 @@ singly_constrained <- function(travel_matrix, 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 data[, weighted_demand := get(demand) * opp_weight] @@ -76,13 +82,24 @@ 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] + # access <- data[, .( + # from_id, + # to_id, + # kappa_singly, + # supply = singly_access, + # B_j = data.table::fifelse(denom_j > 0, 1 / denom_j, 0) + # )] } else { access <- data[, .(supply = sum(singly_access)), by = c("from_id", group_by)] if (fill_missing_ids) { @@ -103,13 +120,24 @@ 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] + # access <- data[, .( + # from_id, + # to_id, + # hatkappa_singly, + # demand = singly_access, + # A_i = data.table::fifelse(denom_i > 0, 1 / denom_i, 0) + # )] } 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 192180f..26bdf7d 100644 --- a/R/total_constrained.R +++ b/R/total_constrained.R @@ -19,7 +19,7 @@ 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", # singly-constrained "denom_i", "denom_j", "kappa_singly", "hatkappa_singly", "A_i", "B_j", "singly_access", # doubly-constrained @@ -115,26 +115,58 @@ total_constrained <- function(travel_matrix, 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" + ), with = FALSE] + + data.table::setnames(access, "constrained_opportunity", "demand") + + access[, hatK_total := total_opportunities_region / total_weighted_system] + access[, total_weighted_system := NULL] + # access <- data[, .( + # from_id, + # to_id, + # weighted_demand, + # hatkappa_total, + # demand = constrained_opportunity, + # hatK_total = total_opportunities_region / total_weighted_system + # )] } 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" + ), with = FALSE] + + data.table::setnames(access, "constrained_opportunity", "supply") + + access[, K_total := total_opportunities_region / total_weighted_system] + access[, total_weighted_system := NULL] + + # 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 + # )] } } else { if (active) { @@ -148,6 +180,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/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index 6faabf7..ab526d6 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 (5 tests) ------------------------------- # test_that("total-constrained: preserves totals on supply/demand sides", { # tm <- make_tm_3x3() # lu <- make_lu_large() @@ -82,25 +82,618 @@ pow_decay_3 <- decay_power(decay_value = 3) # expect_equal(sum(det_demand$demand), sum(lu$population)) # expect_equal(sum(agg_demand$demand), sum(lu$population)) # }) + +# 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( +# 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( +# 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) +# }) + + +# # ------------------------------ SINGLY (5 tests)------------------------------- +# test_that("singly-constrained: preserves totals and kappa properties", { +# tm <- make_tm_3x3() +# lu <- make_lu_large() +# +# # Supply-constrained (returns accessible opportunities) +# det_supply <- constrained_accessibility( +# travel_matrix = tm, +# land_use_data = lu, +# constraint = "singly", +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# active = TRUE +# ) +# agg_supply <- constrained_accessibility( +# constraint = "singly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = FALSE, +# active = TRUE +# ) +# +# # Demand-constrained (returns accessible population) +# det_demand <- constrained_accessibility( +# constraint = "singly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = TRUE, +# active = FALSE +# ) +# agg_demand <- constrained_accessibility( +# constraint = "singly", +# travel_matrix = tm, +# land_use_data = lu, +# travel_cost = "travel_time", +# decay_function = exp_decay_01, +# demand = "population", +# supply = "jobs", +# detailed_results = FALSE, +# active = FALSE +# ) +# +# # Totals +# expect_equal(sum(det_supply$supply), sum(lu$jobs)) +# expect_equal(sum(agg_supply$supply), sum(lu$jobs)) +# expect_equal(sum(det_demand$demand), sum(lu$population)) +# expect_equal(sum(agg_demand$demand), sum(lu$population)) +# +# # κ normalization properties (these DO hold for singly) +# by_to <- det_supply[, .(sum_k = sum(kappa_singly)), by = to_id] +# by_from <- det_demand[, .(sum_k = sum(hatkappa_singly)), by = from_id] +# expect_true(all(abs(by_to$sum_k - 1) < 1e-8)) # per-destination sums == 1 +# expect_true(all(abs(by_from$sum_k - 1) < 1e-8)) # per-origin sums == 1 +# expect_equal(sum(det_supply$kappa_singly), length(unique(det_supply$to_id))) +# 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( +# 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( +# 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", { # -# # ------------------------------ SINGLY ------------------------------- -# test_that("singly-constrained: preserves totals and kappa properties", { # tm <- make_tm_3x3() -# lu <- make_lu_large() +# lu <- make_lu_match20() # -# # Supply-constrained (returns accessible opportunities) -# det_supply <- constrained_accessibility( -# travel_matrix = tm, -# land_use_data = lu, +# 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", -# detailed_results = TRUE, -# active = TRUE +# active = TRUE, +# group_by = "mode" # ) -# agg_supply <- constrained_accessibility( +# +# standalone_active <- constrained_accessibility( # constraint = "singly", # travel_matrix = tm, # land_use_data = lu, @@ -108,23 +701,33 @@ pow_decay_3 <- decay_power(decay_value = 3) # decay_function = exp_decay_01, # demand = "population", # supply = "jobs", -# detailed_results = FALSE, # active = TRUE # ) # -# # Demand-constrained (returns accessible population) -# det_demand <- constrained_accessibility( +# 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, +# travel_matrix = tm_modes, # land_use_data = lu, # travel_cost = "travel_time", # decay_function = exp_decay_01, # demand = "population", # supply = "jobs", -# detailed_results = TRUE, -# active = FALSE +# active = FALSE, +# group_by = "mode" # ) -# agg_demand <- constrained_accessibility( +# +# standalone_passive <- constrained_accessibility( # constraint = "singly", # travel_matrix = tm, # land_use_data = lu, @@ -132,25 +735,20 @@ pow_decay_3 <- decay_power(decay_value = 3) # decay_function = exp_decay_01, # demand = "population", # supply = "jobs", -# detailed_results = FALSE, # active = FALSE # ) # -# # Totals -# expect_equal(sum(det_supply$supply), sum(lu$jobs)) -# expect_equal(sum(agg_supply$supply), sum(lu$jobs)) -# expect_equal(sum(det_demand$demand), sum(lu$population)) -# expect_equal(sum(agg_demand$demand), sum(lu$population)) +# expect_equal( +# grouped_passive[mode == "car"][order(to_id)]$demand, +# standalone_passive[order(to_id)]$demand +# ) # -# # κ normalization properties (these DO hold for singly) -# by_to <- det_supply[, .(sum_k = sum(kappa_singly)), by = to_id] -# by_from <- det_demand[, .(sum_k = sum(hatkappa_singly)), by = from_id] -# expect_true(all(abs(by_to$sum_k - 1) < 1e-8)) # per-destination sums == 1 -# expect_true(all(abs(by_from$sum_k - 1) < 1e-8)) # per-origin sums == 1 -# expect_equal(sum(det_supply$kappa_singly), length(unique(det_supply$to_id))) -# expect_equal(sum(det_demand$hatkappa_singly), length(unique(det_demand$from_id))) +# expect_equal( +# grouped_passive[mode == "bus"][order(to_id)]$demand, +# standalone_passive[order(to_id)]$demand +# ) # }) -# + # # ------------------------------ DOUBLY ------------------------------- # test_that("doubly-constrained: errors when totals mismatch", { # tm <- make_tm_3x3() @@ -483,328 +1081,3 @@ pow_decay_3 <- decay_power(decay_value = 3) # # expect_true(is.null(attr(lu, "index"))) # }) - -# test_that("total-constrained active multiple decay resultes 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( -# 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( - 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("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( -# 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( - 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) - ) -}) From 8ab2cfa647253d8ec33671148da4e3a34111425b Mon Sep 17 00:00:00 2001 From: soukhova Date: Sat, 24 Oct 2026 13:14:24 -0400 Subject: [PATCH 3/7] small --- tests/testthat/test-constrained-essentials.R | 68 ++++++++++++++++++-- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index ab526d6..5e4a094 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 (5 tests) ------------------------------- +# # ------------------------------- TOTAL (6 tests) ------------------------------- # test_that("total-constrained: preserves totals on supply/demand sides", { # tm <- make_tm_3x3() # lu <- make_lu_large() @@ -363,9 +363,38 @@ pow_decay_3 <- decay_power(decay_value = 3) # # expect_equal(nrow(aggregated), 12L) # }) - - -# # ------------------------------ SINGLY (5 tests)------------------------------- +# +# 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 +# ) +# }) +# +# # ------------------------------ SINGLY (6 tests)------------------------------- # test_that("singly-constrained: preserves totals and kappa properties", { # tm <- make_tm_3x3() # lu <- make_lu_large() @@ -748,6 +777,37 @@ pow_decay_3 <- decay_power(decay_value = 3) # 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", { From cf386a98bb99b469acdfc4a707c537ff0824ceb5 Mon Sep 17 00:00:00 2001 From: soukhova Date: Mon, 26 Oct 2026 15:11:04 -0400 Subject: [PATCH 4/7] fix ggroup_by and multi decay handling in total and singly constrained accessibility --- DESCRIPTION | 1 + NAMESPACE | 14 +- R/constrained_accessibility.R | 29 +- R/total_constrained.R | 20 +- man/accessibility.Rd | 1 - man/balancing_cost.Rd | 17 +- man/concentration_index.Rd | 10 +- man/constrained_accessibility.Rd | 52 +- man/cost_to_closest.Rd | 17 +- man/cumulative_cutoff.Rd | 15 +- man/cumulative_interval.Rd | 15 +- man/decay_binary.Rd | 12 +- man/decay_exponential.Rd | 12 +- man/decay_linear.Rd | 12 +- man/decay_logistic.Rd | 12 +- man/decay_power.Rd | 12 +- man/decay_stepped.Rd | 12 +- man/fgt_poverty.Rd | 10 +- man/floating_catchment_area.Rd | 20 +- man/gini_index.Rd | 10 +- man/gravity.Rd | 26 +- man/palma_ratio.Rd | 10 +- man/roxygen/templates/decay_function.R | 8 +- man/roxygen/templates/group_by.R | 11 +- man/spatial_availability.Rd | 24 +- man/theil_t.Rd | 10 +- tests/testthat/test-constrained-essentials.R | 2226 +++++++++--------- 27 files changed, 1326 insertions(+), 1292 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index d57308f..39b3242 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -54,3 +54,4 @@ Encoding: UTF-8 NeedsCompilation: no Roxygen: list(markdown = TRUE) Config/roxygen2/version: 8.1.0 +RoxygenNote: 7.3.3 diff --git a/NAMESPACE b/NAMESPACE index 1ff30c3..5711b67 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -20,13 +20,11 @@ export(palma_ratio) export(spatial_availability) export(theil_t) importFrom(Rdpack,reprompt) -importFrom(data.table, - "%chin%", - ":=", - .GRP, - .I, - .N, - .SD -) +importFrom(data.table,"%chin%") +importFrom(data.table,":=") +importFrom(data.table,.GRP) +importFrom(data.table,.I) +importFrom(data.table,.N) +importFrom(data.table,.SD) importFrom(rlang,abort) importFrom(utils,globalVariables) diff --git a/R/constrained_accessibility.R b/R/constrained_accessibility.R index 62ed461..283e211 100644 --- a/R/constrained_accessibility.R +++ b/R/constrained_accessibility.R @@ -36,6 +36,20 @@ #' This function covers the family of constrained accessibility measures #' proposed in \insertCite{soukhov2025family;textual}{accessibility}. #' +#' ### Grouping variables and multiple decay values +#' +#' When `group_by` is supplied, calculations are performed separately for each +#' unique group and the results are stacked in the output. Likewise, when a +#' decay function is specified with multiple parameter values (e.g. +#' `decay_exponential(c(0.1, 0.5))`), calculations are performed separately +#' for each parameter value and the results are stacked in the output. +#' +#' For constrained accessibility measures, each group or decay value is treated +#' as an independent transportation system. This does not represent a +#' multimodal model that splits demand and/or supply across groups. Instead, +#' each group receives the full demand and/or supply totals and is evaluated +#' independently. +#' #' ## Total Constrained Accessibility #' #' Allocates the system-wide total proportionally based on travel impedance @@ -156,11 +170,12 @@ #' - Both `demand` and `supply` must be provided. #' - Unlike `total` and `singly`, `doubly` requires the sum of demand and supply #' to match; otherwise, the model will not converge. -#' - `active` must be `NULL`. Since supply must match demand, their units are -#' the same and there is no distinction between 'active' and 'passive' notions. -#' - Should be used with `detailed_results = TRUE`. With -#' `detailed_results = FALSE`, it only returns the demand and supply -#' marginals, with a warning. +#' - `active` is ignored. Since supply must match demand, there is no +#' distinction between active and passive accessibility. +#' - `detailed_results = TRUE` is recommended, as the primary output +#' of the doubly-constrained model is the OD flow matrix. When +#' `detailed_results = FALSE`, the function returns the demand and supply +#' marginals, with a warning. #' #' ### Interpretation: #' - Results include OD-level flows (`flow`) along with balancing factors (`A_i`, @@ -199,7 +214,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. +#' Detailed results include the `group_by` columns (and `decay_function_arg`, +#' when present) so results from different groups or decay values can be +#' distinguished. #' #' @references #' \insertAllCited{} diff --git a/R/total_constrained.R b/R/total_constrained.R index 26bdf7d..2c2f318 100644 --- a/R/total_constrained.R +++ b/R/total_constrained.R @@ -107,7 +107,7 @@ total_constrained <- function(travel_matrix, data[, (kappa_col) := get(weighted_col) / total_weighted_system] - ids_for_total <- unique(data[[merge_id]]) # e.g., A,B,C when active=TRUE + 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 @@ -135,14 +135,7 @@ total_constrained <- function(travel_matrix, access[, hatK_total := total_opportunities_region / total_weighted_system] access[, total_weighted_system := NULL] - # access <- data[, .( - # from_id, - # to_id, - # weighted_demand, - # hatkappa_total, - # demand = constrained_opportunity, - # hatK_total = total_opportunities_region / total_weighted_system - # )] + } else { # supply-side details (active accessibility) access <- data[, c( @@ -158,15 +151,6 @@ total_constrained <- function(travel_matrix, access[, K_total := total_opportunities_region / total_weighted_system] access[, total_weighted_system := NULL] - # 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 - # )] } } else { if (active) { diff --git a/man/accessibility.Rd b/man/accessibility.Rd index 7961609..3d1912d 100644 --- a/man/accessibility.Rd +++ b/man/accessibility.Rd @@ -38,7 +38,6 @@ Useful links: Authors: \itemize{ - \item Daniel Herszenhut \email{dhersz@gmail.com} (\href{https://orcid.org/0000-0001-8066-1105}{ORCID}) \item Rafael H. M. Pereira \email{rafa.pereira.br@gmail.com} (\href{https://orcid.org/0000-0003-2125-7465}{ORCID}) \item Anastasia Soukhov } diff --git a/man/balancing_cost.Rd b/man/balancing_cost.Rd index ed54a55..ff10b76 100644 --- a/man/balancing_cost.Rd +++ b/man/balancing_cost.Rd @@ -50,12 +50,11 @@ possibly benefit from a smaller increment of 0.05, for example, resulting in the function looking for balancing costs first at a cost of 0, then 0.05, 0.10, ..., etc. Defaults to 1.} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \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 @@ -101,8 +100,8 @@ head(bc) \insertAllCited{} } \seealso{ -Other accessibility measures: -\code{\link[=cost_to_closest]{cost_to_closest()}}, -\code{\link[=gravity]{gravity()}} +Other accessibility measures: +\code{\link{cost_to_closest}()}, +\code{\link{gravity}()} } \concept{accessibility measures} diff --git a/man/concentration_index.Rd b/man/concentration_index.Rd index ee1a240..5dd40bc 100644 --- a/man/concentration_index.Rd +++ b/man/concentration_index.Rd @@ -97,10 +97,10 @@ ci \insertAllCited{} } \seealso{ -Other equity: -\code{\link[=fgt_poverty]{fgt_poverty()}}, -\code{\link[=gini_index]{gini_index()}}, -\code{\link[=palma_ratio]{palma_ratio()}}, -\code{\link[=theil_t]{theil_t()}} +Other equity: +\code{\link{fgt_poverty}()}, +\code{\link{gini_index}()}, +\code{\link{palma_ratio}()}, +\code{\link{theil_t}()} } \concept{equity} diff --git a/man/constrained_accessibility.Rd b/man/constrained_accessibility.Rd index 1574224..ce27f9e 100644 --- a/man/constrained_accessibility.Rd +++ b/man/constrained_accessibility.Rd @@ -55,7 +55,14 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details.} +details. + +When a decay function is specified with multiple parameter values (e.g. +\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately +for each parameter value and the results are stacked in the output. This +is equivalent to running the function separately for each parameter value +and combining the results. A \code{decay_function_arg} column identifies the +parameter value associated with each result.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from @@ -75,12 +82,11 @@ used only for calibration in the doubly-constrained case \item{max_iterations}{Integer. Maximum iterations used only for calibration in the doubly-constrained case (\code{constraint = "doubly"}).} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \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 +128,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. +Detailed results include the \code{group_by} columns (and \code{decay_function_arg}, +when present) so results from different groups or decay values can be +distinguished. } \description{ Calculates accessibility using constraints, as proposed in @@ -134,6 +142,21 @@ 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}. +\subsection{Grouping variables and multiple decay values}{ + +When \code{group_by} is supplied, calculations are performed separately for each +unique group and the results are stacked in the output. Likewise, when a +decay function is specified with multiple parameter values (e.g. +\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately +for each parameter value and the results are stacked in the output. + +For constrained accessibility measures, each group or decay value is treated +as an independent transportation system. This does not represent a +multimodal model that splits demand and/or supply across groups. Instead, +each group receives the full demand and/or supply totals and is evaluated +independently. +} + \subsection{Total Constrained Accessibility}{ Allocates the system-wide total proportionally based on travel impedance @@ -273,10 +296,11 @@ travel impedance. \item Both \code{demand} and \code{supply} must be provided. \item Unlike \code{total} and \code{singly}, \code{doubly} requires the sum of demand and supply to match; otherwise, the model will not converge. -\item \code{active} must be \code{NULL}. Since supply must match demand, their units are -the same and there is no distinction between 'active' and 'passive' notions. -\item Should be used with \code{detailed_results = TRUE}. With -\code{detailed_results = FALSE}, it only returns the demand and supply +\item \code{active} is ignored. Since supply must match demand, there is no +distinction between active and passive accessibility. +\item \code{detailed_results = TRUE} is recommended, as the primary output +of the doubly-constrained model is the OD flow matrix. When +\code{detailed_results = FALSE}, the function returns the demand and supply marginals, with a warning. } } @@ -380,7 +404,7 @@ constrained_accessibility( \insertAllCited{} } \seealso{ -Other Constrained accessibility: -\code{\link[=spatial_availability]{spatial_availability()}} +Other Constrained accessibility: +\code{\link{spatial_availability}()} } \concept{Constrained accessibility} diff --git a/man/cost_to_closest.Rd b/man/cost_to_closest.Rd index 0545740..780f4f8 100644 --- a/man/cost_to_closest.Rd +++ b/man/cost_to_closest.Rd @@ -40,12 +40,11 @@ be considered. Defaults to 1. If more than one value is provided, the output includes an extra column specifying the number of opportunities that the minimum travel cost refers to.} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from @@ -100,8 +99,8 @@ head(df) \dontshow{\}) # examplesIf} } \seealso{ -Other accessibility measures: -\code{\link[=balancing_cost]{balancing_cost()}}, -\code{\link[=gravity]{gravity()}} +Other accessibility measures: +\code{\link{balancing_cost}()}, +\code{\link{gravity}()} } \concept{accessibility measures} diff --git a/man/cumulative_cutoff.Rd b/man/cumulative_cutoff.Rd index 02023c5..292d810 100644 --- a/man/cumulative_cutoff.Rd +++ b/man/cumulative_cutoff.Rd @@ -48,12 +48,11 @@ example, are included in the accessibility output. The cutoff parameter is not included in the final output if the input includes only a single cutoff for a single travel cost.} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from @@ -132,7 +131,7 @@ head(df) \dontshow{\}) # examplesIf} } \seealso{ -Other cumulative access: -\code{\link[=cumulative_interval]{cumulative_interval()}} +Other cumulative access: +\code{\link{cumulative_interval}()} } \concept{cumulative access} diff --git a/man/cumulative_interval.Rd b/man/cumulative_interval.Rd index 7ec74f1..ca4d4ff 100644 --- a/man/cumulative_interval.Rd +++ b/man/cumulative_interval.Rd @@ -53,12 +53,11 @@ single value. Can be any function that takes an arbitrary number of numeric values as input and returns a single number as output. Defaults to \code{\link[stats:median]{stats::median()}}.} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from @@ -115,7 +114,7 @@ head(df) \insertAllCited{} } \seealso{ -Other cumulative access: -\code{\link[=cumulative_cutoff]{cumulative_cutoff()}} +Other cumulative access: +\code{\link{cumulative_cutoff}()} } \concept{cumulative access} diff --git a/man/decay_binary.Rd b/man/decay_binary.Rd index 66d1827..95e91ff 100644 --- a/man/decay_binary.Rd +++ b/man/decay_binary.Rd @@ -35,11 +35,11 @@ weighting_function(c(20, 35)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link[=decay_exponential]{decay_exponential()}}, -\code{\link[=decay_linear]{decay_linear()}}, -\code{\link[=decay_logistic]{decay_logistic()}}, -\code{\link[=decay_power]{decay_power()}}, -\code{\link[=decay_stepped]{decay_stepped()}} +Other decay functions: +\code{\link{decay_exponential}()}, +\code{\link{decay_linear}()}, +\code{\link{decay_logistic}()}, +\code{\link{decay_power}()}, +\code{\link{decay_stepped}()} } \concept{decay functions} diff --git a/man/decay_exponential.Rd b/man/decay_exponential.Rd index 7ac6cf1..efd2f0a 100644 --- a/man/decay_exponential.Rd +++ b/man/decay_exponential.Rd @@ -35,11 +35,11 @@ weighting_function(c(20, 30)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link[=decay_binary]{decay_binary()}}, -\code{\link[=decay_linear]{decay_linear()}}, -\code{\link[=decay_logistic]{decay_logistic()}}, -\code{\link[=decay_power]{decay_power()}}, -\code{\link[=decay_stepped]{decay_stepped()}} +Other decay functions: +\code{\link{decay_binary}()}, +\code{\link{decay_linear}()}, +\code{\link{decay_logistic}()}, +\code{\link{decay_power}()}, +\code{\link{decay_stepped}()} } \concept{decay functions} diff --git a/man/decay_linear.Rd b/man/decay_linear.Rd index 6eed5e1..5a9d69b 100644 --- a/man/decay_linear.Rd +++ b/man/decay_linear.Rd @@ -35,11 +35,11 @@ weighting_function(c(20, 35)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link[=decay_binary]{decay_binary()}}, -\code{\link[=decay_exponential]{decay_exponential()}}, -\code{\link[=decay_logistic]{decay_logistic()}}, -\code{\link[=decay_power]{decay_power()}}, -\code{\link[=decay_stepped]{decay_stepped()}} +Other decay functions: +\code{\link{decay_binary}()}, +\code{\link{decay_exponential}()}, +\code{\link{decay_logistic}()}, +\code{\link{decay_power}()}, +\code{\link{decay_stepped}()} } \concept{decay functions} diff --git a/man/decay_logistic.Rd b/man/decay_logistic.Rd index fc40e81..c354887 100644 --- a/man/decay_logistic.Rd +++ b/man/decay_logistic.Rd @@ -56,11 +56,11 @@ weighting_function(c(0, 30, 45, 60)) \insertAllCited{} } \seealso{ -Other decay functions: -\code{\link[=decay_binary]{decay_binary()}}, -\code{\link[=decay_exponential]{decay_exponential()}}, -\code{\link[=decay_linear]{decay_linear()}}, -\code{\link[=decay_power]{decay_power()}}, -\code{\link[=decay_stepped]{decay_stepped()}} +Other decay functions: +\code{\link{decay_binary}()}, +\code{\link{decay_exponential}()}, +\code{\link{decay_linear}()}, +\code{\link{decay_power}()}, +\code{\link{decay_stepped}()} } \concept{decay functions} diff --git a/man/decay_power.Rd b/man/decay_power.Rd index fadf779..ba47beb 100644 --- a/man/decay_power.Rd +++ b/man/decay_power.Rd @@ -34,11 +34,11 @@ weighting_function(c(20, 35)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link[=decay_binary]{decay_binary()}}, -\code{\link[=decay_exponential]{decay_exponential()}}, -\code{\link[=decay_linear]{decay_linear()}}, -\code{\link[=decay_logistic]{decay_logistic()}}, -\code{\link[=decay_stepped]{decay_stepped()}} +Other decay functions: +\code{\link{decay_binary}()}, +\code{\link{decay_exponential}()}, +\code{\link{decay_linear}()}, +\code{\link{decay_logistic}()}, +\code{\link{decay_stepped}()} } \concept{decay functions} diff --git a/man/decay_stepped.Rd b/man/decay_stepped.Rd index fedbb84..2e3f7b7 100644 --- a/man/decay_stepped.Rd +++ b/man/decay_stepped.Rd @@ -65,11 +65,11 @@ weighting_function(c(0, 10, 20, 30, 40)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link[=decay_binary]{decay_binary()}}, -\code{\link[=decay_exponential]{decay_exponential()}}, -\code{\link[=decay_linear]{decay_linear()}}, -\code{\link[=decay_logistic]{decay_logistic()}}, -\code{\link[=decay_power]{decay_power()}} +Other decay functions: +\code{\link{decay_binary}()}, +\code{\link{decay_exponential}()}, +\code{\link{decay_linear}()}, +\code{\link{decay_logistic}()}, +\code{\link{decay_power}()} } \concept{decay functions} diff --git a/man/fgt_poverty.Rd b/man/fgt_poverty.Rd index 261d51f..df6df62 100644 --- a/man/fgt_poverty.Rd +++ b/man/fgt_poverty.Rd @@ -126,10 +126,10 @@ poverty \insertAllCited{} } \seealso{ -Other equity: -\code{\link[=concentration_index]{concentration_index()}}, -\code{\link[=gini_index]{gini_index()}}, -\code{\link[=palma_ratio]{palma_ratio()}}, -\code{\link[=theil_t]{theil_t()}} +Other equity: +\code{\link{concentration_index}()}, +\code{\link{gini_index}()}, +\code{\link{palma_ratio}()}, +\code{\link{theil_t}()} } \concept{equity} diff --git a/man/floating_catchment_area.Rd b/man/floating_catchment_area.Rd index 6d05407..525bff9 100644 --- a/man/floating_catchment_area.Rd +++ b/man/floating_catchment_area.Rd @@ -51,14 +51,20 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details.} +details. + +When a decay function is specified with multiple parameter values (e.g. +\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately +for each parameter value and the results are stacked in the output. This +is equivalent to running the function separately for each parameter value +and combining the results. A \code{decay_function_arg} column identifies the +parameter value associated with each result.} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \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/gini_index.Rd b/man/gini_index.Rd index 4fbc2cc..e84b064 100644 --- a/man/gini_index.Rd +++ b/man/gini_index.Rd @@ -67,10 +67,10 @@ gini \dontshow{\}) # examplesIf} } \seealso{ -Other equity: -\code{\link[=concentration_index]{concentration_index()}}, -\code{\link[=fgt_poverty]{fgt_poverty()}}, -\code{\link[=palma_ratio]{palma_ratio()}}, -\code{\link[=theil_t]{theil_t()}} +Other equity: +\code{\link{concentration_index}()}, +\code{\link{fgt_poverty}()}, +\code{\link{palma_ratio}()}, +\code{\link{theil_t}()} } \concept{equity} diff --git a/man/gravity.Rd b/man/gravity.Rd index 0fac893..ff8c0ca 100644 --- a/man/gravity.Rd +++ b/man/gravity.Rd @@ -42,14 +42,20 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details.} +details. -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +When a decay function is specified with multiple parameter values (e.g. +\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately +for each parameter value and the results are stacked in the output. This +is equivalent to running the function separately for each parameter value +and combining the results. A \code{decay_function_arg} column identifies the +parameter value associated with each result.} + +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from @@ -105,8 +111,8 @@ head(df_exp) \dontshow{\}) # examplesIf} } \seealso{ -Other accessibility measures: -\code{\link[=balancing_cost]{balancing_cost()}}, -\code{\link[=cost_to_closest]{cost_to_closest()}} +Other accessibility measures: +\code{\link{balancing_cost}()}, +\code{\link{cost_to_closest}()} } \concept{accessibility measures} diff --git a/man/palma_ratio.Rd b/man/palma_ratio.Rd index 0e46ea2..d976a65 100644 --- a/man/palma_ratio.Rd +++ b/man/palma_ratio.Rd @@ -80,10 +80,10 @@ palma \dontshow{\}) # examplesIf} } \seealso{ -Other equity: -\code{\link[=concentration_index]{concentration_index()}}, -\code{\link[=fgt_poverty]{fgt_poverty()}}, -\code{\link[=gini_index]{gini_index()}}, -\code{\link[=theil_t]{theil_t()}} +Other equity: +\code{\link{concentration_index}()}, +\code{\link{fgt_poverty}()}, +\code{\link{gini_index}()}, +\code{\link{theil_t}()} } \concept{equity} diff --git a/man/roxygen/templates/decay_function.R b/man/roxygen/templates/decay_function.R index c249faf..6a1988b 100644 --- a/man/roxygen/templates/decay_function.R +++ b/man/roxygen/templates/decay_function.R @@ -6,4 +6,10 @@ #' [decay_linear()], [decay_logistic()], [decay_power()] and #' [decay_stepped()]. See the documentation of each decay function for more #' details. - +#' +#' When a decay function is specified with multiple parameter values (e.g. +#' `decay_exponential(c(0.1, 0.5))`), calculations are performed separately +#' for each parameter value and the results are stacked in the output. This +#' is equivalent to running the function separately for each parameter value +#' and combining the results. A `decay_function_arg` column identifies the +#' parameter value associated with each result. diff --git a/man/roxygen/templates/group_by.R b/man/roxygen/templates/group_by.R index 7edc652..febf82f 100644 --- a/man/roxygen/templates/group_by.R +++ b/man/roxygen/templates/group_by.R @@ -1,6 +1,5 @@ -#' @param group_by A `character` vector. When not `character(0)` (the default), -#' indicates the `travel_matrix` columns that should be used to group the -#' accessibility estimates by. For example, if `travel_matrix` includes a -#' 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. +#' @param group_by A string referring to a column in the input data frame. +#' Calculations are performed separately for each unique value (or +#' combination of values) in `group_by`, and the results are stacked in the +#' output. This is equivalent to splitting the input data by group, running +#' the function separately for each group, and combining the results. diff --git a/man/spatial_availability.Rd b/man/spatial_availability.Rd index 6b96f57..93f06e6 100644 --- a/man/spatial_availability.Rd +++ b/man/spatial_availability.Rd @@ -48,19 +48,25 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details.} +details. + +When a decay function is specified with multiple parameter values (e.g. +\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately +for each parameter value and the results are stacked in the output. This +is equivalent to running the function separately for each parameter value +and combining the results. A \code{decay_function_arg} column identifies the +parameter value associated with each result.} \item{alpha}{A \code{numeric}. A parameter used to modulate the effect of demand by population. When less than 1, opportunities are allocated more rapidly to smaller centers relative to larger ones; values higher than 1 achieve the opposite effect.} -\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), -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.} +\item{group_by}{A string referring to a column in the input data frame. +Calculations are performed separately for each unique value (or +combination of values) in \code{group_by}, and the results are stacked in the +output. This is equivalent to splitting the input data by group, running +the function separately for each group, and combining the results.} \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 @@ -137,7 +143,7 @@ detailed_df \insertAllCited{} } \seealso{ -Other Constrained accessibility: -\code{\link[=constrained_accessibility]{constrained_accessibility()}} +Other Constrained accessibility: +\code{\link{constrained_accessibility}()} } \concept{Constrained accessibility} diff --git a/man/theil_t.Rd b/man/theil_t.Rd index 1871804..f3fe056 100644 --- a/man/theil_t.Rd +++ b/man/theil_t.Rd @@ -114,10 +114,10 @@ ti \dontshow{\}) # examplesIf} } \seealso{ -Other equity: -\code{\link[=concentration_index]{concentration_index()}}, -\code{\link[=fgt_poverty]{fgt_poverty()}}, -\code{\link[=gini_index]{gini_index()}}, -\code{\link[=palma_ratio]{palma_ratio()}} +Other equity: +\code{\link{concentration_index}()}, +\code{\link{fgt_poverty}()}, +\code{\link{gini_index}()}, +\code{\link{palma_ratio}()} } \concept{equity} diff --git a/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index 5e4a094..e61b548 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -24,1120 +24,1112 @@ make_lu_match20 <- function() { exp_decay_01 <- decay_exponential(decay_value = 0.1) pow_decay_3 <- decay_power(decay_value = 3) -# # ------------------------------- TOTAL (6 tests) ------------------------------- -# test_that("total-constrained: preserves totals on supply/demand sides", { -# tm <- make_tm_3x3() -# lu <- make_lu_large() -# -# # Supply-side output (returns accessible opportunities) -# det_supply <- constrained_accessibility( -# constraint = "total", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = NULL, -# supply = "jobs", -# detailed_results = TRUE, -# active = TRUE -# ) -# agg_supply <- constrained_accessibility( -# constraint = "total", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = NULL, -# supply = "jobs", -# detailed_results = FALSE, -# active = TRUE -# ) -# -# # Demand-side output (returns accessible population) -# det_demand <- constrained_accessibility( -# constraint = "total", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = NULL, -# detailed_results = TRUE, -# active = FALSE -# ) -# agg_demand <- constrained_accessibility( -# constraint = "total", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = NULL, -# detailed_results = FALSE, -# active = FALSE -# ) -# -# expect_equal(sum(det_supply$supply), sum(lu$jobs)) -# expect_equal(sum(agg_supply$supply), sum(lu$jobs)) -# expect_equal(sum(det_demand$demand), sum(lu$population)) -# expect_equal(sum(agg_demand$demand), sum(lu$population)) -# }) - -# 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( -# 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( -# 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 -# ) -# }) -# -# # ------------------------------ SINGLY (6 tests)------------------------------- -# test_that("singly-constrained: preserves totals and kappa properties", { -# tm <- make_tm_3x3() -# lu <- make_lu_large() -# -# # Supply-constrained (returns accessible opportunities) -# det_supply <- constrained_accessibility( -# travel_matrix = tm, -# land_use_data = lu, -# constraint = "singly", -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE, -# active = TRUE -# ) -# agg_supply <- constrained_accessibility( -# constraint = "singly", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = FALSE, -# active = TRUE -# ) -# -# # Demand-constrained (returns accessible population) -# det_demand <- constrained_accessibility( -# constraint = "singly", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE, -# active = FALSE -# ) -# agg_demand <- constrained_accessibility( -# constraint = "singly", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = FALSE, -# active = FALSE -# ) -# -# # Totals -# expect_equal(sum(det_supply$supply), sum(lu$jobs)) -# expect_equal(sum(agg_supply$supply), sum(lu$jobs)) -# expect_equal(sum(det_demand$demand), sum(lu$population)) -# expect_equal(sum(agg_demand$demand), sum(lu$population)) -# -# # κ normalization properties (these DO hold for singly) -# by_to <- det_supply[, .(sum_k = sum(kappa_singly)), by = to_id] -# by_from <- det_demand[, .(sum_k = sum(hatkappa_singly)), by = from_id] -# expect_true(all(abs(by_to$sum_k - 1) < 1e-8)) # per-destination sums == 1 -# expect_true(all(abs(by_from$sum_k - 1) < 1e-8)) # per-origin sums == 1 -# expect_equal(sum(det_supply$kappa_singly), length(unique(det_supply$to_id))) -# 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( -# 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( -# 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() -# lu_bad <- data.table::copy(make_lu_match20()) -# lu_bad[id == "3", jobs := jobs + 1] # break equality -# -# expect_error( -# constrained_accessibility( -# constraint = "doubly", -# travel_matrix = tm, -# land_use_data = lu_bad, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE, -# active = NULL -# ), -# # cli wraps long messages, so spaces may be line breaks -# "sum of origins must equal the sum of[[:space:]]+destinations" -# ) -# }) -# -# -# -# test_that("doubly-constrained: OD flows match marginals", { -# tm <- make_tm_3x3() -# lu <- make_lu_match20() -# decay <- pow_decay_3 -# -# det <- constrained_accessibility( -# constraint = "doubly", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = decay, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE, -# active = NULL -# ) -# -# # Robustly pick the numeric flow column -# candidate_cols <- c("flow", "supply", "demand") -# value_col <- intersect(candidate_cols, names(det))[1] -# expect_true(!is.null(value_col), info = "No flow/supply/demand column in detailed output") -# expect_true(is.numeric(det[[value_col]]), info = "Flow column must be numeric") -# -# # Sum flows by origin and destination -# by_origin <- det[, .(sum_flow = sum(get(value_col))), by = from_id] -# by_dest <- det[, .(sum_flow = sum(get(value_col))), by = to_id] -# -# # Build expected marginals from land use -# O <- lu[match(by_origin$from_id, lu$id), population] -# D <- lu[match(by_dest$to_id, lu$id), jobs] -# -# expect_equal(by_origin$sum_flow, O, tolerance = 1e-3) -# expect_equal(by_dest$sum_flow, D, tolerance = 1e-3) -# }) -# -# -# test_that("doubly-constrained: results don't depend on row order or sparsity", { -# ids <- c("1", "2", "3") -# cost <- matrix( -# c(0, 10, 25, 15, 0, 5, 30, 20, 0), -# nrow = 3, -# byrow = TRUE, -# dimnames = list(ids, ids) -# ) -# lu <- make_lu_match20() -# -# # independent iterative proportional fitting, as reference -# -# reference_flows <- function(weights) { -# a <- b <- rep(1, 3) -# for (k in 1:2000) { -# a <- 1 / as.vector(weights %*% (b * lu$jobs)) -# b <- 1 / as.vector(t(weights) %*% (a * lu$population)) -# } -# flows <- outer(a * lu$population, b * lu$jobs) * weights -# dimnames(flows) <- list(ids, ids) -# flows -# } -# -# run_doubly <- function(tm, land_use = lu) { -# constrained_accessibility( -# constraint = "doubly", -# travel_matrix = tm, -# land_use_data = land_use, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE, -# error_threshold = 1e-10, -# improvement_threshold = 0 -# ) -# } -# -# to_major <- data.table::data.table( -# expand.grid(from_id = ids, to_id = ids, stringsAsFactors = FALSE) -# ) -# to_major[, travel_time := cost[cbind(from_id, to_id)]] -# from_major <- to_major[order(from_id, to_id)] -# shuffled <- to_major[c(5, 9, 1, 7, 3, 8, 2, 6, 4)] -# -# expected <- reference_flows(exp(-0.1 * cost)) -# for (tm in list(to_major, from_major, shuffled)) { -# result <- run_doubly(tm) -# expect_equal( -# result$flow, -# expected[cbind(result$from_id, result$to_id)], -# tolerance = 1e-6 -# ) -# } -# -# result <- run_doubly(to_major, lu[c(3, 1, 2)]) -# expect_equal( -# result$flow, -# expected[cbind(result$from_id, result$to_id)], -# tolerance = 1e-6 -# ) -# -# # pairs missing from the travel matrix are unreachable -# -# sparse_weights <- exp(-0.1 * cost) -# sparse_weights["1", "3"] <- 0 -# expected <- reference_flows(sparse_weights) -# -# result <- run_doubly(shuffled[!(from_id == "1" & to_id == "3")]) -# expect_equal( -# result$flow, -# expected[cbind(result$from_id, result$to_id)], -# tolerance = 1e-6 -# ) -# expect_identical(result[from_id == "1" & to_id == "3"]$flow, 0) -# }) -# -# 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", -# travel_matrix = make_tm_3x3(), -# land_use_data = make_lu_match20()[1:2], -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE -# )), -# regexp = "sum[[:space:]]+of[[:space:]]+origins[[:space:]]+must" -# ) -# }) -# -# 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")) -# ) -# tm_4[, travel_time := 10 + 5 * abs(as.integer(from_id) - as.integer(to_id))] -# tm_3 <- tm_4[from_id != "4" & to_id != "4"] -# -# lu_na <- rbind( -# make_lu_match20(), -# data.table::data.table(id = "4", population = NA, jobs = NA) -# ) -# -# run <- function(tm, lu) { -# suppressWarnings(constrained_accessibility( -# constraint = "doubly", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE -# )) -# } -# -# expected <- run(tm_3, make_lu_match20()) -# -# for (lu in list(lu_na, make_lu_match20())) { -# result <- run(tm_4, lu) -# -# expect_identical(result[from_id == "4" | to_id == "4"]$flow, rep(0, 7)) -# expect_equal( -# result[from_id != "4" & to_id != "4"]$flow, -# expected$flow, -# tolerance = 1e-6 -# ) -# } -# }) -# -# test_that("doubly-constrained: errors when total demand and supply are 0", { -# lu_zero <- make_lu_match20()[, `:=`(population = NA, jobs = 0)] -# -# expect_error( -# suppressWarnings(constrained_accessibility( -# constraint = "doubly", -# travel_matrix = make_tm_3x3(), -# land_use_data = lu_zero, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE -# )), -# regexp = "total[[:space:]]+demand[[:space:]]+and[[:space:]]+supply" -# ) -# }) -# -# test_that("doubly-constrained: converges with very small impedance weights", { -# tm <- make_tm_3x3() -# tm[, travel_time := travel_time + 60] -# lu <- make_lu_match20() -# -# # exp(-0.5 * c) is ~1e-13 to 1e-19 here -# -# result <- expect_silent( -# constrained_accessibility( -# constraint = "doubly", -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = decay_exponential(decay_value = 0.5), -# demand = "population", -# supply = "jobs", -# detailed_results = TRUE -# ) -# ) -# -# by_origin <- result[, .(flow = sum(flow)), by = from_id] -# by_destination <- result[, .(flow = sum(flow)), by = to_id] -# expect_equal( -# by_origin$flow, -# lu$population[match(by_origin$from_id, lu$id)], -# tolerance = 1e-3 -# ) -# expect_equal( -# by_destination$flow, -# lu$jobs[match(by_destination$to_id, lu$id)], -# tolerance = 1e-3 -# ) -# }) -# -# test_that("doubly-constrained: warns when balancing doesn't converge", { -# expect_warning( -# constrained_accessibility( -# constraint = "doubly", -# travel_matrix = make_tm_3x3(), -# land_use_data = make_lu_match20(), -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# max_iterations = 1, -# detailed_results = TRUE -# ), -# regexp = "did not converge" -# ) -# }) -# -# test_that("fill_missing_ids fills missing combinations when using group_by", { -# tm <- make_tm_3x3() -# 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" -# ) -# -# run <- function(constraint, travel_matrix, group_by = "mode") { -# constrained_accessibility( -# constraint = constraint, -# travel_matrix = travel_matrix, -# land_use_data = lu, -# travel_cost = "travel_time", -# decay_function = exp_decay_01, -# demand = "population", -# supply = "jobs", -# active = TRUE, -# group_by = group_by -# ) -# } -# -# for (constraint in c("total", "singly")) { -# result <- run(constraint, tm_modes) -# expect_identical(nrow(result), 6L) -# expect_identical(result[from_id == "3" & mode == "bus"]$supply, 0) -# } -# -# # 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"] -# expect_equal( -# car$supply, -# ungrouped$supply[match(car$from_id, ungrouped$from_id)] -# ) -# }) -# -# 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))] -# -# constrained_accessibility( -# travel_matrix = tm, -# land_use_data = lu, -# travel_cost = "travel_time", -# supply = "jobs", -# demand = "population", -# constraint = "total", -# decay_function = exp_decay_01, -# active = TRUE -# ) -# -# expect_true(is.null(attr(lu, "index"))) -# }) +#------------------------------- TOTAL (6 tests) ------------------------------- +test_that("total-constrained: preserves totals on supply/demand sides", { + tm <- make_tm_3x3() + lu <- make_lu_large() + + # Supply-side output (returns accessible opportunities) + det_supply <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = NULL, + supply = "jobs", + detailed_results = TRUE, + active = TRUE + ) + agg_supply <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = NULL, + supply = "jobs", + detailed_results = FALSE, + active = TRUE + ) + + # Demand-side output (returns accessible population) + det_demand <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = NULL, + detailed_results = TRUE, + active = FALSE + ) + agg_demand <- constrained_accessibility( + constraint = "total", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = NULL, + detailed_results = FALSE, + active = FALSE + ) + + expect_equal(sum(det_supply$supply), sum(lu$jobs)) + expect_equal(sum(agg_supply$supply), sum(lu$jobs)) + expect_equal(sum(det_demand$demand), sum(lu$population)) + expect_equal(sum(agg_demand$demand), sum(lu$population)) +}) + +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 + ) +}) + + +# ------------------------------ SINGLY (6 tests)------------------------------- +test_that("singly-constrained: preserves totals and kappa properties", { + tm <- make_tm_3x3() + lu <- make_lu_large() + + # Supply-constrained (returns accessible opportunities) + det_supply <- constrained_accessibility( + travel_matrix = tm, + land_use_data = lu, + constraint = "singly", + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE, + active = TRUE + ) + agg_supply <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = FALSE, + active = TRUE + ) + + # Demand-constrained (returns accessible population) + det_demand <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE, + active = FALSE + ) + agg_demand <- constrained_accessibility( + constraint = "singly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = FALSE, + active = FALSE + ) + + # Totals + expect_equal(sum(det_supply$supply), sum(lu$jobs)) + expect_equal(sum(agg_supply$supply), sum(lu$jobs)) + expect_equal(sum(det_demand$demand), sum(lu$population)) + expect_equal(sum(agg_demand$demand), sum(lu$population)) + + # κ normalization properties (these DO hold for singly) + by_to <- det_supply[, .(sum_k = sum(kappa_singly)), by = to_id] + by_from <- det_demand[, .(sum_k = sum(hatkappa_singly)), by = from_id] + expect_true(all(abs(by_to$sum_k - 1) < 1e-8)) # per-destination sums == 1 + expect_true(all(abs(by_from$sum_k - 1) < 1e-8)) # per-origin sums == 1 + expect_equal(sum(det_supply$kappa_singly), length(unique(det_supply$to_id))) + 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() + lu_bad <- data.table::copy(make_lu_match20()) + lu_bad[id == "3", jobs := jobs + 1] # break equality + + expect_error( + constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu_bad, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE, + active = NULL + ), + # cli wraps long messages, so spaces may be line breaks + "sum of origins must equal the sum of[[:space:]]+destinations" + ) +}) + + +test_that("doubly-constrained: OD flows match marginals", { + tm <- make_tm_3x3() + lu <- make_lu_match20() + decay <- pow_decay_3 + + det <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay, + demand = "population", + supply = "jobs", + detailed_results = TRUE, + active = NULL + ) + + # Robustly pick the numeric flow column + candidate_cols <- c("flow", "supply", "demand") + value_col <- intersect(candidate_cols, names(det))[1] + expect_true(!is.null(value_col), info = "No flow/supply/demand column in detailed output") + expect_true(is.numeric(det[[value_col]]), info = "Flow column must be numeric") + + # Sum flows by origin and destination + by_origin <- det[, .(sum_flow = sum(get(value_col))), by = from_id] + by_dest <- det[, .(sum_flow = sum(get(value_col))), by = to_id] + + # Build expected marginals from land use + O <- lu[match(by_origin$from_id, lu$id), population] + D <- lu[match(by_dest$to_id, lu$id), jobs] + + expect_equal(by_origin$sum_flow, O, tolerance = 1e-3) + expect_equal(by_dest$sum_flow, D, tolerance = 1e-3) +}) + + +test_that("doubly-constrained: results don't depend on row order or sparsity", { + ids <- c("1", "2", "3") + cost <- matrix( + c(0, 10, 25, 15, 0, 5, 30, 20, 0), + nrow = 3, + byrow = TRUE, + dimnames = list(ids, ids) + ) + lu <- make_lu_match20() + + # independent iterative proportional fitting, as reference + reference_flows <- function(weights) { + a <- b <- rep(1, 3) + for (k in 1:2000) { + a <- 1 / as.vector(weights %*% (b * lu$jobs)) + b <- 1 / as.vector(t(weights) %*% (a * lu$population)) + } + flows <- outer(a * lu$population, b * lu$jobs) * weights + dimnames(flows) <- list(ids, ids) + flows + } + + run_doubly <- function(tm, land_use = lu) { + constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = land_use, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE, + error_threshold = 1e-10, + improvement_threshold = 0 + ) + } + + to_major <- data.table::data.table( + expand.grid(from_id = ids, to_id = ids, stringsAsFactors = FALSE) + ) + to_major[, travel_time := cost[cbind(from_id, to_id)]] + from_major <- to_major[order(from_id, to_id)] + shuffled <- to_major[c(5, 9, 1, 7, 3, 8, 2, 6, 4)] + + expected <- reference_flows(exp(-0.1 * cost)) + for (tm in list(to_major, from_major, shuffled)) { + result <- run_doubly(tm) + expect_equal( + result$flow, + expected[cbind(result$from_id, result$to_id)], + tolerance = 1e-6 + ) + } + + result <- run_doubly(to_major, lu[c(3, 1, 2)]) + expect_equal( + result$flow, + expected[cbind(result$from_id, result$to_id)], + tolerance = 1e-6 + ) + + # pairs missing from the travel matrix are unreachable + sparse_weights <- exp(-0.1 * cost) + sparse_weights["1", "3"] <- 0 + expected <- reference_flows(sparse_weights) + + result <- run_doubly(shuffled[!(from_id == "1" & to_id == "3")]) + expect_equal( + result$flow, + expected[cbind(result$from_id, result$to_id)], + tolerance = 1e-6 + ) + expect_identical(result[from_id == "1" & to_id == "3"]$flow, 0) +}) + +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", + travel_matrix = make_tm_3x3(), + land_use_data = make_lu_match20()[1:2], + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE + )), + regexp = "sum[[:space:]]+of[[:space:]]+origins[[:space:]]+must" + ) +}) + +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")) + ) + tm_4[, travel_time := 10 + 5 * abs(as.integer(from_id) - as.integer(to_id))] + tm_3 <- tm_4[from_id != "4" & to_id != "4"] + + lu_na <- rbind( + make_lu_match20(), + data.table::data.table(id = "4", population = NA, jobs = NA) + ) + + run <- function(tm, lu) { + suppressWarnings(constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE + )) + } + + expected <- run(tm_3, make_lu_match20()) + + for (lu in list(lu_na, make_lu_match20())) { + result <- run(tm_4, lu) + + expect_identical(result[from_id == "4" | to_id == "4"]$flow, rep(0, 7)) + expect_equal( + result[from_id != "4" & to_id != "4"]$flow, + expected$flow, + tolerance = 1e-6 + ) + } +}) + +test_that("doubly-constrained: errors when total demand and supply are 0", { + lu_zero <- make_lu_match20()[, `:=`(population = NA, jobs = 0)] + + expect_error( + suppressWarnings(constrained_accessibility( + constraint = "doubly", + travel_matrix = make_tm_3x3(), + land_use_data = lu_zero, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + detailed_results = TRUE + )), + regexp = "total[[:space:]]+demand[[:space:]]+and[[:space:]]+supply" + ) +}) + +test_that("doubly-constrained: converges with very small impedance weights", { + tm <- make_tm_3x3() + tm[, travel_time := travel_time + 60] + lu <- make_lu_match20() + + # exp(-0.5 * c) is ~1e-13 to 1e-19 here + result <- expect_silent( + constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(decay_value = 0.5), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + ) + + by_origin <- result[, .(flow = sum(flow)), by = from_id] + by_destination <- result[, .(flow = sum(flow)), by = to_id] + expect_equal( + by_origin$flow, + lu$population[match(by_origin$from_id, lu$id)], + tolerance = 1e-3 + ) + expect_equal( + by_destination$flow, + lu$jobs[match(by_destination$to_id, lu$id)], + tolerance = 1e-3 + ) +}) + +test_that("doubly-constrained: warns when balancing doesn't converge", { + expect_warning( + constrained_accessibility( + constraint = "doubly", + travel_matrix = make_tm_3x3(), + land_use_data = make_lu_match20(), + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + max_iterations = 1, + detailed_results = TRUE + ), + regexp = "did not converge" + ) +}) + +test_that("fill_missing_ids fills missing combinations when using group_by", { + tm <- make_tm_3x3() + 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" + ) + + run <- function(constraint, travel_matrix, group_by = "mode") { + constrained_accessibility( + constraint = constraint, + travel_matrix = travel_matrix, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + active = TRUE, + group_by = group_by + ) + } + + for (constraint in c("total", "singly")) { + result <- run(constraint, tm_modes) + expect_identical(nrow(result), 6L) + expect_identical(result[from_id == "3" & mode == "bus"]$supply, 0) + } + + # 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"] + expect_equal( + car$supply, + ungrouped$supply[match(car$from_id, ungrouped$from_id)] + ) +}) + +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))] + + constrained_accessibility( + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + supply = "jobs", + demand = "population", + constraint = "total", + decay_function = exp_decay_01, + active = TRUE + ) + + expect_true(is.null(attr(lu, "index"))) +}) From 3b507e389b602bcc1622d8cb04fa2b05f23850b7 Mon Sep 17 00:00:00 2001 From: soukhova Date: Tue, 27 Oct 2026 12:16:43 -0400 Subject: [PATCH 5/7] Addresses review comments for issue #66 --- DESCRIPTION | 1 - NAMESPACE | 14 ++-- R/constrained_accessibility.R | 36 ++++----- R/total_constrained.R | 20 +++-- man/accessibility.Rd | 1 + man/balancing_cost.Rd | 21 ++++-- man/concentration_index.Rd | 10 +-- man/constrained_accessibility.Rd | 63 +++++++--------- man/cost_to_closest.Rd | 21 ++++-- man/cumulative_cutoff.Rd | 19 +++-- man/cumulative_interval.Rd | 19 +++-- man/decay_binary.Rd | 12 +-- man/decay_exponential.Rd | 12 +-- man/decay_linear.Rd | 12 +-- man/decay_logistic.Rd | 12 +-- man/decay_power.Rd | 12 +-- man/decay_stepped.Rd | 12 +-- man/fgt_poverty.Rd | 10 +-- man/floating_catchment_area.Rd | 22 +++--- man/gini_index.Rd | 10 +-- man/gravity.Rd | 28 ++++--- man/palma_ratio.Rd | 10 +-- man/roxygen/templates/decay_function.R | 8 +- man/roxygen/templates/group_by.R | 15 ++-- man/spatial_availability.Rd | 28 ++++--- man/theil_t.Rd | 10 +-- tests/testthat/test-constrained-essentials.R | 78 ++++++++++++++++++++ 27 files changed, 299 insertions(+), 217 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 39b3242..d57308f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -54,4 +54,3 @@ Encoding: UTF-8 NeedsCompilation: no Roxygen: list(markdown = TRUE) Config/roxygen2/version: 8.1.0 -RoxygenNote: 7.3.3 diff --git a/NAMESPACE b/NAMESPACE index 5711b67..1ff30c3 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -20,11 +20,13 @@ export(palma_ratio) export(spatial_availability) export(theil_t) importFrom(Rdpack,reprompt) -importFrom(data.table,"%chin%") -importFrom(data.table,":=") -importFrom(data.table,.GRP) -importFrom(data.table,.I) -importFrom(data.table,.N) -importFrom(data.table,.SD) +importFrom(data.table, + "%chin%", + ":=", + .GRP, + .I, + .N, + .SD +) importFrom(rlang,abort) importFrom(utils,globalVariables) diff --git a/R/constrained_accessibility.R b/R/constrained_accessibility.R index 283e211..04ceb02 100644 --- a/R/constrained_accessibility.R +++ b/R/constrained_accessibility.R @@ -36,19 +36,16 @@ #' This function covers the family of constrained accessibility measures #' proposed in \insertCite{soukhov2025family;textual}{accessibility}. #' -#' ### Grouping variables and multiple decay values +#' 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. #' -#' When `group_by` is supplied, calculations are performed separately for each -#' unique group and the results are stacked in the output. Likewise, when a -#' decay function is specified with multiple parameter values (e.g. -#' `decay_exponential(c(0.1, 0.5))`), calculations are performed separately -#' for each parameter value and the results are stacked in the output. -#' -#' For constrained accessibility measures, each group or decay value is treated -#' as an independent transportation system. This does not represent a -#' multimodal model that splits demand and/or supply across groups. Instead, -#' each group receives the full demand and/or supply totals and is evaluated -#' independently. +#' 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 #' @@ -170,12 +167,11 @@ #' - Both `demand` and `supply` must be provided. #' - Unlike `total` and `singly`, `doubly` requires the sum of demand and supply #' to match; otherwise, the model will not converge. -#' - `active` is ignored. Since supply must match demand, there is no -#' distinction between active and passive accessibility. -#' - `detailed_results = TRUE` is recommended, as the primary output -#' of the doubly-constrained model is the OD flow matrix. When -#' `detailed_results = FALSE`, the function returns the demand and supply -#' marginals, with a warning. +#' - `active` must be `NULL`. Since supply must match demand, their units are +#' the same and there is no distinction between 'active' and 'passive' notions. +#' - Should be used with `detailed_results = TRUE`. With +#' `detailed_results = FALSE`, it only returns the demand and supply +#' marginals, with a warning. #' #' ### Interpretation: #' - Results include OD-level flows (`flow`) along with balancing factors (`A_i`, @@ -214,9 +210,7 @@ #' and `flow`, holding the demand of each origin followed by the supply of #' each destination (so an id can appear twice). #' -#' Detailed results include the `group_by` columns (and `decay_function_arg`, -#' when present) so results from different groups or decay values can be -#' distinguished. +#' Detailed results don't include the `group_by` columns. #' #' @references #' \insertAllCited{} diff --git a/R/total_constrained.R b/R/total_constrained.R index 2c2f318..ef2823b 100644 --- a/R/total_constrained.R +++ b/R/total_constrained.R @@ -106,12 +106,11 @@ total_constrained <- function(travel_matrix, 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] @@ -128,13 +127,15 @@ total_constrained <- function(travel_matrix, "weighted_demand", "hatkappa_total", "constrained_opportunity", - "total_weighted_system" + "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) @@ -143,13 +144,16 @@ total_constrained <- function(travel_matrix, "weighted_supply", "kappa_total", "constrained_opportunity", - "total_weighted_system" + "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 { diff --git a/man/accessibility.Rd b/man/accessibility.Rd index 3d1912d..7961609 100644 --- a/man/accessibility.Rd +++ b/man/accessibility.Rd @@ -38,6 +38,7 @@ Useful links: Authors: \itemize{ + \item Daniel Herszenhut \email{dhersz@gmail.com} (\href{https://orcid.org/0000-0001-8066-1105}{ORCID}) \item Rafael H. M. Pereira \email{rafa.pereira.br@gmail.com} (\href{https://orcid.org/0000-0003-2125-7465}{ORCID}) \item Anastasia Soukhov } diff --git a/man/balancing_cost.Rd b/man/balancing_cost.Rd index ff10b76..a7c1d71 100644 --- a/man/balancing_cost.Rd +++ b/man/balancing_cost.Rd @@ -50,11 +50,16 @@ possibly benefit from a smaller increment of 0.05, for example, resulting in the function looking for balancing costs first at a cost of 0, then 0.05, 0.10, ..., etc. Defaults to 1.} -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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 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 @@ -100,8 +105,8 @@ head(bc) \insertAllCited{} } \seealso{ -Other accessibility measures: -\code{\link{cost_to_closest}()}, -\code{\link{gravity}()} +Other accessibility measures: +\code{\link[=cost_to_closest]{cost_to_closest()}}, +\code{\link[=gravity]{gravity()}} } \concept{accessibility measures} diff --git a/man/concentration_index.Rd b/man/concentration_index.Rd index 5dd40bc..ee1a240 100644 --- a/man/concentration_index.Rd +++ b/man/concentration_index.Rd @@ -97,10 +97,10 @@ ci \insertAllCited{} } \seealso{ -Other equity: -\code{\link{fgt_poverty}()}, -\code{\link{gini_index}()}, -\code{\link{palma_ratio}()}, -\code{\link{theil_t}()} +Other equity: +\code{\link[=fgt_poverty]{fgt_poverty()}}, +\code{\link[=gini_index]{gini_index()}}, +\code{\link[=palma_ratio]{palma_ratio()}}, +\code{\link[=theil_t]{theil_t()}} } \concept{equity} diff --git a/man/constrained_accessibility.Rd b/man/constrained_accessibility.Rd index ce27f9e..a7fc8eb 100644 --- a/man/constrained_accessibility.Rd +++ b/man/constrained_accessibility.Rd @@ -55,14 +55,7 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details. - -When a decay function is specified with multiple parameter values (e.g. -\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately -for each parameter value and the results are stacked in the output. This -is equivalent to running the function separately for each parameter value -and combining the results. A \code{decay_function_arg} column identifies the -parameter value associated with each result.} +details.} \item{active}{A logical. When \code{TRUE}, the function calculates active accessibility (the quantity of opportunities that can be reached from @@ -82,11 +75,16 @@ used only for calibration in the doubly-constrained case \item{max_iterations}{Integer. Maximum iterations used only for calibration in the doubly-constrained case (\code{constraint = "doubly"}).} -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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 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 @@ -128,9 +126,7 @@ and \code{flow}, holding the demand of each origin followed by the supply of each destination (so an id can appear twice). } -Detailed results include the \code{group_by} columns (and \code{decay_function_arg}, -when present) so results from different groups or decay values can be -distinguished. +Detailed results don't include the \code{group_by} columns. } \description{ Calculates accessibility using constraints, as proposed in @@ -142,21 +138,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}. -\subsection{Grouping variables and multiple decay values}{ -When \code{group_by} is supplied, calculations are performed separately for each -unique group and the results are stacked in the output. Likewise, when a -decay function is specified with multiple parameter values (e.g. -\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately -for each parameter value and the results are stacked in the output. - -For constrained accessibility measures, each group or decay value is treated -as an independent transportation system. This does not represent a -multimodal model that splits demand and/or supply across groups. Instead, -each group receives the full demand and/or supply totals and is evaluated -independently. -} +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 @@ -296,11 +288,10 @@ travel impedance. \item Both \code{demand} and \code{supply} must be provided. \item Unlike \code{total} and \code{singly}, \code{doubly} requires the sum of demand and supply to match; otherwise, the model will not converge. -\item \code{active} is ignored. Since supply must match demand, there is no -distinction between active and passive accessibility. -\item \code{detailed_results = TRUE} is recommended, as the primary output -of the doubly-constrained model is the OD flow matrix. When -\code{detailed_results = FALSE}, the function returns the demand and supply +\item \code{active} must be \code{NULL}. Since supply must match demand, their units are +the same and there is no distinction between 'active' and 'passive' notions. +\item Should be used with \code{detailed_results = TRUE}. With +\code{detailed_results = FALSE}, it only returns the demand and supply marginals, with a warning. } } @@ -404,7 +395,7 @@ constrained_accessibility( \insertAllCited{} } \seealso{ -Other Constrained accessibility: -\code{\link{spatial_availability}()} +Other Constrained accessibility: +\code{\link[=spatial_availability]{spatial_availability()}} } \concept{Constrained accessibility} diff --git a/man/cost_to_closest.Rd b/man/cost_to_closest.Rd index 780f4f8..a654862 100644 --- a/man/cost_to_closest.Rd +++ b/man/cost_to_closest.Rd @@ -40,11 +40,16 @@ be considered. Defaults to 1. If more than one value is provided, the output includes an extra column specifying the number of opportunities that the minimum travel cost refers to.} -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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 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 @@ -99,8 +104,8 @@ head(df) \dontshow{\}) # examplesIf} } \seealso{ -Other accessibility measures: -\code{\link{balancing_cost}()}, -\code{\link{gravity}()} +Other accessibility measures: +\code{\link[=balancing_cost]{balancing_cost()}}, +\code{\link[=gravity]{gravity()}} } \concept{accessibility measures} diff --git a/man/cumulative_cutoff.Rd b/man/cumulative_cutoff.Rd index 292d810..3e7b261 100644 --- a/man/cumulative_cutoff.Rd +++ b/man/cumulative_cutoff.Rd @@ -48,11 +48,16 @@ example, are included in the accessibility output. The cutoff parameter is not included in the final output if the input includes only a single cutoff for a single travel cost.} -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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 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 @@ -131,7 +136,7 @@ head(df) \dontshow{\}) # examplesIf} } \seealso{ -Other cumulative access: -\code{\link{cumulative_interval}()} +Other cumulative access: +\code{\link[=cumulative_interval]{cumulative_interval()}} } \concept{cumulative access} diff --git a/man/cumulative_interval.Rd b/man/cumulative_interval.Rd index ca4d4ff..bc4c385 100644 --- a/man/cumulative_interval.Rd +++ b/man/cumulative_interval.Rd @@ -53,11 +53,16 @@ single value. Can be any function that takes an arbitrary number of numeric values as input and returns a single number as output. Defaults to \code{\link[stats:median]{stats::median()}}.} -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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 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 @@ -114,7 +119,7 @@ head(df) \insertAllCited{} } \seealso{ -Other cumulative access: -\code{\link{cumulative_cutoff}()} +Other cumulative access: +\code{\link[=cumulative_cutoff]{cumulative_cutoff()}} } \concept{cumulative access} diff --git a/man/decay_binary.Rd b/man/decay_binary.Rd index 95e91ff..66d1827 100644 --- a/man/decay_binary.Rd +++ b/man/decay_binary.Rd @@ -35,11 +35,11 @@ weighting_function(c(20, 35)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link{decay_exponential}()}, -\code{\link{decay_linear}()}, -\code{\link{decay_logistic}()}, -\code{\link{decay_power}()}, -\code{\link{decay_stepped}()} +Other decay functions: +\code{\link[=decay_exponential]{decay_exponential()}}, +\code{\link[=decay_linear]{decay_linear()}}, +\code{\link[=decay_logistic]{decay_logistic()}}, +\code{\link[=decay_power]{decay_power()}}, +\code{\link[=decay_stepped]{decay_stepped()}} } \concept{decay functions} diff --git a/man/decay_exponential.Rd b/man/decay_exponential.Rd index efd2f0a..7ac6cf1 100644 --- a/man/decay_exponential.Rd +++ b/man/decay_exponential.Rd @@ -35,11 +35,11 @@ weighting_function(c(20, 30)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link{decay_binary}()}, -\code{\link{decay_linear}()}, -\code{\link{decay_logistic}()}, -\code{\link{decay_power}()}, -\code{\link{decay_stepped}()} +Other decay functions: +\code{\link[=decay_binary]{decay_binary()}}, +\code{\link[=decay_linear]{decay_linear()}}, +\code{\link[=decay_logistic]{decay_logistic()}}, +\code{\link[=decay_power]{decay_power()}}, +\code{\link[=decay_stepped]{decay_stepped()}} } \concept{decay functions} diff --git a/man/decay_linear.Rd b/man/decay_linear.Rd index 5a9d69b..6eed5e1 100644 --- a/man/decay_linear.Rd +++ b/man/decay_linear.Rd @@ -35,11 +35,11 @@ weighting_function(c(20, 35)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link{decay_binary}()}, -\code{\link{decay_exponential}()}, -\code{\link{decay_logistic}()}, -\code{\link{decay_power}()}, -\code{\link{decay_stepped}()} +Other decay functions: +\code{\link[=decay_binary]{decay_binary()}}, +\code{\link[=decay_exponential]{decay_exponential()}}, +\code{\link[=decay_logistic]{decay_logistic()}}, +\code{\link[=decay_power]{decay_power()}}, +\code{\link[=decay_stepped]{decay_stepped()}} } \concept{decay functions} diff --git a/man/decay_logistic.Rd b/man/decay_logistic.Rd index c354887..fc40e81 100644 --- a/man/decay_logistic.Rd +++ b/man/decay_logistic.Rd @@ -56,11 +56,11 @@ weighting_function(c(0, 30, 45, 60)) \insertAllCited{} } \seealso{ -Other decay functions: -\code{\link{decay_binary}()}, -\code{\link{decay_exponential}()}, -\code{\link{decay_linear}()}, -\code{\link{decay_power}()}, -\code{\link{decay_stepped}()} +Other decay functions: +\code{\link[=decay_binary]{decay_binary()}}, +\code{\link[=decay_exponential]{decay_exponential()}}, +\code{\link[=decay_linear]{decay_linear()}}, +\code{\link[=decay_power]{decay_power()}}, +\code{\link[=decay_stepped]{decay_stepped()}} } \concept{decay functions} diff --git a/man/decay_power.Rd b/man/decay_power.Rd index ba47beb..fadf779 100644 --- a/man/decay_power.Rd +++ b/man/decay_power.Rd @@ -34,11 +34,11 @@ weighting_function(c(20, 35)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link{decay_binary}()}, -\code{\link{decay_exponential}()}, -\code{\link{decay_linear}()}, -\code{\link{decay_logistic}()}, -\code{\link{decay_stepped}()} +Other decay functions: +\code{\link[=decay_binary]{decay_binary()}}, +\code{\link[=decay_exponential]{decay_exponential()}}, +\code{\link[=decay_linear]{decay_linear()}}, +\code{\link[=decay_logistic]{decay_logistic()}}, +\code{\link[=decay_stepped]{decay_stepped()}} } \concept{decay functions} diff --git a/man/decay_stepped.Rd b/man/decay_stepped.Rd index 2e3f7b7..fedbb84 100644 --- a/man/decay_stepped.Rd +++ b/man/decay_stepped.Rd @@ -65,11 +65,11 @@ weighting_function(c(0, 10, 20, 30, 40)) \dontshow{\}) # examplesIf} } \seealso{ -Other decay functions: -\code{\link{decay_binary}()}, -\code{\link{decay_exponential}()}, -\code{\link{decay_linear}()}, -\code{\link{decay_logistic}()}, -\code{\link{decay_power}()} +Other decay functions: +\code{\link[=decay_binary]{decay_binary()}}, +\code{\link[=decay_exponential]{decay_exponential()}}, +\code{\link[=decay_linear]{decay_linear()}}, +\code{\link[=decay_logistic]{decay_logistic()}}, +\code{\link[=decay_power]{decay_power()}} } \concept{decay functions} diff --git a/man/fgt_poverty.Rd b/man/fgt_poverty.Rd index df6df62..261d51f 100644 --- a/man/fgt_poverty.Rd +++ b/man/fgt_poverty.Rd @@ -126,10 +126,10 @@ poverty \insertAllCited{} } \seealso{ -Other equity: -\code{\link{concentration_index}()}, -\code{\link{gini_index}()}, -\code{\link{palma_ratio}()}, -\code{\link{theil_t}()} +Other equity: +\code{\link[=concentration_index]{concentration_index()}}, +\code{\link[=gini_index]{gini_index()}}, +\code{\link[=palma_ratio]{palma_ratio()}}, +\code{\link[=theil_t]{theil_t()}} } \concept{equity} diff --git a/man/floating_catchment_area.Rd b/man/floating_catchment_area.Rd index 525bff9..64bd354 100644 --- a/man/floating_catchment_area.Rd +++ b/man/floating_catchment_area.Rd @@ -51,20 +51,18 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details. +details.} -When a decay function is specified with multiple parameter values (e.g. -\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately -for each parameter value and the results are stacked in the output. This -is equivalent to running the function separately for each parameter value -and combining the results. A \code{decay_function_arg} column identifies the -parameter value associated with each result.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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. -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +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/gini_index.Rd b/man/gini_index.Rd index e84b064..4fbc2cc 100644 --- a/man/gini_index.Rd +++ b/man/gini_index.Rd @@ -67,10 +67,10 @@ gini \dontshow{\}) # examplesIf} } \seealso{ -Other equity: -\code{\link{concentration_index}()}, -\code{\link{fgt_poverty}()}, -\code{\link{palma_ratio}()}, -\code{\link{theil_t}()} +Other equity: +\code{\link[=concentration_index]{concentration_index()}}, +\code{\link[=fgt_poverty]{fgt_poverty()}}, +\code{\link[=palma_ratio]{palma_ratio()}}, +\code{\link[=theil_t]{theil_t()}} } \concept{equity} diff --git a/man/gravity.Rd b/man/gravity.Rd index ff8c0ca..f6078bb 100644 --- a/man/gravity.Rd +++ b/man/gravity.Rd @@ -42,20 +42,18 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details. +details.} -When a decay function is specified with multiple parameter values (e.g. -\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately -for each parameter value and the results are stacked in the output. This -is equivalent to running the function separately for each parameter value -and combining the results. A \code{decay_function_arg} column identifies the -parameter value associated with each result.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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. -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +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 @@ -111,8 +109,8 @@ head(df_exp) \dontshow{\}) # examplesIf} } \seealso{ -Other accessibility measures: -\code{\link{balancing_cost}()}, -\code{\link{cost_to_closest}()} +Other accessibility measures: +\code{\link[=balancing_cost]{balancing_cost()}}, +\code{\link[=cost_to_closest]{cost_to_closest()}} } \concept{accessibility measures} diff --git a/man/palma_ratio.Rd b/man/palma_ratio.Rd index d976a65..0e46ea2 100644 --- a/man/palma_ratio.Rd +++ b/man/palma_ratio.Rd @@ -80,10 +80,10 @@ palma \dontshow{\}) # examplesIf} } \seealso{ -Other equity: -\code{\link{concentration_index}()}, -\code{\link{fgt_poverty}()}, -\code{\link{gini_index}()}, -\code{\link{theil_t}()} +Other equity: +\code{\link[=concentration_index]{concentration_index()}}, +\code{\link[=fgt_poverty]{fgt_poverty()}}, +\code{\link[=gini_index]{gini_index()}}, +\code{\link[=theil_t]{theil_t()}} } \concept{equity} diff --git a/man/roxygen/templates/decay_function.R b/man/roxygen/templates/decay_function.R index 6a1988b..c249faf 100644 --- a/man/roxygen/templates/decay_function.R +++ b/man/roxygen/templates/decay_function.R @@ -6,10 +6,4 @@ #' [decay_linear()], [decay_logistic()], [decay_power()] and #' [decay_stepped()]. See the documentation of each decay function for more #' details. -#' -#' When a decay function is specified with multiple parameter values (e.g. -#' `decay_exponential(c(0.1, 0.5))`), calculations are performed separately -#' for each parameter value and the results are stacked in the output. This -#' is equivalent to running the function separately for each parameter value -#' and combining the results. A `decay_function_arg` column identifies the -#' parameter value associated with each result. + diff --git a/man/roxygen/templates/group_by.R b/man/roxygen/templates/group_by.R index febf82f..a18e6f0 100644 --- a/man/roxygen/templates/group_by.R +++ b/man/roxygen/templates/group_by.R @@ -1,5 +1,10 @@ -#' @param group_by A string referring to a column in the input data frame. -#' Calculations are performed separately for each unique value (or -#' combination of values) in `group_by`, and the results are stacked in the -#' output. This is equivalent to splitting the input data by group, running -#' the function separately for each group, and combining the results. +#' @param group_by A `character` vector. When not `character(0)` (the default), +#' indicates the `travel_matrix` columns that should be used to group the +#' accessibility estimates by. For example, if `travel_matrix` includes a +#' 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 93f06e6..6bad618 100644 --- a/man/spatial_availability.Rd +++ b/man/spatial_availability.Rd @@ -48,25 +48,23 @@ same length as the input. For convenience, the package currently includes the following functions: \code{\link[=decay_binary]{decay_binary()}}, \code{\link[=decay_exponential]{decay_exponential()}}, \code{\link[=decay_linear]{decay_linear()}}, \code{\link[=decay_logistic]{decay_logistic()}}, \code{\link[=decay_power]{decay_power()}} and \code{\link[=decay_stepped]{decay_stepped()}}. See the documentation of each decay function for more -details. - -When a decay function is specified with multiple parameter values (e.g. -\code{decay_exponential(c(0.1, 0.5))}), calculations are performed separately -for each parameter value and the results are stacked in the output. This -is equivalent to running the function separately for each parameter value -and combining the results. A \code{decay_function_arg} column identifies the -parameter value associated with each result.} +details.} \item{alpha}{A \code{numeric}. A parameter used to modulate the effect of demand by population. When less than 1, opportunities are allocated more rapidly to smaller centers relative to larger ones; values higher than 1 achieve the opposite effect.} -\item{group_by}{A string referring to a column in the input data frame. -Calculations are performed separately for each unique value (or -combination of values) in \code{group_by}, and the results are stacked in the -output. This is equivalent to splitting the input data by group, running -the function separately for each group, and combining the results.} +\item{group_by}{A \code{character} vector. When not \code{character(0)} (the default), +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 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 @@ -143,7 +141,7 @@ detailed_df \insertAllCited{} } \seealso{ -Other Constrained accessibility: -\code{\link{constrained_accessibility}()} +Other Constrained accessibility: +\code{\link[=constrained_accessibility]{constrained_accessibility()}} } \concept{Constrained accessibility} diff --git a/man/theil_t.Rd b/man/theil_t.Rd index f3fe056..1871804 100644 --- a/man/theil_t.Rd +++ b/man/theil_t.Rd @@ -114,10 +114,10 @@ ti \dontshow{\}) # examplesIf} } \seealso{ -Other equity: -\code{\link{concentration_index}()}, -\code{\link{fgt_poverty}()}, -\code{\link{gini_index}()}, -\code{\link{palma_ratio}()} +Other equity: +\code{\link[=concentration_index]{concentration_index()}}, +\code{\link[=fgt_poverty]{fgt_poverty()}}, +\code{\link[=gini_index]{gini_index()}}, +\code{\link[=palma_ratio]{palma_ratio()}} } \concept{equity} diff --git a/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index e61b548..515a0e8 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -394,6 +394,84 @@ test_that("total-constrained (active) fills missing group combinations", { ) }) +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)] + ) + } +) # ------------------------------ SINGLY (6 tests)------------------------------- test_that("singly-constrained: preserves totals and kappa properties", { From 5e9dcb27ccb3194d2e5ced5c34db617b694d7736 Mon Sep 17 00:00:00 2001 From: rafapereirabr Date: Tue, 27 Oct 2026 13:50:17 -0300 Subject: [PATCH 6/7] Tidy up the total/singly group_by fix and test uneven groups - Declare total_opportunities_region in utils::globalVariables() (R CMD check NOTE: no visible binding). - Fix the stale doc line: for "total" and "singly", detailed results now include the group_by columns and decay_function_arg. - Remove the commented-out code left in singly_constrained(). - Add a NEWS entry for #66. - Test that each group gets its own regional total against hand-computed values (active, passive, two decay values, K_total), and that grouped results equal standalone runs when groups cover different ids (total and singly, active and passive). Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 5 + R/constrained_accessibility.R | 4 +- R/singly_constrained.R | 14 -- R/total_constrained.R | 1 + man/constrained_accessibility.Rd | 4 +- tests/testthat/test-constrained-essentials.R | 146 +++++++++++++++++++ 6 files changed, 158 insertions(+), 16 deletions(-) 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 04ceb02..4a6c86b 100644 --- a/R/constrained_accessibility.R +++ b/R/constrained_accessibility.R @@ -210,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 ae133b4..27c2607 100644 --- a/R/singly_constrained.R +++ b/R/singly_constrained.R @@ -93,13 +93,6 @@ singly_constrained <- function(travel_matrix, access[, B_j := data.table::fifelse(denom_j > 0, 1 / denom_j, 0)] access[, denom_j := NULL] - # access <- data[, .( - # from_id, - # to_id, - # kappa_singly, - # supply = singly_access, - # B_j = data.table::fifelse(denom_j > 0, 1 / denom_j, 0) - # )] } else { access <- data[, .(supply = sum(singly_access)), by = c("from_id", group_by)] if (fill_missing_ids) { @@ -131,13 +124,6 @@ singly_constrained <- function(travel_matrix, access[, A_i := data.table::fifelse(denom_i > 0, 1 / denom_i, 0)] access[, denom_i := NULL] - # access <- data[, .( - # from_id, - # to_id, - # hatkappa_singly, - # demand = singly_access, - # A_i = data.table::fifelse(denom_i > 0, 1 / denom_i, 0) - # )] } 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 ef2823b..10f42b9 100644 --- a/R/total_constrained.R +++ b/R/total_constrained.R @@ -20,6 +20,7 @@ utils::globalVariables(c( "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", "total_weighted_system", + "total_opportunities_region", # singly-constrained "denom_i", "denom_j", "kappa_singly", "hatkappa_singly", "A_i", "B_j", "singly_access", # doubly-constrained diff --git a/man/constrained_accessibility.Rd b/man/constrained_accessibility.Rd index a7fc8eb..1592abe 100644 --- a/man/constrained_accessibility.Rd +++ b/man/constrained_accessibility.Rd @@ -126,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 diff --git a/tests/testthat/test-constrained-essentials.R b/tests/testthat/test-constrained-essentials.R index 515a0e8..208469a 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -473,6 +473,152 @@ test_that( } ) +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() From bd114d71a5d9c3cbd46ea97e961524dc2f6da19b Mon Sep 17 00:00:00 2001 From: rafapereirabr Date: Wed, 28 Oct 2026 23:15:21 -0300 Subject: [PATCH 7/7] Make error-message tests robust to cli line wrapping cli wraps long messages at the console width, so a test regexp with plain spaces fails when a line break falls inside the phrase (seen on a narrow console in "raises a clear error if id types are incompatible"). Use [[:space:]]+ between words, keeping only the distinctive words where the full phrase would pass 80 columns. With this, the suite passes at cli.width = 20, 40 and 80, except "doubly-constrained: errors when totals mismatch", which PR #71 replaces with a wrap-safe version (left untouched here to avoid a conflict). Co-Authored-By: Claude Opus 5.5 --- tests/testthat/test-assert_land_use_data.R | 12 ++++++------ .../test-assert_sociodemographic_data_warnings.R | 2 +- tests/testthat/test-constrained-essentials.R | 2 +- tests/testthat/test-constrained-wrapper.R | 4 ++-- tests/testthat/test-cumulative_cutoff.R | 2 +- tests/testthat/test-decay_linear.R | 7 +++++-- tests/testthat/test-gravity.R | 2 +- 7 files changed, 17 insertions(+), 14 deletions(-) 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 208469a..403c4cc 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -1293,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" ) }) 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