cppRouting package small example

Construct some locations as x-y points (coord_df). Then make a weighted graph of them (roads_df). Transform this to a graph in R and solve transport problem in the form of fastest route.

    library(sf)
## Warning: package 'sf' was built under R version 4.0.5
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
    library(cppRouting)
## Warning: package 'cppRouting' was built under R version 4.0.5
    set.seed(1)
    # MAke some locations ... 
    ID <- c(1,2,3,4,5,6,7,8,9)
    X <- c(0,0,0,1,1,1,2,2,2)
    Y <- c(0,1,2,0,1,2,0,1,2)

    coord_df <- data.frame(ID,X,Y)

    # plot the nine points ...
    df_sf <- st_as_sf(coord_df,coords=c("X","Y"))
    plot(df_sf)

    # Create weighted graph
    from <- rep(1:9,each=9)
    to <- rep(1:9,9)
    weight <- abs(rnorm(9^2))

    roads_df <- data.frame(from,to,weight)


    #Instantiate a graph with coordinates
    graph <- makegraph(roads_df,directed = T,coords = coord_df)

    # Choose random origin destination
    origin<-sample(graph$dict$ref,3)
    destination<-sample(graph$dict$ref,3)

    get_distance_pair(graph,origin,destination,algorithm = "Dijkstra")
## Running Dijkstra ...
## [1] 0.3886259 0.1788120 0.0000000
    get_distance_pair(graph,origin,destination,algorithm = "bi")
## Running bidirectional Dijkstra...
## [1] 0.3886259 0.1788120 0.0000000
      get_distance_pair(graph,origin,destination,algorithm = "A*",constant = 110/0.06)
## Running A* ...
## [1] 0.3886259 0.1788120 0.0000000
    get_distance_pair(graph,origin,destination,algorithm = "NBA",constant = 110/0.06)
## Running NBA* ...
## [1] 0.3886259 0.1788120 0.0000000
    # The distance is the sum of weights ...
    get_path_pair(graph,from="1",to="3")
## Running bidirectional Dijkstra...
## $`1_3`
## [1] "3" "8" "2" "1"
    get_distance_pair(graph,"1","3",algorithm = "Dijkstra")
## Running Dijkstra ...
## [1] 0.3886259
    roads_df[roads_df$from==1 & roads_df$to==2,]
##   from to    weight
## 2    1  2 0.1836433
    roads_df[roads_df$from==2 & roads_df$to==8,]
##    from to     weight
## 17    2  8 0.01619026
    roads_df[roads_df$from==8 & roads_df$to==3,]
##    from to    weight
## 66    8  3 0.1887923
    a1 <- roads_df[roads_df$from==1 & roads_df$to==2,]$weight
    a2 <- roads_df[roads_df$from==2 & roads_df$to==8,]$weight
    a3 <- roads_df[roads_df$from==8 & roads_df$to==3,]$weight

    a1+a2+a3
## [1] 0.3886259