gtfs.R 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. #' ## Not run:
  23. #' ##
  24. #' ## gtfs()
  25. #' ##
  26. #' ## End(**Not run**)
  27. gtfs <- function(conf = NULL) {
  28. ans <- utils::askYesNo("Do you want to import gtfs data into database?")
  29. if (!ans) {
  30. cat("\n------------------------\n")
  31. cat("Kaardikihte ei lisatud.")
  32. cat("\n------------------------\n")
  33. }
  34. if (ans) {
  35. # Temp directory
  36. tmp_dir <- "/tmp/gtfs"
  37. if (!dir.exists(tmp_dir)) {
  38. dir.create(tmp_dir)
  39. }
  40. # Download link
  41. url <- "http://www.peatus.ee/gtfs/"
  42. # Estonia shapefile (ZIP archive)
  43. map_shapefile <- "gtfs.zip"
  44. # Download and save
  45. url_download <- sprintf("%s%s", url, map_shapefile)
  46. saveTo <- sprintf("%s/%s", tmp_dir, map_shapefile)
  47. if (!file.exists(saveTo)) {
  48. utils::download.file(
  49. url = url_download,
  50. destfile = saveTo, method = "curl", extra = "-L"
  51. )
  52. }
  53. # Unzip
  54. utils::unzip(saveTo, overwrite = T, exdir = tmp_dir)
  55. # List of files
  56. ls <- list.files(path = tmp_dir, pattern = ".txt")
  57. ls_long <- list.files(path = tmp_dir, pattern = ".txt", full.names = T)
  58. tbl_names <- tools::file_path_sans_ext(list.files(path = tmp_dir, pattern = "*.txt"))
  59. # Export to postgis
  60. if (is.null(conf)) {
  61. conf <- ruut::get_config()
  62. conf$schema <- "gtfs"
  63. conf$table <- ""
  64. }
  65. # Multi layer: paneme kõik csv failid üheks failiks.
  66. if (file.exists(saveTo)) {
  67. ## Export to postgis database.
  68. # New schema
  69. ruut::db_create_new_schema(conf = conf)
  70. # Postgresql string
  71. pg <- ruut::construct_ogr2ogr_PG_connect_str()
  72. # Connect to db
  73. conn <- ruut::db_connect()
  74. # ---------- Copy CSV!!! data to database ----------
  75. for (i in 1:length(tbl_names)) {
  76. # Tabeli nimi
  77. conf$table <- tbl_names[i]
  78. # ogr2ogr oskab csv faili lugeda juhul kui laiend on csv. Muudame.
  79. system(sprintf("mv %s %s/%s.csv", ls_long[i], tmp_dir, tbl_names[i]))
  80. # Laeme eraldi andmed shape muutujasse, et teede geomeetriat leida
  81. if (tbl_names[i] == "shapes") {
  82. shapes <- utils::read.csv(file = sprintf("%s/%s.csv", tmp_dir, tbl_names[i]))
  83. ## --------------- Points to SpatialLines -----------------
  84. cat("\n----------------\nMarsruutide geomeetria loomine\n")
  85. sl <- shapes %>%
  86. dplyr::arrange(.data$shape_id, .data$shape_pt_sequence) %>%
  87. sf::st_as_sf(coords = c("shape_pt_lon", "shape_pt_lat"), agr = "constant") %>%
  88. # dplyr::group_by(shape_id) %>%
  89. # dplyr::summarise() %>%
  90. sf::st_cast("POINT")
  91. sf::st_crs(sl) <- 4326
  92. # # Test plot
  93. # sl %>%
  94. # ggplot2::ggplot(ggplot2::aes(colour = shape_id)) +
  95. # ggplot2::geom_sf()
  96. # plot(sl)
  97. # Write to database
  98. tabeli_suffix <- "_source"
  99. sf::st_write(
  100. obj = sl, dsn = conn, layer_options = c("GEOMETRY=AS_XY", "OVERWRITE=yes"),
  101. layer = sprintf("%s%s", conf$table, tabeli_suffix)
  102. )
  103. # Change schema
  104. q <- sprintf("
  105. drop table if exists %s.%s%s cascade; \
  106. ALTER TABLE %s%s SET SCHEMA %s", conf$schema, conf$table, tabeli_suffix, conf$table, tabeli_suffix, conf$schema)
  107. cat("\n----------------\nMuudame schema.\n")
  108. cat(q)
  109. DBI::dbExecute(conn, q)
  110. # ----------- Point to path teisendus ------------
  111. # Algoritmi juhend!
  112. # qgis_algorithm_search_by_word(str = "pointstopath")
  113. algorithm <- "qgis:pointstopath"
  114. # cat(qgis_show_help(algorithm = algorithm))
  115. # Run algorithm.
  116. ## !!!!!!!!!!!!!!!!!!!! NB! pead muutma pythoni skripti 188 rida.
  117. ## File "/usr/share/qgis/python/plugins/processing/algs/qgis/PointsToPaths.py", line 188, in processAlgorithm
  118. ## Panin sinna mingi faili, sest temp faili ei osanud python kirjutada ja pärast lugeda.
  119. output <- sprintf(
  120. 'postgres://dbname=\'%s\' host=%s port=%s user=\'%s\' sslmode=%s password=\'%s\' table=\"%s\".\"%s\" (geom)',
  121. conf$dbname, conf$host, conf$port, conf$user, conf$sslmode, conf$password,
  122. conf$schema, conf$table
  123. )
  124. input <- sprintf(
  125. 'postgres://dbname=\'%s\' host=%s port=%s user=\'%s\' sslmode=%s password=\'%s\' srid=4326 type=Point checkPrimaryKeyUnicity=\'1\' table=\"%s\".\"%s_source\" (geometry)',
  126. conf$dbname, conf$host, conf$port, conf$user, conf$sslmode, conf$password,
  127. conf$schema, conf$table
  128. )
  129. result <- qgisprocess::qgis_run_algorithm(
  130. algorithm = algorithm,
  131. CLOSE_PATH = 0,
  132. DATE_FORMAT = "",
  133. GROUP_FIELD = "shape_id",
  134. INPUT = input,
  135. ORDER_FIELD = "shape_pt_sequence",
  136. OUTPUT = output,
  137. .quiet = TRUE
  138. )
  139. } else {
  140. cmd <- sprintf(
  141. paste0(
  142. "ogr2ogr -f PostgreSQL ",
  143. "%s -lco SCHEMA=%s -lco OVERWRITE=yes -lco FID=%s -nln \"%s\" \"%s/%s.csv\""
  144. ), pg, conf$schema, "fid", conf$table, tmp_dir, tbl_names[i]
  145. )
  146. cat(cmd)
  147. cat("\n\n")
  148. system(cmd)
  149. }
  150. }
  151. # Lisame andmebaasi seosed
  152. q <- sprintf("
  153. ALTER TABLE %s.agency ADD CONSTRAINT agency_un UNIQUE (agency_id); \
  154. ALTER TABLE %s.calendar ADD CONSTRAINT calendar_un UNIQUE (service_id); \
  155. ALTER TABLE %s.fare_attributes ADD CONSTRAINT fare_attributes_un UNIQUE (fare_id); \
  156. ALTER TABLE %s.routes ADD CONSTRAINT routes_un UNIQUE (route_id); \
  157. ALTER TABLE %s.shapes ADD CONSTRAINT shapes_un UNIQUE (shape_id); \
  158. ALTER TABLE %s.stops ADD CONSTRAINT stops_un UNIQUE (stop_id); \
  159. ALTER TABLE %s.trips ADD CONSTRAINT trips_un UNIQUE (trip_id); \
  160. ALTER TABLE %s.fare_rules ADD CONSTRAINT fare_rules_fk FOREIGN KEY (fare_id) REFERENCES %s.fare_attributes(fare_id); \
  161. ALTER TABLE %s.fare_attributes ADD CONSTRAINT fare_attributes_fk FOREIGN KEY (agency_id) REFERENCES %s.agency(agency_id); \
  162. ALTER TABLE %s.routes ADD CONSTRAINT routes_fk FOREIGN KEY (agency_id) REFERENCES %s.agency(agency_id); \
  163. ALTER TABLE %s.calendar_dates ADD CONSTRAINT calendar_dates_fk FOREIGN KEY (service_id) REFERENCES %s.calendar(service_id); \
  164. ALTER TABLE %s.fare_rules ADD CONSTRAINT fare_rules_route_fk FOREIGN KEY (route_id) REFERENCES %s.routes(route_id); \
  165. ALTER TABLE %s.stop_times ADD CONSTRAINT stop_times_stops_fk FOREIGN KEY (stop_id) REFERENCES %s.stops(stop_id); \
  166. ALTER TABLE %s.stop_times ADD CONSTRAINT stop_times_trips_fk FOREIGN KEY (trip_id) REFERENCES %s.trips(trip_id); \
  167. ALTER TABLE %s.trips ADD CONSTRAINT trips_calendar_fk FOREIGN KEY (service_id) REFERENCES %s.calendar(service_id); \
  168. 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)
  169. cat(q)
  170. DBI::dbExecute(conn, q)
  171. # ogr2ogr help.
  172. # system("ogr2ogr --long-usage")
  173. # ogrinfo help.
  174. # system("ogrinfo --help-general")
  175. # pg <- ruut::construct_ogr2ogr_PG_connect_str()
  176. # system(sprintf("ogrinfo %s xgtfs.trips ", pg))
  177. # system(sprintf("ogrinfo %s xgtfs.trips ", pg))
  178. }
  179. # Delete temp directory
  180. # system(sprintf("rm -rf %s/*.csv", tmp_dir))
  181. }
  182. }