10
10
# https://status.met.no/
11
11
12
12
13
- # ' Download data from the metno renanalysis project
13
+ # ' Download data from the MetNordic Re-Analysis v3 dataset
14
14
# '
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.
17
17
# '
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.
25
75
# '
26
76
# ' @param area (string) path to geo-referenced shapefile (polygon or point) of the desired area
27
77
# ' @param directory (string) path to desired working directory (default: working directory)
28
78
# ' @param fromdate (string) date and time for start of time series (ie. "2012-09-01 10:00:00")
29
79
# ' @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
30
81
# ' @param area_buffer desired buffer around the provided shapefile (in meters, default 1500)
31
82
# ' @param grid_resolution (integer) desired resolution of downloaded grid in kilometers. (see help page for more details)
32
83
# ' @param preview generate graphs showing previews of data download? (boolean)
40
91
# ' @importFrom sf read_sf st_crs st_transform st_buffer st_bbox st_as_sf st_intersects st_coordinates st_zm
41
92
# ' @importFrom stringr str_pad str_replace_all str_split
42
93
# ' @importFrom mapview mapview
43
- # ' @importFrom crayon black bold green italic yellow
94
+ # ' @importFrom crayon black bold green italic yellow blue
44
95
# ' @importFrom utils packageVersion
45
96
# '
46
97
# ' @author Moritz Shore
47
98
# ' @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
52
103
# '
53
104
# ' @examples
54
- # ' # for demonstration purposes, use path of package
55
- # ' ##example_file_path <- system.file(package = "miljotools", "/extdata/metno_reanal/watershed.shp")
56
105
# '
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
+ # ' }
64
115
# '
65
116
# '
66
117
@@ -69,6 +120,7 @@ get_metno_reanalysis3 <-
69
120
directory = NULL ,
70
121
fromdate = " 2012-09-01 10:00:00" ,
71
122
todate = " 2012-09-01 20:00:00" ,
123
+ mn_variables = NULL ,
72
124
area_buffer = 1500 ,
73
125
grid_resolution = NULL ,
74
126
preview = TRUE
@@ -218,7 +270,7 @@ get_metno_reanalysis3 <-
218
270
}
219
271
}
220
272
221
- build_query <- function (bounding_coords , swatvars , fromdate , todate ,
273
+ build_query <- function (bounding_coords , mn_variables , fromdate , todate ,
222
274
grid_resolution , verbose ){
223
275
224
276
# time step not really needed since the files are individual
@@ -278,7 +330,7 @@ get_metno_reanalysis3 <-
278
330
# notfull <- c("integral_of_surface_downwelling_longwave_flux_in_air_wrt_time")
279
331
280
332
# 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 = " ," )
282
334
283
335
# paste together the full variable query
284
336
var_query <-
@@ -358,7 +410,7 @@ get_metno_reanalysis3 <-
358
410
}
359
411
360
412
download_ncfiles <- function (directory , foldername , full_urls , filenames ,
361
- years , swatvars , geometry_type ) {
413
+ years , mn_variables , geometry_type ) {
362
414
363
415
# download batches per year
364
416
yearbatch <- split(full_urls , f = years )
@@ -383,12 +435,12 @@ get_metno_reanalysis3 <-
383
435
alt_crop <- ncdf4 :: ncvar_get(ncin_crop ," altitude" )
384
436
385
437
# 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 )
387
439
388
440
ncdf4 :: nc_close(ncin_crop )
389
441
390
442
# set colnames
391
- names(vardl ) <- swatvars
443
+ names(vardl ) <- mn_variables
392
444
393
445
# predefile the master matrix
394
446
mastermatrix <- vardl
@@ -402,12 +454,12 @@ get_metno_reanalysis3 <-
402
454
ncin_crop <- nc_open_retry(url [idate ])
403
455
404
456
# download all vars
405
- vardl <- lapply(swatvars , getncvar , ncin_crop = ncin_crop )
457
+ vardl <- lapply(mn_variables , getncvar , ncin_crop = ncin_crop )
406
458
407
459
ncdf4 :: nc_close(ncin_crop )
408
460
409
461
# set column names
410
- names(vardl ) <- swatvars
462
+ names(vardl ) <- mn_variables
411
463
412
464
if (geometry_type == " point" ){
413
465
mat_dimension = 2
@@ -417,7 +469,7 @@ get_metno_reanalysis3 <-
417
469
mat_dimension = 3
418
470
}
419
471
# 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 ) {
421
473
# if the download failed, add a full frame of NAs to stack
422
474
if (vardl [[variable ]] %> % length() == 0 ) {
423
475
dims <- mastermatrix [[variable ]] %> % dim()
@@ -512,7 +564,7 @@ get_metno_reanalysis3 <-
512
564
return (cover_stations )
513
565
}
514
566
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 ,
516
568
lon_crop , lat_crop , alt_crop , mastermatrix ,
517
569
daterange , foldername , rdsfiles , directory ,
518
570
preview , area ) {
@@ -559,7 +611,7 @@ get_metno_reanalysis3 <-
559
611
master_df <- data.frame (date = daterange )
560
612
561
613
# building the time series data frame column for each variable
562
- for (variable in swatvars ) {
614
+ for (variable in mn_variables ) {
563
615
# get the variable out of the list
564
616
varslice <- mastermatrix [[variable ]]
565
617
# extract the timeseries for the given cell coordinates
@@ -574,7 +626,7 @@ get_metno_reanalysis3 <-
574
626
clat <- lat_crop [xcell , ycell ]
575
627
576
628
# set the col names
577
- colnames(master_df ) <- c(" date" , swatvars )
629
+ colnames(master_df ) <- c(" date" , mn_variables )
578
630
579
631
# get the altitude of the cell (for metadata.csv)
580
632
altitude <- alt_crop [xcell , ycell ]
@@ -642,21 +694,31 @@ get_metno_reanalysis3 <-
642
694
area_buffer = 1
643
695
}
644
696
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
+
654
716
655
717
print(" getting coordinates.." )
656
718
bounding_coords <- get_coord_window(area_path = area , area_buffer , preview )
657
719
658
720
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 )
660
722
661
723
print(" creating download folder.." )
662
724
foldername <- create_download_folder(directory )
@@ -671,7 +733,7 @@ get_metno_reanalysis3 <-
671
733
full_urls = queries $ full_urls ,
672
734
filenames = queries $ filenames ,
673
735
years = queries $ years ,
674
- swatvars = swatvars ,
736
+ mn_variables = mn_variables ,
675
737
geometry_type = geometry_type
676
738
)
677
739
@@ -700,7 +762,7 @@ get_metno_reanalysis3 <-
700
762
write_stations(
701
763
vardl = ncdownload $ vardl ,
702
764
cover_stations = cover_stations ,
703
- swatvars = swatvars ,
765
+ mn_variables = mn_variables ,
704
766
x_crop = ncdownload $ x_crop ,
705
767
y_crop = ncdownload $ y_crop ,
706
768
lon_crop = ncdownload $ lon_crop ,
@@ -759,11 +821,7 @@ get_metno_reanalysis3 <-
759
821
# ' Downscale MetNo Reanalysis3 data to daily resolution
760
822
# '
761
823
# ' 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.
767
825
# '
768
826
# ' @param path path to output of get_metno_reanalysis3()
769
827
# ' @param outpath (optional) path to write the new files to
@@ -894,10 +952,11 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
894
952
# ' `reanalysis3_daily()` and creates SWAT+ meteo input files and weather
895
953
# ' generators for your SWAT+ input with help from SWATprepR.
896
954
# '
955
+ # ' **NOTE** Default parameter value for `mn_variables` in `get_metno_reanalysis3()` is required for this to work.
956
+ # '
897
957
# ' **NOTE** package `SWATprepR` is required for this function
898
958
# '
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
901
960
# '
902
961
# ' @param path path to daily data provided by `reanalysis3_daily()`
903
962
# ' @param start optional parameter to define start date of time series
@@ -909,7 +968,7 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
909
968
# ' @param swat_setup path to your SWAT+ setup. (Required!)
910
969
# ' @param backup (logical, defaults to true) creates a backup of your swat folder before modification
911
970
# '
912
- # ' @return path to generated files.
971
+ # ' @return Files are generated in provided paths
913
972
# ' @export
914
973
# '
915
974
# ' @author Moritz Shore, Svajunas Plunge
0 commit comments