-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverification_plots.py
253 lines (197 loc) · 9.56 KB
/
verification_plots.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
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 20 16:47:54 2022
@author: Dean
"""
# Third party:
import numpy as np # 1.19.2
import matplotlib.pyplot as plt # 3.3.2
import pandas as pd # 1.1.3
import statsmodels.api as sm # 0.12.0
# Local code:
import oversampler
import qxcal_model
import isoxcal_model
import pic2_xcal_fits
def scatter_with_modelfit(year, wisperdata, pars_dD, pars_d18O):
"""
Publication read figure. Colored scatter plot of cross-calibration data
and 2D colored-contour maps of the polynomial fit, for both dD and d18O.
Figures are saved in this folder.
"""
fig = plt.figure(figsize=(6.5,2.5))
ax_D = plt.axes([0.125,0.2,0.29,0.75])
cbax_D = plt.axes([0.435,0.2,0.02,0.625])
ax_18O = plt.axes([0.62,0.2,0.29,0.75])
cbax_18O = plt.axes([0.93,0.2,0.02,0.625])
## Some year-dependent contour/colormapping values:
if year=='2017':
# Min/max values for colormap renormalization:
vmin_D = -650; vmax_D = 0; vmin_18O = -80; vmax_18O = 0
# Contour levels for plotting model output:
clevs_D = np.arange(-600,0,50); clevs_18O = np.arange(-80,0,5)
if year=='2018':
vmin_D = -200; vmax_D = -40; vmin_18O = -30; vmax_18O = -8
clevs_D = np.arange(-200,0,15); clevs_18O = np.arange(-30,0,2)
## WISPER data scatter plots:
##-------------------------------------------------------------------------
# Thin out the wisper data for better visuals:
wisperthin = wisperdata.iloc[np.arange(0,len(wisperdata),10)]
s_D = ax_D.scatter(np.log(wisperthin['h2o_tot2']), wisperthin['dD_tot2'],
c=wisperthin['dD_tot1'], vmin=vmin_D, vmax=vmax_D,
s=5)
s_18O = ax_18O.scatter(np.log(wisperthin['h2o_tot2']), wisperthin['d18O_tot2'],
c=wisperthin['d18O_tot1'],
vmin=vmin_18O, vmax=vmax_18O, s=5)
##-------------------------------------------------------------------------
## Compute model-fit values and plot as contours:
##-------------------------------------------------------------------------
# Predictor variable values to pass into model:
if year=='2017':
logq = np.linspace(np.log(100), np.log(30000), 200)
logq_grid, dD_grid = np.meshgrid(logq, np.linspace(-450, -30, 100))
logq_grid, d18O_grid = np.meshgrid(logq, np.linspace(-55, 0, 100))
if year=='2018':
logq = np.linspace(np.log(2000), np.log(30000), 200)
logq_grid, dD_grid = np.meshgrid(logq, np.linspace(-200, -30, 100))
logq_grid, d18O_grid = np.meshgrid(logq, np.linspace(-55, -30, 100))
predictorvars = {'logq':logq_grid,
'dD':dD_grid,
'd18O':d18O_grid,
'logq*dD':logq_grid*dD_grid,
'logq*d18O':logq_grid*d18O_grid
}
# Run model:
modeldata_dD = isoxcal_model.predict(predictorvars, pars_dD)
modeldata_d18O = isoxcal_model.predict(predictorvars, pars_d18O)
# Contour plots of model output:
ax_D.contour(logq_grid, dD_grid, modeldata_dD,
levels=clevs_D, vmin=vmin_D, vmax=vmax_D, linewidths=2.5)
ax_18O.contour(logq_grid, d18O_grid, modeldata_d18O,
levels=clevs_18O, vmin=vmin_18O, vmax=vmax_18O, linewidths=2.5)
##-------------------------------------------------------------------------
## Include contours of model residuals
##-------------------------------------------------------------------------
# Compute root-mean-square deviations:
if year=='2017':
reslevs_D = [2,5,15,30]; reslevs_18O = [0.2,0.5,1,2,4]; ffact=1.5
if year=='2018':
reslevs_D = [1,2,5,10,20]; reslevs_18O = [0.2,0.5,1,2]; ffact=4
res_dD = model_residual_map('dD', wisperdata, pars_dD, logq_grid, dD_grid, ffact=ffact)
res_d18O = model_residual_map('d18O', wisperdata, pars_d18O, logq_grid, d18O_grid, ffact=ffact)
# Contours:
rescont_D = ax_D.contour(logq_grid, dD_grid, res_dD,
levels=reslevs_D, colors='black', linewidths=1)
rescont_18O = ax_18O.contour(logq_grid, d18O_grid, res_d18O,
levels=reslevs_18O, colors='black', linewidths=1)
plt.clabel(rescont_D, inline=True, fmt='%i')
plt.clabel(rescont_18O, inline=True, fmt='%0.1f')
##-------------------------------------------------------------------------
## Figure axes labels, limits, colobars, ...
##-------------------------------------------------------------------------
# Results axes mods:
if year=='2017':
ax_D.set_xlim(4.5, 10.5); ax_D.set_ylim(-400, -20)
ax_18O.set_xlim(4.5, 10.5); ax_18O.set_ylim(-50, 0)
if year=='2018':
ax_D.set_xlim(7.5, 10.5); ax_D.set_ylim(-180, -40)
ax_18O.set_xlim(7.5, 10.5); ax_18O.set_ylim(-50, -32)
ax_D.set_xlabel(r'log($q_2$[ppmv])', fontsize=12)
ax_D.set_ylabel(r'$\delta D_2$'+u'(\u2030)', fontsize=12, labelpad=0)
ax_18O.set_xlabel(r'log($q_2$[ppmv])', fontsize=12)
ax_18O.set_ylabel(r'$\delta^{18} O_2$'+u'(\u2030)', fontsize=12, labelpad=0)
# Colorbar axes mods:
fig.colorbar(s_D, cax=cbax_D)
fig.colorbar(s_18O, cax=cbax_18O)
cbax_D.set_title(r'$\delta D_1$'+'\n'+u'(\u2030)', fontsize=10)
plt.setp(cbax_D.yaxis.get_majorticklabels(),
ha="center", va="center", rotation=-90, rotation_mode="anchor")
cbax_18O.set_title(r'$\delta^{18} O_1$'+'\n'+u'(\u2030)', fontsize=10)
plt.setp(cbax_18O.yaxis.get_majorticklabels(),
ha="center", va="center", rotation=-90, rotation_mode="anchor")
##-------------------------------------------------------------------------
fig.savefig("pic2_isoratio_xcal_fitresults_%s.png" % year)
def residuals_figure(year, wisperdata, iso, pars, axes):
"""
Publication read figure. Colored scatter plot of cross-calibration data
and 2D colored-contour maps of the polynomial fit, for both dD and d18O.
Figures are saved in this folder.
"""
logq = np.log(wisperdata['h2o_tot2'].values)
# Get model predictions:
predictorvars = {'logq':logq,
iso:wisperdata[iso+'_tot2'].values,
'logq*'+iso:logq*wisperdata[iso+'_tot2'].values,
}
modelresults = isoxcal_model.predict(predictorvars, pars)
res1_dD = wisperdata[iso+'_tot1'].values - wisperdata[iso+'_tot2'].values
res2_dD = wisperdata[iso+'_tot1'].values - modelresults
axes[0].scatter(wisperdata[iso+'_tot2'], wisperdata[iso+'_tot1'],
s=2, label='before cal')
axes[0].scatter(modelresults, wisperdata[iso+'_tot1'],
s=2, label='after cal')
axes[1].hist(res1_dD - np.mean(res1_dD),
bins=200, histtype='step', label='before cal')
axes[1].hist(res2_dD - np.mean(res2_dD),
bins=200, histtype='step', label='after cal')
axes[1].set_yscale('log')
# draw 1-1 line on scatter plot:
axes[0].plot((min(modelresults), max(modelresults)),
(min(modelresults), max(modelresults)),
color='black', label='1-1'
)
axes[0].legend(loc='upper left', markerscale=3)
axes[0].set_xlabel(r'sensor 2 output '+u'(\u2030)', fontsize=12)
axes[0].set_ylabel('sensor 1 output '+u'(\u2030)', fontsize=12)
axes[1].set_xlabel('residuals '+u'(\u2030)', fontsize=12)
axes[1].set_ylabel('counts', fontsize=12)
# Compute some fit metrics:
rmse1 = np.nanmean(res1_dD**2)**0.5
rmse2 = np.nanmean(res2_dD**2)**0.5
print(100*(rmse1-rmse2)/rmse1)
print(np.nanmean((res1_dD - np.nanmean(res1_dD))**2)**0.5)
print(np.nanmean((res2_dD - np.nanmean(res2_dD))**2)**0.5)
def model_residual_map(iso, wisperdata, pars, logq_grid, deliso_grid, ffact=1):
"""
Returns a 2D, q-dD map of residuals for an isotope cross calibration.
"""
# Get model residuals:
res = model_residuals(iso, wisperdata, pars)
# RMSE 2d map:
return rmse_map(
res, np.log(wisperdata['h2o_tot2'].values),
wisperdata[iso+'_tot2'].values,
logq_grid, deliso_grid, ffact=ffact
)
def rmse_map(res, logq, deliso, logq_grid, deliso_grid, ffact=1):
"""
Returns a 2D map of RMSE for an isotope cross calibration.
"""
# Get RMSE 2d map using oversampling:
mse = oversampler.oversampler(res**2, logq, deliso,
logq_grid[0,:], deliso_grid[:,0], ffact=ffact)
rmse = mse**0.5
return rmse
def model_residuals(iso, wisperdata, pars):
"""
Model residuals from the isotope cross-calibration model predictions.
"""
# Get model predictions:
logq = np.log(wisperdata['h2o_tot2'].values)
predictorvars = {'logq':logq,
iso:wisperdata[iso+'_tot2'].values,
'logq*'+iso:logq*wisperdata[iso+'_tot2'].values,
}
modelresults = isoxcal_model.predict(predictorvars, pars)
# Model residuals:
res = modelresults - wisperdata[iso+'_tot1']
return res
year = '2017'
wisperdata = pic2_xcal_fits.get_wisperdata(year)
for iso in ['dD', 'd18O']:
pars = pd.read_csv(iso+"_xcal_results_%s.csv" % year, index_col='predictor_var')
pars = pars.squeeze()
#scatter_with_modelfit(year, wisperdata, pars_dD, pars_d18O)
fig, axes = plt.subplots(1, 2, figsize=(6.5, 3), tight_layout=True)
residuals_figure(year, wisperdata, iso, pars, axes)
fig.savefig('figure_model_assessment.png')