Advertisement
Guest User

Untitled

a guest
Oct 1st, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. # run tarjan with igraph
  2.  
  3. # name of the table
  4. city = 'helsinki'
  5.  
  6. modes = c('car','bike','foot')
  7.  
  8. # connect to database
  9. library("RPostgreSQL")
  10. driver <- dbDriver("PostgreSQL")
  11. connection <- dbConnect(driver, dbname="", password="", user="", host="")
  12.  
  13. # load the graph library
  14. library('igraph')
  15.  
  16. # run for each mode
  17. for(mode in modes){
  18.  
  19. print(paste('constructing the',city,mode,'graph...'))
  20.  
  21. # data goes here
  22. output_file = paste0('~/AAG2016/data/out/',city,'_',mode,'_out.csv')
  23.  
  24. # get only the edges for the current mode
  25. if(mode=='car'){
  26. where_statement = 'WHERE flags % 2 = 1;'
  27. }else if(mode=='bike'){
  28. where_statement = "WHERE flags IN (2,3,6,7);"
  29. }else if(mode=='foot'){
  30. where_statement = "WHERE flags >= 4;"
  31. }
  32.  
  33. # get the relevant edges
  34. d <- dbGetQuery(connection,
  35. paste0(
  36. "SELECT source, target, km AS weight ",
  37. "FROM ",city," ",
  38. where_statement
  39. )
  40. )
  41.  
  42. # turn into a matrix
  43. m = as.matrix(d[,1:2])
  44. # turn into a vector
  45. vd = c(t(m))
  46.  
  47.  
  48. # make the graph
  49. g = make_graph(vd,directed=F)
  50. # add weights to the edges, for later
  51. #E(g)$weight = d$weight
  52.  
  53. # clean up vars to save space in RAM
  54. d = m = vd = NULL
  55.  
  56. # run the big time-consuming function
  57. print(paste('traversing the',city,mode,'graph...'))
  58. bc = biconnected_components(g)
  59.  
  60. # select only components with more than 100 edges
  61. mc = bc$component_edges[lengths(bc$component_edges)>100]
  62.  
  63. # give each edge a component attribute defaulting to -1
  64. E(g)$component = -1
  65.  
  66. # loop over major connected components
  67. # assinging real component id's to major connected components
  68. for(i in 1:length(mc)){
  69. # as.vector(mc[[i]]) returns the ids/keys of the edges
  70. E(g)[as.vector(mc[[i]])]$component = i
  71. }
  72.  
  73. # convert the graph to a dataframe of edges and attributes
  74. results_table = get.data.frame(g)
  75. # ignore the weights field
  76. results_table = results_table[,c('from','to','component')]
  77. # output the results
  78. write.csv(results_table,output_file)
  79.  
  80. } # for each mode
  81.  
  82.  
  83. dbDisconnect(connection)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement