-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_soporte.R
293 lines (212 loc) · 7.57 KB
/
_soporte.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# mensajes en consola
mensaje <- function(x) print(glue::glue("\n\n-- {x} --\n\n"))
# funciones ---------------------------------------------------------------
# cargo todas las librerías sin mensajes de advertencias
f_library <- function(x) {
suppressWarnings(suppressMessages(library(x, character.only = TRUE)))
}
# obtengo la provincia de interés
# casos especiales para Tierra del Fuego e Islas Malvinas
f_provincia <- function(provincia) {
tdf <- c("Ushuaia", "Tolhuin", "Río Grande")
idas <- "Islas del Atlántico Sur"
aa <- "Antártida Argentina"
if (provincia == "Tierra del Fuego") {
pcia <- departamentos[departamentos$departamentos %in% tdf, ] |>
st_cast("MULTILINESTRING") |>
st_cast("POLYGON") |>
st_make_valid() |>
st_geometry()
} else if (provincia == "Islas Malvinas") {
bb <- st_bbox(
c(xmin = 4608412, xmax = 4865186, ymax = 4348687, ymin = 4179525),
crs = st_crs(5346)) |>
st_as_sfc() |>
st_cast("POLYGON")
pcia <- departamentos[departamentos$departamentos == idas, ] |>
st_cast("MULTILINESTRING") |>
st_cast("POLYGON") |>
st_make_valid() |>
st_geometry() |>
st_crop(bb)
} else if (provincia == "Islas del Atlántico Sur") {
pcia <- departamentos[departamentos$departamentos == idas, ] |>
st_cast("MULTILINESTRING") |>
st_cast("POLYGON") |>
st_make_valid() |>
st_geometry()
} else if (provincia == "Antártida Argentina") {
pcia <- departamentos[departamentos$departamentos == aa, ] |>
st_cast("MULTILINESTRING") |>
st_cast("POLYGON") |>
st_make_valid() |>
st_geometry()
} else {
pcia <- departamentos[departamentos$provincia == provincia, ] |>
st_cast("MULTILINESTRING") |>
st_cast("POLYGON") |>
st_make_valid()
}
return(pcia)
}
# modelo digital de elevación de la provincia de interés
f_dem <- function(provincia, zoom = 5) {
# archivo que contiene el dem
dem_file <- glue("{getwd()}/dem/{provincia}_{zoom}.tif")
# provincia, la región de interés
pcia <- f_provincia(provincia)
# si el dem SÍ está descargado, lo leo
# si el dem NO está descargado, lo descargo
if (file.exists(dem_file)) {
dem <- rast(dem_file)
} else {
dem <- elevatr::get_elev_raster(
locations = st_as_sf(pcia),
z = zoom,
clip = "locations"
) |>
terra::rast() |>
terra::project("EPSG:5346")
}
# si el dem NO existe, lo guardo
if (!file.exists(dem_file)) {
writeRaster(dem, glue("dem/{provincia}_{zoom}.tif"))
}
return(dem)
}
# genero los objetos: matriz a partir de DEM, límites internos de los
# departamentos y relación de aspecto
f_rayshader <- function(provincia, zoom) {
mensaje("Provincia")
dem <- f_dem(provincia, zoom)
mensaje("DEM")
d5 <- terra::focal(dem, w = 5, fun = median, na.rm = TRUE)
mensaje("Suavizo DEM")
dem_matriz <- raster_to_matrix(d5)
mensaje("Matriz")
dem_bb <- ext(d5)
asp <- (dem_bb[4] - dem_bb[3])/(dem_bb[2] - dem_bb[1])
names(asp) <- NULL
l <- list(
dem = d5,
matrix = dem_matriz,
asp = asp
)
return(l)
}
# figura con redes sociales y nombre de usuario
f_caption <- function(color1, color2, provincia, ancho = 2000) {
autor <- glue("<span style='color:{color1};'>**Víctor Gauto**</span>")
icon_twitter <- glue("<span style='font-family:jet;'></span>")
icon_instagram <- glue("<span style='font-family:jet;'></span>")
icon_github <- glue("<span style='font-family:jet;'></span>")
icon_mastodon <- glue("<span style='font-family:jet;'>󰫑</span>")
usuario <- glue("<span style='color:{color1};'>**vhgauto**</span>")
sep <- glue("**|**")
mi_caption <- glue(
"{autor} {sep} {icon_github} {icon_twitter} {icon_instagram} ",
"{icon_mastodon} {usuario}"
)
asp <- 66/897
g <- ggplot() +
annotate(
geom = "richtext", x = 0, y = 0, label = mi_caption, fill = NA,
label.color = NA, size = 10, family = "ubuntu", color = color2) +
coord_cartesian(clip = "off") +
theme_void() +
theme(
aspect.ratio = asp)
# guardo
ggsave(
plot = g,
filename = glue("captions/{provincia}.png"),
width = ancho,
height = round(ancho*asp),
units = "px")
mensaje("Caption guardado")
}
# cargo escudo, bandera y autor de la provincia de interés
f_simbolos <- function(provincia) {
tdf <- "Tierra del Fuego, Antártida e Islas del Atlántico Sur"
if (provincia == "Tierra del Fuego" | provincia == "Islas Malvinas") {
escudo <<- image_read(glue("escudos/{tdf}.png"))
bandera <<- image_read(glue("banderas/{tdf}.png"))
autor <<- image_read(glue("captions/{provincia}.png"))
} else {
escudo <<- image_read(glue("escudos/{provincia}.png"))
bandera <<- image_read(glue("banderas/{provincia}.png"))
autor <<- image_read(glue("captions/{provincia}.png"))
}
mensaje("Bandera, escudo y autor cargados")
}
f_nombre <- function(provincia, zoom) {
archivos <- list.files(
path = glue("figuras/{provincia}/"),
pattern = glue("_{zoom}_"),
full.names = TRUE)
# si NUNCA se creó una imagen, se genera la 1ra
if (length(archivos) == 0) {
archivo_nuevo <- glue("figuras/{provincia}/viz_{zoom}_1.png")
return(archivo_nuevo)
}
version <- archivos[str_detect(archivos, glue("_{zoom}"))] |>
str_replace(glue("figuras/{provincia}/viz_(.+)_(.+).png"), "\\2") |>
as.numeric() |>
max() + 1
archivo_nuevo <- glue("figuras/{provincia}/viz_{zoom}_{version}.png")
return(archivo_nuevo)
}
f_actual <- function(provincia, zoom) {
archivos <- list.files(glue("figuras/{provincia}/"), full.names = TRUE)
version <- archivos[str_detect(archivos, glue("_{zoom}"))] |>
str_replace(glue("figuras/{provincia}/viz_(.+)_(.+).png"), "\\2") |>
as.numeric() |>
max()
archivo_nuevo <- glue("figuras/{provincia}/viz_{zoom}_{version}.png")
return(archivo_nuevo)
}
f_imagen <- function(provincia) {
image_read(f_actual(provincia, zoom)) |>
image_scale("2000x") |>
image_write(glue("figuras_sd/{provincia}.png"))
mensaje("Imagen creada")
}
f_corregir <- function(raster, limite) {
raster[raster$focal_median < limite] <- limite
writeRaster(raster, glue("dem/{provincia}_{zoom}.tif"), overwrite = TRUE)
mensaje("DEM corregido")
}
mensaje("Funciones cargadas")
# paquetes ----------------------------------------------------------------
# cargo los paquetes a partir de un vector
# sin advertencias en la consola
paq <- c(
"terra", "rayshader", "sf", "glue", "showtext", "ggtext", "magick",
"tidyverse")
purrr::map(paq, f_library)
mensaje("Paquetes cargados")
# fuentes -----------------------------------------------------------------
# leo las fuentes de texto de interés
font_add_google(name = "Ubuntu", family = "ubuntu")
# íconos
font_add("jet", "fuentes/JetBrainsMonoNLNerdFontMono-Regular.ttf")
showtext_auto()
showtext_opts(dpi = 300)
mensaje("Fuentes cargadas")
# datos -------------------------------------------------------------------
# leo el vector con provincias y departamentos
# departamentos <- st_read("vectores/dptos_pcias_continental.gpkg", quiet = TRUE)
departamentos <- st_read("vectores/dptos_pcias_bicontinental.gpkg", quiet = TRUE)
mensaje("Datos leídos")
# HDRI --------------------------------------------------------------------
# el .hdri que usé en todas: photo_studio_loft_hall_4k.hdr
# https://polyhaven.com/hdris/studio
hdri_file <- function(x = NULL) {
if (is.null(x)) {
hdri <- "hdri/photo_studio_loft_hall_4k.hdr"
} else {
hdri <- list.files("hdri/" , full.names = TRUE)[x]
}
return(hdri)
}
mensaje("HDRI cargado")