-
Notifications
You must be signed in to change notification settings - Fork 7
/
albedoBias.py
285 lines (233 loc) · 12 KB
/
albedoBias.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
283
284
285
# %%
import pandas as pd
import os
import glob
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns
from sklearn.metrics import mean_squared_error
import numpy as np
# %%
# '''
# obtain the albedo and promice station data
# '''
# df = pd.read_csv('/data/shunan/github/Remote-Sensing-of-Albedo/script/promice/promice.csv')
# df['Longitude'] = df['Longitude'] * -1
# folderpath = "promice/multiSat60m"
# searchCriteria = "*.csv"
# globInput = os.path.join(folderpath, searchCriteria)
# csvPath = glob.glob(globInput)
# csvList = os.listdir(folderpath)
# #%%
# # hourly
# for i in range(len(csvList)):
# # promice data
# stationName = os.path.splitext(csvList[i])[0].replace("-", "*")
# index = df.index[df.Station == stationName][0]
# url = df.urlhourly[index]
# dfs = pd.read_table(url, sep=r'\s{1,}', engine='python')
# dfs = dfs[['Albedo_theta<70d', 'Year', 'MonthOfYear','DayOfMonth', 'HourOfDay(UTC)', 'CloudCover']]
# dfs['datetime'] = pd.to_datetime(dict(year=dfs.Year, month=dfs.MonthOfYear, day = dfs.DayOfMonth, hour = dfs['HourOfDay(UTC)']))
# # cloud cover less than 50% and albedo must be valid value
# dfs = dfs[(dfs['Albedo_theta<70d'] > 0) & (dfs['Albedo_theta<70d'] < 1) & (dfs['CloudCover'] < 0.5)]
# dfs['Station'] = stationName
# # satellite data
# dfr = pd.read_csv(csvPath[i])
# # dfr.datetime = pd.to_datetime(dfr.datetime).dt.date # keep only ymd
# dfr.datetime = pd.to_datetime(dfr.datetime)
# # join by datetime
# dfmerge = pd.merge_asof(dfr.sort_values('datetime'), dfs.dropna().sort_values('datetime'), on='datetime',allow_exact_matches=False, tolerance=pd.Timedelta(hours=1),direction='nearest' )
# # dfmerge = pd.merge_asof(dfr.sort_values('datetime'), dfs, on='datetime', tolerance=pd.Timedelta(hours=1) )
# if i==0:
# dfmerge.to_csv('promice/promice vs satellite60m.csv', mode='w', index=False)
# else:
# dfmerge.to_csv('promice/promice vs satellite60m.csv', mode='a', index=False, header=False)
# %%
# Plot
#
#
# # %% different scales
df = pd.read_csv('promice/promice vs satellite60m.csv').dropna()
# # if the scale is less than 60m, filter out landsat
# df = df[df.satellite == 'Sentinel2']
slope, intercept, r_value, p_value, std_err = stats.linregress(df.visnirAlbedo, df["Albedo_theta<70d"])
df['bias'] = df["visnirAlbedo"] - df["Albedo_theta<70d"]
df.datetime = pd.to_datetime(df.datetime)
df['doy'] = df['datetime'].dt.dayofyear
def nse(simulations, evaluation):
"""Nash-Sutcliffe Efficiency (NSE) as per `Nash and Sutcliffe, 1970
<https://doi.org/10.1016/0022-1694(70)90255-6>`_.
:Calculation Details:
.. math::
E_{\\text{NSE}} = 1 - \\frac{\\sum_{i=1}^{N}[e_{i}-s_{i}]^2}
{\\sum_{i=1}^{N}[e_{i}-\\mu(e)]^2}
where *N* is the length of the *simulations* and *evaluation*
periods, *e* is the *evaluation* series, *s* is (one of) the
*simulations* series, and *μ* is the arithmetic mean.
https://github.com/ThibHlln/hydroeval/tree/v0.1.0
Thibault Hallouin, 2021. hydroeval: an evaluator for streamflow time series in Python. https://doi.org/10.5281/zenodo.4709652
"""
nse_ = 1 - (
np.sum((evaluation - simulations) ** 2, axis=0, dtype=np.float64)
/ np.sum((evaluation - np.mean(evaluation)) ** 2, dtype=np.float64)
)
return nse_
def ioa(simulations, evaluation):
"""Index of agreement
"""
ioa_ = 1 - (
np.sum((evaluation - simulations) ** 2, axis=0, dtype=np.float64)
/ np.sum(
(np.abs(simulations - np.mean(evaluation)) + np.abs(evaluation - np.mean(evaluation))) ** 2,
dtype=np.float64)
)
return ioa_
def nse_modified(simulations, evaluation, j):
"""Nash-Sutcliffe Efficiency (NSE) Modified
10.5194/adgeo-5-89-2005
"""
nse_modified_ = 1 - (
np.sum(
(np.abs(evaluation - simulations)) ** j , axis=0, dtype=np.float64
)
/ np.sum(
(np.abs(evaluation - np.mean(evaluation))) ** j , dtype=np.float64
)
)
return nse_modified_
nsecoefficient = nse(df["visnirAlbedo"].values, df["Albedo_theta<70d"].values)
nsecoefficientLog = nse(np.log(df["visnirAlbedo"].values), np.log(df["Albedo_theta<70d"].values))
ioad = ioa(df["visnirAlbedo"].values, df["Albedo_theta<70d"].values)
nsem = nse_modified(df["visnirAlbedo"].values, df["Albedo_theta<70d"].values, 1)
print("nse coefficient is %.4f" % nsecoefficient)
print("nse coefficient (log) is %.4f" % nsecoefficientLog)
print("index of agreement is %.4f" % ioad)
print("nse modified is %.4f" % nsem)
#%% different scale plots
sns.set_theme(style="darkgrid", font="Arial", font_scale=2)
g = sns.jointplot(x="visnirAlbedo", y="Albedo_theta<70d", data=df, kind="hist",
height=8, xlim=(0,1), ylim=(0,1), cbar=True, vmin=0, vmax=55)
g.ax_joint.axline((0, 0), (1, 1), linewidth=1, color='k', linestyle='--')
g.plot_joint(sns.regplot, color='r', scatter=False)
g.set_axis_labels(xlabel="visnir albedo", ylabel="PROMICE albedo")
# ref https://stackoverflow.com/a/60849048/13318759
# get the current positions of the joint ax and the ax for the marginal x
pos_joint_ax = g.ax_joint.get_position()
pos_marg_x_ax = g.ax_marg_x.get_position()
# reposition the joint ax so it has the same width as the marginal x ax
g.ax_joint.set_position([pos_joint_ax.x0, pos_joint_ax.y0, pos_marg_x_ax.width, pos_joint_ax.height])
# reposition the colorbar using new x positions and y positions of the joint ax
g.fig.axes[-1].set_position([.96, pos_joint_ax.y0, .07, pos_joint_ax.height])
g.savefig("promice/albedo60m.png",
dpi=300, bbox_inches="tight")
# g.savefig("promice/albedo60m.pdf",
# dpi=300, bbox_inches="tight")
print('ALL: \ny={0:.4f}x+{1:.4f}\nr_value:{2:.2f} \np:{3:.3f} \nstd_err:{4:.4f}'
.format(slope,intercept,r_value,p_value, std_err))
print('Total RMSE is %.4f' % (mean_squared_error(df["Albedo_theta<70d"], df["visnirAlbedo"], squared=False)))
print("average bias is: %.4f" % df.bias.mean())
# %% bias plot
sns.set_theme(style="darkgrid", font="Arial", font_scale=1)
g = sns.FacetGrid(data=df, col="Station", col_wrap=4, legend_out=True)
g.map(sns.regplot, "doy", "bias")
g.add_legend()
g.refline(y=0)
# ax = g.axes[0]
# ax.annotate('n:%.0f' % (len(df.L8.values)), xy=(0.7, 0.1), xycoords='data',
# horizontalalignment='left', verticalalignment='top',
# )
g.savefig("promice/bias60m.png",
dpi=600, bbox_inches="tight")
# %% ryan 2017
df = df[(df.Station=="KAN_L") | (df.Station=="KAN_M") | (df.Station=="KAN_U") ]
# %%
sns.set_theme(style="darkgrid", font="Arial", font_scale=2)
g = sns.FacetGrid(data=df.sort_values("Station"), col="Station", col_wrap=3,
legend_out=True, size=6)
g.map(sns.regplot, "doy", "bias")
g.add_legend()
g.refline(y=0)
# %%
dfsubset = df[(df.Station=="KAN_L") | (df.Station=="KAN_M")]
# RMSE
print('Total RMSE is %.4f' % (mean_squared_error(dfsubset["Albedo_theta<70d"], dfsubset["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubset.bias.mean())
dfsubsetM = dfsubset[(dfsubset["MonthOfYear"] == 4) | (dfsubset["MonthOfYear"] == 5)]
print('April/May RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 6]
print('June RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 7]
print('July RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 8]
print('August RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubset = df[df.Station=="KAN_L"]
# RMSE
print('KAN_L RMSE is %.4f' % (mean_squared_error(dfsubset["Albedo_theta<70d"], dfsubset["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubset.bias.mean())
dfsubsetM = dfsubset[(dfsubset["MonthOfYear"] == 4) | (dfsubset["MonthOfYear"] == 5)]
print('April/May RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 6]
print('June RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 7]
print('July RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 8]
print('August RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubset = df[df.Station=="KAN_M"]
# RMSE
print('KAN_M RMSE is %.4f' % (mean_squared_error(dfsubset["Albedo_theta<70d"], dfsubset["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubset.bias.mean())
dfsubsetM = dfsubset[(dfsubset["MonthOfYear"] == 4) | (dfsubset["MonthOfYear"] == 5)]
print('April/May RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 6]
print('June RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 7]
print('July RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
dfsubsetM = dfsubset[dfsubset["MonthOfYear"] == 8]
print('August RMSE is %.4f' % (mean_squared_error(dfsubsetM["Albedo_theta<70d"], dfsubsetM["visnirAlbedo"], squared=False)))
print("mean bias is %.4f" % dfsubsetM.bias.mean())
# %% Individual AWS
dfsubset = df[df.Station=="KAN_L"]
slope, intercept, r_value, p_value, std_err = stats.linregress(dfsubset["doy"], dfsubset["bias"])
print('KAN_L: \ny={0:.4f}x+{1:.4f}\nr_value:{2:.2f} \np:{3:.3f}'.format(slope,intercept,r_value,p_value))
dfsubset = df[df.Station=="KAN_M"]
slope, intercept, r_value, p_value, std_err = stats.linregress(dfsubset["doy"], dfsubset["bias"])
print('KAN_M: \ny={0:.4f}x+{1:.4f}\nr_value:{2:.2f} \np:{3:.3f}'.format(slope,intercept,r_value,p_value))
# %%
df = df[(df.Station=="KAN_L") | (df.Station=="KAN_M")]
sns.set_theme(style="darkgrid", font="Arial", font_scale=2)
g = sns.FacetGrid(data=df.sort_values("Station"), col="Station", col_wrap=2,
legend_out=True, height=6)
g.map(sns.regplot, "doy", "bias")
g.add_legend()
g.refline(y=0)
g.savefig("promice/KANbias60m.png",
dpi=300, bbox_inches="tight")
#%%
sns.set_theme(style="darkgrid", font="Arial", font_scale=2)
g = sns.FacetGrid(data=df, col="Station", col_wrap=2, height=6)
g.map(sns.regplot, "visnirAlbedo", "bias")
g.refline(y=0)
g.savefig("promice/KANbiasLinear60m.png",
dpi=300, bbox_inches="tight")
dfsubset = df[df.Station=="KAN_L"]
slope, intercept, r_value, p_value, std_err = stats.linregress(dfsubset["visnirAlbedo"], dfsubset["bias"])
print('KAN_L: \ny={0:.4f}x+{1:.4f}\nr_value:{2:.2f} \np:{3:.3f}'.format(slope,intercept,r_value,p_value))
dfsubset = df[df.Station=="KAN_M"]
slope, intercept, r_value, p_value, std_err = stats.linregress(dfsubset["visnirAlbedo"], dfsubset["bias"])
print('KAN_M: \ny={0:.4f}x+{1:.4f}\nr_value:{2:.2f} \np:{3:.3f}'.format(slope,intercept,r_value,p_value))
# %%
sns.boxplot(data=df, x="Station", y="bias")
# %%
sns.boxplot(data=df, x="Station", y="visnirAlbedo")
# %%