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. sl <- sf::st_transform(sl, 3301)
  97. # # Test plot
  98. # sl %>%
  99. # ggplot2::ggplot(ggplot2::aes(colour = shape_id)) +
  100. # ggplot2::geom_sf()
  101. # plot(sl)
  102. # Write to database
  103. tabeli_suffix <- "_source"
  104. sf::st_write(
  105. obj = sl, dsn = conn, layer_options = c("OVERWRITE=yes"),
  106. layer = sprintf("%s%s", conf$table, tabeli_suffix)
  107. )
  108. # Change schema
  109. q <- sprintf("
  110. drop table if exists %s.%s%s cascade; \
  111. ALTER TABLE %s%s SET SCHEMA %s", conf$schema, conf$table, tabeli_suffix, conf$table, tabeli_suffix, conf$schema)
  112. cat("\n----------------\nMuudame schema.\n")
  113. cat(q)
  114. cat("\n\n")
  115. DBI::dbExecute(conn, q)
  116. # ----------- Point to path teisendus ------------
  117. # Algoritmi juhend!
  118. # qgis_algorithm_search_by_word(str = "pointstopath")
  119. algorithm <- "qgis:pointstopath"
  120. # cat(qgis_show_help(algorithm = algorithm))
  121. # Run algorithm.
  122. output <- sprintf(
  123. 'postgres://dbname=\'%s\' host=%s port=%s user=\'%s\' sslmode=%s password=\'%s\' table=\"%s\".\"%s\" (geom)',
  124. conf$dbname, conf$host, conf$port, conf$user, conf$sslmode, conf$password,
  125. conf$schema, conf$table
  126. )
  127. input <- sprintf(
  128. 'postgres://dbname=\'%s\' host=%s port=%s user=\'%s\' sslmode=%s password=\'%s\' srid=3301 type=Point checkPrimaryKeyUnicity=\'1\' table=\"%s\".\"%s_source\" (geometry)',
  129. conf$dbname, conf$host, conf$port, conf$user, conf$sslmode, conf$password,
  130. conf$schema, conf$table
  131. )
  132. result <- qgisprocess::qgis_run_algorithm(
  133. algorithm = algorithm,
  134. CLOSE_PATH = 0,
  135. DATE_FORMAT = "",
  136. GROUP_FIELD = "shape_id",
  137. INPUT = input,
  138. ORDER_FIELD = "shape_pt_sequence",
  139. OUTPUT_TEXT_DIR = "/tmp/",
  140. OUTPUT = output,
  141. .quiet = TRUE
  142. )
  143. } else {
  144. cmd <- sprintf(
  145. paste0(
  146. "ogr2ogr -f PostgreSQL ",
  147. "%s -lco SCHEMA=%s -lco OVERWRITE=yes -lco FID=%s -nln \"%s\" \"%s/%s.csv\""
  148. ), pg, conf$schema, "id", conf$table, tmp_dir, tbl_names[i]
  149. )
  150. cat(cmd)
  151. cat("\n\n")
  152. system(cmd)
  153. }
  154. }
  155. # Lisame andmebaasi seosed
  156. q <- sprintf("
  157. ALTER TABLE %s.agency ADD CONSTRAINT agency_un UNIQUE (agency_id); \
  158. ALTER TABLE %s.calendar ADD CONSTRAINT calendar_un UNIQUE (service_id); \
  159. ALTER TABLE %s.fare_attributes ADD CONSTRAINT fare_attributes_un UNIQUE (fare_id); \
  160. ALTER TABLE %s.routes ADD CONSTRAINT routes_un UNIQUE (route_id); \
  161. ALTER TABLE %s.shapes ADD CONSTRAINT shapes_un UNIQUE (shape_id); \
  162. ALTER TABLE %s.stops ADD CONSTRAINT stops_un UNIQUE (stop_id); \
  163. ALTER TABLE %s.trips ADD CONSTRAINT trips_un UNIQUE (trip_id); \
  164. ALTER TABLE %s.fare_rules ADD CONSTRAINT fare_rules_fk FOREIGN KEY (fare_id) REFERENCES %s.fare_attributes(fare_id); \
  165. ALTER TABLE %s.fare_attributes ADD CONSTRAINT fare_attributes_fk FOREIGN KEY (agency_id) REFERENCES %s.agency(agency_id); \
  166. ALTER TABLE %s.routes ADD CONSTRAINT routes_fk FOREIGN KEY (agency_id) REFERENCES %s.agency(agency_id); \
  167. ALTER TABLE %s.calendar_dates ADD CONSTRAINT calendar_dates_fk FOREIGN KEY (service_id) REFERENCES %s.calendar(service_id); \
  168. ALTER TABLE %s.fare_rules ADD CONSTRAINT fare_rules_route_fk FOREIGN KEY (route_id) REFERENCES %s.routes(route_id); \
  169. ALTER TABLE %s.stop_times ADD CONSTRAINT stop_times_stops_fk FOREIGN KEY (stop_id) REFERENCES %s.stops(stop_id); \
  170. ALTER TABLE %s.stop_times ADD CONSTRAINT stop_times_trips_fk FOREIGN KEY (trip_id) REFERENCES %s.trips(trip_id); \
  171. ALTER TABLE %s.trips ADD CONSTRAINT trips_calendar_fk FOREIGN KEY (service_id) REFERENCES %s.calendar(service_id); \
  172. 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)
  173. cat(q)
  174. DBI::dbExecute(conn, q)
  175. # ogr2ogr help.
  176. # system("ogr2ogr --long-usage")
  177. # ogrinfo help.
  178. # system("ogrinfo --help-general")
  179. # pg <- ruut::construct_ogr2ogr_PG_connect_str()
  180. # system(sprintf("ogrinfo %s xgtfs.trips ", pg))
  181. # system(sprintf("ogrinfo %s xgtfs.trips ", pg))
  182. }
  183. # Delete unnecessary files.
  184. system(sprintf("rm -rf %s/*.csv", tmp_dir))
  185. }
  186. }