Skip to content

Commit f2fa5bc

Browse files
authored
Solar radiation fix and station downscaling (#16)
* fix daily conversion for solar radiation * bump version number * add grid resolution to chain function * spelling and format fixes * removing outpath code * add backing up of swat directory * re-enable loading of prepR * Update Docs
1 parent ea10444 commit f2fa5bc

4 files changed

+45
-46
lines changed

DESCRIPTION

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ Type: Package
22
Package: miljotools
33
Title: An R package hosting a variety of useful functions for
44
environmental data handling and anaylsis
5-
Version: 0.3.2
5+
Version: 0.3.3
66
Author: Moritz Shore
77
Maintainer: Moritz Shore <[email protected]>
88
Description: A few useful functions for environemental data processing and

R/metnorenal3.R

+35-38
Original file line numberDiff line numberDiff line change
@@ -708,11 +708,11 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
708708
stations <- files[which(grepl(x = files,pattern = "metadata.csv") == FALSE)]
709709
metadata <- files[which(grepl(x = files,pattern = "metadata.csv"))]
710710

711-
# Custom funciton to convert the hourly data to daily data
711+
# Custom function to convert the hourly data to daily data
712712
# certain considerations need to be made when summing or averaging.
713713
hourly2daily <- function(data){
714714
# These will potentially need to be expanded
715-
sum_these <- "precipitation_amount"
715+
sum_these <- c("precipitation_amount", "integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time")
716716
max_these <- "air_temperature_2m"
717717
min_these <- "air_temperature_2m"
718718

@@ -739,7 +739,7 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
739739
summarise(across(all_of(min_data_cols), min)) %>%
740740
dplyr::rename(min_temp = air_temperature_2m)
741741

742-
# -1 to get rid of the date column and round by precisision
742+
# -1 to get rid of the date column and round by precision
743743
full_df <-
744744
cbind(
745745
daily_data[1],
@@ -804,15 +804,14 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
804804
#' function to complete successfully when not writing to the SQL database
805805
#'
806806
#' @param path path to daily data provided by `reanalysis3_daily()`
807-
#' @param start optional parameter to define start date oftimeseries
808-
#' @param end optional parameter to define end date of timeseries
807+
#' @param start optional parameter to define start date of time series
808+
#' @param end optional parameter to define end date of time series
809809
#' @param sqlite_path path to your SWAT+ sqlite file (only needed if you wish to
810810
#' update your database). Warning: start and end parameters will be ignored in this case (SWATprepR limitation)
811-
#' @param outpath path to directory where files will be written. If left blank,
812-
#' this will be your normal path
813811
#' @param verbose print status?
814812
#' @param write_wgn calculate and write the weather generator? defaults to true. (for now just based on station #1 (bottom left))
815813
#' @param swat_setup path to your SWAT+ setup. (Required!)
814+
#' @param backup (logical, defaults to true) creates a backup of your swat folder before modification
816815
#'
817816
#' @return path to generated files.
818817
#' @export
@@ -824,17 +823,27 @@ reanalysis3_daily <- function(path, outpath = NULL, verbose = FALSE, precision =
824823
#' @importFrom readr read_csv
825824
#' @importFrom stringr str_split str_remove
826825
#' @importFrom writexl write_xlsx
826+
#' @importFrom crayon green italic
827827
reanalysis3_swatinput <-
828828
function(path,
829829
swat_setup,
830-
outpath = NULL,
831830
write_wgn = TRUE,
832831
start = NA,
833832
end = NA,
834833
sqlite_path = NULL,
835-
verbose = FALSE) {
834+
verbose = FALSE,
835+
backup = TRUE) {
836+
837+
# create a backup of the SWAT+ setup
838+
if(backup){
839+
backuppath <- paste0(dirname(swat_setup), "/miljotools_swat_backup")
840+
dir.create(backuppath, showWarnings = F)
841+
file.copy(swat_setup, backuppath, recursive = T)
842+
if(verbose){cat(green(italic("backing up SWAT directory in")), underline(backuppath), "\n")}
843+
}
844+
836845

837-
# Check that prepr is installed
846+
# Check that SWATprepR is installed
838847
if ("SWATprepR" %in% utils::installed.packages()) {
839848
# if it is installed, check if it is loaded
840849
if ("SWATprepR" %in% (.packages())) {
@@ -843,11 +852,9 @@ reanalysis3_swatinput <-
843852
cat(green(italic("SWATprepR already loaded!\n")))
844853
}
845854
} else{
855+
if (verbose){cat(green(italic("loading SWATprepR\n")))}
846856
# it is not loaded, then load it
847-
#requireNamespace("SWATprepR")
848-
if (verbose) {
849-
cat(green(italic("loading SWATprepR\n")))
850-
}
857+
requireNamespace("SWATprepR")
851858
}
852859
# it is not installed? then require the user to install it.
853860
} else{
@@ -859,20 +866,17 @@ reanalysis3_swatinput <-
859866

860867
# get the file paths and differentiate between metadata and data
861868
files <- list.files(path, full.names = T)
862-
files_short <- list.files(path, full.names = F)
863-
stations_short <- files_short[which(grepl(x = files,pattern = "metadata.csv") == FALSE)]
864869
stations <- files[which(grepl(x = files,pattern = "metadata.csv") == FALSE)]
865870

866871
# load the metadata
867872
metadata <- readr::read_csv(paste0(path, "/metadata.csv"), show_col_types = F) %>%
868873
as.data.frame()
869874
metadata$Source = ""
870875

871-
# Convert to prepR format
872-
# in order to use PrepR to create the SWAT weather files, we need to create
873-
# an excel template file in the correct format.
874-
# This custom read function will read and process the csv files to be in the
875-
# format we want them in
876+
# Convert to prepR format: in order to use PrepR to create the SWAT weather
877+
# files, we need to create an excel template file in the correct format. This
878+
# custom read function will read and process the csv files to be in the format
879+
# we want them in
876880
custom_read <- function(filepath){
877881
# read
878882
df <- readr::read_csv(filepath, show_col_types = F)
@@ -924,23 +928,14 @@ reanalysis3_swatinput <-
924928
my_data <- purrr::map(stations, custom_read)
925929

926930
if(verbose){cat(green(italic(("converting data into SWATprepR format...\n"))))}
927-
# add station names
931+
# add station names
928932
names(my_data) <- paste0("ID", c(1:length(my_data)))
929933
# append the metadata to the front
930934
stations_list <- append(list(metadata), my_data)
931935
# and set the name of the metadata (prepR format)
932936
names(stations_list)[1] <- "Stations"
933937

934-
# parsing and/or generating outpath and folder/file names
935-
parts <- path %>% stringr::str_split("/") %>% unlist()
936-
folder <- parts[which(nchar(parts) > 1)] %>% dplyr::last()
937-
# time and date should always be the 4th element.
938-
tod <- folder %>% stringr::str_split("_") %>% unlist() %>% dplyr::nth(4)
939-
if(outpath %>% is.null()){
940-
outpath <- path %>% stringr::str_remove(paste0("/", folder, "/"))
941-
}
942-
943-
# recreating metadata format for Svatools
938+
# recreating metadata format for SWATprepR
944939
metadata_spat <-
945940
sf::st_as_sf(dplyr::tibble(metadata),
946941
coords = c("Long",
@@ -952,7 +947,7 @@ reanalysis3_swatinput <-
952947

953948
# recreating data format for SWATprepR
954949

955-
# this function splits the dataframe into indiviudal lists, and appends
950+
# this function splits the dataframe into individual lists, and appends
956951
# the date column to each one in tibble form. The column name for the variable
957952
# at hand is not assigned here because I could not find a way to do it. It
958953
# is done in a later step with for loops
@@ -1012,10 +1007,10 @@ reanalysis3_swatinput <-
10121007
SLR = meteo_lst$data$ID1$SLR
10131008
)
10141009
# writing the weather gen
1015-
if(verbose){cat(green(italic("writing weather generator to file in '", outpath, "'\n")))}
1010+
if(verbose){cat(green(italic("writing weather generator to file in '", swat_setup, "'\n")))}
10161011

1017-
write.csv(wgn$wgn_st, paste0(outpath,"/wgn_st.csv"), row.names = FALSE, quote = FALSE)
1018-
write.csv(wgn$wgn_data, paste0(outpath,"/wgn_data.csv"), row.names = FALSE, quote = FALSE)
1012+
write.csv(wgn$wgn_st, paste0(swat_setup,"/wgn_st.csv"), row.names = FALSE, quote = FALSE)
1013+
write.csv(wgn$wgn_data, paste0(swat_setup,"/wgn_data.csv"), row.names = FALSE, quote = FALSE)
10191014
}
10201015

10211016
# writing
@@ -1059,6 +1054,7 @@ reanalysis3_swatinput <-
10591054
#'
10601055
#' @param area The catchment area to retrieve data for. (must be a shapefile)
10611056
#' @param swat_setup The path to your SWAT+ setup (input files, aka TxtInOut)
1057+
#' @param grid_resolution (integer) desired resolution of downloaded grid in kilometers.
10621058
#' @param directory directory to download and process data in
10631059
#' @param from start of the to-be-dowloaded timeseries (ie. and min: "2012-09-01
10641060
#' 10:00:00")
@@ -1080,6 +1076,7 @@ reanalysis3_swatinput <-
10801076
swat_weather_input_chain <-
10811077
function(area,
10821078
swat_setup,
1079+
grid_resolution = 1,
10831080
directory = NULL,
10841081
from = NULL,
10851082
to = NULL,
@@ -1095,7 +1092,8 @@ swat_weather_input_chain <-
10951092
fromdate = from,
10961093
todate = to,
10971094
area_buffer = area_buffer,
1098-
preview = verbose
1095+
preview = verbose,
1096+
grid_resolution = grid_resolution
10991097
)
11001098

11011099
path2 <- reanalysis3_daily(
@@ -1108,7 +1106,6 @@ swat_weather_input_chain <-
11081106

11091107
path3 <- reanalysis3_swatinput(
11101108
path = path2,
1111-
outpath = directory,
11121109
swat_setup = swat_setup,
11131110
write_wgn = write_wgn,
11141111
sqlite_path = sqlite_path,

man/reanalysis3_swatinput.Rd

+6-7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

man/swat_weather_input_chain.Rd

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)