La historia de la teoría de grafos está íntimamente relacionada con los mapas del callejero, en particular con el problema de los puentes de Königsberg. Al final, un callejero no deja ser un grafo.
Traducir el mapa del callejero a un grafo en R es una operación bastante trivial.
Como primer ejemplo partiré del descrito en la documentación de la librería shp2graph y en el segundo añadiré un poco de realismo con un mapa de OpenStreetMap y la librería osmar.
library(shp2graph)
## Loading required package: maptools
## Loading required package: sp
## Checking rgeos availability: TRUE
## Loading required package: igraph
data(ORN)
plot(rn)
# Obtener los nodos y sus aristas
rtNEL<-readshpnw(rn, ELComputed=TRUE)
# Crear el grafo indicando, nodos, aristas y pesos
# También está la opción de crear un grafo dirigido.
igr<-nel2igraph(rtNEL[[2]],rtNEL[[3]],weight=rtNEL[[4]])
plot(igr, vertex.label=NA, vertex.size=2,vertex.size2=2)
par(cex=0.7)
plot(igr, vertex.label=V(igr), vertex.size=2,vertex.size2=2, vertex.label.dist=0.2)
# Personalizar los layout
plot(igr, vertex.label=NA, vertex.size=2,vertex.size2=2, layout=layout.kamada.kawai)
plot(igr, vertex.label=NA, vertex.size=2,vertex.size2=2, layout=layout.fruchterman.reingold)
El grafo obtenido conserva en sus atributos las coordenadas geográficas de cada nodo. Con lo cuál se pueden representar también el origen de cada nodo en el mapa original.
par(cex=0.8)
plot(rn)
points(vertex.attributes(igr)$x, vertex.attributes(igr)$y)
text(vertex.attributes(igr)$x, vertex.attributes(igr)$y, V(igr), cex=0.7)
Para exportar el grafo.
# Esta función pertenece a la librería igraph y admite otros muchos formatos
write.graph(igr, "file.gml", format=c( "gml"))
Este caso hace referencia al callejero de openstreetmap de la localidad de Loeches, Madrid.
library(osmar)
## Loading required package: XML
## Loading required package: RCurl
## Loading required package: bitops
## Loading required package: geosphere
##
## Attaching package: 'osmar'
##
## The following object is masked from 'package:utils':
##
## find
# Importar el mapa con extensión .osm
loeches<-get_osm(complete_file(), source = osmsource_file("map.osm"))
plot(loeches)
La librería osmar trae una función que facilita mucho más la creación de grafos con el callejero.
gloeches<-as_igraph(loeches)
El grafo que se obtiene es dirigido, lo cuál está muy bien para analizar las rutas en función de la dirección del tráfico, sin embargo lo convertiré en no dirigido por cuestiones de representación visual.
# Lo convertimos en no digido
gloeches<-as.undirected(gloeches)
plot(gloeches, vertex.label=NA, vertex.size=2,vertex.size2=2, layout=layout.fruchterman.reingold)
En caso que se quiera utilizar shp2graph es necesario convertir el objeto de clase osmar a un objeto sp con la función as_sp.
Sería bueno advertir que las intersecciones consideradas por OpenStreetMap no siempre coinciden con la idea generalizada de cruces de calles, es por ello que los grafos generados tienen una cantidad excesiva de nodos.
Si os parece interesante este tema recomiendo el siguiente post.
citation('shp2graph')
##
## To cite package 'shp2graph' in publications use:
##
## Binbin Lu (2014). shp2graph: Convert a SpatialLinesDataFrame
## object to a "igraph-class" object. R package version 0-2.
## http://CRAN.R-project.org/package=shp2graph
##
## A BibTeX entry for LaTeX users is
##
## @Manual{,
## title = {shp2graph: Convert a SpatialLinesDataFrame object to a "igraph-class"
## object},
## author = {Binbin Lu},
## year = {2014},
## note = {R package version 0-2},
## url = {http://CRAN.R-project.org/package=shp2graph},
## }
##
## ATTENTION: This citation information has been auto-generated from
## the package DESCRIPTION file and may need manual editing, see
## 'help("citation")'.
citation('osmar')
##
## To cite the osmar package use:
##
## Manuel J. A. Eugster and Thomas Schlesinger. osmar:
## OpenStreetMap and R. R Journal, 2012. Accepted for publication
## on 2012-08-14. http://osmar.r-forge.r-project.org/RJpreprint.pdf
##
## A BibTeX entry for LaTeX users is
##
## @Article{,
## title = {osmar: OpenStreetMap and R},
## author = {Manuel J. A. Eugster and Thomas Schlesinger},
## journal = {R Journal},
## year = {2010},
## note = {Accepted for publication on 2012-08-14},
## url = {http://osmar.r-forge.r-project.org/RJpreprint.pdf},
## }
citation()
##
## To cite R in publications use:
##
## R Core Team (2015). R: A language and environment for
## statistical computing. R Foundation for Statistical Computing,
## Vienna, Austria. URL http://www.R-project.org/.
##
## A BibTeX entry for LaTeX users is
##
## @Manual{,
## title = {R: A Language and Environment for Statistical Computing},
## author = {{R Core Team}},
## organization = {R Foundation for Statistical Computing},
## address = {Vienna, Austria},
## year = {2015},
## url = {http://www.R-project.org/},
## }
##
## We have invested a lot of time and effort in creating R, please
## cite it when using it for data analysis. See also
## 'citation("pkgname")' for citing R packages.