gtfs.R 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #' GTFS - maanteeameti ühistranspordi andmed
  2. #'
  3. #' General Transit Feed Specification (GTFS). Source: \url{http://peatus.ee/gtfs/}. Ühistranspordiregistri avaandmed sisaldavad lihtsustatud struktuuri andmekoosseisuga väljavõtet Riiklikku Ühistranspordiregistrisse kantud andmetest, mis hõlmavad siseriiklikult käigus olevate ühistranspordiliinide kirjeldusi, sõidugraafikuid ja peatuste asukohtasid. \url{https://www.mnt.ee/et/uhistransport/uhistranspordi-infosusteem} Funktsioon impordib gtfs andmestiku importimine andmebaasi.
  4. #'
  5. #' Ühistranspordiregistri avaandmete andmefailid:
  6. #' - agency.txt
  7. #' - calendar.txt
  8. #' - calendar_dates.txt
  9. #' - feed_info.txt
  10. #' - routes.txt
  11. #' - stop_times.txt
  12. #' - stops.txt
  13. #' - trips.txt
  14. #' @importFrom magrittr %>%
  15. #' @importFrom rlang .data
  16. #' @param conf A list() of configuration variables. Default values \code{\link[ruut]{get_config}}.
  17. #' @return No output.
  18. #' @seealso [ruut::get_config()], [ruut::copy_shp_to_db()]
  19. #' @keywords postgis, maps, ESRI Shpfile, OSM
  20. #' @export
  21. #' @examples
  22. #' \dontrun{
  23. #'
  24. #' conf <- ruut::get_config()
  25. #' gtfs(conf = conf)
  26. #' }
  27. gtfs <- function(conf = NULL) {
  28. ans <- utils::askYesNo("Do you want to import gtfs data into database?", default = F)
  29. if (!ans | is.na(ans)) {
  30. cat("\n------------------------\n")
  31. cat("Kaardikihte ei lisatud.")
  32. cat("\n------------------------\n")
  33. return()
  34. }
  35. if (ans) {
  36. # Temp directory
  37. tmp_dir <- sprintf("%s/tmp/%s", system.file(package = "estmap"), "gtfs")
  38. if (!dir.exists(tmp_dir)) {
  39. dir.create(tmp_dir)
  40. }
  41. cat("\n------------------------\n")
  42. cat(sprintf("Failide salvestamise kataloog: %s", tmp_dir))
  43. cat("\n------------------------\n")
  44. # Download link
  45. url <- "http://www.peatus.ee/gtfs/"
  46. # Estonia shapefile (ZIP archive)
  47. map_shapefile <- "gtfs.zip"
  48. # Download and save
  49. url_download <- sprintf("%s%s", url, map_shapefile)
  50. saveTo <- sprintf("%s/%s", tmp_dir, map_shapefile)
  51. if (!file.exists(saveTo)) {
  52. utils::download.file(
  53. url = url_download,
  54. destfile = saveTo, method = "curl", extra = "-L"
  55. )
  56. }
  57. # Unzip
  58. utils::unzip(saveTo, overwrite = T, exdir = tmp_dir)
  59. # List of files
  60. ls <- list.files(path = tmp_dir, pattern = ".txt")
  61. ls_long <- list.files(path = tmp_dir, pattern = ".txt", full.names = T)
  62. tbl_names <- tools::file_path_sans_ext(list.files(path = tmp_dir, pattern = "*.txt"))
  63. # Export to postgis
  64. if (is.null(conf)) {
  65. conf <- ruut::get_config()
  66. conf$schema <- "gtfs"
  67. conf$table <- ""
  68. }
  69. # Multi layer: paneme kõik csv failid üheks failiks.
  70. if (file.exists(saveTo)) {
  71. ## Export to postgis database.
  72. # New schema
  73. ruut::db_create_new_schema(conf = conf)
  74. # Postgresql string
  75. pg <- ruut::construct_ogr2ogr_PG_connect_str()
  76. # Connect to db
  77. conn <- ruut::db_connect()
  78. # ---------- Copy CSV!!! data to database ----------
  79. for (i in 1:length(tbl_names)) {
  80. # Tabeli nimi
  81. conf$table <- tbl_names[i]
  82. # ogr2ogr oskab csv faili lugeda juhul kui laiend on csv. Muudame.
  83. system(sprintf("mv %s %s/%s.csv", ls_long[i], tmp_dir, tbl_names[i]))
  84. # Laeme eraldi andmed shape muutujasse, et teede geomeetriat leida
  85. if (tbl_names[i] == "shapes") {
  86. shapes <- utils::read.csv(file = sprintf("%s/%s.csv", tmp_dir, tbl_names[i]))
  87. ## --------------- Points to SpatialLines -----------------
  88. cat("\n----------------\nMarsruutide geomeetria loomine\n")
  89. sl <- shapes %>%
  90. dplyr::arrange(.data$shape_id, .data$shape_pt_sequence) %>%
  91. sf::st_as_sf(coords = c("shape_pt_lon", "shape_pt_lat"), agr = "constant") %>%
  92. # dplyr::group_by(shape_id) %>%
  93. # dplyr::summarise() %>%
  94. sf::st_cast("POINT")
  95. sf::st_crs(sl) <- 4326
  96. # # Test plot
  97. # sl %>%
  98. # ggplot2::ggplot(ggplot2::aes(colour = shape_id)) +
  99. # ggplot2::geom_sf()
  100. # plot(sl)
  101. # Write to database
  102. tabeli_suffix <- "_source"
  103. sf::st_write(
  104. obj = sl, dsn = conn, layer_options = c("GEOMETRY=AS_XY", "OVERWRITE=yes"),
  105. layer = sprintf("%s%s", conf$table, tabeli_suffix)
  106. )
  107. # Change schema
  108. q <- sprintf("
  109. drop table if exists %s.%s%s cascade; \
  110. ALTER TABLE %s%s SET SCHEMA %s", conf$schema, conf$table, tabeli_suffix, conf$table, tabeli_suffix, conf$schema)
  111. cat("\n----------------\nMuudame schema.\n")
  112. cat(q)
  113. cat("\n\n")
  114. DBI::dbExecute(conn, q)
  115. # ----------- Point to path teisendus ------------
  116. # Algoritmi juhend!
  117. # qgis_algorithm_search_by_word(str = "pointstopath")
  118. algorithm <- "qgis:pointstopath"
  119. # cat(qgis_show_help(algorithm = algorithm))
  120. # Run algorithm.
  121. output <- sprintf(
  122. 'postgres://dbname=\'%s\' host=%s port=%s user=\'%s\' sslmode=%s password=\'%s\' table=\"%s\".\"%s\" (geometry)',
  123. conf$dbname, conf$host, conf$port, conf$user, conf$sslmode, conf$password,
  124. conf$schema, conf$table
  125. )
  126. input <- sprintf(
  127. 'postgres://dbname=\'%s\' host=%s port=%s user=\'%s\' sslmode=%s password=\'%s\' srid=4326 type=Point checkPrimaryKeyUnicity=\'1\' table=\"%s\".\"%s_source\" (geometry)',
  128. conf$dbname, conf$host, conf$port, conf$user, conf$sslmode, conf$password,
  129. conf$schema, conf$table
  130. )
  131. result <- qgisprocess::qgis_run_algorithm(
  132. algorithm = algorithm,
  133. CLOSE_PATH = 0,
  134. DATE_FORMAT = "",
  135. GROUP_FIELD = "shape_id",
  136. INPUT = input,
  137. ORDER_FIELD = "shape_pt_sequence",
  138. OUTPUT_TEXT_DIR = "/tmp/gtfs_output_text_dir/",
  139. OUTPUT = output,
  140. .quiet = TRUE
  141. )
  142. } else {
  143. cmd <- sprintf(
  144. paste0(
  145. "ogr2ogr -f PostgreSQL ",
  146. "%s -lco SCHEMA=%s -lco OVERWRITE=yes -lco FID=%s -nln \"%s\" \"%s/%s.csv\""
  147. ), pg, conf$schema, "fid", conf$table, tmp_dir, tbl_names[i]
  148. )
  149. cat(cmd)
  150. cat("\n\n")
  151. system(cmd)
  152. }
  153. }
  154. # Lisame andmebaasi seosed
  155. q <- sprintf("
  156. ALTER TABLE %s.agency ADD CONSTRAINT agency_un UNIQUE (agency_id); \
  157. ALTER TABLE %s.calendar ADD CONSTRAINT calendar_un UNIQUE (service_id); \
  158. ALTER TABLE %s.fare_attributes ADD CONSTRAINT fare_attributes_un UNIQUE (fare_id); \
  159. ALTER TABLE %s.routes ADD CONSTRAINT routes_un UNIQUE (route_id); \
  160. ALTER TABLE %s.shapes ADD CONSTRAINT shapes_un UNIQUE (shape_id); \
  161. ALTER TABLE %s.stops ADD CONSTRAINT stops_un UNIQUE (stop_id); \
  162. ALTER TABLE %s.trips ADD CONSTRAINT trips_un UNIQUE (trip_id); \
  163. ALTER TABLE %s.fare_rules ADD CONSTRAINT fare_rules_fk FOREIGN KEY (fare_id) REFERENCES %s.fare_attributes(fare_id); \
  164. ALTER TABLE %s.fare_attributes ADD CONSTRAINT fare_attributes_fk FOREIGN KEY (agency_id) REFERENCES %s.agency(agency_id); \
  165. ALTER TABLE %s.routes ADD CONSTRAINT routes_fk FOREIGN KEY (agency_id) REFERENCES %s.agency(agency_id); \
  166. ALTER TABLE %s.calendar_dates ADD CONSTRAINT calendar_dates_fk FOREIGN KEY (service_id) REFERENCES %s.calendar(service_id); \
  167. ALTER TABLE %s.fare_rules ADD CONSTRAINT fare_rules_route_fk FOREIGN KEY (route_id) REFERENCES %s.routes(route_id); \
  168. ALTER TABLE %s.stop_times ADD CONSTRAINT stop_times_stops_fk FOREIGN KEY (stop_id) REFERENCES %s.stops(stop_id); \
  169. ALTER TABLE %s.stop_times ADD CONSTRAINT stop_times_trips_fk FOREIGN KEY (trip_id) REFERENCES %s.trips(trip_id); \
  170. ALTER TABLE %s.trips ADD CONSTRAINT trips_calendar_fk FOREIGN KEY (service_id) REFERENCES %s.calendar(service_id); \
  171. ALTER TABLE %s.trips ADD CONSTRAINT trips_routes_fk FOREIGN KEY (route_id) REFERENCES %s.routes(route_id);", conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema, conf$schema)
  172. cat(q)
  173. DBI::dbExecute(conn, q)
  174. # ogr2ogr help.
  175. # system("ogr2ogr --long-usage")
  176. # ogrinfo help.
  177. # system("ogrinfo --help-general")
  178. # pg <- ruut::construct_ogr2ogr_PG_connect_str()
  179. # system(sprintf("ogrinfo %s xgtfs.trips ", pg))
  180. # system(sprintf("ogrinfo %s xgtfs.trips ", pg))
  181. }
  182. # Delete unnecessary files.
  183. system(sprintf("rm -rf %s/*.csv", tmp_dir))
  184. }
  185. }