Skip to content

Commit 6f33ce2

Browse files
committed
2 parents 0369d41 + b0ca1da commit 6f33ce2

4 files changed

+197
-88
lines changed

R/metnorenal3.R

+114-55
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,74 @@
1010
# https://status.met.no/
1111

1212

13-
#' Download data from the metno renanalysis project
13+
#' Download data from the MetNordic Re-Analysis v3 dataset
1414
#'
15-
#' This function accesses the THREDDS server of met.no with download queries
16-
#' formatted from user input. (to be expanded upon)
15+
#' The MET Nordic rerun archive version 3 can be accessed using this
16+
#' function. Please see below for more details.
1717
#'
18-
#' The `grid_resolution` parameter lets you choose how many stations to select
19-
#' from the grid. If for example you pass a "3", then every 3 station will be
20-
#' selected in both the horizontal and vertical axis, giving you a grid with
21-
#' stations placed 3km apart from each other on a regular grid. This can help
22-
#' with downloading data from huge catchments where 1x1km grid size is not
23-
#' necessary. Please note, no averaging of the "non-selected" grid cells is
24-
#' performed.
18+
#' For instructions on how to use this function, you can visit the article on
19+
#' the [web page](https://moritzshore.github.io/miljotools/articles/metno_reanal.html).
20+
#'
21+
#' The [MET Nordic Reanalysis Dataset](https://github.com/metno/NWPdocs/wiki/MET-Nordic-dataset)
22+
#' is a reanalysis product from the Meteorologisk institutt (hourly from 2012-09 to
23+
#' 2023-01). Please inform yourself on the limitations of reanalysis data before
24+
#' applying this dataset to your needs.This function accesses the THREDDS server
25+
#' of met.no with download queries formatted from user input:
26+
#'
27+
#' `area` should be a path to a **geo-referenced** shapefile (of either a
28+
#' **polygon** or a **point** geometry) of the area you would like data from.
29+
#' This area must be at least twice the size of the chosen `grid_resolution`,
30+
#' which is by default 1 x 1 km. If a point shapefile is given, then the nearest
31+
#' grid cell is chosen, and data is downloaded from there.
32+
#'
33+
#' `directory` is an optional parameter which lets you chose in which directory
34+
#' the downloads will be stored. If this parameter is not defined, the current
35+
#' working directory will be used.
36+
#'
37+
#' `fromdate` and `todate` are the date and time by which to bound the download
38+
#' by. required format is: **"2012-09-01 10:00:00"**. The dataset spans from this
39+
#' date til 2023-01.
40+
#'
41+
#' `mn_variables` are the MetNordic Variables which the function should
42+
#' download, by default this includes the following:
43+
#'
44+
#' - "air_temperature_2m",
45+
#' - "integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time",
46+
#' - "relative_humidity_2m",
47+
#' - "precipitation_amount",
48+
#' - "wind_speed_10m",
49+
#' - "wind_direction_10m"
50+
#'
51+
#' There are a few more variables which are not downloaded, these have not been
52+
#' tested, and some are known to have data gaps which the function currently
53+
#' cannot deal with, and might cause it to fail. use at own risk, and post an
54+
#' issue if anything does not work.
55+
#'
56+
#' You can read more about these variables on [GitHub (MetNo)](https://github.com/metno/NWPdocs/wiki/MET-Nordic-dataset)
57+
#'
58+
#' `area_buffer` is an optional convienient parameter in which you can buffer
59+
#' your polygon shape file by the given amount of meters. This is useful for
60+
#' downloading stations that are outside of the bounds of your polygon, but are
61+
#' still relatively close to the border (due to the 1x1km grid). A good (and
62+
#' default) value for this is 1500 m
63+
#'
64+
#' `grid_resolution` lets you choose how many stations to select from the grid.
65+
#' If for example you pass a "3", then every 3 station will be selected in both
66+
#' the horizontal and vertical axis, giving you a grid with stations placed 3km
67+
#' apart from each other on a regular grid. This can help with downloading data
68+
#' from huge catchments where 1x1km grid size is not necessary. Please note, no
69+
#' averaging of the "non-selected" grid cells is performed, and the default
70+
#' value is 1 x 1 km.
71+
#'
72+
#' `preview` prints information to the console as to what the function is doing,
73+
#' as well as plotting interactive maps to the viewer which gives you an idea of
74+
#' which grid cells were selected relative to the shapefile you provided.
2575
#'
2676
#' @param area (string) path to geo-referenced shapefile (polygon or point) of the desired area
2777
#' @param directory (string) path to desired working directory (default: working directory)
2878
#' @param fromdate (string) date and time for start of time series (ie. "2012-09-01 10:00:00")
2979
#' @param todate (string) date and time for end of time series (ie. "2013-09-01 10:00:00")
80+
#' @param mn_variables (vector) Leave blank for deafault (tested) variables. See details for more
3081
#' @param area_buffer desired buffer around the provided shapefile (in meters, default 1500)
3182
#' @param grid_resolution (integer) desired resolution of downloaded grid in kilometers. (see help page for more details)
3283
#' @param preview generate graphs showing previews of data download? (boolean)
@@ -40,27 +91,27 @@
4091
#' @importFrom sf read_sf st_crs st_transform st_buffer st_bbox st_as_sf st_intersects st_coordinates st_zm
4192
#' @importFrom stringr str_pad str_replace_all str_split
4293
#' @importFrom mapview mapview
43-
#' @importFrom crayon black bold green italic yellow
94+
#' @importFrom crayon black bold green italic yellow blue
4495
#' @importFrom utils packageVersion
4596
#'
4697
#' @author Moritz Shore
4798
#' @export
48-
#' @return Writes .csv files into a folder located at the provided directory.
49-
#' One .csv file for each grid point within the (buffered) shape file area.
50-
#' Addtionally one metadata file (.csv) is written with the attributes of each
51-
#' other file
99+
#' @return Function returns a path to where .csv files of the download were
100+
#' written. One .csv file for each grid point within the (buffered) shape
101+
#' file area. Additionally one metadata file (.csv) is written with the
102+
#' attributes of each other file
52103
#'
53104
#' @examples
54-
#' # for demonstration purposes, use path of package
55-
#' ##example_file_path <- system.file(package = "miljotools", "/extdata/metno_reanal/watershed.shp")
56105
#'
57-
#' ##get_metno_reanalysis3(
58-
#' ##area = example_file_path,
59-
#' ##fromdate = "2015-01-01",
60-
#' ##todate = "2015-01-02",
61-
#' ##area_buffer = 100,
62-
#' ##preview = TRUE
63-
#' ##)
106+
#' if(FALSE){
107+
#' get_metno_reanalysis3(
108+
#' area = example_file_path,
109+
#' fromdate = "2015-01-01",
110+
#' todate = "2015-01-02",
111+
#' area_buffer = 100,
112+
#' preview = TRUE
113+
#' )
114+
#' }
64115
#'
65116
#'
66117

@@ -69,6 +120,7 @@ get_metno_reanalysis3 <-
69120
directory = NULL,
70121
fromdate = "2012-09-01 10:00:00",
71122
todate = "2012-09-01 20:00:00",
123+
mn_variables = NULL,
72124
area_buffer = 1500,
73125
grid_resolution = NULL,
74126
preview = TRUE
@@ -218,7 +270,7 @@ get_metno_reanalysis3 <-
218270
}
219271
}
220272

221-
build_query <- function(bounding_coords, swatvars, fromdate, todate,
273+
build_query <- function(bounding_coords, mn_variables, fromdate, todate,
222274
grid_resolution, verbose){
223275

224276
# time step not really needed since the files are individual
@@ -278,7 +330,7 @@ get_metno_reanalysis3 <-
278330
# notfull <- c("integral_of_surface_downwelling_longwave_flux_in_air_wrt_time")
279331

280332
# paste together the variable query
281-
var_q <- paste0(swatvars, time_q, y_q, x_q, collapse = ",")
333+
var_q <- paste0(mn_variables, time_q, y_q, x_q, collapse = ",")
282334

283335
# paste together the full variable query
284336
var_query <-
@@ -358,7 +410,7 @@ get_metno_reanalysis3 <-
358410
}
359411

360412
download_ncfiles <- function(directory, foldername, full_urls, filenames,
361-
years, swatvars, geometry_type) {
413+
years, mn_variables, geometry_type) {
362414

363415
# download batches per year
364416
yearbatch <- split(full_urls, f = years)
@@ -383,12 +435,12 @@ get_metno_reanalysis3 <-
383435
alt_crop <- ncdf4::ncvar_get(ncin_crop,"altitude")
384436

385437
# download all the variables using custom function
386-
vardl <- lapply(swatvars, getncvar, ncin_crop = ncin_crop)
438+
vardl <- lapply(mn_variables, getncvar, ncin_crop = ncin_crop)
387439

388440
ncdf4::nc_close(ncin_crop)
389441

390442
# set colnames
391-
names(vardl) <- swatvars
443+
names(vardl) <- mn_variables
392444

393445
# predefile the master matrix
394446
mastermatrix <- vardl
@@ -402,12 +454,12 @@ get_metno_reanalysis3 <-
402454
ncin_crop <- nc_open_retry(url[idate])
403455

404456
# download all vars
405-
vardl <- lapply(swatvars, getncvar, ncin_crop = ncin_crop)
457+
vardl <- lapply(mn_variables, getncvar, ncin_crop = ncin_crop)
406458

407459
ncdf4::nc_close(ncin_crop)
408460

409461
# set column names
410-
names(vardl) <- swatvars
462+
names(vardl) <- mn_variables
411463

412464
if(geometry_type == "point"){
413465
mat_dimension = 2
@@ -417,7 +469,7 @@ get_metno_reanalysis3 <-
417469
mat_dimension = 3
418470
}
419471
# for every variable, bind the matrix slice onto the full matrix (dimension 3 --> "along=3")
420-
for (variable in swatvars) {
472+
for (variable in mn_variables) {
421473
# if the download failed, add a full frame of NAs to stack
422474
if (vardl[[variable]] %>% length() == 0) {
423475
dims <- mastermatrix[[variable]] %>% dim()
@@ -512,7 +564,7 @@ get_metno_reanalysis3 <-
512564
return(cover_stations)
513565
}
514566

515-
write_stations <- function(vardl, cover_stations, swatvars, x_crop, y_crop,
567+
write_stations <- function(vardl, cover_stations, mn_variables, x_crop, y_crop,
516568
lon_crop, lat_crop, alt_crop, mastermatrix,
517569
daterange, foldername, rdsfiles, directory,
518570
preview, area) {
@@ -559,7 +611,7 @@ get_metno_reanalysis3 <-
559611
master_df <- data.frame(date = daterange)
560612

561613
# building the time series data frame column for each variable
562-
for (variable in swatvars) {
614+
for (variable in mn_variables) {
563615
# get the variable out of the list
564616
varslice <- mastermatrix[[variable]]
565617
# extract the timeseries for the given cell coordinates
@@ -574,7 +626,7 @@ get_metno_reanalysis3 <-
574626
clat <- lat_crop[xcell, ycell]
575627

576628
# set the col names
577-
colnames(master_df) <- c("date", swatvars)
629+
colnames(master_df) <- c("date", mn_variables)
578630

579631
# get the altitude of the cell (for metadata.csv)
580632
altitude <- alt_crop[xcell, ycell]
@@ -642,21 +694,31 @@ get_metno_reanalysis3 <-
642694
area_buffer = 1
643695
}
644696

645-
# all relevant variables (ADD TO FUNCTION PARAMS?)
646-
swatvars <- c(
647-
"air_temperature_2m",
648-
"integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time",
649-
"relative_humidity_2m",
650-
"precipitation_amount",
651-
"wind_speed_10m",
652-
"wind_direction_10m"
653-
)
697+
if(mn_variables %>% is.null()){
698+
# all relevant variables and tested variables
699+
mn_variables <- c(
700+
"air_temperature_2m",
701+
"integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time",
702+
"relative_humidity_2m",
703+
"precipitation_amount",
704+
"wind_speed_10m",
705+
"wind_direction_10m"
706+
)
707+
if(preview){
708+
cat(bold("downloading default variables:\n"))
709+
cat(blue(italic(mn_variables)), sep = "\n")
710+
}
711+
}else{
712+
cat(bold("downloading custom variables:\n"))
713+
cat(blue(italic(mn_variables)), sep = "\n")
714+
}
715+
654716

655717
print("getting coordinates..")
656718
bounding_coords <- get_coord_window(area_path = area, area_buffer, preview)
657719

658720
print("building query..")
659-
queries <- build_query(bounding_coords, swatvars, fromdate, todate, grid_resolution, verbose)
721+
queries <- build_query(bounding_coords, mn_variables, fromdate, todate, grid_resolution, verbose)
660722

661723
print("creating download folder..")
662724
foldername <- create_download_folder(directory)
@@ -671,7 +733,7 @@ get_metno_reanalysis3 <-
671733
full_urls = queries$full_urls,
672734
filenames = queries$filenames,
673735
years = queries$years,
674-
swatvars = swatvars,
736+
mn_variables = mn_variables,
675737
geometry_type = geometry_type
676738
)
677739

@@ -700,7 +762,7 @@ get_metno_reanalysis3 <-
700762
write_stations(
701763
vardl = ncdownload$vardl,
702764
cover_stations = cover_stations,
703-
swatvars = swatvars,
765+
mn_variables = mn_variables,
704766
x_crop = ncdownload$x_crop,
705767
y_crop = ncdownload$y_crop,
706768
lon_crop = ncdownload$lon_crop,
@@ -759,11 +821,7 @@ get_metno_reanalysis3 <-
759821
#' Downscale MetNo Reanalysis3 data to daily resolution
760822
#'
761823
#' This function takes the hourly data from get_metno_reanalysis3() and
762-
#' recalculates it into daily time resolution.
763-
#'
764-
#' Warning, this funcitonality requires "svatools" to be installed:
765-
#'
766-
#' https://github.com/biopsichas/svatools
824+
#' recalculates it into daily (temporal) resolution.
767825
#'
768826
#' @param path path to output of get_metno_reanalysis3()
769827
#' @param outpath (optional) path to write the new files to
@@ -894,10 +952,11 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
894952
#' `reanalysis3_daily()` and creates SWAT+ meteo input files and weather
895953
#' generators for your SWAT+ input with help from SWATprepR.
896954
#'
955+
#' **NOTE** Default parameter value for `mn_variables` in `get_metno_reanalysis3()` is required for this to work.
956+
#'
897957
#' **NOTE** package `SWATprepR` is required for this function
898958
#'
899-
#' **NOTE**: the SWAT+ input files must be in your specified 'outpath' for the
900-
#' function to complete successfully when not writing to the SQL database
959+
#' https://github.com/biopsichas/SWATprepR
901960
#'
902961
#' @param path path to daily data provided by `reanalysis3_daily()`
903962
#' @param start optional parameter to define start date of time series
@@ -909,7 +968,7 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
909968
#' @param swat_setup path to your SWAT+ setup. (Required!)
910969
#' @param backup (logical, defaults to true) creates a backup of your swat folder before modification
911970
#'
912-
#' @return path to generated files.
971+
#' @return Files are generated in provided paths
913972
#' @export
914973
#'
915974
#' @author Moritz Shore, Svajunas Plunge

0 commit comments

Comments
 (0)