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..2adbf5a 100644 --- a/R/constrained_accessibility.R +++ b/R/constrained_accessibility.R @@ -29,7 +29,10 @@ #' in the doubly-constrained case (`constraint = "doubly"`). #' @template group_by #' @template fill_missing_ids_combinations -#' @param detailed_results Logical. Whether to return detailed OD-level results. +#' @param detailed_results Logical. Whether to return detailed OD-level +#' results for `constraint = "total"`- and `constraint = "singly"` +#' accessibility. Currently ignored for `constraint = "doubly"` accessibility, +#' which always returns OD-level flows. #' #' #' @section Details: @@ -156,11 +159,10 @@ #' - 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` must be `NULL`. Since supply must match demand, their units are +#' the same and there is no distinction between 'active' and 'passive' notions. +#' - `detailed_results` is currently ignored for doubly-constrained +#' accessibility. OD-level flows are always returned. #' #' ### Interpretation: #' - Results include OD-level flows (`flow`) along with balancing factors (`A_i`, @@ -191,15 +193,14 @@ #' origin-destination pair, with the columns `from_id`, `to_id`, the #' allocation share (`kappa_singly` or `hatkappa_singly`), the allocated flow #' (`supply` or `demand`) and the balancing factor (`B_j` or `A_i`). -#' - `constraint = "doubly"`, `detailed_results = TRUE`: one row per -#' origin-destination pair, with the columns `from_id`, `to_id`, `flow`, the -#' balancing factors `A_i` and `B_j`, `kappa_doubly` and the final balancing -#' `error`. -#' - `constraint = "doubly"`, `detailed_results = FALSE`: the columns `id` -#' and `flow`, holding the demand of each origin followed by the supply of -#' each destination (so an id can appear twice). +#' - `constraint = "doubly"`: one row per origin-destination pair, with the +#' columns `from_id`, `to_id`, `flow`, the balancing factors `A_i` and `B_j`, +#' `kappa_doubly` and the final balancing `error`. `detailed_results` and +#' `active` are not read. #' -#' Detailed results don't include the `group_by` columns. +#' Detailed results retain any grouping columns supplied through +#' `group_by`, as well as `decay_function_arg` when multiple decay +#' parameter values are used. #' #' @references #' \insertAllCited{} @@ -255,7 +256,7 @@ #' ) #' #' # Doubly-constrained: returns units of flow (requires both demand and supply -#' # (totals that match) and `detailed_results = TRUE`) +#' # with matching totals) #' #' # Using a small toy dataset with matching totals. #' tm_small <- data.table::data.table( diff --git a/R/doubly_constrained.R b/R/doubly_constrained.R index b02013c..6bd8a6c 100644 --- a/R/doubly_constrained.R +++ b/R/doubly_constrained.R @@ -8,8 +8,8 @@ #' #' @name doubly_constrained #' @keywords internal -#' @return A `data.table`/`data.frame` with either OD-level flows (`detailed_results = TRUE`) -#' or marginals; see Details. +#' @return A `data.table`/`data.frame` with origin-destination flows, balancing +#' factors (`A_i`, `B_j`), and doubly-constrained weights (`kappa_doubly`). #' @examples NULL #' @importFrom utils globalVariables utils::globalVariables(c( @@ -22,134 +22,117 @@ utils::globalVariables(c( # doubly-constrained "kappa_doubly", "flow", "error" )) -doubly_constrained <- function(travel_matrix, - land_use_data, - travel_cost, - decay_function, - demand, - supply, - error_threshold = 0.001, - improvement_threshold = 1e-6, - max_iterations = 1000, - active, - group_by = character(0), - fill_missing_ids = TRUE, - detailed_results = FALSE - ) { - # Validate inputs - checkmate::assert_string(demand) - checkmate::assert_string(supply) - checkmate::assert_number(error_threshold, lower = 0) - checkmate::assert_number(improvement_threshold, lower = 0) - checkmate::assert_int(max_iterations, lower = 1) - - # Convert to data.table - if (!inherits(travel_matrix, "data.table")) { - original_class <- class(travel_matrix) - data <- data.table::as.data.table(travel_matrix) - } else { - data <- data.table::copy(travel_matrix) - } - if (!inherits(land_use_data, "data.table")) { - land_use_data <- data.table::as.data.table(land_use_data) - } - - # Merge demand and supply - merge_by_reference( +run_standalone_doubly_ipf <- function( data, land_use_data, demand, - left_df_idcol = "from_id", - na_as_zero = TRUE - ) - merge_by_reference( - data, - land_use_data, supply, - left_df_idcol = "to_id", - na_as_zero = TRUE - ) - - # Apply decay - data <- apply_gravity_measure(data, decay_function, travel_cost) + error_threshold, + improvement_threshold, + max_iterations +) { # Prepare vectors and impedance matrix origins <- unique(data$from_id) destinations <- unique(data$to_id) + O <- land_use_data[[demand]][match(origins, land_use_data$id)] D <- land_use_data[[supply]][match(destinations, land_use_data$id)] - # NA values and ids missing from land_use_data count as 0 demand/supply - O[is.na(O)] <- 0 D[is.na(D)] <- 0 - # Validate totals match if (abs(sum(O) - sum(D)) > 1e-6) { cli::cli_abort( - "For doubly-constrained, the sum of origins must equal the sum of - destinations. NA values and ids missing from {.arg land_use_data} count - as 0.", + "For doubly-constrained, the sum of origins must equal the sum of destinations. + NA values and ids missing from {.arg land_use_data} count as 0.", call = NULL ) } if (sum(O) <= 0) { cli::cli_abort( - "For doubly-constrained, the total demand and supply must be greater - than 0.", + "For doubly-constrained, the total demand and supply must be greater than 0.", call = NULL ) } - # Build impedance matrix - # filled by id, so the result doesn't depend on the row order of - # travel_matrix. pairs missing from travel_matrix are unreachable (weight 0) - impedance_matrix <- matrix( 0, nrow = length(origins), ncol = length(destinations), dimnames = list(origins, destinations) ) + impedance_matrix[ - cbind(match(data$from_id, origins), match(data$to_id, destinations)) + cbind( + match(data$from_id, origins), + match(data$to_id, destinations) + ) ] <- data$opp_weight - # Iterative proportional fitting Ai <- rep(1, length(O)) Bj <- rep(1, length(D)) + previous_error <- Inf iteration_count <- 0 stop_reason <- "" repeat { + iteration_count <- iteration_count + 1 - # Update Ai - # a null denominator means the zone reaches (or is reached by) no one, so - # its factor is 0 and it gets no flow. the denominators of all zones are - # calculated at once with matrix products + denominator_i <- drop( + impedance_matrix %*% (Bj * D) + ) + + Ai <- data.table::fifelse( + denominator_i > 0, + 1 / denominator_i, + 0 + ) - denominator_i <- drop(impedance_matrix %*% (Bj * D)) - Ai <- data.table::fifelse(denominator_i > 0, 1 / denominator_i, 0) + denominator_j <- drop( + crossprod( + impedance_matrix, + Ai * O + ) + ) - # Update Bj - denominator_j <- drop(crossprod(impedance_matrix, Ai * O)) - Bj_new <- data.table::fifelse(denominator_j > 0, 1 / denominator_j, 0) + Bj_new <- data.table::fifelse( + denominator_j > 0, + 1 / denominator_j, + 0 + ) - # Compute error - # the row and column sums of the flows (Tij = Ai * O_i * Bj * D_j * f_ij) - # are calculated from the factors, without building the flow matrix + flow_from <- Ai * O * + drop(impedance_matrix %*% (Bj_new * D)) - flow_from <- Ai * O * drop(impedance_matrix %*% (Bj_new * D)) flow_to <- Bj_new * D * denominator_j - error <- (sum(abs(O - flow_from)) + sum(abs(D - flow_to))) / sum(O) + + error <- ( + sum(abs(O - flow_from)) + + sum(abs(D - flow_to)) + ) / sum(O) + error_change <- abs(previous_error - error) - if (error < error_threshold || error_change < improvement_threshold || iteration_count >= max_iterations) { + if ( + error < error_threshold || + error_change < improvement_threshold || + iteration_count >= max_iterations + ) { + Bj <- Bj_new - stop_reason <- if (iteration_count >= max_iterations) "Max iterations reached" else if (error < error_threshold) "Error threshold met" else "Slow improvement" + + stop_reason <- if (iteration_count >= max_iterations) { + "Max iterations reached" + } else if (error < error_threshold) { + "Error threshold met" + } else { + "Slow improvement" + } + break } @@ -159,23 +142,23 @@ doubly_constrained <- function(travel_matrix, if (error >= error_threshold) { cli::cli_warn( - "Doubly-constrained balancing did not converge ({stop_reason} after - {iteration_count} iterations). Final error is {signif(error, 3)}, above - {.arg error_threshold} ({error_threshold}), so flows don't fully match - the demand and supply totals. Consider increasing - {.arg max_iterations} or decreasing {.arg improvement_threshold}." + "Doubly-constrained balancing did not converge ({stop_reason} + after {iteration_count} iterations). Final error is + {signif(error, 3)}." ) } - # Compute flows - Tij <- outer(Ai * O, Bj * D) * impedance_matrix + Tij <- outer( + Ai * O, + Bj * D + ) * impedance_matrix - # Compute kappa_doubly -# kappa_ij^D = A_i * B_j * O_i * f(c_ij) - kappa_matrix <- outer(Ai * O, Bj) * impedance_matrix + kappa_matrix <- outer( + Ai * O, + Bj + ) * impedance_matrix - # Prepare output - detailed_dt <- data.table::data.table( + data.table::data.table( from_id = rep(origins, each = length(destinations)), to_id = rep(destinations, times = length(origins)), flow = as.vector(t(Tij)), @@ -185,20 +168,145 @@ doubly_constrained <- function(travel_matrix, error = error ) - if (detailed_results) { - if (exists("original_class")) class(detailed_dt) <- original_class - return(detailed_dt[]) - } else { - cli::cli_warn( - "Aggregated results equal marginals (O_i or D_j). Interpret with - caution." +} + +run_grouped_doubly_ipf <- function( + data, + group_by, + land_use_data, + demand, + supply, + error_threshold, + improvement_threshold, + max_iterations +) { + + if ("decay_function_arg" %in% names(data)) { + group_by <- c(group_by, "decay_function_arg") + } + + if (length(group_by) == 0) { + + return( + run_standalone_doubly_ipf( + data = data, + land_use_data = land_use_data, + demand = demand, + supply = supply, + error_threshold = error_threshold, + improvement_threshold = improvement_threshold, + max_iterations = max_iterations + ) ) - agg <- data.table::rbindlist(list( - data.table::data.table(id = origins, flow = O), - data.table::data.table(id = destinations, flow = D) - )) - if (exists("original_class")) class(agg) <- original_class - return(agg[]) } + grouped_data <- split( + data, + by = group_by, + keep.by = TRUE + ) + + results <- data.table::rbindlist( + lapply(grouped_data, function(dt) { + + out <- run_standalone_doubly_ipf( + data = dt, + land_use_data = land_use_data, + demand = demand, + supply = supply, + error_threshold = error_threshold, + improvement_threshold = improvement_threshold, + max_iterations = max_iterations + ) + + group_vals <- dt[1, ..group_by] + + for (g in group_by) { + out[, (g) := group_vals[[g]]] + } + + out + + }), + fill = TRUE + ) + + return(results[]) + +} + +doubly_constrained <- function(travel_matrix, + land_use_data, + travel_cost, + decay_function, + demand, + supply, + error_threshold = 0.001, + improvement_threshold = 1e-6, + max_iterations = 1000, + active, + group_by = character(0), + fill_missing_ids = TRUE, + detailed_results = FALSE +) { + # Validate inputs + checkmate::assert_string(demand) + checkmate::assert_string(supply) + checkmate::assert_number(error_threshold, lower = 0) + checkmate::assert_number(improvement_threshold, lower = 0) + checkmate::assert_int(max_iterations, lower = 1) + + assert_decay_function(decay_function) + assert_group_by(group_by) + assert_travel_matrix(travel_matrix, travel_cost, group_by) + assert_land_use_data(land_use_data, travel_matrix, opportunity = supply, demand = demand) + + # Convert to data.table + if (!inherits(travel_matrix, "data.table")) { + original_class <- class(travel_matrix) + data <- data.table::as.data.table(travel_matrix) + } else { + data <- data.table::copy(travel_matrix) + } + if (!inherits(land_use_data, "data.table")) { + land_use_data <- data.table::as.data.table(land_use_data) + } + + # Merge demand and supply + merge_by_reference( + data, + land_use_data, + demand, + left_df_idcol = "from_id", + na_as_zero = TRUE + ) + merge_by_reference( + data, + land_use_data, + supply, + left_df_idcol = "to_id", + na_as_zero = TRUE + ) + + # Apply decay + data <- apply_gravity_measure(data, decay_function, travel_cost) + + # Run doubly-constrained model + result <- run_grouped_doubly_ipf( + data = data, + group_by = group_by, + land_use_data = land_use_data, + demand = demand, + supply = supply, + error_threshold = error_threshold, + improvement_threshold = improvement_threshold, + max_iterations = max_iterations + ) + + if (exists("original_class")) { + class(result) <- original_class + } + + return(result[]) + } 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..7ba52ba 100644 --- a/man/balancing_cost.Rd +++ b/man/balancing_cost.Rd @@ -101,8 +101,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..11762c9 100644 --- a/man/constrained_accessibility.Rd +++ b/man/constrained_accessibility.Rd @@ -92,7 +92,10 @@ the function identifies which combinations would be left out and fills their respective accessibility values with 0, which incurs a performance penalty.} -\item{detailed_results}{Logical. Whether to return detailed OD-level results.} +\item{detailed_results}{Logical. Whether to return detailed OD-level +results for \code{constraint = "total"}- and \code{constraint = "singly"} +accessibility. Currently ignored for \code{constraint = "doubly"} accessibility, +which always returns OD-level flows.} } \value{ A data frame of the same class as \code{travel_matrix} (\code{data.table}, @@ -113,16 +116,15 @@ the allocated flow (\code{supply} or \code{demand}) and the scaling constant origin-destination pair, with the columns \code{from_id}, \code{to_id}, the allocation share (\code{kappa_singly} or \code{hatkappa_singly}), the allocated flow (\code{supply} or \code{demand}) and the balancing factor (\code{B_j} or \code{A_i}). -\item \code{constraint = "doubly"}, \code{detailed_results = TRUE}: one row per -origin-destination pair, with the columns \code{from_id}, \code{to_id}, \code{flow}, the -balancing factors \code{A_i} and \code{B_j}, \code{kappa_doubly} and the final balancing -\code{error}. -\item \code{constraint = "doubly"}, \code{detailed_results = FALSE}: the columns \code{id} -and \code{flow}, holding the demand of each origin followed by the supply of -each destination (so an id can appear twice). +\item \code{constraint = "doubly"}: one row per origin-destination pair, with the +columns \code{from_id}, \code{to_id}, \code{flow}, the balancing factors \code{A_i} and \code{B_j}, +\code{kappa_doubly} and the final balancing \code{error}. \code{detailed_results} and +\code{active} are not read. } -Detailed results don't include the \code{group_by} columns. +Detailed results retain any grouping columns supplied through +\code{group_by}, as well as \code{decay_function_arg} when multiple decay +parameter values are used. } \description{ Calculates accessibility using constraints, as proposed in @@ -275,9 +277,8 @@ travel impedance. 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 -marginals, with a warning. +\item \code{detailed_results} is currently ignored for doubly-constrained +accessibility. OD-level flows are always returned. } } @@ -351,7 +352,7 @@ constrained_accessibility( ) # Doubly-constrained: returns units of flow (requires both demand and supply -# (totals that match) and `detailed_results = TRUE`) +# with matching totals) # Using a small toy dataset with matching totals. tm_small <- data.table::data.table( @@ -380,7 +381,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..42a818f 100644 --- a/man/cost_to_closest.Rd +++ b/man/cost_to_closest.Rd @@ -100,8 +100,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..059fc18 100644 --- a/man/cumulative_cutoff.Rd +++ b/man/cumulative_cutoff.Rd @@ -132,7 +132,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..40f6639 100644 --- a/man/cumulative_interval.Rd +++ b/man/cumulative_interval.Rd @@ -115,7 +115,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/doubly_constrained.Rd b/man/doubly_constrained.Rd index 1a62da9..3ad7c13 100644 --- a/man/doubly_constrained.Rd +++ b/man/doubly_constrained.Rd @@ -4,8 +4,8 @@ \alias{doubly_constrained} \title{Doubly constrained accessibility} \value{ -A \code{data.table}/\code{data.frame} with either OD-level flows (\code{detailed_results = TRUE}) -or marginals; see Details. +A \code{data.table}/\code{data.frame} with origin-destination flows, balancing +factors (\code{A_i}, \code{B_j}), and doubly-constrained weights (\code{kappa_doubly}). } \description{ Calculates accessibility using Wilson's doubly-constrained gravity model. 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/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..63265cd 100644 --- a/man/gravity.Rd +++ b/man/gravity.Rd @@ -105,8 +105,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/spatial_availability.Rd b/man/spatial_availability.Rd index 6b96f57..13d3754 100644 --- a/man/spatial_availability.Rd +++ b/man/spatial_availability.Rd @@ -137,7 +137,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 9bba5d2..e12afa9 100644 --- a/tests/testthat/test-constrained-essentials.R +++ b/tests/testthat/test-constrained-essentials.R @@ -151,29 +151,7 @@ test_that("singly-constrained: preserves totals and kappa properties", { 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" - ) -}) - +# ------------------------------ DOUBLY (13 tests)------------------------------- test_that("doubly-constrained: OD flows match marginals", { @@ -483,3 +461,223 @@ test_that("total-constrained: doesn't add an index to land_use_data", { expect_true(is.null(attr(lu, "index"))) }) + +test_that("doubly-constrained grouped results equal standalone runs", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list(car = tm, bus = tm), + idcol = "mode" + ) + + grouped <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + group_by = "mode", + detailed_results = TRUE + ) + + standalone <- 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 + ) + + expect_equal( + grouped[mode == "car"]$flow, + standalone$flow + ) + + expect_equal( + grouped[mode == "bus"]$flow, + standalone$flow + ) +}) + +test_that("doubly-constrained multiple decay values equal separate runs", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + multi <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.1, 0.5)), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + + run_01 <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.1), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + + run_05 <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.5), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + + expect_equal( + multi[decay_function_arg == 0.1]$flow, + run_01$flow + ) + + expect_equal( + multi[decay_function_arg == 0.5]$flow, + run_05$flow + ) +}) + +test_that("doubly-constrained preserves grouping columns", { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list(car = tm, bus = tm), + idcol = "mode" + ) + + grouped <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = exp_decay_01, + demand = "population", + supply = "jobs", + group_by = "mode", + detailed_results = TRUE + ) + + expect_true("mode" %in% names(grouped)) + + multi <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.1, 0.5)), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + + expect_true("decay_function_arg" %in% names(multi)) +}) + + +test_that( + "doubly-constrained handles grouped and multi-decay runs at the same time", + { + + tm <- make_tm_3x3() + lu <- make_lu_match20() + + tm_modes <- data.table::rbindlist( + list( + car = tm, + bus = tm + ), + idcol = "mode" + ) + + result <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm_modes, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(c(0.1, 0.5)), + demand = "population", + supply = "jobs", + group_by = "mode", + detailed_results = TRUE + ) + + run_01 <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.1), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + + run_05 <- constrained_accessibility( + constraint = "doubly", + travel_matrix = tm, + land_use_data = lu, + travel_cost = "travel_time", + decay_function = decay_exponential(0.5), + demand = "population", + supply = "jobs", + detailed_results = TRUE + ) + + expect_identical( + sort(unique(result$mode)), + c("bus", "car") + ) + + expect_identical( + sort(unique(result$decay_function_arg)), + c(0.1, 0.5) + ) + + # 2 modes × 2 decay values × 9 OD pairs + + expect_identical( + nrow(result), + 36L + ) + + expect_equal( + result[mode == "car" & decay_function_arg == 0.1]$flow, + run_01$flow + ) + + expect_equal( + result[mode == "bus" & decay_function_arg == 0.1]$flow, + run_01$flow + ) + + expect_equal( + result[mode == "car" & decay_function_arg == 0.5]$flow, + run_05$flow + ) + + expect_equal( + result[mode == "bus" & decay_function_arg == 0.5]$flow, + run_05$flow + ) + } +)