-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutils.R
More file actions
2051 lines (1875 loc) · 57.9 KB
/
Copy pathutils.R
File metadata and controls
2051 lines (1875 loc) · 57.9 KB
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
#' @title
#' instantiate a memory cache store for maximum 1 hour
#'
#' @importFrom cachem cache_mem
#'
#' @noRd
m <- cachem::cache_mem(max_age = 3600)
utils::globalVariables(
c(
"allocation_mode_types",
"analog_types",
"api_req_safe",
"area_eic",
"asset_types",
"auction_types",
"business_types",
"category_types",
"classification_types",
"coding_scheme_types",
"contract_types",
"coordinate_system_types",
"currency_types",
"curve_types",
"direction_types",
"doc_status",
"eic_types",
"energy_product_types",
"extract_response",
"fuel_types",
"get_all_allocated_eic",
"get_eiccodes",
"hvdc_mode_types",
"indicator_types",
"m",
"market_product_types",
"message_types",
"object_aggregation_types",
"price_direction_types",
"process_types",
"quality_types",
"reason_code_types",
"rights_types",
"role_types",
"status_types",
"tariff_types",
"there_is_provider",
"timeframe_types",
"TimeSeries.mRID",
"transmission_pair_eic_dict",
"ts_point_position",
"ts_resolution",
"ts_resolution_ok",
"ts_resolution_real_length",
"ts_resolution_requ_length",
"ts_time_interval_start",
"unit_multiplier",
"unit_of_measure_types",
"unit_symbol_types",
"url_posixct_format"
)
)
#' @title
#' Organize list of strings into group
#'
#' @description
#' This function solves a connected components problem where vectors
#' are connected if they share at least one common string.
#' It returns with groups containing the indices of elements.
#'
#' @noRd
grouping_by_common_strings <- function(vector_list) {
n <- length(vector_list)
if (n == 0L) {
return(list())
}
if (n == 1L) {
return(list(1L))
}
# Build an inverted index: string -> vector indices containing that string
string_to_indices <- new.env(hash = TRUE)
for (i in 1L:n) {
unique_strings <- unique(vector_list[[i]])
for (s in unique_strings) {
if (exists(x = s, envir = string_to_indices)) {
string_to_indices[[s]] <- c(string_to_indices[[s]], i)
} else {
string_to_indices[[s]] <- i
}
}
}
# Union-Find with path compression
parent <- 1L:n
find_root <- function(i) {
if (parent[i] != i) {
parent[i] <<- find_root(parent[i])
}
parent[i]
}
union_sets <- function(i, j) {
root_i <- find_root(i)
root_j <- find_root(j)
if (root_i != root_j) {
parent[root_j] <<- root_i
}
}
# For each string, union all vectors that contain it
for (s in ls(string_to_indices)) {
indices <- string_to_indices[[s]]
if (length(indices) > 1L) {
for (k in 2L:length(indices)) {
union_sets(i = indices[1L], j = indices[k])
}
}
}
# Normalize all parents
for (i in 1L:n) {
parent[i] <- find_root(i)
}
# Group indices by their root parent
base::split(x = 1L:n, f = parent) |>
unname()
}
#' @title
#' Calculate the Number of Children for a Given Nodeset
#'
#' @description
#' iterate through XML all children of a given XML nodeset,
#' and detect if they have children as well or not
#' and finally count the number of detected children
#'
#' @noRd
number_of_children <- function(nodeset) {
have_no_child <- purrr::map_lgl(
xml2::xml_children(nodeset),
~ xml2::xml_children(.x) |>
unlist(recursive = FALSE) |>
is.null()
)
sum(have_no_child == FALSE)
}
#' @title
#' Extract the Contents of XML nodesets
#'
#' @description
#' extract the content of the provided XML nodesets,
#' and compose a list of data.tables from them
#'
#' @noRd
extract_nodesets <- function(nodesets, prefix = NULL) {
purrr::map(
nodesets,
\(nodeset) {
# convert the branches into a named vector
named_vect <- nodeset |>
xml2::as_list() |>
unlist(recursive = TRUE)
# convert the named_vect from NULL to NA if there is no value in it
if (is.null(named_vect)) named_vect <- NA_character_
# adjust element names
names(named_vect) <- stringr::str_c(
prefix,
xml2::xml_name(nodeset),
names(named_vect),
sep = "."
)
# extract unique vector element names
unique_names <- names(named_vect) |>
unique()
# compose a table from the elements and
# adjust column names accordingly
purrr::map(
unique_names,
~ named_vect[names(named_vect) == .x]
) |>
data.table::as.data.table() |>
stats::setNames(nm = unique_names)
}
)
}
#' @title
#' Extract Data From an XML Document into Tabular Format
#'
#' @description
#' Mine data from all levels (leaf,twig, branch)
#' of an XML document and convert them to a tibble
#'
#' @noRd
extract_leaf_twig_branch <- function(nodesets) {
# detect the number of children for each element
children_of_nodes <- purrr::map_int(nodesets, number_of_children)
# compose a sub table from first level data
first_level_tbl <- nodesets[children_of_nodes == 0L] |>
extract_nodesets() |>
data.table::as.data.table()
second_level_tbl <- nodesets[children_of_nodes > 0L] |>
purrr::map(
\(scnd_ns) {
# define an empty list
compound_tbls <- list()
# extract child nodesets
my_xml_paths <- xml2::xml_contents(scnd_ns) |>
xml2::xml_path()
child_nodesets <- purrr::map(
my_xml_paths,
~ xml2::xml_find_all(x = scnd_ns, xpath = .x)
)
# convert the childless child nodes into a table
ch_children_of_nodes <- purrr::map_int(
child_nodesets,
number_of_children
)
compound_tbls[[1L]] <- extract_nodesets(
nodesets = child_nodesets[ch_children_of_nodes == 0L],
prefix = xml2::xml_name(scnd_ns)
) |>
data.table::as.data.table()
# convert the grandchild nodes into a table
nodeset_tbls <- extract_nodesets(
nodesets = child_nodesets[ch_children_of_nodes > 0L],
prefix = xml2::xml_name(scnd_ns)
)
nodeset_groups <- purrr::map(nodeset_tbls, names) |>
grouping_by_common_strings()
if (length(nodeset_groups) == 1L) {
compound_tbls[[2L]] <- nodeset_tbls |>
data.table::rbindlist(use.names = TRUE, fill = TRUE)
} else {
compound_tbls[[2L]] <- seq_along(nodeset_groups) |>
purrr::map(
~ nodeset_tbls[nodeset_groups[[.x]]] |>
data.table::rbindlist(use.names = TRUE, fill = TRUE)
) |>
dplyr::bind_cols()
}
# column-wise append the tables
compound_tbl <- compound_tbls |>
purrr::compact() |>
dplyr::bind_cols()
compound_tbl
}
) |>
data.table::rbindlist(use.names = TRUE, fill = TRUE)
list(first_level_tbl, second_level_tbl) |>
purrr::compact() |>
dplyr::bind_cols() |>
tibble::tibble()
}
#' @title
#' Converts Extracted Data into a Tidy or a Nested format
#'
#' @description
#' In tidy format each record has a calculated 'ts_point_dt_start' timestamp.
#' In nested format each submitted time unit record contains a nested table
#' with detailed data series
#'
#' @noRd
tidy_or_not <- function(tbl, tidy_output = FALSE) {
# detect if there is any 'bid_ts_' column names
have_bid_ts_col <- stringr::str_detect(
string = names(tbl),
pattern = "^bid_ts_"
) |>
any()
# convert the original 'bid_ts_' column names to 'ts_'
if (have_bid_ts_col) {
names(tbl) <- names(tbl) |>
stringr::str_replace_all(
pattern = "^bid_ts_",
replacement = "ts_"
)
}
# extract the ts_point_ column names
ts_point_cols <- stringr::str_subset(
string = names(tbl),
pattern = "^ts_point_"
)
# extract the ts_reason_ column names
ts_reason_cols <- stringr::str_subset(
string = names(tbl),
pattern = "^ts_reason_"
)
# if there is no ts_point_ column
if (length(ts_point_cols) == 0L) {
# convert the original 'bid_ts_' column names back
if (have_bid_ts_col) {
names(tbl) <- names(tbl) |>
stringr::str_replace_all(
pattern = "^ts_",
replacement = "bid_ts_"
)
}
return(tbl)
}
# extract curve type from tbl
curve_type <- base::subset(
x = tbl,
select = stringr::str_match_all(
string = names(tbl),
pattern = ".*curve_type$"
) |>
unlist()
) |>
unlist() |>
unique()
# select the group by columns
group_cols <- base::setdiff(
x = names(tbl),
y = c(ts_point_cols, ts_reason_cols)
)
# calculate 'by' values which will be used to calculate
# the 'ts_point_dt_start' values
tbl <- tbl |>
dplyr::mutate(
by = data.table::fcase(
ts_resolution == "PT4S", "4 sec",
ts_resolution == "PT1M", "1 min",
ts_resolution == "PT15M", "15 mins",
ts_resolution == "PT30M", "30 mins",
ts_resolution == "PT60M", "1 hour",
ts_resolution == "P1D", "1 DSTday",
ts_resolution == "P7D", "7 DSTdays",
ts_resolution == "P1M", "1 month",
ts_resolution == "P1Y", "1 year",
default = "n/a"
)
)
# if curve_type not defined or 'A01', then
if (is.null(curve_type) || curve_type == "A01") {
# do nothing in this case
Sys.sleep(time = 0)
# if curve_type is 'A03', then
} else if (curve_type == "A03") {
ts_resolution_requ_length <- ts_resolution_real_length <- ts_mrid <- NULL
ts_resolution_ok <- ts_time_interval_start <- ts_time_interval_end <- NULL
# calculate 'ts_resolution_requ_length', 'ts_resolution_real_length'
# and 'ts_resolution_ok' values
tbl <- tbl |>
dplyr::group_by(dplyr::across(tidyselect::all_of(group_cols))) |>
dplyr::mutate(
ts_resolution_requ_length =
(max(ts_time_interval_end) - min(ts_time_interval_start)) /
lubridate::duration(by),
ts_resolution_real_length = dplyr::n(),
ts_resolution_ok =
ts_resolution_real_length == ts_resolution_requ_length
) |>
dplyr::ungroup()
# filter on those periods which have missing timeseries
# data points (ts_point_position)
tbl_adj <- base::subset(x = tbl, subset = !ts_resolution_ok)
# check if there is any need to adjust the timeseries data points
if (nrow(tbl_adj) > 0L) {
# remove the to be adjusted rows from the base 'tbl'
# or in other words stash the records with 'ok' resolution
tbl <- base::subset(x = tbl, subset = ts_resolution_ok)
# create a frame table to adjust the timeseries data points
frame_tbl <- base::subset(
x = tbl_adj,
select = c(
ts_time_interval_start,
ts_time_interval_end,
ts_resolution_requ_length,
ts_resolution,
ts_mrid
)
) |>
unique() |>
purrr::pmap(
~ tibble::tibble(
ts_time_interval_start = ..1,
ts_time_interval_end = ..2,
ts_point_position = seq.int(from = 1, to = ..3),
ts_resolution = ..4,
ts_mrid = ..5
)
) |>
data.table::rbindlist(use.names = TRUE, fill = TRUE)
# full join the adjusted timeseries data points with the frame table
tbl_adj <- data.table::merge.data.table(
x = tbl_adj,
y = frame_tbl,
by = c(
"ts_time_interval_start",
"ts_time_interval_end",
"ts_point_position",
"ts_resolution",
"ts_mrid"
),
all = TRUE
) |>
data.table::as.data.table()
# fill the missing values with the last observation carry forward method
group_cols_adj <- c("ts_resolution", "ts_mrid")
tbl_adj <- tbl_adj |>
dplyr::group_by(dplyr::across(tidyselect::all_of(group_cols_adj))) |>
tidyr::fill(dplyr::everything()) |>
dplyr::ungroup()
# append the adjusted timeseries data points to the 'ok' timeseries data
tbl <- list(tbl, tbl_adj) |>
data.table::rbindlist(use.names = TRUE, fill = TRUE)
data.table::setorderv(
x = tbl,
cols = c(
"ts_time_interval_start",
"ts_time_interval_end",
"ts_point_position"
)
)
}
} else {
# hints: https://eepublicdownloads.entsoe.eu/clean-documents/EDI/
# Library/cim_based/
# Introduction_of_different_Timeseries_possibilities__curvetypes
# __with_ENTSO-E_electronic_document_v1.4.pdf
cli::cli_abort("The curve type is not defined, but {curve_type}!")
}
# calculate the 'ts_point_dt_start' values accordingly
tbl <- tbl |>
base::subset(
subset = !is.na(ts_time_interval_start) & !is.na(ts_point_position)
) |>
dplyr::group_by(dplyr::across(tidyselect::all_of(group_cols))) |>
dplyr::mutate(
ts_point_dt_start = seq.POSIXt(
from = min(ts_time_interval_start),
length.out = max(ts_point_position),
by = unique(by),
)[ts_point_position] |> # handle the unusual case of any missing period
as.POSIXct(tz = "UTC")
) |>
dplyr::ungroup()
# if tidy output is needed, then
if (tidy_output == TRUE) {
# set the not_needed_cols
not_needed_cols <- c(
"ts_point_position", "by", "ts_resolution_requ_length",
"ts_resolution_real_length", "ts_resolution_ok"
)
# remove the not needed columns
not_needed_cols <- base::intersect(
x = not_needed_cols,
y = names(tbl)
)
tbl[not_needed_cols] <- list(NULL)
} else {
# set the not_needed_cols
not_needed_cols <- c(
"ts_point_dt_start", "by", "ts_resolution_requ_length",
"ts_resolution_real_length", "ts_resolution_ok"
)
# remove the not needed columns
not_needed_cols <- base::intersect(
x = not_needed_cols,
y = names(tbl)
)
tbl[not_needed_cols] <- list(NULL)
# nest the timeseries data points
tbl <- tidyr::nest(
tbl,
ts_point = tidyselect::all_of(ts_point_cols)
)
}
# convert the original 'bid_ts_' column names back
if (have_bid_ts_col) {
names(tbl) <- names(tbl) |>
stringr::str_replace_all(
pattern = "^ts_",
replacement = "bid_ts_"
)
}
# return
tbl
}
#' @title
#' calculate offset URLs
#'
#' @noRd
calc_offset_urls <- function(reason, query_string) {
# extract the number of the allowed documents
docs_allowed <- stringr::str_extract(
string = reason,
pattern = "allowed maximum \\([0-9]{1,8}\\)"
) |>
stringr::str_extract(pattern = "[0-9]{1,8}") |>
as.integer()
if (is.na(docs_allowed)) {
docs_allowed <- stringr::str_extract(
string = reason,
pattern = "allowed:\\s+[0-9]{1,8}"
) |>
stringr::str_extract(pattern = "[0-9]{1,8}") |>
as.integer()
}
# extract the number of the requested documents
docs_requested <- stringr::str_extract(
string = reason,
pattern = "number of instances \\([0-9]{1,8}\\)"
) |>
stringr::str_extract(pattern = "[0-9]{1,8}") |>
as.integer()
if (is.na(docs_requested)) {
docs_requested <- stringr::str_extract(
string = reason,
pattern = "requested:\\s[0-9]{1,8}"
) |>
stringr::str_extract(pattern = "[0-9]{1,8}") |>
as.integer()
}
# calculate how many offset round is needed
all_offset_nr <- docs_requested %/% docs_allowed +
ceiling(docs_requested %% docs_allowed / docs_allowed)
all_offset_seq <- (seq(all_offset_nr) - 1L) * docs_allowed
# recompose offset URLs
cli::cli_alert_info("*** The request has been rephrased. ***")
query_string <- query_string |>
gsub(pattern = "\\&offset=[0-9]+", replacement = "")
paste0(query_string, "&offset=", all_offset_seq)
}
#' @title
#' read XML content from a zip compressed file
#'
#' @noRd
read_zipped_xml <- function(temp_file_path) {
# safely decompress zip file into several files on disk
unzip_safe <- purrr::safely(utils::unzip)
unzipped_files <- unzip_safe(
zipfile = temp_file_path,
overwrite = TRUE,
exdir = fs::path_dir(temp_file_path)
)
# read the xml content from each the decompressed files
en_cont_list <- unzipped_files$result |>
purrr::map(~ {
xml_content <- xml2::read_xml(.x)
cli::cli_alert_success("{.x} has been read in")
return(xml_content)
})
# return with the xml content list
en_cont_list
}
#' @title
#' call request against the ENTSO-E API and converts the response into xml
#'
#' @noRd
api_req <- function(
api_scheme = "https://",
api_domain = "web-api.tp.entsoe.eu/",
api_name = "api?",
query_string = NULL,
security_token = NULL
) {
checkmate::assert_string(query_string)
checkmate::assert_string(security_token)
url <- paste0(
api_scheme, api_domain, api_name, query_string, "&securityToken="
)
cli::cli_h1("API call")
cli::cli_alert("{url}<...>")
# retrieve data from the API
req <- httr2::request(base_url = paste0(url, security_token)) |>
httr2::req_method(method = "GET") |>
httr2::req_verbose(
header_req = FALSE,
header_resp = TRUE,
body_req = FALSE,
body_resp = FALSE
) |>
httr2::req_timeout(seconds = 60)
resp <- "No response."
resp <- req_perform_safe(req = req)
if (is.null(x = resp$error)) {
result_obj <- resp$result
cli::cli_alert_success("response has arrived")
# if the get request is successful, then ...
if (httr2::resp_status(resp = result_obj) == 200) {
# retrieve content-type from response headers
rhct <- httr2::resp_content_type(resp = result_obj)
expt_zip <- c(
"application/zip",
"application/octet-stream"
)
expt_xml <- c(
"text/xml",
"application/xml"
)
# if the request is a zip file, then ...
if (rhct %in% expt_zip) {
# save raw data to disk from memory
temp_file_path <- tempfile(fileext = ".zip")
writeBin(
object = httr2::resp_body_raw(resp = result_obj),
con = temp_file_path
)
# read the xml content from each the decompressed files
en_cont_list <- read_zipped_xml(temp_file_path = temp_file_path)
# return with the xml content list
en_cont_list
} else if (rhct %in% expt_xml) {
# read the xml content from the response and return
result_obj |>
httr2::resp_body_xml(encoding = "UTF-8")
} else {
cli::cli_abort(
"Not known response content-type: {result_obj$headers$`content-type`}"
)
}
}
} else {
error_obj <- resp$error
# retrieve content-type from response headers
if (isTRUE(error_obj$status == 503)) cli::cli_abort(error_obj$message)
if (is.null(error_obj$resp)) cli::cli_abort(error_obj$parent$message)
rhct <- httr2::resp_content_type(resp = error_obj$resp)
expt_html <- c("text/html")
expt_xml <- c("text/xml", "application/xml")
expt_json <- c("text/xml", "application/json")
if (rhct %in% expt_html) {
# extract reason code and text
response_reason_code <- httr2::resp_status(error_obj$resp)
response_reason_text <- error_obj$resp |>
httr2::resp_body_html(encoding = "utf-8") |>
xmlconvert::xml_to_list() |>
purrr::pluck("body")
sprintf("/s: %s", response_reason_code, response_reason_text) |>
cli::cli_abort()
}
if (rhct %in% expt_xml) {
# extract reason from reason text
response_reason <- error_obj$resp |>
httr2::resp_body_xml(encoding = "utf-8") |>
xmlconvert::xml_to_list() |>
purrr::pluck("Reason")
if (!is.list(response_reason) ||
!identical(names(response_reason), c("code", "text"))) {
cli::cli_abort(
paste(
"{httr2::resp_status(error_obj$resp)}:",
"{httr2::resp_status_desc(error_obj$resp)}"
)
)
}
if (response_reason$code == 999) {
# check if query offsetting is forbidden
offset_forbidden <- stringr::str_detect(
string = query_string,
pattern = sprintf(
fmt = "(%s|%s|%s|%s|%s|%s)",
"(?=.*documentType=A63)(?=.*businessType=A(46|85))",
"(?=.*documentType=A65)(?=.*businessType=A85)",
"(?=.*documentType=B09)(?=.*StorageType=archive)",
"documentType=A91",
"documentType=A92",
"(?=.*documentType=A94)(?=.*auction.Type=A02)"
)
)
# if offset usage is not forbidden, then ...
if (isFALSE(offset_forbidden)) {
# check if offset usage needed
offset_needed <- stringr::str_detect(
string = response_reason$text,
pattern = "exceeds the allowed maximum"
)
# if offset usage needed and not forbidden, then ...
if (isTRUE(offset_needed)) {
# calculate offset URLs
offset_query_strings <- calc_offset_urls(
reason = response_reason$text,
query_string = query_string
)
# recursively call the api_req() function itself
en_cont_list <- offset_query_strings |>
purrr::map(
~ api_req(
query_string = .x,
security_token = security_token
)
)
return(en_cont_list)
}
}
cli::cli_abort(paste(response_reason, collapse = "\n"))
} else {
cli::cli_abort("{response_reason$code}: {response_reason$text}")
}
}
if (rhct %in% expt_json) {
# extract reason from reason text
response_reason <- error_obj$resp |>
httr2::resp_body_json(encoding = "utf-8") |>
purrr::pluck("uuAppErrorMap", "URI_FORMAT_ERROR")
cli::cli_abort(response_reason$message)
}
}
}
#' @title
#' safely call api_req() function
#'
#' @noRd
api_req_safe <- purrr::safely(api_req)
#' @title
#' safely call req_perform() function
#'
#' @noRd
req_perform_safe <- purrr::safely(httr2::req_perform)
#' @title
#' converts the given POSIXct or character timestamp into the acceptable format
#'
#' @noRd
url_posixct_format <- function(x) {
if (is.null(x)) {
y <- NULL
} else if (inherits(x = x, what = "POSIXct")) {
y <- strftime(x = x, format = "%Y%m%d%H%M", tz = "UTC", usetz = FALSE)
} else if (inherits(x = x, what = "character")) {
y <- lubridate::parse_date_time(
x = x,
orders = c(
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y.%m.%d %H:%M:%S",
"%Y.%m.%d %H:%M",
"%Y.%m.%d",
"%Y%m%d%H%M%S",
"%Y%m%d%H%M",
"%Y%m%d"
),
tz = "UTC",
quiet = TRUE
) |>
strftime(format = "%Y%m%d%H%M", tz = "UTC", usetz = FALSE)
if (is.na(y)) {
cli::cli_abort(
paste(
"Only the class POSIXct or '%Y-%m-%d %H:%M:%S' formatted text",
"are supported by the converter."
)
)
} else {
cli::cli_alert_warning("The {x} value has been interpreted as UTC!")
}
} else {
cli::cli_abort("The argument is not in an acceptable timestamp format!")
}
y
}
#' @title
#' downloads approved Energy Identification Codes
#'
#' @description
#' from ENTSO-E Transparency Platform under link "f"
#'
#' @noRd
get_eiccodes <- function(
base_url = "https://eepublicdownloads.blob.core.windows.net/cio-lio/csv/",
f = NA_character_
) {
# compose the complete url
complete_url <- paste0(base_url, f)
# reading input file into a character vector
# and replacing erroneous semicolons to commas
# unfortunately there is no general rule for that,
# hence it must be set manually!!
readlines_safe <- purrr::safely(readLines, quiet = TRUE)
content <- suppressWarnings(
expr = readlines_safe(
con = complete_url, encoding = "UTF-8"
)
)
if (is.null(content$error)) {
lns <- content$result |>
stringr::str_replace_all(
pattern = "tutkimustehdas;\\sImatra",
replacement = "tutkimustehdas, Imatra"
) |>
stringr::str_replace_all(
pattern = "; S\\.L\\.;",
replacement = ", S.L.;"
) |>
stringr::str_replace_all(
pattern = "\\$amp;",
replacement = "&"
)
# reading lines as they would be a csv
eiccodes <- data.table::fread(
text = lns,
sep = ";",
na.strings = c("", "n / a", "n/a", "N/A", "-", "-------", "."),
encoding = "UTF-8"
)
# trimming character columns
eiccodes <- eiccodes |>
purrr::map(~ {
if (is.character(.x)) {
utf8::utf8_encode(x = .x) |>
trimws(which = "both")
} else {
.x
}
}) |>
tibble::as_tibble()
# return
eiccodes
} else {
cli::cli_abort(content$error$message)
}
}
#' @title
#' downloads all allocated Energy Identification Codes
#'
#' @description
#' from https://eepublicdownloads.blob.core.windows.net
#'
#' @noRd
get_all_allocated_eic <- function() {
# define those variables as NULL which are used under non-standard evaluation
doc_status_value <- NULL
# set the link of the xml file
base_url <- "https://eepublicdownloads.blob.core.windows.net"
# retrieve data from the API
req <- httr2::request(base_url = base_url) |>
httr2::req_url_path_append("cio-lio") |>
httr2::req_url_path_append("xml") |>
httr2::req_url_path_append("allocated-eic-codes.xml") |>
httr2::req_method(method = "GET") |>
httr2::req_progress() |>
httr2::req_verbose(
header_req = FALSE,
header_resp = TRUE,
body_req = FALSE,
body_resp = FALSE
) |>
httr2::req_timeout(seconds = 120) |>
httr2::req_retry(
max_tries = 3L,
backoff = \(resp) 10
)
resp <- "No response."
resp <- req_perform_safe(req = req)
if (is.null(resp$error)) {
cli::cli_alert_success("response has arrived")
# read the xml content from each the decompressed files
en_cont <- httr2::resp_body_raw(resp = resp$result) |>
rawToChar() |>
xml2::as_xml_document()
# convert XML to table
result_tbl <- tryCatch(
expr = {
nodesets <- xml2::xml_contents(x = en_cont)
# detect the number of children for each element
children_of_nodes <- purrr::map_int(nodesets, number_of_children)
# compose a sub table from the first level data
first_level_tbl <- nodesets[children_of_nodes == 0L] |>
extract_nodesets() |>
data.table::as.data.table()
# remove the not needed columns from the first_level_tbl
not_needed_patt <- paste(
"^(sender|receiver)_MarketParticipant\\.",
"^mRID$|^type$",
sep = "|"
)
first_level_tbl <- first_level_tbl |>
dplyr::select(!dplyr::matches(match = not_needed_patt))
# compose a sub table from the second level data
second_level_length <- nodesets[children_of_nodes > 0L] |>
length()
prb_envir2 <- parent.frame()
cli::cli_progress_bar(
name = "converting",
total = second_level_length,
.envir = prb_envir2
)
second_level_tbl <- nodesets[children_of_nodes > 0L] |>
purrr::imap(
\(scnd_ns, idx) {
cli::cli_progress_update(.envir = prb_envir2)
# extract as named list
nodeset_list <- xmlconvert::xml_to_list(
xml = scnd_ns,
convert.types = FALSE
)
# collapse duplicated elements
if (anyDuplicated(names(nodeset_list))) {
dupl_lgl <- names(nodeset_list) |>
duplicated()
dupl_col <- names(nodeset_list)[dupl_lgl] |>
unique()
for (col in dupl_col) {
indices <- which(names(nodeset_list) == col)
first_idx <- indices[[1L]]
rest_idx <- indices[-1L]