-
Notifications
You must be signed in to change notification settings - Fork 0
/
post-process.py
282 lines (248 loc) · 8.38 KB
/
post-process.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
This script can be used to post process the *.out file.
"""
# imports ---------------------------------------------------------------------
import numpy as np
import matplotlib as mpl
from matplotlib.ticker import AutoMinorLocator
import matplotlib.pyplot as plt
import sys, os
# functions -------------------------------------------------------------------
def load_args():
"""
Function that loads data
"""
argl = sys.argv
# try to find help
for arg in argl:
if arg=='-h':
fusage()
# find arguments
argdict = ARGD
for n, arg in enumerate(argl):
if arg[0]=='-':
Arg = arg[1:]
if Arg=='name':
try:
argdict[Arg] = argl[n+1]
except IndexError:
ferror(key=1, msg=Arg)
elif Arg=='plot':
argdict['plot'] = True
elif Arg=='compf':
try:
argdict['compf'] = argl[n+1]
except IndexError:
ferror(key=1, msg=Arg)
elif Arg=='tf':
try:
argdict['tf'] = int(argl[n+1])
except IndexError:
ferror(key=1, msg=Arg)
elif Arg=='fname':
try:
argdict['fname'] = argl[n+1]
except IndexError:
ferror(key=1, msg=Arg)
elif Arg=='doption':
try:
tmp = argl[n+1]
varfound = False
for i, var in enumerate(VARS):
if tmp==var:
varfound = True
argdict['col'] = i
break
argdict['doption'] = tmp if varfound else ferror(key=2)
except IndexError:
ferror(key=1, msg=Arg)
print('\n> Arguments loaded')
return argdict
def load_data(args):
"""
Fonction to load data from gemmes.
"""
fname = args['fname']
data1 = np.loadtxt(fname=fname, skiprows=1)
if args['compf']!=False:
data2 = np.loadtxt(fname=args['compf'], skiprows=1)
datas = [data1, data2]
else:
datas = [data1]
print('\n> Gemmes data loaded')
return datas
def moy(time, dat, sta, sto):
select = (time>=sta) * (time<=sto)
mean = np.mean(dat[select])
return mean
def fusage():
"""
Function Usage
"""
print('\n> Usage: python post-process.py [-h] [-name figure name] [-plot]')
print('> [-fname file name] [-compf] [-tf final time] [-doption option]')
print('>\n> Options:')
print('> -h :: display this message.')
print('> -name : string :: name of figure.')
print('> -fname :: string :: name of .out file')
print('> -compf : string :: name of the file *.out to compare with.')
print('> -plot :: to show the figures instead to save them.')
print('> -tf :: int :: final time for post-process.')
print('> -doption : string :: name of the considerd option in:', VARS)
print()
ferror()
def change_mpl_opt(opt):
"""
This function changes matplotlib options.
"""
size = SIZE
figsize = FIGSIZE
if opt!='all':
size = 12
figsize = (5, 5)
SMALL_SIZE = SIZE
MEDIUM_SIZE = SIZE
BIGGER_SIZE = SIZE
plt.rc('font', size = SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize = BIGGER_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize = MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize = SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize = SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize = MEDIUM_SIZE) # legend fontsize
plt.rc('figure', titlesize = BIGGER_SIZE) # fontsize of the figure title
mpl.rcParams['lines.linewidth'] = 0.5
mpl.rcParams['lines.markersize'] = 1.5
return figsize
def draw_figure(args, datas):
"""
Draw the figure and save it.
"""
opt = args['doption']
col = args['col']
name = args['name']
compf = args['compf']
boolcompf = compf!=False
tstop = args['tf']
if name=='default':
name = 'gemmes_'+opt+'.pdf'
if boolcompf: # there are two *.out files to compare
opt = 'all'
nbs = 35
nbr, nbc = nbs//5, nbs//7
datp = datas[0]
time = datp[:,0]
time = time[time<=tstop]
ts = time.size
datp = datp[:,1:]
datp2 = datas[1]
time2 = datp2[:,0]
time2 = time2[time2<=tstop]
t2s = time2.size
datp2 = datp2[:,1:]
Vars = VARS[1:]
name = 'comp_gemmes.pdf'
else: # there is only one *.out file
data = datas[0]
if opt=='all':
nbs = 35
nbr, nbc = nbs//5, nbs//7
datp = data[:,1:]
Vars = VARS[1:]
else:
nbr, nbc = 1, 1
datp = data[:,col:col+1]
Vars = VARS[col:col+1]
time = data[:,0]
time = time[time<=tstop]
ts = time.size
# make figure
figsize = change_mpl_opt(opt)
fig, axes = plt.subplots(nrows=nbr, ncols=nbc, sharex=True, figsize=figsize)
j = -1
if len(Vars)==1:
axes = np.asarray([[axes]])
for n, var in enumerate(Vars):
if n%5==0:
j += 1
i = 0
ax = axes[j, i]
try:
ax.plot(time, datp[:ts,n], label='gemmes.out')
if boolcompf:
ax.plot(time2, datp2[:t2s,n], linestyle='--', marker='',
label='GemmesF90/iLOVECLIM')
if n==12:
mean = moy(time, datp[:ts,n], sta, sto)
ax.text(x=2020, y=2.8, s='+{:.2f}°C'.format(mean),
color='C0')
if boolcompf:
mean = moy(time2, datp2[:t2s,n], sta, sto)
ax.text(x=2020, y=2.5, s='+{:.2f}°C'.format(mean),
color='C1')
if j==(nbr-1):
ax.set_xlabel('t')
ax.set_ylabel(var)
ax.xaxis.set_minor_locator(AutoMinorLocator())
ax.yaxis.set_minor_locator(AutoMinorLocator())
ax.grid(which='both', linewidth=.0001, color='silver', alpha=.4)
except IndexError:
continue
i += 1
#if opt=='all' and not boolcompf:
# datdic = makedatadic(data)
#
# ax = axes[6,3]
# ax.plot(time, datdic['inflation']/np.amax(datdic['inflation']),
# time, 1.8-datdic['smallpi_k']/np.amax(datdic['smallpi_k']))
if boolcompf:
axes[0,0].legend()
if args['plot']:
plt.show()
else:
print('\n> Writing file {}.'.format(name))
plt.tight_layout()
plt.savefig(fname=name)
plt.close(fig)
def makedatadic(data):
"""
Turn np array into dict.
"""
datadic = {}
for n, var in enumerate(VARS):
datadic[var] = data[:,n]
datadic['time'] = data[:,0]
return datadic
def ferror(key=0, msg=''):
"""
Error function.
"""
if key==0:
print('\n> Post process run with sucess.\n')
else:
print('\n> Error {:d}'.format(key))
if key==1:
print('> Need arguments in option {}, try -h'.format(msg))
elif key==2:
print('> doption must be in the list, try -h.')
print('\n> Post process run with an error.\n')
# exit script
print()
sys.exit()
# global constants ------------------------------------------------------------
VARS = ['all', 'capital', 'npop', 'debt', 'wage', 'productivity', 'price',
'eland', 'sigma', 'gsigma', 'co2at', 'co2up', 'co2lo', 'temp',
'temp0', 'pbs', 'pcar', 'omega', 'lambda', 'debtratio', 'gdp0', 'gdp',
'eind', 'inflation', 'abat', 'n_red_fac', 'smallpi', 'smallpi_k',
'dam', 'dam_k', 'dam_y', 'fexo', 'find', 'rcb']
ARGD = {'name':'default', 'doption':'all', 'col':0, 'plot':False,
'compf':False, 'tf':10000000, 'fname':'gemmes.out'}
FIGSIZE = (20, 20)
SIZE = 8
sta, sto = 2085, 2115
# script ----------------------------------------------------------------------
if __name__=='__main__':
print('\n> Script is launched')
args = load_args()
datas = load_data(args)
draw_figure(args, datas)
ferror()