-
Notifications
You must be signed in to change notification settings - Fork 0
/
MINTLab.R
327 lines (307 loc) · 13.4 KB
/
MINTLab.R
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
#
# A flexible R script for general initializations and calibrations
# of the SWAT model
# Initialization of observations, forcing weather and climate files
# for data downloaded from the
# https://www.bafg.de/GRDC/EN/Home/homepage_node.html
# Generate a download link and replace this grdcurl var with the link
grdcurl="https://portal.grdc.bafg.de/grdcdownload/external/4ed147e2-1951-4d31-92f9-3d888fbd28c3/2022-04-28_23-45.zip"
# library(devtools)
# install_github("R-EcoHydRology/EcoHydRology/ecohydrology/pkg/EcoHydRology")
# install_github("R-EcoHydRology/EcoHydRology/ecohydrology/pkg/SWATmodel")
if (!require("pacman")) install.packages("pacman")
pacman::p_load(SWATmodel,RSQLite,argparse,stringi,stringr,rgdal,ggplot2,rgeos,rnoaa,moments,sf,readr,tools,
diffobj,png,grid,gridExtra,ncdfgeom,purrr,raster,sampSurf,parallelly)
source("https://raw.githubusercontent.com/vtdrfuka/MINTSWATmodel/main/MINTSWATcalib.R")
source("https://raw.githubusercontent.com/mintproject/MINTSWATmodel/main/SWAToutput.R")
setwd("~")
basedir=getwd()
outbasedir=paste0(basedir,"/MINTSWATmodel_output")
inbasedir=paste0(basedir,"/MINTSWATmodel_input")
dir.create(outbasedir)
dir.create(inbasedir)
setwd(inbasedir)
Sys.setenv(R_USER_CACHE_DIR=inbasedir)
# If a parameter change scenario, we use --swatscen
parser <- ArgumentParser()
parser$add_argument("-p","--swatparam", action="append", metavar="param:val[:regex_file]",
help = "Add in SWAT parameters that need to be modified")
parser$add_argument("-s","--swatscen", metavar="calib01",
help = "Scenario folder name, 'calib' for calibration, 'scen' for scenario")
parser$add_argument("-d","--swatiniturl", metavar="url to ArcSWAT init or GRDC format dataset",
help = "Scenario folder name")
# Examples:
# geojson example
# exampleargs=c("-d https://data.mint.isi.edu/files/files/geojson/guder.json")
# GRDC Calibration example
exampleargs=c("-s calib01","-p GW_DELAY:12","-p deiter:100","-p rch:3",paste0("-d ",grdcurl))
# ArcSWAT example
#exampleargs=c("-d https://raw.githubusercontent.com/vtdrfuka/MINTSWATmodel/main/tb_s2.zip")
#
args <- parser$parse_args()
if(is.null(args$swatiniturl)){
args <- parser$parse_args(c(exampleargs))
}
print(paste0("This run's args: ",args))
dlfilename=basename(args$swatiniturl)
dlurl=trimws(args$swatiniturl)
paramloc=grep("deiter",args$swatparam)
if(length(paramloc)>0){
deiter=as.numeric(strsplit(args$swatparam[paramloc],split = ":")[[1]][2])
}else{
deiter=200
}
paramloc=grep("rch",args$swatparam)
if(length(paramloc)>0){
rch=as.numeric(strsplit(args$swatparam[paramloc],split = ":")[[1]][2])
}else{
rch=3
}
# *** download
dlfiletype=file_ext(dlfilename)
if(dlfiletype=="json"){
print("geojson single run")
download.file(dlurl,paste0("data.",dlfiletype))
swatrun="basic"
} else {
print("different")
dlfiletype="zip"
download.file(dlurl,paste0("data.",dlfiletype))
if(grepl("Q_Day",unzip("data.zip", list=T)[1])){
swatrun="GRDC"
}
}
if(swatrun=="GRDC"){
print("GRDC Format Uninitialized")
dir.create("GRDCstns")
setwd("GRDCstns")
currentdir=getwd()
unzip("../data.zip")
stationbasins_shp=readOGR("stationbasins.geojson")
for(grdcfilename in list.files(pattern = "_Q_Day")){
print(grdcfilename)
setwd(currentdir)
flowgage=get_grdc_gage(lfilename = grdcfilename)
if(is.null(flowgage)){print("Not enough Gage Info");next()}
basinid=strsplit(grdcfilename,"_")[[1]][1]
basinname=basinid
if(is.character(flowgage)){next()}
GRDC_mindate=min(flowgage$flowdata$mdate)
GRDC_maxdate=max(flowgage$flowdata$mdate)
# Depends on: rnoaa, lubridate::month,ggplot2
declat=flowgage$declat
declon=flowgage$declon
proj4_utm = paste0("+proj=utm +zone=", trunc((180+declon)/6+1), " +datum=WGS84 +units=m +no_defs")
print(proj4_utm)
basin_area=flowgage$area
# Building 3 basin Feature for NetCDF based on basin shape if available
# or a virtual circular basins on area and outlet.
if(any(stationbasins_shp@data$grdc_no==basinid)){
subs1_shp=subset(stationbasins_shp,grdc_no==basinid)
proj4_utm = paste0("+proj=utm +zone=", trunc((180+gCentroid(subs1_shp)$x)/6+1), " +datum=WGS84 +units=m +no_defs")
proj4_ll = "+proj=longlat"
crs_ll=CRS(proj4_ll)
crs_utm=CRS(proj4_utm)
subs1_shp_utm=spTransform(subs1_shp,crs_utm)
initsizeguess=-sqrt(gArea(subs1_shp_utm))/6
f <- function (x,a) {(gArea(subs1_shp_utm)*a-
gArea(gBuffer(subs1_shp_utm,width=x)))^2}
hru3scale <- optimize(f, c(initsizeguess, 0), tol = 0.0001,a=1/3)$minimum
hru2scale <- optimize(f, c(initsizeguess, 0), tol = 0.0001,a=2/3)$minimum
hru3_utm=gBuffer(subs1_shp_utm,width=hru3scale)
hru2_utm=gBuffer(subs1_shp_utm,width=hru2scale)
gArea(hru2_utm)/gArea(subs1_shp_utm)
gArea(hru3_utm)/gArea(subs1_shp_utm)
hru1_utm=gDifference(subs1_shp_utm,hru2_utm)
hru2_utm=gDifference(hru2_utm,hru3_utm)
combined_hrus=list(c(hru1_utm,hru2_utm,hru3_utm))
list(combined_hrus, makeUniqueIDs = T) %>%
flatten() %>%
do.call(rbind, .)
subs1_shp_utm <- do.call(bind, combined_hrus)
subs1_shp_ll=spTransform(subs1_shp_utm,crs_ll)
} else{
latlon <- cbind(declon,declat)
gagepoint_ll <- SpatialPoints(latlon)
proj4string(gagepoint_ll)=proj4_ll
gagepoint_utm=spTransform(gagepoint_ll,crs_utm)
hru1_utm=spCircle(sqrt(basin_area*1000^2/pi), spUnits = crs_utm,
centerPoint = c(x = gagepoint_utm@coords[1], y = gagepoint_utm@coords[2]),
nptsPerimeter = 30,spID = 1)$spCircle
hru2_utm=spCircle(sqrt(basin_area*2/3*1000^2/pi), spUnits = crs_utm,
centerPoint = c(x = gagepoint_utm@coords[1], y = gagepoint_utm@coords[2]),
nptsPerimeter = 30,spID = 1 )$spCircle
hru3_utm=spCircle(sqrt(basin_area/3*1000^2/pi), spUnits = crs_utm,
centerPoint = c(x = gagepoint_utm@coords[1], y = gagepoint_utm@coords[2]),
nptsPerimeter = 30,spID = 1 )$spCircle
hru1_utm=gDifference(hru1_utm,hru2_utm)
hru2_utm=gDifference(hru2_utm,hru3_utm)
combined_hrus=list(c(hru1_utm,hru2_utm,hru3_utm))
list(combined_hrus, makeUniqueIDs = T) %>%
flatten() %>%
do.call(rbind, .)
subs1_shp_utm <- do.call(bind, combined_hrus)
proj4string(subs1_shp_utm)=proj4_utm
subs1_shp_ll=spTransform(subs1_shp_utm,crs_ll)
}
if(length(try(which(stationbasins_shp$grdc_no==as.numeric(flowgage$id))))>0){
basinloc=which(stationbasins_shp$grdc_no==as.numeric(flowgage$id))
basin=stationbasins_shp[basinloc,]
basinutm=spTransform(basin,CRS(proj4_utm))
wxlat=gCentroid(basin)$y
wxlon=gCentroid(basin)$x
} else {
wxlat=declat
wxlon=declon
}
stradius=20;minstns=30
station_data=ghcnd_stations()
while(stradius<2000){
print(paste0("Looking for WX Stations within: ",stradius,"km"))
junk=meteo_distance(
station_data=station_data,
lat=wxlat, long=wxlon,
units = "deg",
radius = stradius,
limit = NULL
)
if(length(unique(junk$id))>minstns){break()}
stradius=stradius*1.2
}
basinoutdir=paste0(outbasedir,"/",basinid);dir.create(basinoutdir)
WXData=FillMissWX(gCentroid(basin)$y,gCentroid(basin)$x,date_min = "1979-01-01",date_max = "2022-01-01", StnRadius = stradius,method = "IDW",alfa = 2)
GRDC_mindate=min(WXData$date)
GRDC_maxdate=max(WXData$date)
AllDays=data.frame(date=seq(GRDC_mindate, by = "day", length.out = GRDC_maxdate-GRDC_mindate))
WXData=merge(AllDays,WXData,all=T)
WXData$PRECIP=WXData$P
WXData$PRECIP[is.na(WXData$PRECIP)]=-99
WXData$TMX=WXData$MaxTemp
WXData$TMX[is.na(WXData$TMX)]=-99
WXData$TMN=WXData$MinTemp
WXData$TMN[is.na(WXData$TMN)]=-99
WXData$DATE=WXData$date
build_swat_basic(dirname=basinoutdir, iyr=min(year(WXData$DATE),na.rm=T), ###***basin name!
nbyr=(max(year(WXData$DATE),na.rm=T)-min(year(WXData$DATE),na.rm=T)),
wsarea=basin_area, elev=mean(WXData$prcpElevation,na.rm=T),
declat=declat, declon=declon, hist_wx=WXData)
build_wgn_file(metdata_df=WXData,declat=declat,declon=declon)
if(!is.null(args$swatscen) &&
substr(trimws(args$swatscen),1,5)=="calib"){
cl <- parallel::makeCluster(availableCores())
MINTSWATcalib()
}
runSWAT2012()
SWAToutput()
}
}
if(dlfiletype=="json"){
basinname=strsplit(basename(args$swatiniturl),split = "\\.")[[1]][1]
basinoutdir=paste0(outbasedir,"/",basinname);dir.create(basinoutdir)
basin=readOGR("data.json")
declat=gCentroid(basin)$y
declon=gCentroid(basin)$x
proj4_utm = paste0("+proj=utm +zone=", trunc((180+declon)/6+1), " +datum=WGS84 +units=m +no_defs")
proj4_ll = "+proj=longlat"
crs_ll=CRS(proj4_ll)
crs_utm=CRS(proj4_utm)
basinutm=spTransform(basin,CRS(proj4_utm))
basin_area=gArea(basinutm)/10^6
# Replace with conversion of geojson
latlon <- cbind(declon,declat)
gagepoint_ll <- SpatialPoints(latlon)
proj4string(gagepoint_ll)=proj4_ll
gagepoint_utm=spTransform(gagepoint_ll,crs_utm)
hru1_utm=spCircle(sqrt(basin_area*1000^2/pi), spUnits = crs_utm,
centerPoint = c(x = gagepoint_utm@coords[1], y = gagepoint_utm@coords[2]),
nptsPerimeter = 30,spID = 1)$spCircle
hru2_utm=spCircle(sqrt(basin_area*2/3*1000^2/pi), spUnits = crs_utm,
centerPoint = c(x = gagepoint_utm@coords[1], y = gagepoint_utm@coords[2]),
nptsPerimeter = 30,spID = 1 )$spCircle
hru3_utm=spCircle(sqrt(basin_area/3*1000^2/pi), spUnits = crs_utm,
centerPoint = c(x = gagepoint_utm@coords[1], y = gagepoint_utm@coords[2]),
nptsPerimeter = 30,spID = 1 )$spCircle
hru1_utm=gDifference(hru1_utm,hru2_utm)
hru2_utm=gDifference(hru2_utm,hru3_utm)
combined_hrus=list(c(hru1_utm,hru2_utm,hru3_utm))
list(combined_hrus, makeUniqueIDs = T) %>%
flatten() %>%
do.call(rbind, .)
subs1_shp_utm <- do.call(bind, combined_hrus)
proj4string(subs1_shp_utm)=proj4_utm
subs1_shp_ll=spTransform(subs1_shp_utm,crs_ll)
# End replace with GeoJSON conversion
stradius=20;minstns=30
station_data=ghcnd_stations()
while(stradius<2000){
print(stradius)
junk=meteo_distance(
station_data=station_data,
lat=gCentroid(basin)$y, long=gCentroid(basin)$x,
units = "deg",
radius = stradius,
limit = NULL
)
if(length(unique(junk$id))>minstns){break()}
stradius=stradius*1.2
}
WXData=FillMissWX(gCentroid(basin)$y,gCentroid(basin)$x,date_min = "1979-01-01",date_max = "2022-01-01", StnRadius = stradius,method = "IDW",alfa = 2)
GRDC_mindate=min(WXData$date)
GRDC_maxdate=max(WXData$date)
AllDays=data.frame(date=seq(GRDC_mindate, by = "day", length.out = GRDC_maxdate-GRDC_mindate))
WXData=merge(AllDays,WXData,all=T)
WXData$PRECIP=WXData$P
WXData$PRECIP[is.na(WXData$PRECIP)]=-99
WXData$TMX=WXData$MaxTemp
WXData$TMX[is.na(WXData$TMX)]=-99
WXData$TMN=WXData$MinTemp
WXData$TMN[is.na(WXData$TMN)]=-99
WXData$DATE=WXData$date
build_swat_basic(dirname=basinoutdir, iyr=min(year(WXData$DATE),na.rm=T),
nbyr=(max(year(WXData$DATE),na.rm=T)-min(year(WXData$DATE),na.rm=T)),
wsarea=basin_area, elev=mean(WXData$prcpElevation,na.rm=T),
declat=declat, declon=declon, hist_wx=WXData)
build_wgn_file(metdata_df=WXData,declat=declat,declon=declon)
runSWAT2012()
SWAToutput()
output_rch=readSWAT("rch",".")
output_plot=merge(output_rch,WXData,by.x="mdate",by.y="date")
output_plot$Qpredmm=output_plot$FLOW_OUTcms/(basin_area*10^6)*3600*24*1000
output_plot$Qmm=output_plot$Qm3ps/(basin_area*10^6)*3600*24/10
}
setwd(outbasedir)
unlink(list.files(pattern = "output.*",recursive = TRUE))
unlink(list.files(pattern = "*.out",recursive = TRUE))
unlink(list.files(pattern = "pcp1.pcp",recursive = TRUE))
unlink(list.files(pattern = "tmp1.tmp",recursive = TRUE))
quit()
# Good study to compare P/Q S against CN from:
# https://www.nature.com/articles/s41597-019-0155-x Reference dataset
# CN250url="https://figshare.com/ndownloader/files/15377363"
# download.file(CN250url,"GCN250_ARCII.tif")
setwd("./Scenarios/Default/TxtInOut/")
load(paste(path.package("EcoHydRology"), "data/change_params.rda", sep = "/"))
if(!is.null(args$swatscen)){
junk=NULL
junknames=c("parameter","current","filetype")
if(max(stri_count_regex(args$swatparam,pattern=":"))==1){junknames=c("parameter","current")}
parrep=setDT(junk)[,tstrsplit(args$swatparam,":",names=junknames)]
calib_params=merge(parrep,change_params,by.x="parameter",by.y="parameter")
names(calib_params)[names(calib_params) == 'current.x'] <- 'current'
names(calib_params)[names(calib_params) == 'filetype.x'] <- 'filetype'
if(length(parrep)==3){
calib_params$filetype[is.na(calib_params$filetype)]=
as.character(calib_params$filetype.y[is.na(calib_params$filetype)])
}
if("filetype.y" %in% colnames(calib_params)) {
calib_params = subset(calib_params, select = -c(filetype.y) )
}
calib_params = subset(calib_params, select = -c(current.y) )
tmpdir=paste0("../",args$swatscen)
file.remove(list.files(pattern="output."))
dir.create(tmpdir)
file.copy(list.files(),tmpdir)
setwd(tmpdir)
setup_swatcal(calib_params)
alter_files(calib_params)
}