Skip to content

Commit 1463402

Browse files
authored
NCDF4 support (#23)
Adds support for downloading files as NCDF4, converting them to daily files, and preparing them as input for model CWATM
1 parent 6f33ce2 commit 1463402

11 files changed

+774
-50
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ _pkgdown.yaml
66
inst/doc
77
/doc/
88
/Meta/
9+
.RData

NAMESPACE

+19
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,28 @@
11
# Generated by roxygen2: do not edit by hand
22

33
export(classify_soil)
4+
export(convert_to_cwatm)
5+
export(cwatm_hourly_to_daily_ncdf4)
46
export(get_metno_reanalysis3)
57
export(reanalysis3_daily)
68
export(reanalysis3_swatinput)
79
export(swat_weather_input_chain)
810
importFrom(RColorBrewer,brewer.pal)
911
importFrom(abind,abind)
12+
importFrom(crayon,bgBlue)
13+
importFrom(crayon,bgCyan)
14+
importFrom(crayon,bgGreen)
15+
importFrom(crayon,bgYellow)
1016
importFrom(crayon,black)
1117
importFrom(crayon,blue)
1218
importFrom(crayon,bold)
19+
importFrom(crayon,cyan)
1320
importFrom(crayon,green)
1421
importFrom(crayon,italic)
22+
importFrom(crayon,magenta)
23+
importFrom(crayon,red)
1524
importFrom(crayon,underline)
25+
importFrom(crayon,white)
1626
importFrom(crayon,yellow)
1727
importFrom(dplyr,"%>%")
1828
importFrom(dplyr,across)
@@ -27,18 +37,26 @@ importFrom(dplyr,tibble)
2737
importFrom(ggplot2,aes)
2838
importFrom(ggtern,ggtern)
2939
importFrom(grDevices,colorRampPalette)
40+
importFrom(lubridate,as_datetime)
3041
importFrom(lubridate,date)
3142
importFrom(lubridate,day)
3243
importFrom(lubridate,hour)
3344
importFrom(lubridate,month)
3445
importFrom(lubridate,year)
3546
importFrom(mapview,mapview)
3647
importFrom(ncdf4,nc_close)
48+
importFrom(ncdf4,nc_create)
3749
importFrom(ncdf4,nc_open)
50+
importFrom(ncdf4,ncatt_get)
51+
importFrom(ncdf4,ncdim_def)
52+
importFrom(ncdf4,ncvar_add)
53+
importFrom(ncdf4,ncvar_def)
3854
importFrom(ncdf4,ncvar_get)
55+
importFrom(ncdf4,ncvar_put)
3956
importFrom(plotly,layout)
4057
importFrom(plotly,plot_ly)
4158
importFrom(purrr,map)
59+
importFrom(purrr,map2)
4260
importFrom(readr,read_csv)
4361
importFrom(readr,write_csv)
4462
importFrom(readxl,read_excel)
@@ -53,6 +71,7 @@ importFrom(sf,st_transform)
5371
importFrom(sf,st_zm)
5472
importFrom(stringr,str_pad)
5573
importFrom(stringr,str_remove)
74+
importFrom(stringr,str_remove_all)
5675
importFrom(stringr,str_replace_all)
5776
importFrom(stringr,str_split)
5877
importFrom(utils,packageVersion)

R/metnorenal3.R

+100-49
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,11 @@
8181
#' @param area_buffer desired buffer around the provided shapefile (in meters, default 1500)
8282
#' @param grid_resolution (integer) desired resolution of downloaded grid in kilometers. (see help page for more details)
8383
#' @param preview generate graphs showing previews of data download? (boolean)
84+
#' @param ncdf Set this parameter to be `TRUE` if you would like the downloaded files to remain in NCDF format (*.nc).
85+
#' @param continue if `ncdf` is `TRUE`, then you can pass a folder name (in passed directory) here to continue an aborted download session.
8486
#' @importFrom abind abind
8587
#' @importFrom dplyr nth mutate %>% tibble
86-
#' @importFrom lubridate year month day hour
88+
#' @importFrom lubridate year month day hour as_datetime
8789
#' @importFrom mapview mapview
8890
#' @importFrom ncdf4 nc_open ncvar_get nc_close
8991
#' @importFrom purrr map
@@ -123,43 +125,11 @@ get_metno_reanalysis3 <-
123125
mn_variables = NULL,
124126
area_buffer = 1500,
125127
grid_resolution = NULL,
126-
preview = TRUE
128+
preview = TRUE,
129+
ncdf = FALSE,
130+
continue = NULL
127131
){
128132

129-
# supporting functions ----
130-
nc_open_retry <- function(link) {
131-
132-
nc_file <- tryCatch(expr = {ncdf4::nc_open(link)},
133-
error = function(cond){
134-
warning("failed..")
135-
return(NA)
136-
})
137-
138-
if(nc_file %>% length() > 1){
139-
return(nc_file)
140-
} else{
141-
print("retry download..")
142-
attempt = 1
143-
while((attempt < 10) & (length(nc_file) == 1)){
144-
Sys.sleep(5)
145-
attempt = attempt + 1
146-
nc_file <- tryCatch(expr = {ncdf4::nc_open(link)},
147-
error = function(cond){
148-
warning("failed..", cond, "retry!")
149-
return(NA)
150-
})
151-
152-
}
153-
154-
if(length(nc_file) > 1){
155-
print("connection re-established!")
156-
return(nc_file)
157-
}else{
158-
stop("download failed after 10 attempts.")
159-
}
160-
}
161-
}
162-
163133
get_coord_window <- function(area_path, area_buffer, preview){
164134

165135
# get a base file to find the right x y
@@ -349,7 +319,7 @@ get_metno_reanalysis3 <-
349319
var_q)
350320

351321
# create the daterange
352-
daterange <- seq(as.POSIXct(fromdate, tz = "CET"), as.POSIXct(todate, tz = "CET"), by="hour")
322+
daterange <- seq(as_datetime(fromdate), as_datetime(todate), by="hour")
353323
years <- lubridate::year(daterange)
354324
months <- lubridate::month(daterange) %>% stringr::str_pad(width = 2, side = "left", pad = "0")
355325
days <- lubridate::day(daterange) %>% stringr::str_pad(width = 2, side = "left", pad = "0")
@@ -410,20 +380,35 @@ get_metno_reanalysis3 <-
410380
}
411381

412382
download_ncfiles <- function(directory, foldername, full_urls, filenames,
413-
years, mn_variables, geometry_type) {
414-
415-
# download batches per year
416-
yearbatch <- split(full_urls, f = years)
417-
filebatch <- split(filenames, f = years)
383+
years, mn_variables, geometry_type,
384+
ncdf = FALSE, verbose = FALSE) {
385+
386+
### This is where the switch to netcdf download should take place
387+
### if the user opts for it! (ncdf4)
388+
if(ncdf){
389+
savefiles = paste(directory, foldername, filenames, sep = "/")
390+
read_write_ncdf(url = full_urls, savefiles = savefiles,
391+
foldername = foldername, directory = directory,
392+
verbose = preview)
393+
return(directory)
394+
}
418395

419-
# set list names
420-
years_string <- years %>% unique() %>% sort()
421-
names(yearbatch) <- paste0("y", years_string)
396+
# else: continue as normal
397+
# download batches per year
398+
yearbatch <- split(full_urls, f = years)
399+
filebatch <- split(filenames, f = years)
400+
# set list names
401+
years_string <- years %>% unique() %>% sort()
402+
names(yearbatch) <- paste0("y", years_string)
422403

423404
for (cbyear in names(yearbatch)) {
424405
print(paste0("downloading: ", cbyear))
425406
url <- yearbatch[[cbyear]]
426407

408+
409+
410+
411+
427412
ncin_crop <- nc_open_retry(url[1])
428413
# pre-download first frame to get dimensions set
429414

@@ -684,7 +669,8 @@ get_metno_reanalysis3 <-
684669
if(grid_resolution < 1){stop("`grid_resolution` must be greater than 1 km")}
685670
}
686671

687-
if(preview == TRUE){verbose = TRUE}
672+
# this is truly crap, should fix..
673+
if(preview == TRUE){verbose = TRUE}else{verbose = FALSE}
688674

689675
if(directory %>% is.null()){
690676
directory <- getwd()
@@ -720,8 +706,14 @@ get_metno_reanalysis3 <-
720706
print("building query..")
721707
queries <- build_query(bounding_coords, mn_variables, fromdate, todate, grid_resolution, verbose)
722708

723-
print("creating download folder..")
724-
foldername <- create_download_folder(directory)
709+
if(is.null(continue) == FALSE){
710+
print("continuing download folder..")
711+
foldername = continue
712+
}else{
713+
print("creating download folder..")
714+
foldername <- create_download_folder(directory)
715+
716+
}
725717

726718
print("starting download")
727719
if(bounding_coords %>% length() == 2){geometry_type = "point"}else{geometry_type = "polygon"}
@@ -734,9 +726,14 @@ get_metno_reanalysis3 <-
734726
filenames = queries$filenames,
735727
years = queries$years,
736728
mn_variables = mn_variables,
737-
geometry_type = geometry_type
729+
geometry_type = geometry_type, ncdf = ncdf, verbose = preview
738730
)
739731

732+
if(ncdf){
733+
if(preview){cat(bold(green("NCDF files finished downloading and are located here:")), "\n",
734+
blue(italic(underline(paste0(directory, "/",foldername)))), "\n")}
735+
return(paste0(directory, "/",foldername))
736+
}
740737
print("download complete!, merging files..")
741738

742739
merged_data <- merge_rds(directory = directory,
@@ -1269,3 +1266,57 @@ swat_weather_input_chain <-
12691266

12701267
print("miljotools: pipeline finished!")
12711268
}
1269+
1270+
# supporting functions ----
1271+
nc_open_retry <- function(link) {
1272+
1273+
nc_file <- tryCatch(expr = {ncdf4::nc_open(link)},
1274+
error = function(cond){
1275+
warning("failed..")
1276+
return(NA)
1277+
})
1278+
1279+
1280+
if (nc_file %>% length() > 1) {
1281+
return(nc_file)
1282+
} else{
1283+
mt_print(TRUE, "nc_open_retry", "retrying donwload with out longwave radiation")
1284+
1285+
# https://github.com/metno/NWPdocs/wiki/MET-Nordic-dataset#parameters
1286+
# find the location in the link where longwave radiation is, and remove it,
1287+
# then try to open the file wihtout this variable.
1288+
split = link %>% stringr::str_split(",", simplify = T)
1289+
longwave_index <- grepl(x = split, pattern = "longwave") %>% which()
1290+
new_link = paste(split[-longwave_index], collapse = ",")
1291+
new_nc_file <- tryCatch(
1292+
expr = {ncdf4::nc_open(new_link)},
1293+
error = function(cond) {
1294+
warning("failed..", cond, "retry!")
1295+
return(NA)})
1296+
}
1297+
1298+
if (length(new_nc_file)>1) {
1299+
mt_print(TRUE, "nc_open_retry", "download sans longradiation succeeded!")
1300+
warning("file missing longwave radiation")
1301+
return(new_nc_file)
1302+
} else{
1303+
mt_print(TRUE, "nc_open_retry", "retrying donwload..")
1304+
1305+
attempt = 1
1306+
while ((attempt < 10) & (length(nc_file) == 1)) {
1307+
Sys.sleep(5)
1308+
attempt = attempt + 1
1309+
nc_file <- tryCatch(expr = {ncdf4::nc_open(link)},
1310+
error = function(cond) {
1311+
warning("failed..", cond, "retry!")
1312+
return(NA)})
1313+
}
1314+
1315+
if (length(nc_file) > 1) {
1316+
mt_print(TRUE, "nc_open_retry", "connection re-established!")
1317+
return(nc_file)
1318+
} else{
1319+
stop("download failed after 10 attempts.")
1320+
}
1321+
}
1322+
}

R/misc.R

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#' custom print function for miljotools
2+
#'
3+
#' @param verbose print or not
4+
#' @param function_name function name string
5+
#' @param text string 1
6+
#' @param text2 string 2
7+
#' @param rflag in place replacement flag
8+
#'
9+
#' @return nothing
10+
#' @keywords internal
11+
#'
12+
#' @importFrom crayon bold bgGreen italic bgBlue bgYellow black bgCyan yellow underline
13+
#'
14+
#'
15+
#'
16+
mt_print <- function(verbose, function_name, text, text2 = NULL, rflag = FALSE) {
17+
miljotheme <- bold$bgGreen
18+
tools_theme <- bold$italic$bgBlue
19+
20+
if (function_name == "cwatm_hourly_to_daily_ncdf4") {
21+
f_theme <- bgYellow$black$bold
22+
} else{
23+
f_theme <- bgCyan$black$bold
24+
25+
}
26+
text_theme <- italic$yellow
27+
text_2_theme <- black $ underline
28+
29+
if(rflag){
30+
prefix = "\r"
31+
suffix = NULL
32+
}else{
33+
prefix = NULL
34+
suffix = "\n"
35+
}
36+
if (verbose) {
37+
cat(
38+
prefix,
39+
miljotheme("miljo"),
40+
bgBlue("\U1F33F"),
41+
tools_theme("tools "),
42+
f_theme(paste0("", function_name, "")),
43+
text_theme(" >>", text, ""),
44+
text_2_theme(text2),
45+
suffix,
46+
sep = ""
47+
)
48+
}
49+
}

0 commit comments

Comments
 (0)