0

我正在计算 sfnetwork my_sfn中两点之间的最短路径。

计算出的路径由保存在可变路径中的图形 id和 I 组成,并希望获得连接到这些 id 的几何图形(gps 值)。

这是通过以下方式完成的:

coordinates_of_the_path<-mclapply(paths,function(x) cbind(as.data.frame(st_coordinates(igraph::get.edge.attribute(graph = my_sfn, name = "geometry", index = x[1]))),id=x),mc.preschedule=TRUE, mc.cores = n.cores)

整个区块:

首先我得到开放的街道地图数据:

library(sf)
library(tidygraph)
library(sfnetworks)
library(osmdata)
library(parallel)
library(data.table)
library(tictoc)

if ((n.cores <- detectCores()) > 4) n.cores <- 4
setDTthreads(threads = n.cores)

my_osm_data <- opq(bbox = c(11.68771, 47.75233, 12.35058, 48.19743 )) %>%
  add_osm_feature(
    key = 'highway', 
    value = c("trunk", "trunk_link", "primary","primary_link", "secondary", "secondary_link", "tertiary","tertiary_link", "residential", "unclassified")
  ) %>% 
  osmdata_sf(quiet = FALSE)

my_osm_data<-osmdata::osm_poly2line(my_osm_data)
my_roads <- my_osm_data$osm_lines[, c("osm_id","name")]
#my_roads <- st_geometry(my_osm_data$osm_lines)
my_sfn <- as_sfnetwork(my_roads, directed = FALSE, length_as_weight = TRUE)

然后我设置起点和终点:

start_point =st_sfc(st_point(c(11.829831, 48.110075)))
st_crs(start_point) = st_crs(my_sfn)
dest_point =st_sfc(st_point(c(12.20747, y = 47.83937)))
st_crs(dest_point) = st_crs(my_sfn)

计算路径:

paths = st_network_paths(my_sfn, from = start_point, to = dest_point)

paths = paths %>%
  slice(1) %>%
  pull(edge_paths) %>%
  unlist()

在这里我想得到这条路径的几何形状。

coordinates_of_the_path<-mclapply(paths,function(x) cbind(as.data.frame(st_coordinates(igraph::get.edge.attribute(graph = my_sfn, name = "geometry", index = x[1]))),id=x),mc.preschedule=TRUE, mc.cores = n.cores)

但是这最后一个电话需要很长时间。有没有办法让它更快?

4

1 回答 1

0

我通过使用 data.frame 中最后一列中的索引作为路径向量的索引来解决它

coordinates_of_the_path<-as.data.frame(st_coordinates(igraph::get.edge.attribute(graph = my_sfn, name = "geometry", index = paths)))
  coordinates_of_the_path<-cbind(coordinates_of_the_path,id=paths[coordinates_of_the_path$L1])
于 2021-03-26T21:21:19.033 回答