forked from e-sensing/sits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_data.R
833 lines (819 loc) · 29 KB
/
api_data.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
#' @title Dispatch function to get time series from data cubes and cloud
#' services
#' @name .data_get_ts
#' @author Gilberto Camara
#' @keywords internal
#' @noRd
#' @param cube Data cube from where data is to be retrieved.
#' @param samples Samples to be retrieved.
#' @param crs A coordinate reference system of samples.
#' The provided crs could be a character
#' (e.g, "EPSG:4326" or "WGS84" or a proj4string), or a
#' a numeric with the EPSG code (e.g. 4326).
#' This parameter only works for 'csv' or data.frame'
#' samples. Default is 4326.
#' @param bands Bands to be retrieved (optional).
#' @param impute_fn Imputation function to remove NA.
#' @param multicores Number of threads to process the time series.
#' @param progress A logical value indicating if a progress bar
#' should be shown. Default is \code{FALSE}.
#'
#' @return A tibble with a set of time series retrieved
#' from a data cube.
#'
.data_get_ts <- function(cube,
samples, ...,
bands,
impute_fn,
multicores,
progress) {
# Dispatch
UseMethod(".data_get_ts", cube)
}
#' @name .data_get_ts
#' @keywords internal
#' @noRd
#' @export
.data_get_ts.raster_cube <- function(cube,
samples, ...,
bands,
impute_fn,
multicores,
progress) {
# Pre-condition
.check_cube_bands(cube, bands = bands)
# Is the cloud band available?
cld_band <- .source_cloud()
if (cld_band %in% bands) {
bands <- bands[bands != cld_band]
} else {
cld_band <- NULL
}
if (.cube_is_base(cube)) {
bands <- setdiff(bands, .cube_bands(.cube_base_info(cube)))
}
# define parallelization strategy
# find block size
rast <- .raster_open_rast(.tile_path(cube))
block <- .raster_file_blocksize(rast)
# 1st case - split samples by tiles
if ((.raster_nrows(rast) == block[["nrows"]] &&
.raster_ncols(rast) == block[["ncols"]]) ||
inherits(cube, "dem_cube")) {
# split samples by bands and tile
ts_tbl <- .data_by_tile(
cube = cube,
samples = samples,
bands = bands,
impute_fn = impute_fn,
cld_band = cld_band,
multicores = multicores,
progress = progress
)
} else {
# get data by chunks
ts_tbl <- .data_by_chunks(
cube = cube,
samples = samples,
bands = bands,
impute_fn = impute_fn,
cld_band = cld_band,
multicores = multicores,
progress = progress
)
}
if (.has(cube[["base_info"]])) {
# get base info
cube_base <- .cube_base_info(cube)
# get bands
bands_base <- .cube_bands(cube_base)
# extract data
base_tbl <- .data_get_ts(
cube = cube_base,
samples = samples,
bands = bands_base,
impute_fn = impute_fn,
multicores = multicores,
progress = progress
)
# prepare output data
base_tbl <- base_tbl |>
dplyr::select("longitude", "latitude", "time_series") |>
dplyr::rename("base_data" = "time_series")
# joining samples data from cube and base_cube by longitude / latitude
ts_tbl <- dplyr::left_join(
x = ts_tbl,
y = base_tbl,
by = c("longitude", "latitude")
)
# add base class
class(ts_tbl) <- c("sits_base", class(ts_tbl))
}
return(ts_tbl)
}
#' @name .data_get_ts
#' @keywords internal
#' @noRd
#' @export
.data_get_ts.class_cube <- function(cube,
samples, ...,
bands,
crs,
multicores,
progress) {
# Filter only tiles that intersects with samples
cube <- .cube_filter_spatial(
cube = cube,
roi = .point_as_sf(point = .point(x = samples, crs = crs))
)
# pre-condition - check bands
if (is.null(bands)) {
bands <- .cube_bands(cube)
}
.check_cube_bands(cube, bands = bands)
# get cubes timeline
tl <- .cube_timeline(cube)[[1]]
# create tile-band pairs for parallelization
tiles_bands <- tidyr::expand_grid(
tile = .cube_tiles(cube),
band = bands
) |>
purrr::pmap(function(tile, band) {
return(list(tile, band))
})
# set output_dir
output_dir <- tempdir()
if (Sys.getenv("SITS_SAMPLES_CACHE_DIR") != "") {
output_dir <- Sys.getenv("SITS_SAMPLES_CACHE_DIR")
}
# prepare parallelization
.parallel_start(workers = multicores)
on.exit(.parallel_stop(), add = TRUE)
# get the samples in parallel using tile-band combination
samples_tiles_bands <- .parallel_map(
tiles_bands,
function(tile_band) {
# select tile and band
tile_id <- tile_band[[1]]
band <- tile_band[[2]]
tile <- .select_raster_cube(cube, bands = band, tiles = tile_id)
# create a hash to store temporary samples file
hash_bundle <- digest::digest(list(tile, samples), algo = "md5")
filename <- .file_path(
"samples", hash_bundle,
ext = ".rds",
output_dir = output_dir
)
# does the file exist?
if (file.exists(filename)) {
tryCatch(
{ # ensure that the file is not corrupted
timeseries <- readRDS(filename)
return(timeseries)
},
error = function(e) {
unlink(filename)
gc()
}
)
}
# get XY
xy_tb <- .proj_from_latlong(
longitude = samples[["longitude"]],
latitude = samples[["latitude"]],
crs = .cube_crs(tile)
)
# join lat-long with XY values in a single tibble
samples <- dplyr::bind_cols(samples, xy_tb)
# filter the points inside the data cube space-time extent
samples <- dplyr::filter(
samples,
.data[["X"]] > tile[["xmin"]],
.data[["X"]] < tile[["xmax"]],
.data[["Y"]] > tile[["ymin"]],
.data[["Y"]] < tile[["ymax"]],
.data[["start_date"]] <= as.Date(tl[[length(tl)]]),
.data[["end_date"]] >= as.Date(tl[[1]])
)
# are there points to be retrieved from the cube?
if (nrow(samples) == 0) {
return(NULL)
}
# create a matrix to extract the values
xy <- matrix(
c(samples[["X"]], samples[["Y"]]),
nrow = nrow(samples),
ncol = 2
)
colnames(xy) <- c("X", "Y")
# build the sits tibble for the storing the points
samples_tbl <- slider::slide_dfr(samples, function(point) {
# get the valid timeline
dates <- .timeline_during(
timeline = tl,
start_date = as.Date(point[["start_date"]]),
end_date = as.Date(point[["end_date"]])
)
sample <- tibble::tibble(
longitude = point[["longitude"]],
latitude = point[["latitude"]],
start_date = dates[[1]],
end_date = dates[[length(dates)]],
label = point[["label"]],
cube = tile[["collection"]],
polygon_id = point[["polygon_id"]]
)
# store them in the sample tibble
sample[["predicted"]] <- list(tibble::tibble(
# from 1 to the number of dates (can be more than one)
from = dates[[1]], to = dates[[length(dates)]]
))
# return valid row of time series
return(sample)
})
ts <- .ts_get_raster_class(
tile = tile,
points = samples_tbl,
band = "class",
xy = xy
)
ts[["tile"]] <- tile_id
ts[["#..id"]] <- seq_len(nrow(ts))
saveRDS(ts, filename)
return(ts)
},
progress = progress
)
# reorganise the samples
ts_tbl <- samples_tiles_bands |>
dplyr::bind_rows() |>
tidyr::unnest("predicted") |>
dplyr::group_by(
.data[["longitude"]], .data[["latitude"]],
.data[["start_date"]], .data[["end_date"]],
.data[["label"]], .data[["cube"]],
.data[["from"]], .data[["to"]], .data[["tile"]],
.data[["#..id"]]
)
# is there a polygon id? This occurs when we have segments
if ("polygon_id" %in% colnames(ts_tbl)) {
ts_tbl <- dplyr::group_by(ts_tbl, .data[["polygon_id"]], .add = TRUE)
}
ts_tbl <- ts_tbl |>
dplyr::summarise(
dplyr::across(
dplyr::all_of(bands), stats::na.omit
)
) |>
dplyr::arrange(.data[["from"]]) |>
dplyr::ungroup() |>
tidyr::nest(
predicted = !!c("from", "to", bands)
) |>
dplyr::select(-c("tile", "#..id"))
# get the first point that intersect more than one tile
# eg sentinel 2 mgrs grid
ts_tbl <- ts_tbl |>
dplyr::group_by(
.data[["longitude"]], .data[["latitude"]],
.data[["start_date"]], .data[["end_date"]],
.data[["label"]], .data[["cube"]]
) |>
dplyr::slice_head(n = 1) |>
dplyr::ungroup()
# recreate hash values
hash_bundle <- purrr::map_chr(tiles_bands, function(tile_band) {
tile_id <- tile_band[[1]]
band <- tile_band[[2]]
tile <- .select_raster_cube(cube, bands = band, tiles = tile_id)
digest::digest(list(tile, samples), algo = "md5")
})
# recreate file names to delete them
# samples will be recycled for each hash_bundle
temp_timeseries <- .file_path(
"samples", hash_bundle,
ext = "rds",
output_dir = output_dir
)
# delete temporary rds
unlink(temp_timeseries)
gc()
# check if data has been retrieved
if (progress) {
.data_check(nrow(samples), nrow(ts_tbl))
}
class(ts_tbl) <- unique(c("predicted", "sits", class(ts_tbl)))
return(ts_tbl)
}
#' @title Check if all points have been retrieved
#' @name .data_check
#' @keywords internal
#' @noRd
#' @param n_rows_input Number of rows in input.
#' @param n_rows_output Number of rows in output.
#'
#' @return No return value, called for side effects.
#'
.data_check <- function(n_rows_input, n_rows_output) {
# Have all input rows being read?
if (n_rows_output == 0) {
message("No points have been retrieved")
return(invisible(FALSE))
}
if (n_rows_output < n_rows_input) {
message("Some points could not be retrieved")
} else {
message("All points have been retrieved")
}
return(invisible(n_rows_input))
}
#' @title Extracts the time series average by polygon.
#' @name .data_avg_polygon
#' @keywords internal
#' @noRd
#' @description This function extracts the average of the automatically
#' generated points for each polygon in a shapefile.
#'
#' @param data A sits tibble with points time series.
#'
#' @return A sits tibble with the average of all points by each polygon.
.data_avg_polygon <- function(data) {
bands <- .samples_bands(data)
columns_to_avg <- c(bands, "latitude", "longitude")
data_avg <- data |>
tidyr::unnest(cols = "time_series") |>
dplyr::group_by(
.data[["Index"]],
.data[["start_date"]],
.data[["end_date"]],
.data[["label"]],
.data[["cube"]],
.data[["polygon_id"]]
) |>
dplyr::summarise(dplyr::across(!!columns_to_avg, function(x) {
mean(x, na.rm = TRUE)
}), .groups = "drop") |>
tidyr::nest("time_series" = c("Index", dplyr::all_of(bands))) |>
dplyr::select(!!colnames(data))
class(data_avg) <- class(data)
return(data_avg)
}
#' @title get time series from data cubes on tile by tile bassis
#' @name .data_by_tile
#' @keywords internal
#' @noRd
#' @param cube Data cube from where data is to be retrieved.
#' @param samples Samples to be retrieved.
#' @param bands Bands to be retrieved (optional).
#' @param impute_fn Imputation function to remove NA.
#' @param cld_band Cloud band
#' @param multicores Number of threads to process the time series.
#' @param progress A logical value indicating if a progress bar
#' should be shown.
.data_by_tile <- function(cube,
samples,
bands,
impute_fn,
cld_band,
multicores,
progress) {
.check_set_caller(".data_by_tile")
# Get cube timeline
tl <- .cube_timeline(cube)[[1]]
# Get tile-band combination
tiles_bands <- .cube_split_tiles_bands(cube = cube, bands = bands)
# Set output_dir
output_dir <- tempdir()
if (Sys.getenv("SITS_SAMPLES_CACHE_DIR") != "") {
output_dir <- Sys.getenv("SITS_SAMPLES_CACHE_DIR")
}
# To avoid open more process than tiles and bands combinations
if (multicores > length(tiles_bands)) {
multicores <- length(tiles_bands)
}
# Prepare parallelization
.parallel_start(workers = multicores)
on.exit(.parallel_stop(), add = TRUE)
# Get the samples in parallel using tile-band combination
samples_tiles_bands <- .parallel_map(tiles_bands, function(tile_band) {
tile_id <- tile_band[[1]]
band <- tile_band[[2]]
tile <- .select_raster_cube(
data = cube,
bands = c(band, cld_band),
tiles = tile_id
)
hash_bundle <- digest::digest(list(tile, samples), algo = "md5")
# File to store the samples
filename <- .file_path(
"samples", hash_bundle,
ext = ".rds",
output_dir = output_dir
)
# Does the file exist?
if (file.exists(filename)) {
tryCatch(
{ # ensure that the file is not corrupted
timeseries <- readRDS(filename)
return(timeseries)
},
error = function(e) {
unlink(filename)
gc()
}
)
}
# get XY
xy_tb <- .proj_from_latlong(
longitude = samples[["longitude"]],
latitude = samples[["latitude"]],
crs = .cube_crs(tile)
)
# join lat-long with XY values in a single tibble
samples <- dplyr::bind_cols(samples, xy_tb)
# filter the points inside the data cube space-time extent
samples <- dplyr::filter(
samples,
.data[["X"]] > tile[["xmin"]],
.data[["X"]] < tile[["xmax"]],
.data[["Y"]] > tile[["ymin"]],
.data[["Y"]] < tile[["ymax"]],
.data[["start_date"]] <= as.Date(tl[length(tl)]),
.data[["end_date"]] >= as.Date(tl[[1]])
)
# are there points to be retrieved from the cube?
if (nrow(samples) == 0) {
return(NULL)
}
# create a matrix to extract the values
xy <- matrix(
c(samples[["X"]], samples[["Y"]]),
nrow = nrow(samples),
ncol = 2
)
colnames(xy) <- c("X", "Y")
# build the sits tibble for the storing the points
samples_tbl <- slider::slide_dfr(samples, function(point) {
# get the valid timeline
dates <- .timeline_during(
timeline = tl,
start_date = as.Date(point[["start_date"]]),
end_date = as.Date(point[["end_date"]])
)
sample <- tibble::tibble(
longitude = point[["longitude"]],
latitude = point[["latitude"]],
start_date = dates[[1]],
end_date = dates[[length(dates)]],
label = point[["label"]],
cube = tile[["collection"]],
polygon_id = point[["polygon_id"]]
)
# store them in the sample tibble
sample[["time_series"]] <- list(tibble::tibble(Index = dates))
# return valid row of time series
return(sample)
})
# extract time series
ts <- .ts_get_raster_data(
tile = tile,
points = samples_tbl,
bands = band,
impute_fn = impute_fn,
xy = xy,
cld_band = cld_band
)
ts[["tile"]] <- tile_id
ts[["#..id"]] <- seq_len(nrow(ts))
saveRDS(ts, filename)
return(ts)
},
progress = progress
)
# bind rows to get a melted tibble of samples
ts_tbl <- dplyr::bind_rows(samples_tiles_bands)
if (!.has_ts(ts_tbl)) {
warning(.conf("messages", ".data_by_tile"),
immediate. = TRUE, call. = FALSE
)
return(.tibble())
}
# reorganise the samples
ts_tbl <- ts_tbl |>
tidyr::unnest("time_series") |>
dplyr::group_by(
.data[["longitude"]], .data[["latitude"]],
.data[["start_date"]], .data[["end_date"]],
.data[["label"]], .data[["cube"]],
.data[["Index"]], .data[["tile"]], .data[["#..id"]]
)
# is there a polygon id? This occurs when we have segments
if ("polygon_id" %in% colnames(ts_tbl)) {
ts_tbl <- dplyr::group_by(ts_tbl, .data[["polygon_id"]], .add = TRUE)
}
# create time series
ts_tbl <- ts_tbl |>
dplyr::reframe(
dplyr::across(dplyr::all_of(bands), stats::na.omit)
) |>
dplyr::arrange(.data[["Index"]]) |>
dplyr::ungroup() |>
tidyr::nest(time_series = !!c("Index", bands)) |>
dplyr::select(-c("tile", "#..id"))
# get the first point that intersect more than one tile
# eg sentinel 2 mgrs grid
ts_tbl <- ts_tbl |>
dplyr::group_by(
.data[["longitude"]], .data[["latitude"]],
.data[["start_date"]], .data[["end_date"]],
.data[["label"]], .data[["cube"]]
) |>
dplyr::slice_head(n = 1) |>
dplyr::ungroup()
# recreate hash values
hash_bundle <- purrr::map_chr(tiles_bands, function(tile_band) {
tile_id <- tile_band[[1]]
band <- tile_band[[2]]
tile <- .select_raster_cube(cube, bands = c(band, cld_band),
tiles = tile_id
)
digest::digest(list(tile, samples), algo = "md5")
})
# recreate file names to delete them
# samples will be recycled for each hash_bundle
temp_timeseries <- .file_path(
"samples", hash_bundle,
ext = "rds",
output_dir = output_dir
)
# delete temporary rds
unlink(temp_timeseries)
gc()
# check if data has been retrieved
if (progress) {
.data_check(nrow(samples), nrow(ts_tbl))
}
if (!inherits(ts_tbl, "sits")) {
class(ts_tbl) <- c("sits", class(ts_tbl))
}
return(ts_tbl)
}
#' @title get time series from data cubes using chunks
#' @name .data_by_tile
#' @keywords internal
#' @noRd
#' @param cube Data cube from where data is to be retrieved.
#' @param samples Samples to be retrieved.
#' @param bands Bands to be retrieved (optional).
#' @param impute_fn Imputation function to remove NA.
#' @param cld_band Cloud band
#' @param multicores Number of threads to process the time series.
#' @param progress A logical value indicating if a progress bar
#' should be shown.
.data_by_chunks <- function(cube,
samples,
bands,
impute_fn,
cld_band,
multicores,
progress) {
# Get cube timeline
tl <- .cube_timeline(cube)[[1]]
# transform sits tibble to sf
samples_sf <- sits_as_sf(samples)
# Get chunks samples
chunks_samples <- .cube_split_chunks_samples(
cube = cube, samples_sf = samples_sf
)
# Set output_dir
output_dir <- tempdir()
if (Sys.getenv("SITS_SAMPLES_CACHE_DIR") != "") {
output_dir <- Sys.getenv("SITS_SAMPLES_CACHE_DIR")
}
# To avoid open more process than chunks and samples combinations
if (multicores > length(chunks_samples)) {
multicores <- length(chunks_samples)
}
# Prepare parallelization
.parallel_start(workers = multicores)
on.exit(.parallel_stop(), add = TRUE)
# Get the samples in parallel using tile-band combination
samples_tiles_bands <- .parallel_map(chunks_samples, function(chunk) {
tile <- .select_raster_cube(
data = cube,
bands = c(bands, cld_band),
tiles = chunk[["tile"]]
)
# Get chunk samples
samples <- chunk[["samples"]][[1]]
hash_bundle <- digest::digest(list(tile, samples), algo = "md5")
# Create a file to store the samples
filename <- .file_path(
"samples", hash_bundle,
ext = ".rds",
output_dir = output_dir
)
# Does the file exist?
if (file.exists(filename)) {
tryCatch(
{ # ensure that the file is not corrupted
timeseries <- readRDS(filename)
return(timeseries)
},
error = function(e) {
unlink(filename)
gc()
}
)
}
# get XY
xy_tb <- .proj_from_latlong(
longitude = samples[["longitude"]],
latitude = samples[["latitude"]],
crs = .cube_crs(tile)
)
# join lat-long with XY values in a single tibble
samples <- dplyr::bind_cols(samples, xy_tb)
# filter the points inside the data cube space-time extent
samples <- dplyr::filter(
samples,
.data[["X"]] > tile[["xmin"]],
.data[["X"]] < tile[["xmax"]],
.data[["Y"]] > tile[["ymin"]],
.data[["Y"]] < tile[["ymax"]],
.data[["start_date"]] <= as.Date(tl[[length(tl)]]),
.data[["end_date"]] >= as.Date(tl[[1]])
)
# are there points to be retrieved from the cube?
if (nrow(samples) == 0) {
return(NULL)
}
# create a matrix to extract the values
xy <- matrix(
c(samples[["X"]], samples[["Y"]]),
nrow = nrow(samples),
ncol = 2
)
colnames(xy) <- c("X", "Y")
# build the sits tibble for the storing the points
samples_tbl <- slider::slide_dfr(samples, function(point) {
# get the valid timeline
dates <- .timeline_during(
timeline = tl,
start_date = as.Date(point[["start_date"]]),
end_date = as.Date(point[["end_date"]])
)
sample <- tibble::tibble(
longitude = point[["longitude"]],
latitude = point[["latitude"]],
start_date = dates[[1]],
end_date = dates[[length(dates)]],
label = point[["label"]],
cube = tile[["collection"]],
polygon_id = point[["polygon_id"]]
)
# store them in the sample tibble
sample[["time_series"]] <- list(tibble::tibble(Index = dates))
# return valid row of time series
return(sample)
})
# extract time series
ts <- .ts_get_raster_data(
tile = tile,
points = samples_tbl,
bands = bands,
impute_fn = impute_fn,
xy = xy,
cld_band = cld_band
)
ts[["tile"]] <- chunk[["tile"]]
ts[["#..id"]] <- seq_len(nrow(ts))
saveRDS(ts, filename)
return(ts)
}, progress = progress)
# bind rows to get a melted tibble of samples
ts_tbl <- dplyr::bind_rows(samples_tiles_bands)
if (!.has_ts(ts_tbl)) {
warning(.conf("messages", ".data_by_chunks"),
immediate. = TRUE, call. = FALSE
)
return(.tibble())
}
# reorganise the samples
ts_tbl <- ts_tbl |>
tidyr::unnest("time_series") |>
dplyr::group_by(
.data[["longitude"]], .data[["latitude"]],
.data[["start_date"]], .data[["end_date"]],
.data[["label"]], .data[["cube"]],
.data[["Index"]], .data[["tile"]], .data[["#..id"]]
)
# is there a polygon id? This occurs when we have segments
if ("polygon_id" %in% colnames(ts_tbl)) {
ts_tbl <- dplyr::group_by(ts_tbl, .data[["polygon_id"]], .add = TRUE)
}
# create time series
ts_tbl <- ts_tbl |>
dplyr::reframe(
dplyr::across(dplyr::all_of(bands), stats::na.omit)
) |>
dplyr::arrange(.data[["Index"]]) |>
dplyr::ungroup() |>
tidyr::nest(time_series = !!c("Index", bands)) |>
dplyr::select(-c("tile", "#..id"))
# get the first point that intersect more than one tile
# eg sentinel 2 mgrs grid
ts_tbl <- ts_tbl |>
dplyr::group_by(
.data[["longitude"]], .data[["latitude"]],
.data[["start_date"]], .data[["end_date"]],
.data[["label"]], .data[["cube"]]
) |>
dplyr::slice_head(n = 1) |>
dplyr::ungroup()
# recreate hash values
hash_bundle <- purrr::map_chr(chunks_samples, function(chunk) {
tile <- .select_raster_cube(
data = cube,
bands = c(bands, cld_band),
tiles = chunk[["tile"]]
)
# Get chunk samples
samples <- chunk[["samples"]][[1]]
digest::digest(list(tile, samples), algo = "md5")
})
# recreate file names to delete them
# samples will be recycled for each hash_bundle
temp_timeseries <- .file_path(
"samples", hash_bundle,
ext = "rds",
output_dir = output_dir
)
# delete temporary rds
unlink(temp_timeseries)
gc()
# check if data has been retrieved
if (progress) {
.data_check(nrow(samples), nrow(ts_tbl))
}
if (!inherits(ts_tbl, "sits")) {
class(ts_tbl) <- c("sits", class(ts_tbl))
}
return(ts_tbl)
}
#' @title get time series from base tiles
#' @name .data_base_tiles
#' @keywords internal
#' @noRd
#' @param cube Data cube from where data is to be retrieved.
#' @param samples Samples to be retrieved.
#' @param ts_time Time series from multitemporal bands
#'
#' @return Time series information with base tile data
#'
.data_base_tiles <- function(cube, samples) {
# retrieve values from samples
#
# read each tile
samples <- slider::slide_dfr(cube, function(tile){
# get XY
xy_tb <- .proj_from_latlong(
longitude = samples[["longitude"]],
latitude = samples[["latitude"]],
crs = .cube_crs(tile)
)
# join lat-long with XY values in a single tibble
samples <- dplyr::bind_cols(samples, xy_tb)
# filter the points inside the data cube space-time extent
samples <- dplyr::filter(
samples,
.data[["X"]] > tile[["xmin"]],
.data[["X"]] < tile[["xmax"]],
.data[["Y"]] > tile[["ymin"]],
.data[["Y"]] < tile[["ymax"]]
)
# are there points to be retrieved from the cube?
if (nrow(samples) == 0) {
return(NULL)
}
# create a matrix to extract the values
xy <- matrix(
c(samples[["X"]], samples[["Y"]]),
nrow = nrow(samples),
ncol = 2
)
colnames(xy) <- c("X", "Y")
# get the values of the time series as matrix
base_bands <- .tile_base_bands(tile)
samples <- purrr::map_dbl(base_bands, function(band){
values_base_band <- .tile_base_extract(
tile = tile,
band = band,
xy = xy
)
samples[[band]] <- values_base_band
return(samples)
})
return(samples)
})
}