-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_sampling.R
407 lines (311 loc) · 10.5 KB
/
06_sampling.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#ENV
pacman::p_load(rgdal, raster, terra, stars, sp, sf, tidyverse, ggplot2, clhs)
# DATA
# data <- readRDS("./data/harmonized_covs/harmonized_data.rds")
# covariates_aoi <- readRDS("D:/DOCS/CIENCIA DE SUELOS/R_SUELOS/glacier_mlMODIS/data/harmonized_covs/harmonized_data_pred.rds")
covariates_aoi_names <- list.files(path = "./data/harmonized_covs/stacks/",
recursive = TRUE,
full.name = TRUE,
pattern = "*.gri$")
raster_list <- list()
for (file in covariates_aoi_names) {
raster_stack <- raster::stack(file)
raster_list[[file]] <- raster_stack
}
raster_list
lits_names <- c("Blanca",
"Central",
"Huallanca",
"Huayhuasha",
"Huaytapallana",
"LaRaya",
"LaViuda",
"Raura",
"Urubamba",
"Vilcabamba",
"VIlcanota"
)
names(raster_list) <- lits_names
#FUNCION
# sampling_clh <- function(lista_stack, sampling_size){
#
# set.seed(1234)
# # crear mask rasters
# # si es clasificacion multicategoria usar un raster para cada categoria
#
# sampling_list <- list()
#
# for (i in 1:length(lista_stack)) {
#
# mask_in <- lista_stack[[i]]$CLASS # mascara clase glaciar lista_stack[[i]][[1]]
# mask_out <- lista_stack[[i]]$CLASS # mask class no glaciar lista_stack[[i]][[1]]
#
# mask_in[mask_in != 1] <- NA # 1 : glaciar, NA: no glaciar
# mask_out[mask_out == 1] <- NA # 1: no glaiar, NA : glaciar
#
#
# # masking
#
# stack_in <- raster::mask(
# lista_stack[[i]], #rasterstack original
# mask_in, # mask
# maskvalue = NA)
#
# stack_out <- raster::mask(
# lista_stack[[i]],
# mask_out,
# maskvalue = NA)
#
# #clh, ambas clases igual sampling_size de puntos, muestreo balanciado
#
# # MUESTREO ESTRATIFICADO EN CADA CLASE
# # clase 1
# stack_df_in <- rasterToPoints(stack_in, spatial=TRUE) # all pixels to dataframe
# sample_in <- sampleRandom(stack_in, size = sampling_size, sp = TRUE) # all pixels to dataframe
# # sample_in <- clhs(stack_df_in, size = sampling_size,
# # progress = FALSE, iter = 10000, simple = FALSE) # clh object
#
#
# # #clase 2
# # stack_df_out <- rasterToPoints(stack_out, spatial=TRUE) # all pixels to dataframe
# sample_out <- sampleRandom(stack_out, size = sampling_size, sp = TRUE)
# # sample_out <- clhs(stack_df_out, size = sampling_size,
# # progress = FALSE, iter = 10000, simple = FALSE)
# #
#
# # sampling original stack on clh points
#
# # muestra <- rbind(clhs_points_df_in$sampled_data,
# # clhs_points_df_out$sampled_data )
# #
# #unir sp objetcs
#
#
# muestra <- rbind(sample_in, # $sampled_data si se usa clh
# sample_out)
#
# muestra_sf <- st_as_sf(muestra)
#
# # sampling_list <- list()
# sampling_list[[i]] <- muestra_sf
#
# }
#
# return(sampling_list)
# }
#
#
# # limpiar memoria
#
# # rm(list=setdiff(ls(), "data"))
# # # rm(list = ls()) # limpiar todo el envi
# # memory.size()
# # memory.limit()
# # memory.limit(size=56000)
# # gc() # limpiar ram
# #
#
# ### apply function a toda la lista de stacks
# sample1000 <- sampling_clh(data[9], 500) # escoger 500 como paper AGB ploton # falta el 10
#
# #Huallanca 3
# #Huayhuasha 4
# # Huaytapallana 5
# # raura 8
# # la raya 6
# # vilcanota 11
# #urubamba 9
# #vilcabamba 10
#
# #contar nas
# sapply(sample1000[[1]], function(x) sum(is.na(x)))
#
#
# #WRITE COMO CSV
#
# # saveRDS(sample1000[[1]], "./data/sampling_points/Blanca_samples1000.rds")
# st_write(sample1000[[1]],
# "./data/sampling_points/Urubamba_samples1000.gpkg",
# driver="GPKG")
#
# #WRITE COMO geopkg
#
#
# # for (i in 1:length(list_stck)) {
# #
# # raster::writeRaster(list_stck[[i]],
# # filename = paste0("./data/landsat/indices/index-",
# # landsat_cordilleras_chr[i], ".grd"),
# # format = "raster")
# #
# # }
#
#
# cordilleras <- c("Blanca",
# "Central",
# "Huallanca",
# "Huayhuasha",
# "Huaytapallana",
# "LaRaya",
# "LaViuda",
# "Raura",
# "Urubamba",
# "Vilcabamba",
# "Vilcanota"
# )
#
#
#
# for (i in 1:length(sample1000)) {
#
# st_write(sample1000[[i]],
# # "./data/sampling_points/sampling_points_blanca.gpkg",
# paste0("./data/sampling_points/sample_",cordilleras[i], ".gpkg"),
# driver="GPKG")
# }
#
# sampling_points_gpkg <- st_as_sf(sampling_points[[1]])
# st_write(sampling_points[[1]], "./data/sampling_points/sampling_points_blanca.gpkg", driver="GPKG") # Create a geopackage file
# saveRDS(sampling_points[[1]], "./data/harmonized_covs/sampling_points_blanca.rds")
#puntos
# x <- sampleStratified(data$Vilcanota$CLASS, size=500, sp = TRUE)
# #extraer data from stacks
# x_ <- raster::extract(data$Vilcanota, x, sp=TRUE, method = "simple")
# # #write
# st_write(st_as_sf(x_),
# "./data/sampling_points/sample1000_vilcanota.gpkg",
# driver="GPKG")
#plot
# par(mar = c(1,1,1,1))
# plot(data$Vilcanot$BLUE, axes=FALSE)
# plot(x_, col = "red", add=TRUE)
#
####
#### MUESTREO ESTRATIFICADOO
####
sample_list <- list()
for (i in 1:length(data)) {
sample_point <- sampleStratified(data[[i]]$CLASS, size=500, sp = TRUE) #1000 puntos de muestreo
sample <- raster::extract(data[[i]], sample_point, sp=TRUE, method = "simple")
sample <- st_as_sf(sample)
sample_list[[i]] <- sample
}
#####
##### CHECK CRS
for (i in 1:length(sample_list)) {
crs <- st_crs(sample_list[[i]])$input
print(crs)
}
# # warp one to crs of others
#
# for (i in 1:length(samples_gpkg)) {
# # Transform the CRS of each sf object to the target CRS
# samples_gpkg[[i]] <- st_transform(samples_gpkg[[i]], st_crs("EPSG:4326"))
# # Print the CRS of the transformed sf object
# print(st_crs(samples_gpkg[[i]])$input)
# }
#
for (i in 1:length(sample_list)) {
st_write(sample_list[[i]],
paste0("./data/sampling_points/sample1000_",cordilleras[i], ".gpkg"),
driver="GPKG")
}
####
#### MUESTREO SIMPLE
####
sample_list <- list()
for (i in 1:length(raster_list)) {
sample_point <- sampleRandom(raster_list[[i]], size= 1000, sp = TRUE) #1000 puntos de muestreo
sample <- raster::extract(raster_list[[i]], sample_point, sp=TRUE, method = "simple")
sample <- st_as_sf(sample)
sample_list[[i]] <- sample
}
#####
##### CHECK CRS
for (i in 1:length(sample_list)) {
crs <- st_crs(sample_list[[i]])$input
print(crs)
}
# # warp one to crs of others
#
# for (i in 1:length(samples_gpkg)) {
# # Transform the CRS of each sf object to the target CRS
# samples_gpkg[[i]] <- st_transform(samples_gpkg[[i]], st_crs("EPSG:4326"))
# # Print the CRS of the transformed sf object
# print(st_crs(samples_gpkg[[i]])$input)
# }
#
for (i in 1:length(sample_list)) {
st_write(sample_list[[i]],
paste0("./output/test_samples/", lits_names[i], "_test",".gpkg"),
driver="GPKG")
}
##############
############## CRS TRANSFORMATION
#############
pacman::p_load(mlr,mlrMBO,DiceKriging, rgenoud, sf, terra, ranger, xgboost, tidyverse, ggplot2, ggExtra )
#data/task
list_files <- list.files(path = "./data/sampling_points/",
recursive = TRUE,
full.name = TRUE, # directorio relativo raster
pattern = "\\.gpkg$")
list_gpkg <- lapply(list_files, FUN = sf::read_sf)
# set crs EPSG:4326
for (i in seq_along(list_gpkg)) {
sf::st_crs(list_gpkg[[i]]) <- 4326
}
# sf::st_crs(list_gpkg[[8]])
# proyectar a utm 18 y 19 (vilcanota y la raya)
cordilleras <- c("Blanca","Central","Huallanca",
"Huayhuasha","Huaytapallana","LaRaya",
"LaViuda","Raura","Urubamba",
"Vilcabamba","Vilcanota")
names(list_gpkg) <- cordilleras
cordilleras_utm18<- c("Blanca","Central","Huallanca",
"Huayhuasha","Huaytapallana","LaRaya",
"LaViuda","Raura","Urubamba",
"Vilcabamba")
cordilleras_utm19<- c("LaRaya","Vilcanota")
list_gpkg_utm <- list()
for (i in seq(list_gpkg)) {
epsg <- list(utm18 = 32718,
utm19 = 32719 )
if (names(list_gpkg[i]) %in% cordilleras_utm18 ) {
list_gpkg_utm[[i]] <- sf::st_transform(list_gpkg[[i]], crs = epsg[[1]] )
} else {
list_gpkg_utm[[i]] <- sf::st_transform(list_gpkg[[i]], crs = epsg[[2]] )
}
}
list_gpkg_utm
# revisar cuadros, extrare 500 puntos el benchmarking y 500 para evaluacion final
#etiquetar 500 obs
names(list_gpkg_utm) <- cordilleras
train_points <- c(rep("train", 500) , rep("test", 500))
train_points_ <- sample(train_points, size = 1000, replace = FALSE)
x <- list_gpkg_utm$Raura
# contar obseraciones de la clase 1 y clase 0
# y <- x %>% dplyr::mutate(train_test = train_points_)
list_gpkg_utm_ <- list()
for (i in seq_along(list_gpkg_utm)) {
set.seed(1234)
train_points <- c(rep("train", 500) , rep("test", 500))
train_points_ <- sample(train_points, size = 1000, replace = FALSE)
list_gpkg_utm_[[i]] <- list_gpkg_utm[[i]] %>%
dplyr::mutate(train_test = train_points_)
}
#comprobar balance data de entrenamiento
list_gpkg_utm_[[11]] %>%
dplyr::filter(train_test=="train") %>%
count(CLASS, sort = TRUE, name= "Code_frequency")
#comprobar nas
x <- list_gpkg_utm_[[11]]
sapply(x, function(x) sum(is.na(x)))
#write
# st_write(y,
# "./test/raura_train_points_.gpkg",
# driver="GPKG")
for (i in 1:length(list_gpkg_utm_)) {
st_write(list_gpkg_utm_[[i]],
paste0("./data/sampling_points/sample1000utm_",cordilleras[i], ".gpkg"),
driver="GPKG")
}