pk_teisendame_polygoone.R 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #' Piirkonnale andmebaasides olevate polügoonide teisendamine
  2. #'
  3. #' Etteantud piirkonna geomeetrilise piirjoone ('piir') ja selle joone piirikasti ('bb') järele leitakse nende aladega kaetud polügoonid. Andmed salvestatakse postgis andmebaasi.
  4. #'
  5. #' @param obj str Objekti nimi. Edaspidi on oluline ainult see nimi. Piirkonna geomeetrilist joont ei ole vaja lisada.
  6. #' @param conf A list() of configuration variables. Default values \code{\link[ruut]{get_config}}.
  7. #' @return Uute andmebaasi kihtide 'piir_...' ja 'bb_...' loomine.
  8. #' @seealso [sf::st_read()], [sf::write_sf()],[sf::st_transform()],[ruut::pk_sellest_alustame_db_loomist()],[ruut::pk_lisame_ruudustikud()] ,[ruut::pk_lisame_polygoonid()],[ruut::pk_lisame_jooned()],[ruut::pk_lisame_punktid()],[ruut::pk_teisendame_polygoone()],[ruut::pk_teisendame_jooni()],[ruut::pk_teisendame_punkte()]
  9. #' @keywords postgis, boundary box, EPSG:3301
  10. #' @export
  11. #' @examples
  12. #' \dontrun{
  13. #'
  14. #' obj <- "marja"
  15. #' pk_teisendame_polygoone(obj = obj, conf = NULL)
  16. #'
  17. #' # Layers list.
  18. #' ruut::db_schema_tablenames(conf = conf)
  19. #' }
  20. pk_teisendame_polygoone <- function(obj = NULL, conf = NULL) {
  21. ## ------------- muutujad ja teisendused ---------------
  22. vars <- ajutised_muutujad(pk = NULL, obj, conf)
  23. obj <- vars$obj
  24. piir <- vars$pk
  25. conf <- vars$conf
  26. ## Konfiguratsiooni muutujale väärtuste omistamine, kui seda pole antud.
  27. if (!any("a00_piir" %in% ruut::db_schema_tablenames(conf = conf))) {
  28. cat("\nAndmebaas loomata. Palun funktsiooniga ruut::pk_sellest_alustame_db_loomist() andmebaasi loomist.\n")
  29. return(NULL)
  30. }
  31. ## ====================== teisendused =====================
  32. # Layers list
  33. layer_names <- ruut::db_schema_tablenames(conf = conf)
  34. layer_names <- layer_names[!layer_names %in% c("a00_bb2", "a00_piir_bb", "bb2_epk10t_grid", "bb2_epk02t_grid", "bb2_epk2t_grid")]
  35. for (layer_name in layer_names) {
  36. conn <- ruut::db_connect(conf = conf)
  37. try(ruumiline_obj <- sf::st_read(dsn = conn, layer = c(conf$schema, layer_name)))
  38. ## Kontlrollime kas geomeetriline objekt on polügoon.
  39. ## Arvutame sel juhul pindala.
  40. is_polygon <- any(grepl("polygon", tolower(attributes(ruumiline_obj$geom)$class), fixed = TRUE))
  41. if (is_polygon) {
  42. ## 1. Lõikame objekti ruudistikga tükkideks. Ühte ruutu võib jääda mitu tükki.
  43. ## Peame need pärast ühendama
  44. # ruut::qgis_algorithm_search_by_word("Intersection")
  45. algorithm <- "native:intersection"
  46. conf$table <- sprintf("%s", layer_name)
  47. input <- ruut::construct_to_gpkg_output_postgres_str(
  48. conf = conf, geometry_type = "MultiPolygon", srid = 3301,
  49. checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
  50. )
  51. conf$table <- sprintf("%s", "bb2_epk02t_grid")
  52. overlay <- ruut::construct_to_gpkg_output_postgres_str(
  53. conf = conf, geometry_type = "Polygon", srid = 3301,
  54. checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
  55. )
  56. output <- vars$tmp_gpkg_file_output_1 # ajutine fail
  57. str <- sprintf("{ 'INPUT' : '%s', 'INPUT_FIELDS' : ['fid'], 'OUTPUT' : '%s', 'OVERLAY' : '%s', 'OVERLAY_FIELDS' : [], 'OVERLAY_FIELDS_PREFIX' : '' }", input, output, overlay)
  58. cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
  59. system(cmd)
  60. ## 2. Ühendame ruudus olevad pinnad
  61. # ruut::qgis_algorithm_search_by_word("Dissolve")
  62. algorithm <- "native:dissolve"
  63. input <- vars$tmp_gpkg_file_input_1 # ajutine fail
  64. output <- vars$tmp_gpkg_file_output_2 # ajutine fail
  65. str <- sprintf("{ 'FIELD' : ['%s'], 'INPUT' : '%s', 'OUTPUT' : '%s' }", "id", input, output)
  66. cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
  67. system(cmd)
  68. ## 3. Lisame pindade pindalad ja perimeetri
  69. # ruut::qgis_algorithm_search_by_word("attributes")
  70. algorithm <- "qgis:exportaddgeometrycolumns"
  71. input <- vars$tmp_gpkg_file_input_2 # ajutine fail
  72. output <- vars$tmp_gpkg_file_output_1 # ajutine fail
  73. str <- sprintf("{ 'CALC_METHOD' : 0, 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
  74. cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
  75. system(cmd)
  76. ## 4. Add field
  77. ## Arvutame pindala protsendi ruudust
  78. # ruut::qgis_algorithm_search_by_word("pythonfield")
  79. algorithm <- "qgis:advancedpythonfieldcalculator"
  80. input <- vars$tmp_gpkg_file_input_1 # ajutine fail
  81. epk02t_table_name <- sprintf("epk02t_%s", gsub("^data_", "", layer_name))
  82. conf$table <- epk02t_table_name
  83. output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "Polygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
  84. str <- sprintf("{ 'FIELD_NAME' : 'area_pc', 'FIELD_TYPE' : 1, 'FIELD_LENGTH' : 4, 'FIELD_PRECISION' : 2, 'GLOBAL' : '', 'FORMULA' : 'value = round($geom.area()/10000,4)', 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
  85. cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
  86. system(cmd)
  87. ## ------------- TIFF ----------------
  88. ## 5. Lisame pindade pindalad ja perimeetri
  89. # ruut::qgis_algorithm_search_by_word("attributes")
  90. algorithm <- "native:joinattributesbylocation"
  91. conf$table <- "bb2_epk02t_grid"
  92. input <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
  93. conf$table <- epk02t_table_name
  94. join <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
  95. output <- vars$tmp_gpkg_file_output_1
  96. str <- sprintf("{ 'DISCARD_NONMATCHING' : False, 'INPUT' : '%s', 'JOIN' : '%s', 'JOIN_FIELDS' : ['area_pc'], 'METHOD' : 0, 'OUTPUT' : '%s', 'PREDICATE' : [0], 'PREFIX' : '' }", input, join, output)
  97. cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
  98. system(cmd)
  99. ## 6. Asendame NULL väärtustega 0.
  100. algorithm <- "qgis:advancedpythonfieldcalculator"
  101. input <- vars$tmp_gpkg_file_input_1 # ajutine fail
  102. output <- vars$tmp_gpkg_file_output_2
  103. cmd <- sprintf("qgis_process run %s --FIELD_NAME='value' --FIELD_TYPE=1 --FIELD_LENGTH=4 --FIELD_PRECISION=2 --GLOBAL=\"def getValue(x):
  104. if not x:
  105. value = 0
  106. else:
  107. value = x * 100
  108. return value\" --FORMULA='value = getValue( <area_pc> )' --INPUT='%s' --OUTPUT='%s' ", algorithm, input, output)
  109. system(cmd)
  110. ## 7. Eemaldame üleliigsed veerud
  111. # ruut::qgis_algorithm_search_by_word("Drop ")
  112. algorithm <- "native:deletecolumn"
  113. input <- vars$tmp_gpkg_file_input_2
  114. conf$table <- sprintf("grid_%s", gsub("^data_", "", layer_name))
  115. output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "Polygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "fid")
  116. cmd <- sprintf("qgis_process run %s --COLUMN='area_pc' --INPUT='%s' --OUTPUT='%s' ", algorithm, input, output)
  117. system(cmd)
  118. ## 8. tif salvestamine tmp kataloogi
  119. grid_layer <- sf::read_sf(dsn = conn, layer = c(conf$schema, "bb2_epk02t_grid"))
  120. # sf::st_crs(grid_layer) <- 3301
  121. pk_attributes <- attributes(grid_layer$geom)
  122. extent <- sprintf("%s,%s,%s,%s [EPSG:3301]", round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["xmax"] / 100)) * 100, round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["ymax"] / 100)) * 100)
  123. # ruut::qgis_algorithm_search_by_word("Rasterize")
  124. algorithm <- "gdal:rasterize"
  125. # ruut::qgis_show_help(algorithm = algorithm)
  126. input <- ruut::construct_to_gpkg_output_postgres_str(
  127. conf = conf, geometry_type = "MultiPolygon", srid = 3301,
  128. checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
  129. )
  130. tif_file_name <- sprintf("tif_%s", gsub("^data_", "", layer_name))
  131. output <- sprintf("%s/%s.tif", vars$tmp_dir, tif_file_name)
  132. str <- sprintf("{ 'BURN' : 0, 'DATA_TYPE' : 5, 'EXTENT' : '%s', 'EXTRA' : '-a_srs epsg:3301', 'FIELD' : 'value', 'HEIGHT' : 100, 'INIT' : None, 'INPUT' : '%s', 'INVERT' : False, 'NODATA' : -1, 'OPTIONS' : '', 'OUTPUT' : '%s', 'UNITS' : 1, 'WIDTH' : 100 }", extent, input, output)
  133. cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
  134. system(cmd) # Salvestame kataloogi
  135. ## 9. ----------- TIF TO POSTGIS -------------
  136. (cmd <- sprintf(
  137. "export PGPASSWORD=%s && raster2pgsql -d -I %s %s.%s_tif | psql -U %s -d %s -h %s -p %s",
  138. conf$password, output, conf$schema, tif_file_name, conf$user, conf$dbname, conf$host, conf$port
  139. ))
  140. system(cmd)
  141. }
  142. }
  143. ## Layers list
  144. conf$schema <- obj
  145. ruut::db_schema_tablenames(conf = conf)
  146. sf::st_layers(dsn = vars$tmp_gpkg_file)
  147. }