-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_shapefile.R
1080 lines (1026 loc) · 38.1 KB
/
utils_shapefile.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
point_to_polygon <- function(sf_object, n_sides = 500) {
# Extract CRS of the input sf object
crsobj <- sf::st_crs(sf_object)
# Create a new geometry list
new_geometries <- lapply(seq_len(nrow(sf_object)), function(i) {
geom_type <- sf::st_geometry_type(sf_object[i, ])
if (geom_type == "POINT") {
# Get the point coordinates
point <- sf::st_coordinates(sf_object[i, ])
radius <- sf_object[["radius"]][i]
if (is.na(radius)) {
stop("Radius is missing for a POINT geometry!")
}
angles <- seq(0, 2 * pi, length.out = n_sides + 1)
circle_coords <- cbind(
point[1] + radius * cos(angles), # X coordinates
point[2] + radius * sin(angles) # Y coordinates
)
sf::st_polygon(list(circle_coords))
} else {
sf::st_geometry(sf_object[i, ])
}
})
# Function to ensure all geometries in a list are valid sfg objects
validate_geometries <- function(geometry_list) {
lapply(geometry_list, function(geom) {
if (inherits(geom, "sfg")) {
return(geom) # Valid sfg object, return as is
} else if (inherits(geom, "sfc")) {
return(geom[[1]]) # Unnest if it's an sfc object
} else if (is.list(geom) && inherits(geom[[1]], "sfg")) {
return(geom[[1]]) # Handle nested lists containing sfg objects
} else {
stop("Invalid geometry found in the list")
}
})
}
sf_object <-
sf::st_set_geometry(sf_object, sf::st_sfc(validate_geometries(new_geometries))) |>
sf::st_set_crs(crsobj)
return(sf_object)
}
add_width_height <- function(grid, width, height, mosaic, points_align) {
gridl <-lapply(sf::st_geometry(grid), sf::st_coordinates)
gridadj <- add_width_height_cpp(gridl, height, width, points_align)
grd <- lapply(gridadj, function(x){sf::st_polygon(list(x))}) |> sf::st_sfc()
grd <- sf::st_sf(geometry = grd)
sf::st_crs(grd) <- sf::st_crs(grid)
return(grd)
}
create_buffer <- function(coords, buffer_col, buffer_row) {
# Calculate the new x-min, x-max, y-min, and y-max after adjustment
coords <- sf::st_coordinates(coords)
x_min <- min(coords[, 1])
x_max <- max(coords[, 1])
y_min <- min(coords[, 2])
y_max <- max(coords[, 2])
new_x_min <- x_min - buffer_col * (x_max - x_min)
new_x_max <- x_max + buffer_col * (x_max - x_min)
new_y_min <- y_min - buffer_row * (y_max - y_min)
new_y_max <- y_max + buffer_row * (y_max - y_min)
# Calculate the scaling factors for x and y
x_scale_factor <- (new_x_max - new_x_min) / (x_max - x_min)
y_scale_factor <- (new_y_max - new_y_min) / (y_max - y_min)
# Apply the scaling to the coordinates
resized_coords <- coords
resized_coords[, 1] <- (resized_coords[, 1] - x_min) * x_scale_factor + new_x_min
resized_coords[, 2] <- (resized_coords[, 2] - y_min) * y_scale_factor + new_y_min
sf::st_polygon(list(resized_coords[, 1:2]))
# return(resized_coords)
# return(data.frame(resized_coords) |> sf::st_as_sf(coords = c("X", "Y")))
}
make_grid <- function(points, nrow, ncol, mosaic, buffer_col = 0, buffer_row = 0, plot_width = NULL, plot_height = NULL) {
points_align <-
sf::st_transform(points, sf::st_crs(mosaic)) |>
sf::st_coordinates()
grids <-
sf::st_make_grid(points, n = c(nrow, ncol)) |>
sf::st_transform(sf::st_crs(mosaic))
sxy <-
points |>
sf::st_make_grid(n = c(1, 1)) |>
sf::st_cast("POINT") |>
rev() |>
sf::st_transform(sf::st_crs(mosaic)) |>
sf::st_coordinates()
txy <-
points |>
sf::st_transform(sf::st_crs(mosaic)) |>
sf::st_coordinates()
txy <- txy[1:4, 1:2]
cvm <- lm(txy ~ sxy[1:4, ])
parms <- cvm$coefficients[2:3, ]
intercept <- cvm$coefficients[1, ]
geometry <- grids * parms + intercept
if (buffer_row != 0 | buffer_col != 0) {
geometry <- lapply(geometry, function(g) {
create_buffer(g, buffer_col, buffer_row)
}) |>
sf::st_sfc(crs = sf::st_crs(mosaic))
}
if (!is.null(plot_width) & !is.null(plot_height)) {
geometry <-
add_width_height(grid = geometry, width = plot_width, height = plot_height, points_align = points_align[2:3, 1:2]) |>
sf::st_as_sfc(crs = sf::st_crs(mosaic))
}
return(sf::st_sf(geometry = geometry, crs = sf::st_crs(mosaic)))
}
#' Generate plot IDs with different layouts
#'
#' Based on a shapefile, number of columns and rows, generate plot IDs with
#' different layouts.
#'
#' @param shapefile An object computed with [shapefile_build()]
#' @param nrow The number of columns
#' @param ncol The number of rows
#' @param layout Character: one of
#' * `'tblr'` for top/bottom left/right orientation
#' * `'tbrl'` for top/bottom right/left orientation
#' * `'btlr'` for bottom/top left/right orientation
#' * `'btrl'` for bottom/top right/left orientation
#' * `'lrtb'` for left/right top/bottom orientation
#' * `'lrbt'` for left/right bottom/top orientation
#' * `'rltb'` for right/left top/bottom orientation
#' * `'rlbt'` for right/left bottom/top orientation
#' @param plot_prefix The plot_id prefix. Defaults to `'P'`.
#' @param serpentine Create a serpentine-based layout? Defaults to `FALSE`.
#' @return A vector of plot IDs with specified layout
#' @export
#'
plot_id <- function(shapefile,
nrow,
ncol,
layout = c("tblr", "tbrl", "btlr", "btrl", "lrtb", "lrbt", "rltb", "rlbt"),
plot_prefix = "P",
serpentine = FALSE) {
# Ensure the specified layout is valid
allowed <- c("tblr", "tbrl", "btlr", "btrl", "lrtb", "lrbt", "rltb", "rlbt")
layout <- layout[[1]]
if (!layout %in% allowed) {
stop(paste0("`layout` must be one of the following: ", paste0(allowed, collapse = ", ")))
}
# Ensure that the number of rows in the shapefile matches expected dimensions
expected_rows <- nrow * ncol
if (nrow(shapefile) != expected_rows) {
stop(paste("Expected", expected_rows, "rows, but shapefile has", nrow(shapefile), "rows."))
}
# Helper function for generating plot names
leading_zeros <- function(x, n) {
sprintf(paste0("%0", n, "d"), x)
}
plots_tblr <- paste0(plot_prefix, leading_zeros(1:nrow(shapefile), 4))
# Define layout functions
make_tblr <- function() {
plots_tblr
}
make_tbrl <- function() {
plots_tblr_rev <- rev(plots_tblr)
plots_tbrl <- NULL
for (i in 1:ncol) {
start <- (i - 1) * nrow + 1
end <- start + nrow - 1
plots_tbrl <- c(plots_tbrl, rev(plots_tblr_rev[start:end]))
}
plots_tbrl
}
make_btrl<- function() {
plots_rev <- rev(plots_tblr)
plots_btlr <- NULL
for (i in 1:ncol) {
start <- (i - 1) * nrow + 1
end <- start + nrow - 1
plots_btlr <- c(plots_btlr, plots_rev[start:end])
}
plots_btlr
}
make_btlr <- function() {
plots_btlr_rev <- rev(make_btrl())
plots_btrl <- NULL
for (i in seq_len(ncol)) {
start <- (i - 1) * nrow + 1
end <- start + nrow - 1
plots_btrl <- c(plots_btrl, rev(plots_btlr_rev[start:end]))
}
plots_btrl
}
make_lrtb <- function() {
plots_lrtb <- NULL
for (i in 1:ncol) {
plots_lrtb <- c(plots_lrtb, plots_tblr[seq(i, length(plots_tblr), by = ncol)])
}
plots_lrtb
}
make_lrbt <- function() {
plots_lrbt <- NULL
plots_lrtb <- make_lrtb()
for (i in 1:ncol) {
start <- (i - 1) * nrow + 1
end <- start + nrow - 1
plots_lrbt <- c(plots_lrbt, rev(plots_lrtb[start:end]))
}
plots_lrbt
}
make_rltb <- function() {
plots_rltb <- NULL
for (i in 1:ncol) {
# Columns from right to left
plots_rltb <- c(plots_rltb, plots_tblr[seq(ncol - i + 1, length(plots_tblr), by = ncol)])
}
plots_rltb
}
make_rlbt <- function() {
plots_rltb <- make_rltb()
plots_rlbt <- NULL
for (i in seq_len(ncol)) {
start <- (i - 1) * nrow + 1
end <- start + nrow - 1
plots_rlbt <- c(plots_rlbt, rev(plots_rltb[start:end]))
}
plots_rlbt
}
# Return the appropriate layout
plots <- switch(layout,
"tblr" = make_tblr(),
"tbrl" = make_tbrl(),
"btlr" = make_btlr(),
"btrl" = make_btrl(),
"lrtb" = make_lrtb(),
"lrbt" = make_lrbt(),
"rltb" = make_rltb(),
"rlbt" = make_rlbt())
mat <- matrix(plots, ncol = ncol, nrow = nrow)
if(serpentine){
# column serpentine
if(layout %in% c("tblr", "btlr")){
mat2 <- mat
for (j in 1:ncol(mat)) {
if(j %% 2 == 0){
mat2[, j] <- rev(mat[, j])
} else{
mat2[, j]
}
}
}
if(layout %in% c( "tbrl", "btrl")){
mat2 <- mat
cols <- ncol(mat):1
for (j in cols[seq(2, ncol, by = 2)]) {
mat2[, j] <- rev(mat[, j])
}
}
# row serpentine
if(layout %in% c("lrtb", "rltb")){
mat2 <- mat
for (j in 1:nrow(mat)) {
if(j %% 2 == 0){
mat2[j, ] <- rev(mat[j, ])
} else{
mat2[j, ]
}
}
}
if(layout %in% c("lrbt", "rlbt")){
mat2 <- mat
rows <- nrow(mat):1
for (j in rows[seq(2, nrow, by = 2)]) {
mat2[j, ] <- rev(mat[j, ])
}
}
} else{
mat2 <- mat
}
return(as.vector(mat2))
}
#' Build a shapefile from a mosaic raster
#'
#' This function takes a mosaic raster to create a shapefile containing polygons
#' for the specified regions. Users can drawn Areas of Interest (AOIs) that can
#' be either a polygon with n sides, or a grid, defined by `nrow`, and `ncol`
#' arguments.
#' @details
#' Since multiple blocks can be created, the length of arguments `grid`, `nrow`,
#' `ncol`, `buffer_edge`, `buffer_col`, and `buffer_row` can be either an scalar
#' (the same argument applied to all the drawn blocks), or a vector with the
#' same length as the number of drawn blocks. In the last, shapefiles in each
#' block can be created with different dimensions.
#' @param sf_to_polygon Convert sf geometry like POINTS and LINES to POLYGONS?
#' Defaults to `FALSE`. Using `TRUE` allows using POINTS to extract values
#' from a raster using `exactextractr::exact_extract()`.
#' @param basemap An optional `mapview` object.
#' @param controlpoints An `sf` object created with [mapedit::editMap()],
#' containing the polygon that defines the region of interest to be analyzed.
#' @param nsides The number of sides if the geometry is generated with `Draw
#' Circle` tool.
#' @inheritParams mosaic_analyze
#' @inheritParams mosaic_index
#' @inheritParams mosaic_view
#' @inheritParams utils_shapefile
#' @inheritParams plot_id
#' @return A list with the built shapefile. Each element is an `sf` object with
#' the coordinates of the drawn polygons.
#' @export
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' mosaic <- mosaic_input(system.file("ex/elev.tif", package="terra"))
#' shps <-
#' shapefile_build(mosaic,
#' nrow = 6,
#' ncol = 3,
#' buffer_row = -0.05,
#' buffer_col = -0.25,
#' check_shapefile = FALSE,
#' build_shapefile = FALSE) ## Use TRUE to interactively build the plots
#' mosaic_plot(mosaic)
#' shapefile_plot(shps[[1]], add = TRUE)
#' }
#'
shapefile_build <- function(mosaic,
basemap = NULL,
controlpoints = NULL,
r = 3,
g = 2,
b = 1,
crop_to_shape_ext = TRUE,
grid = TRUE,
nrow = 1,
ncol = 1,
nsides = 200,
plot_width = NULL,
plot_height = NULL,
layout = "lrtb",
serpentine = TRUE,
build_shapefile = TRUE,
check_shapefile = FALSE,
sf_to_polygon = FALSE,
buffer_edge = 1,
buffer_col = 0,
buffer_row = 0,
as_sf = TRUE,
verbose = TRUE,
max_pixels = 1000000,
downsample = NULL,
quantiles = c(0, 1)){
check_mapview()
if(terra::crs(mosaic) == ""){
terra::crs(mosaic) <- terra::crs("EPSG:4326")
}
ress <- terra::res(mosaic)
nlyrs <- terra::nlyr(mosaic)
if(build_shapefile){
if(verbose){
message("\014","\nBuilding the mosaic...\n")
}
if(is.null(basemap)){
basemap <- mosaic_view(mosaic,
r = r,
g = g,
b = b,
max_pixels = max_pixels,
downsample = downsample,
quantiles = quantiles)
}
if(is.null(controlpoints)){
points <- mapedit::editMap(basemap,
editor = "leafpm",
editorOptions = list(toolbarOptions = list(
drawMarker = TRUE,
drawPolygon = TRUE,
drawPolyline = TRUE,
drawCircle = TRUE,
drawRectangle = TRUE,
editMode = TRUE,
cutPolygon = TRUE,
removalMode = TRUE,
position = "topleft"
))
)
cpoints <- points$finished |>
sf::st_transform(sf::st_crs(mosaic)) |>
point_to_polygon(n_sides = nsides)
} else{
cpoints <- controlpoints
}
if(sf_to_polygon){
cpoints <- cpoints |> sf_to_polygon()
}
} else{
extm <- terra::ext(mosaic)
xmin <- extm[1]
xmax <- extm[2]
ymin <- extm[3]
ymax <- extm[4]
coords <- matrix(c(xmin, ymax, xmax, ymax, xmax, ymin, xmin, ymin, xmin, ymax), ncol = 2, byrow = TRUE)
# Create a Polygon object
polygon <- sf::st_polygon(list(coords))
# Create an sf object with a data frame that includes the 'geometry' column
if(sum(ress) == 2){
crop_to_shape_ext <- FALSE
}
cpoints <- sf::st_sf(data.frame(id = 1),
geometry = sf::st_sfc(polygon),
crs = sf::st_crs(mosaic))
}
# crop to the analyzed area
if(crop_to_shape_ext){
if(sum(ress) != 2){
cpoints <- cpoints |> sf::st_transform(crs = sf::st_crs(terra::crs(mosaic)))
}
poly_ext <-
cpoints |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
mosaiccr <- terra::crop(mosaic, poly_ext)
} else{
mosaiccr <- mosaic
}
# check the parameters
nrow <- validate_and_replicate2(nrow, cpoints, verbose = verbose)
ncol <- validate_and_replicate2(ncol, cpoints, verbose = verbose)
layout <- validate_and_replicate2(layout, cpoints, verbose = verbose)
buffer_col <- validate_and_replicate2(buffer_col, cpoints, verbose = verbose)
buffer_row <- validate_and_replicate2(buffer_row, cpoints, verbose = verbose)
plot_width <- validate_and_replicate2(plot_width, cpoints, verbose = verbose)
plot_height <- validate_and_replicate2(plot_height, cpoints, verbose = verbose)
serpentine <- validate_and_replicate2(serpentine, cpoints, verbose = verbose)
grid <- validate_and_replicate2(grid, cpoints, verbose = verbose)
# check the created shapes?
if(verbose){
message("\014","\nCreating the shapes...\n")
}
created_shapes <- list()
for(k in 1:nrow(cpoints)){
if(inherits(cpoints[k, ]$geometry, "sfc_POLYGON") & nrow(sf::st_coordinates(cpoints[k, ])) == 5 & grid[[k]]){
pg <-
make_grid(cpoints[k, ],
nrow = nrow[k],
ncol = ncol[k],
mosaic = mosaic,
buffer_col = buffer_col[k],
buffer_row = buffer_row[k],
plot_width = plot_width[k],
plot_height = plot_height[k]) |>
dplyr::mutate(row = rep(1:nrow[k], ncol[k]),
column = rep(1:ncol[k], each = nrow[k]),
.before = geometry)
pg <-
pg |>
dplyr::mutate(unique_id = dplyr::row_number(),
block = paste0("B", leading_zeros(k, 2)),
plot_id = plot_id(pg, nrow = nrow[k], ncol = ncol[k], layout = layout[k], serpentine = serpentine[k]),
.before = 1)
} else{
pg <-
cpoints[k, ] |>
sf::st_transform(sf::st_crs(mosaic)) |>
dplyr::select(geometry) |>
dplyr::mutate(unique_id = dplyr::row_number(),
block = paste0("B", leading_zeros(k, 2)),
plot_id = "P0001",
row = 1,
column = 1,
.before = 1)
}
created_shapes[[k]] <- pg
}
if(check_shapefile){
if(verbose){
message("\014","\nChecking the built shapefile...\n")
}
lengths <- sapply(created_shapes, nrow)
pg_edit <-
do.call(rbind, lapply(seq_along(created_shapes), function(i){
created_shapes[[i]] |>
dplyr::mutate(`_leaflet_id` = 1:nrow(created_shapes[[i]]),
feature_type = "polygon") |>
dplyr::relocate(geometry, .after = 4) |>
sf::st_transform(crs = 4326)
}))
downsample <- find_aggrfact(mosaiccr, max_pixels = max_pixels)
if(downsample > 0){
mosaiccr <- mosaic_aggregate(mosaiccr, pct = round(100 / downsample))
}
if(build_shapefile){
mapview::mapview() |> mapedit::editMap()
}
edited <-
mapedit::editFeatures(pg_edit, basemap) |>
dplyr::select(geometry, block, plot_id, row, column) |>
dplyr::mutate(unique_id = dplyr::row_number(), .before = 1) |>
sf::st_transform(sf::st_crs(mosaic))
sfeat <- sf::st_as_sf(edited)
sf::st_geometry(sfeat) <- "geometry"
created_shapes <- split(sfeat, edited$block)
}
if(verbose){
message("\014","\nShapefile finished...\n")
}
if(!as_sf){
return(shapefile_input(created_shapes, info = FALSE, as_sf = FALSE))
} else{
return(created_shapes)
}
}
#' A wrapper around terra::plot()
#'
#' Plot the values of a SpatVector
#'
#' @param shapefile An SpatVector of sf object.
#' @param ... Further arguments passed on to [terra::plot()].
#'
#' @return A `NULL` object
#' @export
#'
#' @examples
#' if(interactive()){
#' library(pliman)
#' r <- shapefile_input(system.file("ex/lux.shp", package="terra"))
#' shapefile_plot(r)
#' }
shapefile_plot <- function(shapefile, ...){
if(!inherits(shapefile, "SpatVector") & !inherits(shapefile, "sf") ){
stop("'mosaic' must be an object of class 'SpatVector' of 'sf'")
}
if(inherits(shapefile, "sf")){
shapefile <- terra::vect(shapefile)
}
terra::plot(shapefile, ...)
}
#' Import/export shapefiles.
#' @description
#'
#' * `shapefile_input()` creates or imports a shapefile and optionally converts
#' it to an `sf` object. It can also cast `POLYGON` or `MULTIPOLYGON` geometries
#' to `MULTILINESTRING` if required.
#' * `shapefile_export()` exports an object (`sf` or `SpatVector`) to a file.
#' * `shapefile_view()` is a simple wrapper around `mapview()` to plot a shapefile.
#'
#' @name utils_shapefile
#'
#' @param shapefile For `shapefile_input()`, character (filename), or an object that can be
#' coerced to a SpatVector, such as an `sf` (simple features) object. See
#' [terra::vect()] for more details.
#'
#' For `shapefile_export()`, a `SpatVector` or an `sf` object to be exported as
#' a shapefile.
#'
#' @param info Logical value indicating whether to print information about the
#' imported shapefile (default is `TRUE`).
#' @param as_sf Logical value indicating whether to convert the imported
#' shapefile to an `sf` object (default is `TRUE`).
#' @param multilinestring Logical value indicating whether to cast polygon geometries
#' to `MULTILINESTRING` geometries (default is `FALSE`).
#' @param type A character string specifying whether to visualize the shapefile
#' as `"shape"` or as `"centroid"`. Partial matching is allowed. If set to
#' `"centroid"`, the function will convert the shapefile's geometry to
#' centroids before displaying. Defaults to `"shape"`.
#' @param filename The path to the output shapefile.
#' @param attribute The attribute to be shown in the color key. It must be a
#' variable present in `shapefile`.
#' @param color_regions The color palette to represent `attribute`.
#' @param ... Additional arguments to be passed to [terra::vect()]
#' (`shapefile_input()`), [terra::writeVector()] (`shapefile_export()`) or
#' [mapview::mapview()] (`shapefile_view()`).
#'
#' @return
#' * `shapefile_input()` returns an object of class `sf` (default) representing
#' the imported shapefile.
#'
#' * `shapefile_export()` returns a `NULL` object.
#'
#' * `shapefile_view()` returns an object of class `mapview`.
#'
#' @examples
#' if(interactive()){
#' library(pliman)
#' shp <- system.file("ex/lux.shp", package="terra")
#' shp_file <- shapefile_input(shp, as_sf = FALSE)
#' shapefile_view(shp_file)
#' }
#'
#' @export
shapefile_input <- function(shapefile,
info = TRUE,
as_sf = TRUE,
multilinestring = FALSE,
...) {
check_mapview()
# Check if shapefile is a URL and download it
if (is.character(shapefile) && grepl("^http", shapefile)) {
check_and_install_package("curl")
temp_shapefile <- tempfile(fileext = ".rds")
curl::curl_download(shapefile, temp_shapefile)
shapefile <- temp_shapefile
}
create_shp <- function(shapefile, info, as_sf, ...){
shp <- terra::vect(shapefile, ...)
if (terra::crs(shp) == "") {
message("Missing Coordinate Reference System. Setting to EPSG:3857")
terra::crs(shp) <- terra::crs("EPSG:3857")
}
if (as_sf) {
shp <- sf::st_as_sf(shp)
if(multilinestring){
shp <- sf::st_cast(shp, "MULTILINESTRING")
}
}
if (info) {
print(shp)
}
return(shp)
}
if(inherits(shapefile, "list")){
shapes <- do.call(rbind, lapply(shapefile, function(x){x}))
create_shp(shapes, info, as_sf, ...) |> add_missing_columns()
} else{
create_shp(shapefile, info, as_sf, ...) |> add_missing_columns()
}
}
#' @name utils_shapefile
#' @export
shapefile_export <- function(shapefile, filename, ...) {
if (inherits(shapefile, "list")) {
shapefile <- shapefile_input(shapefile, info = FALSE)
}
if (!inherits(shapefile, "SpatVector")) {
shapefile <- try(terra::vect(shapefile))
}
if (inherits(shapefile, "try-error")) {
stop("Unable to coerce the input shapefile to a SpatVector object")
}
terra::writeVector(shapefile, filename, ...)
}
#' @name utils_shapefile
#' @export
shapefile_view <- function(shapefile,
attribute = NULL,
type = c("shape", "centroid"),
color_regions = custom_palette(c("red", "yellow", "forestgreen")),
...){
type <- match.arg(type, choices = c("shape", "centroid"))
# Example usage of the checked 'type'
if (type == "centroid") {
shapefile <- suppressWarnings(sf::st_centroid(shapefile))
}
if(!is.null(attribute) && attribute == "plot_id"){
if(inherits(shapefile, "list")){
shapefile <-
lapply(shapefile, function(x){
x |> dplyr::mutate(plot_id = as.numeric(gsub("\\D", "", plot_id)))
})
} else{
shapefile <- shapefile |> dplyr::mutate(plot_id = as.numeric(gsub("\\D", "", plot_id)))
}
}
suppressWarnings(
mapview::mapview(shapefile,
zcol = attribute,
col.regions = color_regions,
...)
)
}
#' Edit Features in a Shapefile
#'
#' This function allows you to interactively edit features in a shapefile using
#' the mapedit package.
#'
#' @param shapefile A shapefile (`sf` object) that can be created with
#' [shapefile_input()].
#' @param mosaic Optionally, a mosaic (SpatRaster) to be displayed as a
#' background.
#' @param basemap An optional `mapview` object.
#' @param r Red band index for RGB display (default is 3).
#' @param g Green band index for RGB display (default is 2).
#' @param b Blue band index for RGB display (default is 1).
#' @param max_pixels Maximum number of pixels for down-sampling the mosaic
#' (default is 3e6).
#' @export
#' @return A modified shapefile with user-edited features.
#'
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' shp <- shapefile_input(system.file("ex/lux.shp", package="terra"))
#' edited <- shapefile_edit(shp)
#' }
shapefile_edit <- function(shapefile,
mosaic = NULL,
basemap = NULL,
r = 3,
g = 2,
b = 1,
max_pixels = 3e6){
shapefile <- shapefile_input(shapefile, info = FALSE)
if(!is.null(mosaic)){
if(is.null(basemap)){
downsample <- find_aggrfact(mosaic, max_pixels = max_pixels)
if(downsample > 0){
mosaic <- mosaic_aggregate(mosaic, pct = round(100 / downsample))
}
nlyrs <- terra::nlyr(mosaic)
if(nlyrs > 2){
map <-
mapview::viewRGB(
x = as(mosaic, "Raster"),
layer.name = "base",
r = r,
g = g,
b = b,
na.color = "#00000000",
maxpixels = 5e6
)
} else{
map <-
mapview::mapview() %>%
leafem::addGeoRaster(x = as(mosaic[[1]], "Raster"),
colorOptions = leafem::colorOptions(palette = custom_palette(),
na.color = "transparent"))
}
} else{
map <- basemap
}
edited <- mapedit::editFeatures(shapefile |> sf::st_transform(crs = 4326), map)
} else{
edited <- mapedit::editFeatures(shapefile)
}
return(edited)
}
#' Extract geometric measures from a shapefile object
#'
#' `shapefile_measures()` calculates key geometric measures such as the number
#' of points, area, perimeter, width, height, and centroid coordinates for a
#' given shapefile (polygon) object.
#'
#' @param shapefile An `sf` object representing the shapefile. It should contain
#' polygonal geometries for which the measures will be calculated.
#' @param n An integer specifying the number of polygons to process. If `NULL`,
#' all polygons are considered.
#' @return A modified `sf` object with added columns for:
#' - `xcoord`: The x-coordinate of the centroid.
#' - `ycoord`: The y-coordinate of the centroid.
#' - `area`: The area of the polygon (in square units).
#' - `perimeter`: The perimeter of the polygon (in linear units).
#' - `width`: The calculated width based on sequential distances between points.
#' The result will only be accurate if the polygon is rectangular.
#' - `height`: The calculated height based on sequential distances between points.
#' The result will only be accurate if the polygon is rectangular.
#'
#' @details
#' This function processes a single or multi-polygon `sf` object and computes
#' geometric properties. It calculates distances between points, extracts the
#' centroid coordinates, and computes the area and perimeter of the polygons.
#' The width and height are derived from sequential distances between points.
#'
#' @export
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#'
#' path_shp <- paste0(image_pliman(), "/soy_shape.rds")
#' shp <- shapefile_input(path_shp)
#' shapefile_measures(shp)
#' }
#'
#'
shapefile_measures <- function(shapefile, n = NULL) {
if (inherits(shapefile, "list")) {
shapefile <- shapefile_input(shapefile, info = FALSE)
}
if(!is.null(n)){
shapefile <- shapefile |> dplyr::slice(1:n)
}
results <- lapply(1:nrow(shapefile), function(i) {
# Extract points from the current geometry
geom <- shapefile[i, ]$geometry
if(nrow(geom[[1]][[1]]) == 5){
points <- sf::st_cast(geom, "POINT")
# Calculate pairwise distances between points
dists <- suppressWarnings(as.matrix(sf::st_distance(points)))
# Extract width and height
width <- as.numeric(round(dists[[4]], 3))
height <- as.numeric(round(dists[[2]], 3))
c(width, height)
} else{
c(NA, NA)
}
})
wh <- do.call(rbind, results)
# Calculate the centroid and add measurements
coords <- suppressWarnings(sf::st_centroid(shapefile))|> sf::st_coordinates()
measures <-
shapefile |>
dplyr::mutate(
xcoord = coords[, 1],
ycoord = coords[, 2],
area = as.numeric(sf::st_area(shapefile)),
perimeter = rcpp_st_perimeter(as.list(sf::st_geometry(shapefile))),
width = wh[, 1],
height = wh[, 2],
.before = geometry
)
return(measures)
}
#' Interpolate values at specific points based on coordinates and a target variable
#'
#' This function interpolates values at specified points using x, y coordinates and a target variable
#' from a shapefile. It supports "Kriging" and "Tps" interpolation methods.
#'
#' @param shapefile An sf object containing the x, y, and target variable (z)
#' columns. It is highly recommended to use `shapefile_measures()` to obtain
#' this data.
#' @param z A string specifying the name of the column in the shapefile that
#' contains the target variable to be interpolated.
#' @param x A string specifying the name of the column containing x-coordinates.
#' Default is 'x'.
#' @param y A string specifying the name of the column containing y-coordinates.
#' Default is 'y'.
#' @param interpolation A character vector specifying the interpolation method.
#' Options are "Kriging" or "Tps".
#' @param verbose Logical; if TRUE, progress messages will be displayed.
#'
#' @return A vector of interpolated values at the specified points.
#' @export
shapefile_interpolate <- function(shapefile,
z,
x = 'x',
y = 'y',
interpolation = c("Kriging", "Tps"),
verbose = FALSE) {
check_and_install_package("fields")
# Validate shapefile input
if (!all(c(x, y, z) %in% names(shapefile))) {
stop("The shapefile must contain the specified x, y, and z columns")
}
# Extract coordinates and values from shapefile object
xy <- cbind(shapefile[[x]], shapefile[[y]])
values <- shapefile[[z]] # The target variable to be interpolated
if (verbose){
message("Interpolating the points using ", interpolation[[1]], "...")
}
# Perform interpolation
if (interpolation[[1]] == "Kriging") {
fit <- suppressMessages(suppressWarnings(fields::Krig(xy, values, aRange = 20)))
} else if (interpolation[[1]] == "Tps") {
fit <- suppressMessages(suppressWarnings(fields::Tps(xy, values)))
} else {
stop("Invalid interpolation method. Choose 'Kriging' or 'Tps'.")
}
return(fit)
}
#' Generate a spatial surface plot based on interpolated values
#'
#' This function creates a surface plot from an interpolated spatial model, with options to customize
#' plot appearance, grid resolution, and color palette.
#'
#' @param model An interpolated spatial object (e.g., from `shapefile_interpolate()`) containing the data for plotting.
#' @param curve Logical; if TRUE, a contour plot is generated (`type = "C"`), otherwise an image plot (`type = "I"`). Default is TRUE.
#' @param nx Integer; the number of grid cells in the x-direction. Default is 300.
#' @param ny Integer; the number of grid cells in the y-direction. Default is 300.
#' @param xlab Character; label for the x-axis. Default is "Longitude (UTM)".
#' @param ylab Character; label for the y-axis. Default is "Latitude (UTM)".
#' @param col A color palette function for the surface plot. Default is a custom palette from dark red to yellow to forest green.
#' @param ... Additional parameters to pass to `fields::surface`.
#'
#' @return A surface plot showing spatially interpolated data.
#' @export
shapefile_surface <- function(model,
curve = TRUE,
nx = 300,
ny = 300,
xlab = "Longitude (UTM)",
ylab = "Latitude (UTM)",
col = custom_palette(c("darkred", "yellow", "forestgreen"), n = 100),
...) {
check_and_install_package("fields")
# Generate the surface plot
fields::surface(model,
type = ifelse(curve, "C", "I"), # "C" for contour, "I" for image plot
nx = nx,
ny = ny,
xlab = xlab,
ylab = ylab,
col = col,
...)
}
check_cols_shp <- function(shpimp){
if(!"unique_id" %in% colnames(shpimp)){
shpimp <- shpimp |> dplyr::mutate(unique_id = dplyr::row_number())
}
if(!"block" %in% colnames(shpimp)){
shpimp <- shpimp |> dplyr::mutate(block = "B01")
}
if(!"plot_id" %in% colnames(shpimp)){
shpimp <- shpimp |> dplyr::mutate(plot_id = paste0("P", leading_zeros(1:nrow(shpimp), 3)))
}
if(!"row" %in% colnames(shpimp)){
shpimp <- shpimp |> dplyr::mutate(row = 1)
}
if(!"column" %in% colnames(shpimp)){
shpimp <- shpimp |> dplyr::mutate(column = 1)
}
shpimp |> dplyr::relocate(geometry, .after = dplyr::last_col())
}
#' Spatial Operations on Shapefiles
#'
#' These functions perform various spatial operations on two shapefiles, including determining which geometries fall within, outside, touch, cross, overlap, or intersect another geometry. They also include functions for geometric operations such as intersection, difference, and union.
#'
#' @param shp1 An `sf` object representing the first shapefile.
#' @param shp2 An `sf` object representing the second shapefile.
#'
#' @details All functions ensure that the coordinate reference systems (CRS) of both shapefiles are the same before performing operations. If the CRSs are different, `shp2` will be transformed to match the CRS of `shp1`.
#' - `shapefile_within()`: Filters features in `shp1` that are fully within `shp2`.
#' - `shapefile_outside()`: Filters features in `shp1` that are outside or do not overlap `shp2`.
#' - `shapefile_overlaps()`: Filters features in `shp1` that overlap with `shp2`.
#' - `shapefile_touches()`: Filters features in `shp1` that touch the boundary of `shp2`.
#' - `shapefile_crosses()`: Filters features in `shp1` that cross through `shp2`.
#' - `shapefile_intersection()`: Computes the geometric intersection of `shp1` and `shp2`.
#' - `shapefile_difference()`: Computes the geometric difference of `shp1` minus `shp2`.
#' - `shapefile_union()`: Computes the geometric union of `shp1` and `shp2`.
#'
#' @return A filtered `sf` object or the result of the geometric operation.
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#'
#' shp1 <- shapefile_input(paste0(image_pliman(), "/shp1.rds"))
#' shp2 <- shapefile_input(paste0(image_pliman(), "/shp2.rds"))
#' shapefile_view(shp1) + shapefile_view(shp1)
#'
#' # Apply operations
#' shapefile_within(shp1, shp2)
#' shapefile_outside(shp1, shp2)
#' shapefile_overlaps(shp1, shp2)
#' shapefile_touches(shp1, shp2)
#' shapefile_crosses(shp1, shp2)
#' shapefile_intersection(shp1, shp2)
#' shapefile_difference(shp1, shp2)
#' shapefile_union(shp1, shp2)
#' }
#' @name shapefile_operations
#' @export
#'
shapefile_within <- function(shp1, shp2){
if(sf::st_crs(shp1) != sf::st_crs(shp2)){
warning("CRS are different, matching CRS of shp1 to shp2")