Learn R Programming

⚠️There's a newer version (0.4.4.6) of this package.Take me there.

spNetwork

A R package to perform spatial analysis on networks.

The package’s website is available here

Breaking news

Changes in bandwidths selection functions

The latest version (0.4.4) has modifications in the arguments of the functions bw_cvl_calc, bw_cvl_calc.mc, bw_cv_likelihood_calc, bw_cv_likelihood_calc,bw_tnkde_cv_likelihood_calc.mc. The parameters about bandwidths range and step were replaced by a unique parameter requiring and ordered vector of bandwidths. Code from previous version need to be modified accordingly.

Moving to sf

Considering that rgeos and maptools will be deprecated soon, we are moving to sf! This requires some adjustment in the code and the documentation. The development version and the releases on CRAN are now using sf. Please, report any bug or error in the documentation.

To install the previous version using sp, rgeos and maptools, you can run the following command:

devtools::install_github("JeremyGelb/spNetwork", ref = "a3bc982")

Note that all the new developments will use sf and you should switch as soon as possible.

Removing gpkgs

Because of a new CRAN policy, it is not possible anymore to read data in gpkg if they are stored in the user library. On Debian systems, this library is now mounted as read-only for checking. All the datasets provided by spNetwork are now stored as .rda file, and can be loaded with the function data.

What is this package ?

This package can be used to perform several types of analysis on geographical networks. This type of network have spatial coordinates associated with their nodes. They can be directed or undirected. In the actual development version the implemented methods are:

  • Network Kernel Density Estimate, a method estimating density of a point pattern constrained on a network (see the vignettes Network Kernel Density Estimate and Details about NKDE).
  • Temporal Network Kernel Density Estimate, a temporal extension of the previous methods Temporal Network Kernel Density Estimate.
  • Spatial weight matrices based on network distances, which can be used in a great number of traditional methods in spatial analysis (see the vignette Spatial Weight Matrices).
  • Network k Functions, used to investigate the spatial distribution of a set of points on a network at several scales (see the vignette Network k Functions).
  • K nearest neighbours, to calculate for each point on a network its K nearest neighbour (see the function network_knn).
  • Graph analysis, using the functions of the package igraph (see the vignette Building graphs)
  • Isochrones, to delineate accessible area around points localized on a network (see the vignette Calculating isochrones)

Calculation on network can be long, efforts were made to reduce computation time by implementing several functions with Rcpp and RcppArmadillo and by using multiprocessing when possible.

Installing

you can install the CRAN version of this package with the following code in R.

install.packages("spNetwork")

To use all the new features before they are available in the CRAN version, you can download the development version.

devtools::install_github("JeremyGelb/spNetwork")

The packages uses mainly the following packages in its internal structure :

  • igraph
  • sf
  • future
  • future.apply
  • data.table
  • Rcpp
  • RcppArmadillo
  • BH

Some examples

We provide here some short examples of several features. Please, check the vignettes for more details.

  • realizing a kernel network density estimate
library(spNetwork)
library(tmap)
library(sf)

# loading the dataset
data(mtl_network)
data(bike_accidents)


# generating sampling points at the middle of lixels
samples <- lines_points_along(mtl_network, 50)

# calculating densities
densities <- nkde(lines = mtl_network,
                 events = bike_accidents,
                 w = rep(1,nrow(bike_accidents)),
                 samples = samples,
                 kernel_name = "quartic",
                 bw = 300, div= "bw",
                 method = "discontinuous",
                 digits = 2, tol =  0.1,
                 grid_shape = c(1,1),
                 max_depth = 8,
                 agg = 5, sparse = TRUE,
                 verbose = FALSE)

densities <- densities*1000
samples$density <- densities

tm_shape(samples) + 
  tm_dots(col = "density", size = 0.05, palette = "viridis",
          n = 7, style = "kmeans")

An extension for spatio-temporal dataset is also available Temporal Network Kernel Density Estimate

  • Building a spatial matrix based on network distance
library(spdep)

# creating a spatial weight matrix for the accidents
listw <- network_listw(bike_accidents,
                       mtl_network,
                       mindist = 10,
                       maxdistance = 400,
                       dist_func = "squared inverse",
                       line_weight = 'length',
                       matrice_type = 'W',
                       grid_shape = c(1,1),
                       verbose=FALSE)

# using the matrix to find isolated accidents (more than 500m)
no_link <- sapply(listw$neighbours, function(n){
  if(sum(n) == 0){
    return(TRUE)
  }else{
    return(FALSE)
  }
})

bike_accidents$isolated <- as.factor(ifelse(no_link,
                                  "isolated","not isolated"))

tm_shape(mtl_network) + 
  tm_lines(col = "black") +
  tm_shape(bike_accidents) + 
  tm_dots(col = "isolated", size = 0.1,
          palette = c("isolated" = "red","not isolated" = "blue"))

Note that you can use this in every spatial analysis you would like to perform. With the converter function of spdep (like listw2mat), you can convert the listw object into regular matrix if needed

  • Calculating k function
# loading the data
data(main_network_mtl)
data(mtl_theatres)

# calculating the k function
kfun_theatre <- kfunctions(main_network_mtl, mtl_theatres,
                           start = 0, end = 5000, step = 50, 
                           width = 1000, nsim = 50, resolution = 50,
                           verbose = FALSE, conf_int = 0.05)
kfun_theatre$plotg

Work in progress

New methods will be probably added in the future, but we will focus on performance for the next release. Do no hesitate to open an issue here if you have suggestion or if you encounter a bug.

Features that will be added to the package in the future:

  • temporal NKDE, a two dimensional kernel density estimation in network space and time
  • rework for using sf objects rather than sp (rgeos and maptools will be deprecated in 2023). This work is undergoing, please report any bug or error in the new documentation.

Reporting a bug

If you encounter a bug when using spNetwork, please open an issue here. To ensure that the problem is quickly identified, the issue should follow the following guidelines:

  1. Provide an informative title and do not copy-paste the error message as the title.
  2. Provide the ALL code which lead to the bug.
  3. Indicate the version of R and spNetwork.
  4. If possible, provide a sample of data and a reproductible example.

Authors

  • Jeremy Gelb - Creator and maintainer

Contribute

To contribute to spNetwork, please follow these guidelines.

Please note that the spNetwork project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Citation

An article presenting spNetwork and NKDE has been accepted in the RJournal!

Gelb Jérémy (2021). spNetwork, a package for network kernel density estimation. The R Journal. https://journal.r-project.org/archive/2021/RJ-2021-102/index.html.

You can also cite the package for other methods:

Gelb Jérémy (2021). spNetwork: Spatial Analysis on Network. https://jeremygelb.github.io/spNetwork/.

License

spNetwork is licensed under GPL2 License.

Acknowledgments

  • Hat tip to Philippe Apparicio for his support during the development
  • Hat tip to Hadley Wickham and his helpful book R packages

Copy Link

Version

Install

install.packages('spNetwork')

Monthly Downloads

559

Version

0.4.4.3

License

GPL-2

Maintainer

Jeremy Gelb

Last Published

June 21st, 2024

Functions in spNetwork (0.4.4.3)

bw_cvl_calc

Bandwidth selection by Cronie and Van Lieshout's Criterion
build_quadtree

Build a quadtree
bw_cv_likelihood_calc

Bandwidth selection by likelihood cross validation
build_graph_directed

Directed network generation
bike_accidents

Road accidents including a bicyle in Montreal in 2016
check_geometries

Geometry sanity check
bw_checks

Check function for parameters in bandwidth selection methods
bw_tnkde_cv_likelihood_calc.mc

Bandwidth selection by likelihood cross validation for temporal NKDE (multicore)
bw_tnkde_cv_likelihood_calc

Bandwidth selection by likelihood cross validation for temporal NKDE
calc_isochrones

Isochrones calculation
bw_cvl_calc.mc

Bandwidth selection by Cronie and Van Lieshout's Criterion (multicore version)
bw_tnkde_corr_factor

Time and Network bandwidth correction calculation
clean_events

Clean events geometries
calcEuclideanDistance3

euclidean distance between rows of a matrix and a vector (arma mode)
calc_gamma

Gamma parameter for Abramson’s adaptive bandwidth
bw_tnkde_corr_factor_arr

Time and Network bandwidth correction calculation for arrays
closest_points

Find closest points
continuousfunction

The main function to calculate continuous NKDE (with ARMADILO and integer matrix)
continuousWorker_sparse

The worker function to calculate continuous NKDE (with ARMADILLO and sparse matrix)
corrfactor_continuous_sparse

A function to calculate the necessary information to apply the Diggle correction factor with a continuous method (sparse)
continuousfunction2

The main function to calculate continuous NKDE (with ARMADILO and sparse matrix)
correction_factor_time

Time extent correction for NKDE
continuousWorker

The worker function to calculate continuous NKDE (with ARMADILLO and integer matrix)
correction_factor

Border correction for NKDE
cross_gfunc_cpp

c++ cross g function
corrfactor_discontinuous

A function to calculate the necessary informations to apply the Diggle correction factor with a discontinuous method
direct_lines

Make a network directed
cut_lines_at_distance

Cut lines at a specified distance
epanechnikov_kernel_cpp

c++ epanechnikov kernel
corrfactor_continuous

A function to calculate the necessary information to apply the Diggle correction factor with a continuous method
cosine_kernel

Cosine kernel
epanechnikov_kernel

Epanechnikov kernel
cosine_kernelos

c++ cosine kernel for one distance
cosine_kernel_cpp

c++ cosine kernel
corrfactor_discontinuous_sparse

A function to calculate the necessary information to apply the Diggle correction factor with a discontinuous method (sparse)
cross_kfunctions

Network cross k and g functions (maturing)
cross_kfunctions.mc

Network cross k and g functions (multicore, maturing)
esc_kernel_loo_nkde

The worker function to calculate continuous TNKDE likelihood cv
esd_kernel_loo_tnkde

The worker function to calculate discontinuous TNKDE likelihood cv
g_nt_func_cpp

c++ g space-time function
k_nt_func_cpp

c++ k space-time function
ess_kernel

Worker for simple NKDE algorithm
ess_kernel_loo_tnkde_adpt

The worker function to calculate simple TNKDE likelihood cv (adaptive case)
esd_kernel_loo_nkde

The worker function to calculate discontinuous TNKDE likelihood cv
gfunc_cpp

c++ g function
graph_checking

Topological error
k_nt_functions

Network k and g functions for spatio-temporal data (experimental, NOT READY FOR USE)
epanechnikov_kernelos

c++ epanechnikov kernel for one distance
is_projected

Projection test
dist_mat_dupl

Distance matrix with dupicated
discontinuousfunction

The main function to calculate discontinuous NKDE (ARMA and sparse matrix)
gm_mean

Geometric mean
esd_kernel_loo_tnkde_adpt

The worker function to calculate discontinuous TNKDE likelihood cv (adaptive case)
kfunc_cpp

c++ k function
k_nt_functions.mc

Network k and g functions for spatio-temporal data (multicore, experimental, NOT READY FOR USE)
kfunctions

Network k and g functions (maturing)
heal_edges

Heal edges
discontinuousWorker_int

The worker function to calculate discontinuous NKDE (with ARMADILLO and Integer matrix)
lixelize_lines.mc

Cut lines into lixels (multicore)
gaussian_kernel

Gaussian kernel
discontinuousWorker_sparse

The worker function to calculate discontinuous NKDE (with ARMADILLO and sparse matrix)
kfunctions.mc

Network k and g functions (multicore, maturing)
mtl_network

Road network of Montreal
gaussian_kernelos

c++ gaussian kernel for one distance
mtl_libraries

Libraries of Montreal
nkde

Network Kernel density estimate
lines_direction

Unify lines direction
lines_coordinates_as_list

Lines coordinates as list
nkde_get_loo_values

The exposed function to calculate NKDE likelihood cv
lines_center

Centre points of lines
nkde.mc

Network Kernel density estimate (multicore)
mtl_theatres

Theatres of Montreal
gaussian_kernel_scaledos

c++ scaled gaussian kernel for one distance
nkde_worker

NKDE worker
nearestPointOnLine

Nearest point on Line
main_network_mtl

Primary road network of Montreal
remove_mirror_edges

Remove mirror edges
prepare_elements_netlistw

Data preparation for network_listw
quartic_kernelos

c++ quartic kernel for one distance
prepare_data

Prior data preparation
randomize_distmatrix

Points on network randomization
nearestPointOnSegment

Nearest point on segment
gaussian_kernel_cpp

c++ gaussian kernel
remove_loop_lines

Remove loops
select_dist_function

Select the distance to weight function
sanity_check_knn

Sanity check for the knn functions
randomize_distmatrix2

Points on network randomization simplified
cross_kfunc_cpp

c++ cross k function
esc_kernel_loo_tnkde

The worker function to calculate continuous TNKDE likelihood cv
esc_kernel_loo_tnkde_adpt

The worker function to calculate continuous TNKDE likelihood cv (adaptive case)
network_knn

K-nearest points on network
simplify_network

Simplify a network
network_knn.mc

K-nearest points on network (multicore version)
ess_kernel_loo_nkde

The worker function to calculate simple NKDE likelihood cv
network_listw

Network distance listw
nearest_lines

Nearest line for points
nkde_worker_bw_sel

Bandwidth selection by likelihood cross validation worker function
network_knn_worker

worker function for K-nearest points on network
tnkde_get_loo_values

The exposed function to calculate TNKDE likelihood cv
gaussian_kernel_scaled

Scaled gaussian kernel
ess_kernel_loo_tnkde

The worker function to calculate simple TNKDE likelihood cv
tnkde

Temporal Network Kernel density estimate
spatial_request

Spatial request
split_border

Split boundary of polygon
tnkde.mc

Temporal Network Kernel density estimate (multicore)
lines_extremities

Get lines extremities
gaussian_kernel_scaled_cpp

c++ scale gaussian kernel
small_mtl_network

Smaller subset road network of Montreal
split_by_grid_abw.mc

Split data with a grid for the adaptive bw function (multicore)
triangle_kernel_cpp

c++ triangle kernel
split_by_grid_abw

Split data with a grid for the adaptive bw function
reverse_lines

Reverse lines
split_by_grid.mc

Split data with a grid (multicore)
triangle_kernelos

c++ triangle kernel for one distance
tnkde_worker_bw_sel

Worker function fo Bandwidth selection by likelihood cross validation for temporal NKDE
simple_lines

LineString to simple Line
split_by_grid

Split data with a grid
plot_graph

Plot graph
select_kernel

Select kernel function
sp_char_index

Coordinates to unique character vector
tnkde_worker

TNKDE worker
spatial_index

An object (c++ pointer) to do some spatial query of rectanlges (internal)
lines_points_along

Points along lines
lixelize_lines

Cut lines into lixels
list_coordinates_as_lines

List of coordinates as lines
network_listw.mc

Network distance listw (multicore)
split_graph_components

Split graph components
network_listw_worker

network_listw worker
quartic_kernel

Quartic kernel
triweight_kernel

Triweight kernel
uniform_kernel_cpp

c++ uniform kernel
split_lines_at_vertex

Split lines at vertices in a feature collection of linestrings
tnkdediscontinuousfunction

The main function to calculate discontinuous NKDE (ARMA and Integer matrix)
uniform_kernelos

c++ uniform kernel for one distance
tnkdecontinuousfunction

The main function to calculate continuous TNKDE (with ARMADILO and sparse matrix)
triweight_kernel_cpp

c++ triweight kernel
triangle_kernel

triangle kernel
tnkde_get_loo_values2

The exposed function to calculate TNKDE likelihood cv
uniform_kernel

Uniform kernel
triweight_kernelos

c++ triweight kernel for one distance
tnkdediscontinuousfunctionsparse

The main function to calculate discontinuous NKDE (ARMA and sparse matrix)
surrounding_points

Points along polygon boundary
snapPointsToLines2

Snap points to lines
simple_nkde

Simple NKDE algorithm
simple_tnkde

Simple TNKDE algorithm
quartic_kernel_cpp

c++ quartic kernel
worker_adaptive_bw_tnkde

Worker function for adaptive bandwidth for TNDE
spNetwork-package

spNetwork: Spatial Analysis on Network
tkde

Temporal Kernel density estimate
tricube_kernel

Tricube kernel
st_bbox_by_feature

Obtain all the bounding boxes of a feature collection
tricube_kernel_cpp

c++ tricube kernel
tricube_kernelos

c++ tricube kernel for one distance
st_bbox_geom

sf geometry bbox
trim_lines_at

Helper for isochrones lines cutting
adaptive_bw_tnkde_cpp

The exposed function to calculate adaptive bandwidth with space-time interaction for TNKDE (INTERNAL)
add_center_lines

Add center vertex to lines
adaptive_bw_1d

Adaptive bw in one dimension
add_vertices_lines

Add vertices to a feature collection of linestrings
adaptive_bw_tnkde.mc

Adaptive bandwidth for TNDE (multicore)
adaptive_bw_tnkde_cpp2

The exposed function to calculate adaptive bandwidth with space-time interaction for TNKDE (INTERNAL)
aggregate_points

Events aggregation
build_graph

Network generation
bw_cv_likelihood_calc.mc

Bandwidth selection by likelihood cross validation (multicore)
adaptive_bw_tnkde

Adaptive bandwidth for TNDE
adaptive_bw

Adaptive bandwidth
adaptive_bw.mc

Adaptive bandwidth (multicore)
build_grid

Spatial grid
bw_cv_likelihood_calc_tkde

Bandwidth selection for Temporal Kernel density estimate by likelihood cross validation