-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc_dist_matrix.R
57 lines (45 loc) · 1.69 KB
/
calc_dist_matrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#' Calculate distance matrix in parallel
#'
#' @param x simple feature object. See \code{?sf}
#' @param split_att attribute name (column) from \code{x} to use as file name.
#' @param output_dir path to store distance matrix RDS files.
#' Default is work dir
#' @param pb progress bar. See \code{?progress::progress_bar}.
#' Default is NULL
#' @importFrom magrittr %>%
#' @importFrom stats as.dist
#' @importFrom parallel mclapply detectCores
#' @importFrom sf st_distance st_geometry
#' @importFrom stringr str_glue
#'
#' @return TRUE if success FALSE if could not create the distance matrix
#' @export
calc_dist_matrix <-
function(x,
split_att,
output_dir = ".",
pb = NULL) {
if(!"lwgeom" %in% loadedNamespaces())
stop("Error: load lwgeom first - library(lwgeom)")
if(!is.null(pb)) pb$tick()
path_features_dist_meter <- stringr::str_glue("{output_dir}/dist_matrix/{x[[split_att]][1]}.rds")
dir.create(dirname(path_features_dist_meter), showWarnings = FALSE, recursive = TRUE)
# stop processing if job has less than two features --------------------------
if( nrow(x) < 2 ){
return(NULL)
}
# compute geographical distance in parallel ----------------------------------
ids <- x$id
x <- sf::st_geometry(x)
cores <- parallel::detectCores()
if(!file.exists(path_features_dist_meter)){
dist_matrix <-
split(x, 1:length(x)) %>%
parallel::mclapply(mc.cores = cores, FUN = sf::st_distance, y = x)
dist_matrix <- do.call("rbind", dist_matrix)
row.names(dist_matrix) <- ids
as.dist(dist_matrix) %>%
saveRDS(file = path_features_dist_meter)
}
return(path_features_dist_meter)
}