forked from yjkim1028/CWatM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cwatm.py
260 lines (207 loc) · 8.71 KB
/
cwatm.py
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
#!/usr/bin/env python3.7
"""
::
-------------------------------------------------
######## ## ## #### ###### ## ##
## ## ## ## ## ## #### ####
## ## ## ## ## ## ## #### ##
## ## ## ## ######## ## ## ## ##
## ## #### ## ## ## ## ## ##
## #### #### ## ## ## ## ##
########## ## ## ## ## ## ## ##
Community WATer Model
CWATM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
CWATM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details
<http://www.gnu.org/licenses/>.
# --------------------------------------------------
"""
__author__ = "WATER Program, IIASA"
__version__ = "Version: 1.04"
__date__ = "16/04/2020"
__copyright__ = "Copyright 2016, IIASA"
__maintainer__ = "Peter Burek"
__status__ = "Development"
# to work with some versions of Linux - a workaround with pyexpat is needed
from pyexpat import *
import os
import sys
import numpy as np
# to work with some versions of Linux - a workaround with pyexpat is needed
import glob
import sys
import time
import datetime
from cwatm.management_modules.configuration import globalFlags, settingsfile, versioning, platform1, parse_configuration, read_metanetcdf, dateVar, CWATMRunInfo, outputDir, timeMesSum, timeMesString, globalclear
from cwatm.management_modules.data_handling import Flags, cbinding
from cwatm.management_modules.timestep import checkifDate
from cwatm.management_modules.dynamicModel import ModelFrame
from cwatm.cwatm_model import CWATModel
# ---------------------------
def usage():
"""
Prints some lines describing how to use this program which arguments and parameters it accepts, etc
* -q --quiet output progression given as .
* -v --veryquiet no output progression is given
* -l --loud output progression given as time step, date and discharge
* -c --check input maps and stack maps are checked, output for each input map BUT no model run
* -h --noheader .tss file have no header and start immediately with the time series
* -t --printtime the computation time for hydrological modules are printed
"""
print('CWatM - Community Water Model')
print('Authors: ', __author__)
print('Version: ', __version__)
print('Date: ', __date__)
print('Status: ', __status__)
print("""
Arguments list:
settings.ini settings file
-q --quiet output progression given as .
-v --veryquiet no output progression is given
-l --loud output progression given as time step, date and discharge
-c --check input maps and stack maps are checked, output for each input map BUT no model run
-h --noheader .tss file have no header and start immediately with the time series
-t --printtime the computation time for hydrological modules are printed
-w --warranty copyright and warranty information
""")
return True
# ==================================================
def CWATMexe(settings):
"""
Base subroutine of the CWATM model
* parses the settings file
* read the information for the netcdf files
* check if dates are alright
* check flags for screen output
* runs the model
"""
parse_configuration(settings)
# print option
# print binding
# read all the possible option for modelling and for generating output
# read the settings file with all information about the catchments(s)
# read the meta data information for netcdf outputfiles
read_metanetcdf(cbinding('metaNetcdfFile'), 'metaNetcdfFile')
# os.chdir(outputDir[0])
# this prevent from using relative path in settings!
checkifDate('StepStart', 'StepEnd', 'SpinUp', cbinding('PrecipitationMaps'))
# checks if end date is later than start date and puts both in modelSteps
if Flags['check']:
dateVar["intEnd"] = dateVar["intStart"]
CWATM = CWATModel()
stCWATM = ModelFrame(CWATM, firstTimestep=dateVar["intStart"], lastTimeStep=dateVar["intEnd"])
"""
----------------------------------------------
Deterministic run
----------------------------------------------
"""
print(CWATMRunInfo([outputDir[0], settingsfile[0]]))
start_time = datetime.datetime.now().time()
if Flags['loud']:
print("%-6s %10s %11s\n" % ("Step", "Date", "Discharge"), end=' ')
stCWATM.run()
# cProfile.run('stLisflood.run()')
# python -m cProfile -o l1.pstats cwatm.py settings1.ini
# gprof2dot -f pstats l1.pstats | dot -T png -o callgraph.png
# pyreverse -AS -f ALL -o png cwatm.py -p Main
if Flags['printtime']:
print("\n\nTime profiling")
print("%2s %-17s %10s %8s" % ("No", "Name", "time[s]", "%"))
timeSum = np.array(timeMesSum)
timePrint = timeSum
for i in range(len(timePrint)):
print("%2i %-17s %10.2f %8.1f" % (i, timeMesString[i], timePrint[i], 100 * timePrint[i] / timePrint[-1]))
current_time = datetime.datetime.now().time()
print(start_time.isoformat())
print(current_time.isoformat())
# return with last value and true for successfull run for pytest
return(True, CWATM.firstout)
# ==================================================
# ============== USAGE ==============================
# ==================================================
def GNU():
"""
prints GNU General Public License information
"""
print('CWatM - Community Water Model')
print('Authors: ', __author__)
print('Version: ', __version__)
print('Date: ', __date__)
print()
print("""
CWATM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details
<http://www.gnu.org/licenses/>.
""")
sys.exit(1)
def headerinfo():
"""
Print the information on top of each run
this is collecting the last change of one of the source files
in order to give more information of the settingsfile and the version of cwatm
this information is put in the result files .tss and .nc
"""
versioning['exe'] = __file__
realPath = os.path.dirname(os.path.realpath(versioning['exe']))
i = 0
for (dirpath, _, filenames) in os.walk(realPath):
for file in filenames:
if file[-3:] == ".py":
i += 1
file1 = dirpath + "/" + file
if i == 1:
lasttime = os.path.getmtime(file1)
lastfile = file
else:
if os.path.getmtime(file1) > lasttime:
lasttime = os.path.getmtime(file1)
lastfile = file
versioning['lastdate'] = datetime.datetime.fromtimestamp(lasttime).strftime("%Y/%m/%d %H:%M")
__date__ = versioning['lastdate']
versioning['lastfile'] = lastfile
versioning['version'] = __version__
versioning['platform'] = platform1
if not (Flags['veryquiet']) and not (Flags['quiet']):
print("CWATM - Community Water Model ", __version__, " Date: ", versioning['lastdate'], " ")
print("International Institute of Applied Systems Analysis (IIASA)")
print("Running under platform: ", platform1)
print("-----------------------------------------------------------")
def main(settings, args):
success = False
if Flags['test']: globalclear()
globalFlags(settings, args, settingsfile, Flags)
if Flags['use']:
usage()
if Flags['warranty']:
GNU()
# setting of global flag e.g checking input maps, producing more output information
headerinfo()
success, last_dis = CWATMexe(settingsfile[0])
#if Flags['test']:
return success, last_dis
def run_from_command_line():
if len(sys.argv) < 2:
usage()
return
else:
CWatM_Path = os.path.dirname(sys.argv[0])
CWatM_Path = os.path.abspath(CWatM_Path)
main(sys.argv[1],sys.argv[2:])
if __name__ == "__main__":
if len(sys.argv) < 2:
usage()
else:
CWatM_Path = os.path.dirname(sys.argv[0])
CWatM_Path = os.path.abspath(CWatM_Path)
main(sys.argv[1],sys.argv[2:])